package com.engine.attendance.workflow.cmd;

import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.common.util.CommonUtil;
import com.engine.common.util.DateUtil;
import com.engine.common.util.DbTools;
import com.engine.common.util.Utils;
import com.engine.core.interceptor.CommandContext;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class GetKqCycleTimeIntervalCmd extends AbstractCommonCommand<Map<String, Object>> {

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

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

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        String userId = Util.null2String(params.get("userId"));
        List<Map<String, Object>> submitDataList = (List<Map<String, Object>>)params.get("submitDataList");
        String submitStr = Util.null2String(params.get("submitStr"));
        //提交日期
        String submitDate = Util.null2String(params.get("submitDate"));

        Map<String,Object> resultMap = Maps.newHashMap();
        resultMap.put("status",true);
        Set<String> yearSet = Sets.newHashSet();
        for (Map<String, Object> map : submitDataList){
            yearSet.add(map.get(submitStr).toString().split("-")[0]);
        }

        log.info("GetKqCycleTimeIntervalCmd userId:[{}],submitDateList:[{}],submitStr:[{}]",userId,submitDataList,submitStr);
        String modeId = Utils.getFormmodeIdMap().get("uf_jcl_kq_kqzqmc");

        Set<String> attendanceSetIdsSets = CommonUtil.getDataIds(userId,modeId,null,null);
        log.info("attendanceSetIdsSets : {}",attendanceSetIdsSets);
        if (attendanceSetIdsSets.size() == 0){
            //取默认周期
            String sql = "select id from uf_jcl_kq_kqzqmc where mrzq=1";
            List<Map<String,Object>> dataList = DbTools.getSqlToList(sql);
            if (dataList.size() > 0){
                attendanceSetIdsSets.add(dataList.get(0).get("id").toString());
            }
        }


        String sql = "select id,departmentid,subcompanyid1 from hrmresource where id =?";
        Map<String,Object> departMentMap = DbTools.getSqlToMap(sql,userId);
        String deptid = Util.null2String(departMentMap.get("departmentid"));
        String pdeptids = "";
        List<Map<String,Object>> closeList = Lists.newArrayList();
        List<String> nocycleList = Lists.newArrayList();
        List<Map<String,Object>> dataList = Lists.newArrayList();

        try {
            pdeptids = new DepartmentComInfo().getAllParentDepartId(Util.null2String(departMentMap.get("departmentid")), pdeptids);
            pdeptids = deptid + pdeptids;
            log.info("pdeptids : [{}]",pdeptids);

            sql = "select a.zt,a.ksrq,a.jsrq,a.gzrq,a.gzsj,b.zt dtzt,b.tsbm,b.gzrq dtgzrq,b.gzsj dtgzsj from uf_jcl_kq_kqzq a left join uf_jcl_kq_kqzq_dt1 b on a.id=b.mainid where  a.mc=? and a.nd in ("+String.join(",",yearSet)+")";
            if (attendanceSetIdsSets.toArray().length == 0){
                resultMap.put("status",false);
                return resultMap;
            }
            List<Map<String,Object>> list = DbTools.getSqlToList(sql,attendanceSetIdsSets.toArray()[0]);
            log.info("GetKqCycleTimeIntervalCmd list : [{}]",list);
            for (Map<String,Object> detailData:submitDataList){
                String ksrq = Util.null2String(detailData.get(submitStr)).split(" ")[0];
                List<Map<String,Object>> cycleTime = list.stream().filter(e->DateUtil.getTime(e.get("ksrq").toString()).compareTo(DateUtil.getTime(ksrq)) <= 0 &&
                        DateUtil.getTime(e.get("jsrq").toString()).compareTo(DateUtil.getTime(ksrq)) >=0).collect(Collectors.toList());
                log.info("数据业务日期:[{}],周期数据:[{}]",ksrq,cycleTime);
                if (cycleTime.size() > 0){
                    Map<String,Object> date = Maps.newHashMap();
                    date.put("startDate",cycleTime.get(0).get("ksrq"));
                    date.put("endDate",cycleTime.get(0).get("jsrq"));
                    dataList.add(date);

                    //0:待关账 1:已关账,2:已结账
                    String zt = Util.null2String(cycleTime.get(0).get("zt"));
                    String gzrq = Util.null2String(cycleTime.get(0).get("gzrq"));
                    String gzsj = Util.null2String(cycleTime.get(0).get("gzsj"));

                    String tsbm = Util.null2String(cycleTime.get(0).get("tsbm"));
                    String dtzt = Util.null2String(cycleTime.get(0).get("dtzt"));
                    String dtgzrq = Util.null2String(cycleTime.get(0).get("dtgzrq"));
                    String dtgzsj = Util.null2String(cycleTime.get(0).get("dtgzsj"));

                    if (!"".equals(tsbm) && CommonUtil.ifContainStr(pdeptids,tsbm,",")){
                        //人员在特殊部门里
                        if ("1".equals(dtzt) || DateUtil.getTime(submitDate).compareTo(DateUtil.getTime(dtgzrq+" "+dtgzsj+":00")) >0){
                            //处于关账状态或提交日期大于关账时间
                            closeList.add(new HashMap(){{
                                put("rq",detailData.get(submitStr));
                                put("cycle",cycleTime);
                            }});
                        }
                    }else {
                        if ("1".equals(zt) || "2".equals(zt) || DateUtil.getTime(submitDate).compareTo(DateUtil.getTime(gzrq+" "+gzsj+":00")) >0){
                            //数据已关账或提交日期大于关账时间
                            closeList.add(new HashMap(){{
                                put("rq",detailData.get(submitStr));
                                put("cycle",cycleTime);
                            }});
                        }
                    }
                }else {
                    nocycleList.add(detailData.get(submitStr).toString());
                }
            }
        }catch (Exception e){
            log.error("catch error :{}",e);
        }
        log.info("GetKqCycleTimeIntervalCmd closeList : [{}]",closeList);
        log.info("GetKqCycleTimeIntervalCmd nocycleList : [{}]",nocycleList);

        resultMap.put("closeList",closeList);
        resultMap.put("nocycleList",nocycleList);
        resultMap.put("dataList",dataList);


        return resultMap;
    }
}
