package com.engine.kq.cmd.balanceofleave;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogSmallType4Hrm;
import com.engine.common.constant.BizLogType;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.KQLeaveRulesComInfo;
import com.engine.kq.biz.KQLeaveRulesDetailComInfo;
import com.engine.kq.biz.KQUsageHistoryBiz;
import com.engine.kq.entity.KQUsageHistoryEntity;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;

import java.util.*;

/**
 * 假期余额--保存
 */
public class SaveBalanceOfLeaveCmd extends AbstractCommonCommand<Map<String, Object>> {

    private SimpleBizLogger logger;

    public SaveBalanceOfLeaveCmd(Map<String, Object> params, User user) {
        this.user = user;
        this.params = params;
        this.logger = new SimpleBizLogger();
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            boolean canEdit = HrmUserVarify.checkUserRight("KQLeaveRulesEdit:Edit", user);//是否具有新建权限
            if (!canEdit) {
                resultMap.put("status", "-1");
                resultMap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
                return resultMap;
            }
            //假期类型的ID
            String leaveRulesId = Util.null2String(params.get("ruleId"));
            //搜索条件中的年份
            String searchYearSelect = Util.null2String(params.get("searchYearSelect"));//日期控件的选择值
            String searchYear = Util.null2String(params.get("searchYear"));//年份
            if (searchYearSelect.equals("5") || searchYearSelect.equals("8")) {
                searchYear = TimeUtil.getDateByOption(searchYearSelect, "0").substring(0, 4);
            }
            //人员和余额数据(JSON字符串)
            String datas = Util.null2String(params.get("datas"));
            //获取当前日期，当前时间
            Calendar today = Calendar.getInstance();
            //当前日期
            String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-" +
                    Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-" +
                    Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
            //当前时间
            String currentTime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":" +
                    Util.add0(today.get(Calendar.MINUTE), 2) + ":" +
                    Util.add0(today.get(Calendar.SECOND), 2);
            //人力资源缓存类
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            //获取假期类型的缓存类
            KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
            //请假最小单位：1-按天请假、2-按半天请假、3-按小时请假、4-按整天请假
            String minimumUnit = kqLeaveRulesComInfo.getMinimumUnit(leaveRulesId);
            //获取假期规则的缓存类
            KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo();

            /**********************************************************************************************************/

            String insertOrUpdate = "";
            KQUsageHistoryEntity usageHistoryEntity = new KQUsageHistoryEntity();//员工假期余额变更记录实体类
            List<KQUsageHistoryEntity> usageHistoryEntityList = new ArrayList<KQUsageHistoryEntity>();//员工假期余额变更记录集合

            String oldBaseAmount = "0";
            String oldUsedAmount = "0";
            String oldExtraAmount = "0";
            String oldBaseAmount2 = "0";
            String oldUsedAmount2 = "0";
            String oldExtraAmount2 = "0";

            String newBaseAmount = "0";
            String newUsedAmount = "0";
            String newExtraAmount = "0";
            String newBaseAmount2 = "0";
            String newUsedAmount2 = "0";
            String newExtraAmount2 = "0";

            //哪些人已经在数据库中有记录了
            RecordSet recordSet = new RecordSet();
            RecordSet tmpSet = new RecordSet();
            String searchSql = "select * from kq_BalanceOfLeave where leaveRulesId=? and resourceId=? and belongYear=? order by id";

            //修改了哪些人的假期余额
            List<String> resourceIdList = new ArrayList<String>();
            JSONArray dataArr = JSONArray.parseArray(datas);
            for (int i = 0; i < dataArr.size(); i++) {
                JSONObject jsonObject = dataArr.getJSONObject(i);
                String resourceId = jsonObject.getString("randomFieldId");
                if (resourceId.equals("")) {
                    continue;
                }
                if (!resourceIdList.contains(resourceId)) {
                    resourceIdList.add(resourceId);
                }
            }
            //记录右键操作日志
            if (resourceIdList.size() > 0) {
                String resourceIdStr = String.join(",", resourceIdList);
                BizLogContext bizLogContext = new BizLogContext();
                bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型
                bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_BALANCEOFLEAVE);//所属大类型
                bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_BALANCEOFLEAVE);//当前小类型
                bizLogContext.setParams(params);//当前request请求参数
                logger.setUser(user);//当前操作人
                String mainSql = "select * from kq_balanceOfleave where resourceId in (" + resourceIdStr + ") and leaveRulesId=" + leaveRulesId;
                logger.setMainSql(mainSql, "id");//主表sql
                logger.setMainPrimarykey("id");//主日志表唯一key
                logger.setMainTargetNameMethod("com.engine.kq.util.KQTransMethod.getTargetName4Balance");
                logger.setMethodOtherParams("column:resourceId+column:leaveRulesId");
                logger.before(bizLogContext);
            }

            boolean flag = true;//记录SQL操作是否成功
            String updateSql = "update kq_BalanceOfLeave set baseAmount=?,extraAmount=?,usedAmount=?,baseAmount2=?,extraAmount2=?,usedAmount2=? where leaveRulesId=? and resourceId=? and belongYear=?";
            String insertSql = "insert into kq_BalanceOfLeave(baseAmount,extraAmount,usedAmount,baseAmount2,extraAmount2,usedAmount2,leaveRulesId,resourceId,belongYear) values(?,?,?,?,?,?,?,?,?) ";
            String delSql = "delete from kq_BalanceOfLeave where leaveRulesId=? and resourceId=? and belongYear=? and id !=? ";
//            List<String> existdata = new ArrayList<String>();
            Map<String,String> existmap = new HashMap<String,String>();
            JSONArray jsonArray = JSONArray.parseArray(datas);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String resourceId = jsonObject.getString("randomFieldId");
                String baseAmount = "" + Util.getDoubleValue(jsonObject.getString("baseAmountspan"), 0);
                String extraAmount = "" + Util.getDoubleValue(jsonObject.getString("extraAmountspan"), 0);
                String usedAmount = "" + Util.getDoubleValue(jsonObject.getString("usedAmountspan"), 0);
                String baseAmount2 = "" + Util.getDoubleValue(jsonObject.getString("baseAmount2span"), 0);
                String extraAmount2 = "" + Util.getDoubleValue(jsonObject.getString("extraAmount2span"), 0);
                String usedAmount2 = "" + Util.getDoubleValue(jsonObject.getString("usedAmount2span"), 0);
                //获取人员相关信息
                if (resourceId.equals("")) {
                    continue;
                }
                String lastName = resourceComInfo.getLastname(resourceId);
                String subcompanyId = resourceComInfo.getSubCompanyID(resourceId);
                /*目前没有为该人员所在分部或者总部设置任何假期规则，不允许保存*/
                if (Util.getIntValue(detailComInfo.getId(leaveRulesId, subcompanyId), 0) <= 0) {
                    resultMap.put("sign", "-1");
                    resultMap.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10004211,weaver.general.ThreadVarLanguage.getLang())+"" + lastName + ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005331,weaver.general.ThreadVarLanguage.getLang())+"");//保存失败
                    return resultMap;
                }

                //最近有遇到一些假期余额人员重复的问题，单独优化下，重复垃圾数据，保留id小的
                //加下面的逻辑是因为当有重复的垃圾数据时，前端传过来的数据也是重复，即使遍历的第一次有删除多余的垃圾，后面的重复数据会覆盖掉前面的id小的数据
                String key = resourceId+"#"+leaveRulesId+"#"+searchYear;
                if(existmap!=null && existmap.containsKey(key)){
                    continue;
                }else{
                    existmap.put(key,key);
                }

                //在数据库里是否已经存在记录了
                recordSet.executeQuery(searchSql, leaveRulesId, resourceId, searchYear);
                int datacount = recordSet.getCounts();
                if (recordSet.next()) {
                    String tmpid = Util.null2String(recordSet.getString("id"));
                    if(datacount>1){//最近有遇到一些假期余额人员重复的问题，单独优化下
                        tmpSet.executeUpdate(delSql, leaveRulesId, resourceId, searchYear,tmpid);
                    }
                    oldBaseAmount = "" + Util.getDoubleValue(recordSet.getString("baseAmount"), 0);
                    oldExtraAmount = "" + Util.getDoubleValue(recordSet.getString("extraAmount"), 0);
                    oldUsedAmount = "" + Util.getDoubleValue(recordSet.getString("usedAmount"), 0);
                    oldBaseAmount2 = "" + Util.getDoubleValue(recordSet.getString("baseAmount2"), 0);
                    oldExtraAmount2 = "" + Util.getDoubleValue(recordSet.getString("extraAmount2"), 0);
                    oldUsedAmount2 = "" + Util.getDoubleValue(recordSet.getString("usedAmount2"), 0);

                    newBaseAmount = baseAmount == null ? oldBaseAmount : baseAmount;
                    newExtraAmount = extraAmount == null ? oldExtraAmount : extraAmount;
                    newUsedAmount = usedAmount == null ? oldUsedAmount : usedAmount;
                    newBaseAmount2 = baseAmount2 == null ? oldBaseAmount2 : baseAmount2;
                    newExtraAmount2 = extraAmount2 == null ? oldExtraAmount2 : extraAmount2;
                    newUsedAmount2 = usedAmount2 == null ? oldUsedAmount2 : usedAmount2;

                    if (oldBaseAmount.equals(newBaseAmount) && oldExtraAmount.equals(newExtraAmount) && oldUsedAmount.equals(newUsedAmount)
                            && oldBaseAmount2.equals(newBaseAmount2) && oldExtraAmount2.equals(newExtraAmount2) && oldUsedAmount2.equals(newUsedAmount2)) {
                        continue;
                    }

                    /*更新员工假期余额 start*/
                    flag = recordSet.executeUpdate(updateSql, newBaseAmount, newExtraAmount, newUsedAmount, newBaseAmount2, newExtraAmount2, newUsedAmount2, leaveRulesId, resourceId, searchYear);
                    if (!flag) {
                        resultMap.put("sign", "-1");
                        resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败
                        return resultMap;
                    }
                    /*更新员工假期余额 end*/
                } else {
					oldBaseAmount = "0";
                    oldExtraAmount = "0";
                    oldUsedAmount =  "0";
                    oldBaseAmount2 = "0";
                    oldExtraAmount2 =  "0";
                    oldUsedAmount2 =  "0";
					
                    newBaseAmount = baseAmount == null ? "0" : baseAmount;
                    newExtraAmount = extraAmount == null ? "0" : extraAmount;
                    newUsedAmount = usedAmount == null ? "0" : usedAmount;
                    newBaseAmount2 = baseAmount2 == null ? "0" : baseAmount2;
                    newExtraAmount2 = extraAmount2 == null ? "0" : extraAmount2;
                    newUsedAmount2 = usedAmount2 == null ? "0" : usedAmount2;

                    /*新增员工假期余额 start*/
                    flag = recordSet.executeUpdate(insertSql, newBaseAmount, newExtraAmount, newUsedAmount, newBaseAmount2, newExtraAmount2, newUsedAmount2, leaveRulesId, resourceId, searchYear);
                    if (!flag) {
                        resultMap.put("sign", "-1");
                        resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败
                        return resultMap;
                    }
                    /*新增员工假期余额 end*/
                }

                /*员工假期余额变更记录 start*/
                usageHistoryEntity = new KQUsageHistoryEntity();
                usageHistoryEntity.setLeaveRulesId(leaveRulesId);
                usageHistoryEntity.setRelatedId(resourceId);
                usageHistoryEntity.setOperator("" + user.getUID());
                usageHistoryEntity.setOperateDate(currentDate);
                usageHistoryEntity.setOperateTime(currentTime);
                usageHistoryEntity.setOperateType("5");
                usageHistoryEntity.setBelongYear(searchYear);
                usageHistoryEntity.setOldBaseAmount(oldBaseAmount);
                usageHistoryEntity.setNewBaseAmount(newBaseAmount);
                usageHistoryEntity.setOldExtraAmount(oldExtraAmount);
                usageHistoryEntity.setNewExtraAmount(newExtraAmount);
                usageHistoryEntity.setOldUsedAmount(oldUsedAmount);
                usageHistoryEntity.setNewUsedAmount(newUsedAmount);
                usageHistoryEntity.setOldBaseAmount2(oldBaseAmount2);
                usageHistoryEntity.setNewBaseAmount2(newBaseAmount2);
                usageHistoryEntity.setOldExtraAmount2(oldExtraAmount2);
                usageHistoryEntity.setNewExtraAmount2(newExtraAmount2);
                usageHistoryEntity.setOldUsedAmount2(oldUsedAmount2);
                usageHistoryEntity.setNewUsedAmount2(newUsedAmount2);
                usageHistoryEntity.setOldMinimumUnit(minimumUnit);
                usageHistoryEntity.setNewMinimumUnit(minimumUnit);
                usageHistoryEntity.setInsertOrUpdate(insertOrUpdate);

                usageHistoryEntityList.add(usageHistoryEntity);
            }

            //记录使用记录
            if (usageHistoryEntityList.size() > 0) {
                KQUsageHistoryBiz usageHistoryBiz = new KQUsageHistoryBiz();
                flag = usageHistoryBiz.save(usageHistoryEntityList);
                if (!flag) {
                    resultMap.put("sign", "-1");
                    resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败
                    return resultMap;
                }
            }

            resultMap.put("sign", "1");
            resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功
        } catch (Exception e) {
            writeLog(e);
        }
        return resultMap;
    }

    @Override
    public List<BizLogContext> getLogContexts() {
        return logger.getBizLogContexts();
    }
}
