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

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 修改
 */
public class EditBalanceCmd extends AbstractCommonCommand<Map<String, Object>> {

    private SimpleBizLogger logger;

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

        String id = Util.null2String(params.get("id"));
        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 =" + id;
        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 {
            //获取当前日期，当前时间
            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);

            String id = Util.null2String(params.get("id"));
            String overtimeType = Util.null2String(params.get("overtimeType"));
            String totalAmount = Util.null2String(params.get("totalAmount"));//总数
            String usedAmount = Util.null2String(params.get("usedAmount"));
            String tiaoxiuAmount = Util.null2String(params.get("tiaoxiuamount"));
            String effectiveDate = Util.null2String(params.get("effectiveDate"));
            String expirationDate = Util.null2String(params.get("expirationDate"));

            double _totalAmount = Util.getDoubleValue(totalAmount, 0.00);
            double _usedAmount = Util.getDoubleValue(usedAmount, 0.00);
            double _tiaoxiuAmount = Util.getDoubleValue(tiaoxiuAmount, 0.00);
            BigDecimal _tiaoxiuamount = new BigDecimal(Util.getDoubleValue(tiaoxiuAmount, 0.00)).setScale(2,RoundingMode.HALF_UP);
            /*已休不能大于总数*/
/*            if ((_totalAmount+_tiaoxiuAmount) < _usedAmount) {
                resultMap.put("sign", "-1");
                resultMap.put("message", SystemEnv.getHtmlLabelName(529202, user.getLanguage()));
                return resultMap;
            }*/
            /*失效日期不能小于加班日期*/
            if (!"".equals(expirationDate)&& !"".equals(effectiveDate) && expirationDate.compareTo(effectiveDate) < 0) {
                resultMap.put("sign", "-1");
                resultMap.put("message", SystemEnv.getHtmlLabelName(508125, user.getLanguage()));
                return resultMap;
            }
            String oldExtraAmount = "";
            String oldUsedAmount = "";

            KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo();

            List<KQUsageHistoryEntity> entities = new ArrayList<KQUsageHistoryEntity>();
            KQUsageHistoryEntity entity = new KQUsageHistoryEntity();
            entity.setInsertOrUpdate("update");
            entity.setNewExtraAmount(totalAmount);
			entity.setWfRequestId("0");
            entity.setNewUsedAmount(usedAmount);

            String searchSql = "select * from KQ_BalanceOfLeave where id=? ";
            RecordSet recordSet = new RecordSet();
            recordSet.executeQuery(searchSql, id);
            if (recordSet.next()) {
                String resourceId = recordSet.getString("resourceId");
                String leaveRulesId = recordSet.getString("leaveRulesId");
                String miniumUnit = rulesComInfo.getMinimumUnit(leaveRulesId);
                String belongYear = recordSet.getString("belongYear");
                oldExtraAmount = Util.null2s(recordSet.getString("extraAmount"), "0.00");
                oldUsedAmount =  Util.null2s(recordSet.getString("usedAmount"),"0.00");

                entity.setRelatedId(resourceId);
                entity.setLeaveRulesId(leaveRulesId);
                entity.setOperator("" + user.getUID());
                entity.setOperateDate(currentDate);
                entity.setOperateTime(currentTime);
                entity.setOperateType("5");
                entity.setOldMinimumUnit(miniumUnit);
                entity.setNewMinimumUnit(miniumUnit);
                entity.setBelongYear(belongYear);
                entity.setOldExtraAmount(oldExtraAmount);
                entity.setOldUsedAmount(oldUsedAmount);
            }
            entities.add(entity);

            String sql = "update KQ_BalanceOfLeave set baseAmount=0,extraAmount=?,usedAmount=?,effectiveDate=?,expirationDate=?,tiaoxiuamount=? where id=?";
            boolean flag = recordSet.executeUpdate(sql, totalAmount, usedAmount, effectiveDate, expirationDate,_tiaoxiuamount.toPlainString(), id);
            if (flag) {
                if (oldExtraAmount.compareTo(totalAmount) != 0 || oldUsedAmount.compareTo(usedAmount) != 0) {
                    KQUsageHistoryBiz usageHistoryBiz = new KQUsageHistoryBiz();
                    usageHistoryBiz.save(entities);
                }

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