package com.engine.kq.cmd.balanceofleavedetail;

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.KQUsageHistoryBiz;
import com.engine.kq.entity.KQUsageHistoryEntity;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

import java.util.*;

/**
 * 删除
 */
public class DeleteBalanceCmd extends AbstractCommonCommand<Map<String, Object>> {

    private SimpleBizLogger logger;

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

        String ids = Util.null2String(params.get("ids"));
        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 (isDelete is null or isDelete<>1) and id in (" + ids + ")";
        logger.setMainSql(mainSql, "id");//主表sql
        logger.setMainPrimarykey("id");//主日志表唯一key
        logger.setMainTargetNameMethod("com.engine.kq.util.KQTransMethod.getTargetName4BalanceDetail", "column:resourceId+column:belongYear+column:belongMonth+" + user.getLanguage());
        logger.before(bizLogContext);
    }

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

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

    @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;
            }

            //获取当前日期，当前时间
            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);
            double restAmount = 0;
            String resourceId = "";
            String leaveRulesId = "";
            String belongYear = "";
            String ids = Util.null2String(params.get("ids"));
            String searchSql = "select * from KQ_BalanceOfLeave where id in (" + ids + ")";
            RecordSet recordSet = new RecordSet();
            recordSet.executeQuery(searchSql);
            while (recordSet.next()) {
                String expirationDate = recordSet.getString("expirationDate");
                if (expirationDate != null && !"".equals(expirationDate) && expirationDate.compareTo(currentDate) < 0) {
                    continue;
                }

                resourceId = recordSet.getString("resourceId");
                leaveRulesId = recordSet.getString("leaveRulesId");
                belongYear = recordSet.getString("belongYear");

                double oldBaseAmount = Util.getDoubleValue(recordSet.getString("baseAmount"), 0);
                double oldExtraAmount = Util.getDoubleValue(recordSet.getString("extraAmount"), 0);
                double oldUsedAmount = Util.getDoubleValue(recordSet.getString("usedAmount"), 0);
                restAmount += oldBaseAmount + oldExtraAmount - oldUsedAmount;
            }
            KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo();
            String miniumUnit = rulesComInfo.getMinimumUnit(leaveRulesId);

            KQUsageHistoryBiz kqUsageHistoryBiz = new KQUsageHistoryBiz();
            KQUsageHistoryEntity entity = new KQUsageHistoryEntity();
            List<KQUsageHistoryEntity> entities = new ArrayList<KQUsageHistoryEntity>();

            entity.setRelatedId(resourceId);
            entity.setLeaveRulesId(leaveRulesId);
            entity.setBelongYear(leaveRulesId);
            entity.setBelongYear(belongYear);
            entity.setOperator("" + user.getUID());
            entity.setOperateDate(currentDate);
            entity.setOperateTime(currentTime);
            entity.setOperateType("5");
            entity.setOldMinimumUnit(miniumUnit);
            entity.setNewMinimumUnit(miniumUnit);
            entity.setOldExtraAmount(String.format("%.2f", restAmount));
            entity.setNewExtraAmount("0");
            entity.setInsertOrUpdate("update");
            entities.add(entity);

            String sql = "update KQ_BalanceOfLeave set isDelete=1 where id in (" + ids + ")";
            boolean flag = recordSet.executeUpdate(sql);
            if (flag) {
                kqUsageHistoryBiz.save(entities);

                resultMap.put("status", "1");
                resultMap.put("message", SystemEnv.getHtmlLabelName(20461, user.getLanguage()));
            } else {
                resultMap.put("status", "-1");
                resultMap.put("message", SystemEnv.getHtmlLabelName(20462, user.getLanguage()));
            }
        } catch (Exception e) {
            writeLog(e);
            resultMap.put("status", "-1");
            resultMap.put("message", e.getMessage());
        }
        return resultMap;
    }
}
