package com.engine.kq.cmd.balanceofleaverp;

import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.*;
import com.engine.kq.util.KQTransMethod;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;

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

/**
 * 员工假期余额报表--某假期的详细使用记录
 */
public class GetUsageRecordDetailCmd extends AbstractCommonCommand<Map<String, Object>> {

    public GetUsageRecordDetailCmd(Map<String, Object> params, User user) {
        this.user = user;
        this.params = params;
    }

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

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            String resourceId = Util.null2String(params.get("resourceId"));//人员ID
            String ruleId = Util.null2String(params.get("ruleId"));//假期类型的ID(对应的是数据库kq_leaveRules表的主键ID)
            String changeType = Util.null2String(params.get("changeType"));//使用记录还是新增记录

            int pageSize = Util.getIntValue((String) params.get("pageSize"), 10);//每页多少行数据
            int currentPage = Util.getIntValue((String) params.get("currentPage"), 1);//当前是多少页

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

            /*获取假期类型的相关设置*/
            KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo();

            /*假期规则名称*/
            String leaveName = Util.formatMultiLang(rulesComInfo.getLeaveName(ruleId), "" + user.getLanguage());

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

            /*计算请假时长方式：1-按工作日计算请假时长、2-按自然日计算请假时长*/
            int computingMode = Util.getIntValue(rulesComInfo.getComputingMode(ruleId), -1);

            /*启用假期余额：0-不启用、1-启用*/
            int balanceEnable = Util.getIntValue(rulesComInfo.getBalanceEnable(ruleId), 0);

            /*假期规则的请假单位是天还是小时*/
            String unitName = "";//单位名称，天/小时
            if (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4) {
                unitName = SystemEnv.getHtmlLabelName(389325, user.getLanguage());//(天)
            } else {
                unitName = SystemEnv.getHtmlLabelName(389326, user.getLanguage());//(小时)
            }

            /*是否是混合模式(法定年假+福利年假)*/
            boolean isMixMode = KQLeaveRulesBiz.isMixMode(ruleId);

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

            ResourceComInfo resourceComInfo = new ResourceComInfo();

            /*分部ID*/
            String subcompanyId = resourceComInfo.getSubCompanyID(resourceId);

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

            /*获取假期类型下对应的假期规则的相关设置*/
            KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo();

            /*余额发放方式：1-手动发放、2-按司龄自动发放、3-按工龄自动发放、4-每年自动发放固定天数、5-加班时长自动计入余额、6-按工龄+工龄自动发放*/
            int distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(ruleId, subcompanyId), 1);

            /*释放规则：0-不限制、1-按天释放、2-按月释放*/
            int releaseRule = Util.getIntValue(detailComInfo.getReleaseRule(ruleId, subcompanyId), 0);

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

            String balanceOfLeave = KQBalanceOfLeaveBiz.getRestAmount("" + resourceId, "" + ruleId, DateUtil.getCurrentDate());
            String topTips = balanceOfLeave + unitName;
            resultMap.put("topTips", topTips);

            RecordSet recordSet = new RecordSet();
            Map<String, Object> dataMap = new HashMap<String, Object>();
            List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
            String sql = "select * from kq_UsageHistory where leaveRulesId=" + ruleId + " and relatedId=" + resourceId;
            if(changeType.equals("Reduce")){
                sql += " and ((newBaseAmount+newExtraAmount-newUsedAmount)-(oldBaseAmount+oldExtraAmount-oldUsedAmount)+(newBaseAmount2+newExtraAmount2-newUsedAmount2)-(oldBaseAmount2+oldExtraAmount2-oldUsedAmount2))<0 ";
            }else if(changeType.equals("Add")){
                sql += " and ((newBaseAmount+newExtraAmount-newUsedAmount)-(oldBaseAmount+oldExtraAmount-oldUsedAmount)+(newBaseAmount2+newExtraAmount2-newUsedAmount2)-(oldBaseAmount2+oldExtraAmount2-oldUsedAmount2))>0 ";
            }
            if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
                sql = "select *,ROW_NUMBER() OVER(order by operateDate desc,operateTime desc) as rn from kq_UsageHistory where leaveRulesId=" + ruleId + " and relatedId=" + resourceId;
            }
            if (!recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
                sql += " order by operateDate desc,operateTime desc";
            }
            String pageSql = "select * from (select tmp.*,rownum rn from (" + sql + ") tmp where rownum<=" + pageSize * currentPage + ") where rn>=" + (pageSize * (currentPage - 1) + 1);
            if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
                pageSql = "select t.* from (" + sql + ") t where 1=1 and rn>=" + (pageSize * (currentPage - 1) + 1) + " and rn<=" + (pageSize * currentPage);
            } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) {
                pageSql = sql + " limit " + (currentPage - 1) * pageSize + "," + pageSize;
            }else if (recordSet.getDBType().equalsIgnoreCase("postgresql")) {
                pageSql = sql + " limit " + pageSize + " offset " + (currentPage - 1) * pageSize ;
            }
            recordSet.executeQuery(pageSql);
            while (recordSet.next()) {
                String id = recordSet.getString("id");
                String wfRequestId = recordSet.getString("wfRequestId");
                String operateDate = recordSet.getString("operateDate");
                String operateTime = recordSet.getString("operateTime");
                String operateType = recordSet.getString("operateType");

                double oldBaseAmount = Util.getDoubleValue(recordSet.getString("oldBaseAmount"), 0.00);
                double newBaseAmount = Util.getDoubleValue(recordSet.getString("newBaseAmount"), 0.00);
                double oldExtraAmount = Util.getDoubleValue(recordSet.getString("oldExtraAmount"), 0.00);
                double newExtraAmount = Util.getDoubleValue(recordSet.getString("newExtraAmount"), 0.00);
                double oldUsedAmount = Util.getDoubleValue(recordSet.getString("oldUsedAmount"), 0.00);
                double newUsedAmount = Util.getDoubleValue(recordSet.getString("newUsedAmount"), 0.00);
                double oldBaseAmount2 = Util.getDoubleValue(recordSet.getString("oldBaseAmount2"), 0.00);
                double newBaseAmount2 = Util.getDoubleValue(recordSet.getString("newBaseAmount2"), 0.00);
                double oldExtraAmount2 = Util.getDoubleValue(recordSet.getString("oldExtraAmount2"), 0.00);
                double newExtraAmount2 = Util.getDoubleValue(recordSet.getString("newExtraAmount2"), 0.00);
                double oldUsedAmount2 = Util.getDoubleValue(recordSet.getString("oldUsedAmount2"), 0.00);
                double newUsedAmount2 = Util.getDoubleValue(recordSet.getString("newUsedAmount2"), 0.00);

                int oldMinimumUnit = Util.getIntValue(recordSet.getString("oldMinimumUnit"));
                if(oldMinimumUnit<0){//表示是第一条insert的假期数据，oldMinimumUnit字段值是为null
                    oldMinimumUnit = Util.getIntValue(recordSet.getString("newMinimumUnit"));
                }
                if (oldMinimumUnit == 1 || oldMinimumUnit == 2 || oldMinimumUnit == 4) {
                    unitName = SystemEnv.getHtmlLabelName(389325, user.getLanguage());//(天)
                } else {
                    unitName = SystemEnv.getHtmlLabelName(389326, user.getLanguage());//(小时)
                }

                /*获取员工假期余额变更的文字描述*/
                String operateDesc = KQUsageHistoryBiz.getDescription(id, user);

                double changeAmount = 0.00;
                /*获取员工假期余额变更前后的差值*/
                if (!operateType.equals("0")) {
                    if (isMixMode) {
                        changeAmount = (newBaseAmount + newExtraAmount - newUsedAmount) - (oldBaseAmount + oldExtraAmount - oldUsedAmount) +
                                (newBaseAmount2 + newExtraAmount2 - newUsedAmount2) - (oldBaseAmount2 + oldExtraAmount2 - oldUsedAmount2);
                    } else {
                        changeAmount = (newBaseAmount + newExtraAmount - newUsedAmount) - (oldBaseAmount + oldExtraAmount - oldUsedAmount);
                    }
                }
                if (changeType.equals("Reduce") && changeAmount >= 0.00) {
                    continue;
                }
                if (changeType.equals("Add") && changeAmount <= 0.00) {
                    continue;
                }
                if (!wfRequestId.equals("") && !wfRequestId.equals("0")) {
                    operateDesc = "<a href=javaScript:openFullWindowHaveBarForWFList('/workflow/request/ViewRequestForwardSPA.jsp?ismonitor=1&requestid=" + wfRequestId + "&isovertime=0'," + wfRequestId + ");>" + operateDesc + "</a>";
                }
                dataMap = new HashMap<String, Object>();
                dataMap.put("operateDate", operateDate);
                dataMap.put("operateTime", operateTime);
                dataMap.put("operateDesc", operateDesc);
                dataMap.put("changeAmount", operateType.equals("0") ? SystemEnv.getHtmlLabelName(10000812,weaver.general.Util.getIntValue(user.getLanguage())) : String.format("%.2f", changeAmount) + unitName);
                dataList.add(dataMap);
            }
            resultMap.put("dataDetail", dataList);

            KQTransMethod kqTransMethod = new KQTransMethod();
            String bottomTips = "";
            if (balanceEnable == 0) {
                bottomTips = SystemEnv.getHtmlLabelName(524, user.getLanguage()) + " " + leaveName + " " + SystemEnv.getHtmlLabelName(579, user.getLanguage()) + "：" + kqTransMethod.getComputingModeName("" + computingMode, "" + user.getLanguage());
            } else {
                bottomTips = SystemEnv.getHtmlLabelName(524, user.getLanguage()) + " " + leaveName + " " + SystemEnv.getHtmlLabelName(579, user.getLanguage()) + "：" + kqTransMethod.getDistributionModName("" + distributionMode, "" + user.getLanguage());
                boolean isTiaoXiu = KQLeaveRulesBiz.isTiaoXiu(ruleId);
                if (!isTiaoXiu) {
                    bottomTips += "-" + kqTransMethod.getReleaseRuleName("" + releaseRule, "" + user.getLanguage());
                }
            }
            resultMap.put("bottomTips", bottomTips);
            resultMap.put("balanceEnable", balanceEnable);
        } catch (Exception e) {
            writeLog(e);
        }
        return resultMap;
    }


}
