package com.engine.kq.cmd.leavetypes;

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.KQAttFlowSetComInfo;
import com.engine.kq.biz.KQLeaveRulesComInfo;
import com.engine.kq.util.KQTransMethod;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

/**
 * @Auther: xiaj
 * @Date: 2019-03-07 16:41
 * @Description:
 */
public class AddLeaveTypesCmd extends AbstractCommonCommand<Map<String, Object>> {

    private SimpleBizLogger logger;

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

        String leaveName = Util.null2String(params.get("leaveName"));
        BizLogContext bizLogContext = new BizLogContext();
        bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型
        bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_LEAVETYPES);//所属大类型
        bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_LEAVETYPES);//当前小类型
        bizLogContext.setParams(params);//当前request请求参数
        logger.setUser(user);//当前操作人
        String mainSql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and leaveName like '%" + leaveName + "%'";
        logger.setMainSql(mainSql, "id");//主表sql
        logger.setMainPrimarykey("id");//主日志表唯一key
        logger.setMainTargetNameColumn("leavename");
        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;
            }
            /*假期类型的ID*/
            KQTransMethod kqTransMethod = new KQTransMethod();
            String ruleId = "" + kqTransMethod.getNextId();

            /*假期类型的名称*/
            String leaveName = Util.null2String(params.get("leaveName"));

            /*校验名称是否已经有其他假期类型使用*/
            String nameSql = "select * from kq_leaveRules where (isDelete is null or isDelete<>1) and leaveName=?";
            RecordSet recordSet = new RecordSet();
            recordSet.executeQuery(nameSql, leaveName);
            if (recordSet.next()) {
                resultMap.put("status", "-1");
                resultMap.put("message", SystemEnv.getHtmlLabelName(505662, user.getLanguage()));
                return resultMap;
            }

            /*流程可见范围：0-总部、1-分部(只有在此范围内的人请假的时候才能看见此假期类型)*/
            int scopeType = Util.getIntValue((String) params.get("scopeType"), 0);

            /*流程可见范围为分部时，选择的分部ID*/
            String scopeValue = Util.null2String(params.get("scopeValue"));

            /*最小请假单位：1-按天请假、2-按半天请假、3-按小时请假、4-按整天请假*/
            int minimumUnit = Util.getIntValue((String) params.get("minimumUnit"), 1);

            /*折算方式：1-四舍五入、2-向上取整、3-向下取整*/
            int conversion = Util.getIntValue((String) params.get("conversion"), 1);

            /*计算请假时长方式：1-按工作日计算请假时长、2-按自然气计算请假时长*/
            int computingMode = Util.getIntValue((String) params.get("computingMode"), 1);

            /*日折算时长(按自然气计算请假时长时有效)*/
            double hoursToDay = Util.getDoubleValue((String) params.get("hoursToDay"), 8.00);

            /*按自然日计算请假时长，是否过滤节假期：0-不启用，1-启用*/
            String filterHolidays = Util.null2String((String)params.get("filterHolidays"), "0");

            /*启用假期余额：0-不启用、1-启用*/
            int balanceEnable = Util.getIntValue((String) params.get("balanceEnable"), 0);

            //显示顺序
            double showOrder = Util.getDoubleValue((String) params.get("showOrder"), 0.00);

            //半天单位 时间选择方式：1-下拉框选择 、2-具体时间
            int timeselection = Util.getIntValue((String) params.get("timeselection"), 1);

            if(minimumUnit != 2){
              //如果请假类型不再是半天了，需要删除原半天设置
              String del_2_sql = "delete from kq_timeselection where selectiontype=0 and leaveruleid=? and minimumUnit=2";
              boolean is_2_del = recordSet.executeUpdate(del_2_sql,ruleId);
              timeselection = 1;
            }

            String sql = "insert into kq_LeaveRules(Id,leaveName,scopeType,scopeValue,minimumUnit,computingMode,hoursToDay,filterHolidays,balanceEnable,isEnable,showOrder,isDelete,timeselection,conversion) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            boolean flag = recordSet.executeUpdate(sql, ruleId, leaveName, scopeType, scopeValue, minimumUnit, computingMode, hoursToDay,filterHolidays, balanceEnable, 1, showOrder, 0,timeselection,conversion);

            if (flag) {
                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) {
            e.printStackTrace();
            resultMap.put("sign", "-1");
            resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败
        } finally {
            KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo();
            KQAttFlowSetComInfo kqAttFlowSetComInfo = new KQAttFlowSetComInfo();
            rulesComInfo.removeCache();
            kqAttFlowSetComInfo.removeKQAttFlowSetComInfoCache();
        }
        return resultMap;
    }
}
