package com.engine.jucailinkq.attendance.attendanceanalysis.cmd;

import com.engine.jucailinkq.attendance.enums.AccountingUnitEnum;
import com.engine.jucailinkq.attendance.enums.CheckBoxEnum;
import com.engine.jucailinkq.attendance.enums.ClassBelongToEnum;
import com.engine.jucailinkq.attendance.enums.ClassSegmentTypeEnum;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.jucailinkq.common.util.CommonUtil;
import com.engine.jucailinkq.common.util.DateUtil;
import com.engine.jucailinkq.common.util.DbTools;
import com.engine.jucailinkq.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 java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 获得请假数据
 */
@Slf4j
public class GetAskForLeaveCmd extends AbstractCommonCommand<Map<String,Object>> {

    public GetAskForLeaveCmd(Map<String,Object> params){
        this.params=params;
    }
    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Map<String,Object> resultMap = Maps.newHashMap();
        String userId = Util.null2String(params.get("userId"));
        String analysisDate = Util.null2String(params.get("analysisDate"));
        List<Map<String, Object>> scheduleResult =  (List<Map<String, Object>>)params.get("scheduleResult");
        String sql = "select b.qjry,b.jqlx,b.ksrq,b.kssj,b.jsrq,b.jssj,b.qjsc,b.qtj,b.btj from uf_jcl_kq_qjjl a left join uf_jcl_kq_qjjl_dt1 b on a.id = b.mainid where b.qjry=? and b.ksrq<=? and b.jsrq>=? and (b.cxqj=0 or b.cxqj is null) and a.jlzt=1";
        List<Map<String,Object>> askForLeaveList = DbTools.getSqlToList(sql,userId,DateUtil.AfterDay(analysisDate,1), DateUtil.beforeDay(analysisDate,1));
        Map<String,Map<String,Object>> askForLeaveItems = Maps.newHashMap();


        String firstKssj = Utils.getkssjTime(scheduleResult.get(0),analysisDate);

        String lastjssj = Utils.getjssjTime(scheduleResult.get(scheduleResult.size()-1),analysisDate);

        Set<String> jplxSet = Sets.newHashSet();
        List<Map<String,Object>> haveAskForLeaveList = askForLeaveList.stream().filter(e->{
            String kssj = e.get("ksrq")+" "+e.get("kssj");
            String jssj = e.get("jsrq")+" "+e.get("jssj");
            if (e.get("ksrq").equals(analysisDate) && "".equals(Util.null2String(e.get("kssj")))){
                jplxSet.add(e.get("jqlx").toString());
                return true;
            }else if (!"".equals(Util.null2String(e.get("kssj"))) && DateUtil.getTime(kssj).compareTo(DateUtil.getTime(lastjssj)) <0 && DateUtil.getTime(jssj).compareTo(DateUtil.getTime(firstKssj)) >0 ){
                jplxSet.add(e.get("jqlx").toString());
                return true;
            }else {
                return false;
            }
        }).collect(Collectors.toList());
        log.debug("haveAskForLeaveList : [{}]",haveAskForLeaveList);



        List<Map<String,Object>> resultList = Lists.newArrayList();
        List<Map<String,Object>> askForLeaveSchedule = Lists.newArrayList();
        resultMap.put("askForLeaveList",haveAskForLeaveList);
        resultMap.put("askForLeaveItems",askForLeaveItems);
        resultMap.put("askForLeaveSchedule",askForLeaveSchedule);
        if (jplxSet.size() == 0){
            return resultMap;
        }

        sql = "select * from uf_jcl_kq_kqxm where id in ("+String.join(",",jplxSet)+")";
        List<Map<String,Object>> askForLeaveItemList = DbTools.getSqlToList(sql);
        List<String> fatherItems = askForLeaveItemList.stream().filter(e->Util.null2String(e.get("sffzcx")).equals(CheckBoxEnum.CHECKED.getKey())).map(e->e.get("id").toString()).collect(Collectors.toList());
        if (fatherItems.size() > 0){
            sql = "select id keyid,mc kqxm,a.* from uf_jcl_kq_kqxm a where  (xmzt is null or  xmzt <> '0') and a.sjxm in ("+String.join(",",fatherItems)+")";
            List<Map<String,Object>> sonItemList = DbTools.getSqlToList(sql);
            Map<String,List<Map<String,Object>>> sonGroupMap = sonItemList.stream().collect(Collectors.groupingBy(e->e.get("sjxm").toString()));
            for (Map<String,Object> attendanceItem :askForLeaveItemList){
                if (CheckBoxEnum.CHECKED.getKey().equals(attendanceItem.get("sffzcx"))){
                    attendanceItem.put("sonItems",sonGroupMap.get(attendanceItem.get("id")));
                }
            }

        }

        Map<String,List<Map<String,Object>>> collect = askForLeaveItemList.stream().collect(Collectors.groupingBy(e->e.get("id").toString()));


        for (Map<String,Object> askForLeaveData : haveAskForLeaveList){
            Map<String,Object> askForLeaveItem = collect.get(askForLeaveData.get("jqlx")).get(0);
            //是否分组呈现
            String sffzcx = Util.null2String(askForLeaveItem.get("sffzcx"));
            //全天请假
            if (CheckBoxEnum.CHECKED.getKey().equals(askForLeaveData.get("qtj"))){
                if (sffzcx.equals(CheckBoxEnum.CHECKED.getKey())){
                    Map<String,Object> proportionMap = Utils.getClassSegmentTimeProportion(scheduleResult,analysisDate);
                    for (Map.Entry<String,Object> entry: proportionMap.entrySet()){
                        String bdlx = entry.getKey();
                        int betweenTimes = Integer.valueOf(entry.getValue().toString());
                        Map<String,Object> item = CommonUtil.assembleAskForOrEvectionItem(askForLeaveItem,bdlx);
                        if (item != null){
                            Map<String, Object> itemMap = Maps.newHashMap();
                            itemMap.put("itemduration",Utils.getItemduration(Double.valueOf(Util.null2String(item.get("hsl"))),Util.null2String(item.get("hsdw")),betweenTimes, AccountingUnitEnum.MINUTES,Double.valueOf(scheduleResult.get(0).get("edsc").toString())));
                            itemMap.put("item",item.get("keyid"));
                            resultList.add(itemMap);
                        }
                    }
                }else {
                    Map<String,Object> map = Maps.newHashMap();
                    map.put("item",askForLeaveData.get("jqlx"));
                    map.put("itemduration",scheduleResult.get(0).get("edsc"));
                    resultList.add(map);
                }

                resultMap.put("alldayVaction",resultList);
            }

            askForLeaveItems.put(askForLeaveData.get("jqlx").toString(),askForLeaveItem);
        }


        Map<String,List<Map<String,Object>>> askForLeaveGroupMap = haveAskForLeaveList.stream().filter(e->!"".equals(Util.null2String(e.get("kssj"))) && !"".equals(Util.null2String(e.get("jssj"))))
                .collect(Collectors.groupingBy(e->Util.null2String(e.get("ksrq"))+Util.null2String(e.get("kssj"))+"&"+Util.null2String(e.get("jsrq"))+Util.null2String(e.get("jssj"))));
        List<Map<String,Object>> filterAskForLeaveList = Lists.newArrayList();
        askForLeaveGroupMap.entrySet().forEach(e->{
            if (e.getValue().size()>1){
                Map<String,Object> beforeAskForMap = e.getValue().get(0);
                Map<String,Object> beforeAskForLeaveItem = collect.get(beforeAskForMap.get("jqlx")).get(0);
                String beforeJcbyxsyqjb = Util.null2String(beforeAskForLeaveItem.get("jcbyxsyqjb"));
                String beforeyxsydjb = Util.null2String(beforeAskForLeaveItem.get("yxsydjb"));
                Map<String,Object> afterAskForMap = e.getValue().get(1);
                Map<String,Object> afterAskForLeaveItem = collect.get(afterAskForMap.get("jqlx")).get(0);
                String afterJcbyxsyqjb = Util.null2String(afterAskForLeaveItem.get("jcbyxsyqjb"));
                String afteryxsydjb = Util.null2String(afterAskForLeaveItem.get("yxsydjb"));
                if (CheckBoxEnum.CHECKED.getKey().equals(beforeJcbyxsyqjb)){
                    if (beforeyxsydjb.equals(afterAskForMap.get("jqlx"))){
                        filterAskForLeaveList.add(beforeAskForMap);
                    }

                }else if (CheckBoxEnum.CHECKED.getKey().equals(afterJcbyxsyqjb)){
                    if (afteryxsydjb.equals(beforeAskForMap.get("jqlx"))){
                        filterAskForLeaveList.add(afterAskForMap);
                    }
                }else {
                    filterAskForLeaveList.add(beforeAskForMap);
                }

            }else if (e.getValue().size() == 1){
                filterAskForLeaveList.addAll(e.getValue());
            }
        });


        for (Map<String,Object> askForLeaveData : filterAskForLeaveList){
            Map<String,Object> askForLeaveItem = collect.get(askForLeaveData.get("jqlx")).get(0);
            if (!"".equals(Util.null2String(askForLeaveData.get("kssj"))) && !"".equals(Util.null2String(askForLeaveData.get("jssj")))){
                Map<String,Object> askForLeaveMap = new HashMap(){{
                    put("bcxx", scheduleResult.get(0).get("bcxx"));
                    put("bcsdxx", scheduleResult.get(0).get("bcsdxx"));
                    put("edsc", scheduleResult.get(0).get("edsc"));
                    put("bdlx", ClassSegmentTypeEnum.ASK_FOR_LEAVE.getKey());
                    put("dtkssj",askForLeaveData.get("ksrq")+" "+askForLeaveData.get("kssj"));
                    put("dtjssj",askForLeaveData.get("jsrq")+" "+askForLeaveData.get("jssj"));
                    put("ksdk",askForLeaveItem.get("lgsbxydk"));
                    put("jsdk",askForLeaveItem.get("fgsbxydk"));
                    put("tqdkfzs","60");
                    put("thdkfzs","60");
                    put("tqlghlfzs",askForLeaveItem.get("tqlghlfzs"));
                    put("thfghlfzs",askForLeaveItem.get("thfghlfzs"));
                }};
                askForLeaveSchedule.add(askForLeaveMap);
            }
        }
        return resultMap;
    }
}
