package com.engine.jucailinkq.attendance.component.persongroup.cmd;

import com.engine.jucailinkq.attendance.component.persongroup.commonutil.PersongroupCommonUtil;
import com.engine.jucailinkq.attendance.enums.CheckBoxEnum;
import com.engine.jucailinkq.attendance.enums.SchedulingApproachEnum;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;

import com.engine.jucailinkq.common.util.DateUtil;
import com.engine.jucailinkq.common.util.DbTools;
import com.engine.core.interceptor.CommandContext;
import com.engine.jucailinkq.common.util.Utils;
import com.google.common.collect.Lists;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;

import java.time.ZoneOffset;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 当递归查询时获得表格数据
 */
@Slf4j
public class GetDatatableRecurrenceCmd extends AbstractCommonCommand<Map<String,Object>> {

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

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        String tableName = Util.null2String(params.get("tableName"));
        String startDate = Util.null2String(params.get("startDate"));
        String endDate = Util.null2String(params.get("endDate"));
        String pblx = Util.null2String(params.get("pblx"));
        String pbdx = Util.null2String(params.get("pbdx"));
        String showAll = Util.null2String(params.get("showAll"));

        String sql = "select a.id as keyid,b.lastname,a.* from "+tableName +" a left join hrmresource b on a.pbdxry=b.id where 1=1 ";

        String conditions = "";
        List<Object> Dateparam = Lists.newArrayList();
        if (!"".equals(startDate) && !"".equals(endDate)){
            conditions += " and bcrq >= ? and bcrq<= ?";
            Dateparam.add(startDate);
            Dateparam.add(endDate);
        }
        Map<String,Object> resultMap = Maps.newHashMap();
        List<Map<String, Object>> dataTableList = Lists.newArrayList();

        try {

            if (!"".equals(pbdx)){
                if ("0".equals(pblx)){
                    //人员递归查人员、人员分组、部门、分部
                    String querySqlbyPbdx = sql +conditions + " and pbdxry = ? order by bcrq";
                    List<Object> param = Lists.newArrayList();
                    param.addAll(Dateparam);
                    param.add(pbdx);
                    log.debug("递归查询人员-人员节点，sql:{},param:{}",querySqlbyPbdx,param);
                    List<Map<String,Object>> dataList = DbTools.getSqlToList(querySqlbyPbdx,param.toArray());
                    //人员数据
                   // Map<String,List<Map<String,Object>>> personCollect = dataList.stream().collect(Collectors.groupingBy(e->e.get("pbtj").toString()));


                    //人员分组数据
                    List<Map<String,Object>> personGroupList = Lists.newArrayList();
                    //查人员分组
                    String currentTime = DateUtil.getCurrentDate();
                    String queryryfz = "select a.mainid,a.empid,a.filters,a.bdate,a.edate,a.sqltj from uf_ryqz_dt1 a,(select pbdxryfz from uf_pbjg where dxlx=1 group by pbdxryfz) b where a.mainid =b.pbdxryfz and a.bdate <= '"+currentTime+"'";
                    List<Map<String,Object>> personGroupData = DbTools.getSqlToList(queryryfz);
                    List<Map<String,Object>> personnelGroups = PersongroupCommonUtil.getPersonnelGroupByPerson(personGroupData,pbdx,null);
                    Map<String,List<Map<String,Object>>> personnelGroupsCollect = personnelGroups.stream().collect(Collectors.groupingBy(e->e.get("mainid").toString()));
                    Set<String> personnelGroupIds  = personnelGroups.stream().map(e->e.get("mainid").toString()).collect(Collectors.toSet());
                    querySqlbyPbdx = sql +conditions + " and pbdxryfz in (";
                    log.debug("递归查询人员-人员分组节点，sql:{},personnelGroupIds:{}",querySqlbyPbdx,personnelGroupIds);
                    if(personnelGroupIds.size() > 0){
                        querySqlbyPbdx = querySqlbyPbdx + String.join(",",personnelGroupIds)+") order by bcrq";
                        log.debug("递归查询人员-人员分组节点，sql:{}",querySqlbyPbdx);
                        personGroupList = DbTools.getSqlToList(querySqlbyPbdx,Dateparam.toArray());
                    }
                    personGroupList = personGroupList.stream().filter(e->{
                        String bcrq = e.get("bcrq").toString();
                        String pbdxryfz = e.get("pbdxryfz").toString();
                        Map<String,Object> personnelGroup = personnelGroupsCollect.get(pbdxryfz).get(personnelGroupsCollect.get(pbdxryfz).size()-1);
                        String edate = Util.null2String(personnelGroup.get("edate"));
                        String bdate = Util.null2String(personnelGroup.get("bdate"));
                        e.put("bdate",bdate);
                        if ((!"".equals(bdate) && DateUtil.getTime(bcrq).compareTo(DateUtil.getTime(bdate)) <0) ||
                                (!"".equals(edate) && DateUtil.getTime(bcrq).compareTo(DateUtil.getTime(edate)) > 0)){
                            return false;
                        }else {
                            return true;
                        }
                    }).collect(Collectors.toList());

                    //Map<String,List<Map<String,Object>>> personGroupCollect = personGroupList.stream().collect(Collectors.groupingBy(e->e.get("pbtj").toString()));


                    //部门数据
                    List<Map<String,Object>> departmentList = Lists.newArrayList();
                    //查询部门数据
                    String queryDepartmentidAndSubcompanyid = "select id,departmentid,subcompanyid1 from hrmresource where id =?";
                    Map<String,Object> dataMap = DbTools.getSqlToMap(queryDepartmentidAndSubcompanyid,pbdx);
                    String pdeptids = "";
                    pdeptids = new DepartmentComInfo().getAllParentDepartId(Util.null2String(dataMap.get("departmentid")), pdeptids);
                    pdeptids = Util.null2String(dataMap.get("departmentid")) + pdeptids;
                    log.debug("pdeptids : [{}]",pdeptids);
                    querySqlbyPbdx = sql + conditions + " and pbdxbm in (";
                    log.debug("递归查询人员-部门节点，sql:{},pdeptids:{}",querySqlbyPbdx,pdeptids);
                    querySqlbyPbdx = querySqlbyPbdx + pdeptids+") order by bcrq";
                    departmentList = DbTools.getSqlToList(querySqlbyPbdx,Dateparam.toArray());
                   // Map<String,List<Map<String,Object>>> departmentCollect = departmentList.stream().collect(Collectors.groupingBy(e->e.get("pbtj").toString()));


                    //分部数据
                    List<Map<String,Object>> subCompanyList = Lists.newArrayList();
                    //查询人员分部
                    querySqlbyPbdx = sql + conditions + " and pbdxfb = ? order by bcrq";
                    log.debug("递归查询人员-分部节点，sql:{},pdeptids:{}",querySqlbyPbdx,dataMap.get("subcompanyid1"));
                    param.clear();
                    param.addAll(Dateparam);
                    param.add(dataMap.get("subcompanyid1"));
                    subCompanyList = DbTools.getSqlToList(querySqlbyPbdx,param.toArray());
                    //Map<String,List<Map<String,Object>>> subCompanyCollect = subCompanyList.stream().collect(Collectors.groupingBy(e->e.get("pbtj").toString()));



                    //排班途径枚举集合
                    dataList.addAll(personGroupList);
                    dataList.addAll(departmentList);
                    dataList.addAll(subCompanyList);

                    if (!CheckBoxEnum.CHECKED.getKey().equals(showAll)){
                        Map<String,List<Map<String,Object>>> dataCollect = dataList.stream().collect(Collectors.groupingBy(e->e.get("pbtj").toString()));
                        for (SchedulingApproachEnum schedulingApproachEnum :SchedulingApproachEnum.values()){
                            List<Map<String,Object>> resulstList = dataCollect.get(schedulingApproachEnum.getKey());
                            if (resulstList == null || resulstList.size() == 0){
                                continue;
                            }
                            Map<String,List<Map<String, Object>>> resulstCollect = resulstList.stream().collect(Collectors.groupingBy(e->Util.null2String(e.get("bcrq"))));
                            for (Map.Entry<String,List<Map<String, Object>>> entry:resulstCollect.entrySet()){
                                String bcrq = entry.getKey();
                                List<Map<String, Object>> scheduleList = entry.getValue();
                                if (scheduleList.size() > 1){
                                    //优先级。人员 》人员分组》部门》分部
                                    List<Map<String, Object>> psersonList = scheduleList.stream().filter(e->!Util.null2String(e.get("pbdxry")).equals("")).collect(Collectors.toList());
                                    if (psersonList.size() == 0){
                                        psersonList = scheduleList.stream().filter(e->!Util.null2String(e.get("pbdxryfz")).equals("")).collect(Collectors.toList());
                                        if (psersonList.size() > 1){
                                            psersonList = psersonList.stream().sorted(Comparator.comparing(e -> DateUtil.getTime(e.get("bdate").toString()).toInstant(ZoneOffset.of("+8")).toEpochMilli())).collect(Collectors.toList());
                                            psersonList = Lists.newArrayList(psersonList.get(psersonList.size()-1));
                                        }
                                    }
                                    if (psersonList.size() == 0){
                                        psersonList = scheduleList.stream().filter(e->!Util.null2String(e.get("pbdxbm")).equals("")).collect(Collectors.toList());
                                    }
                                    if (psersonList.size() == 0){
                                        psersonList = scheduleList.stream().filter(e->!Util.null2String(e.get("pbdxfb")).equals("")).collect(Collectors.toList());
                                    }
                                    if (psersonList.size() > 0){
                                        if (schedulingApproachEnum == SchedulingApproachEnum.RULE){
                                            psersonList = psersonList.stream().sorted(Comparator.comparing(e->Long.valueOf(e.get("pbgl").toString()))).collect(Collectors.toList());
                                        }else {
                                            psersonList = psersonList.stream().sorted(Comparator.comparing(e->Long.valueOf(e.get("keyid").toString()))).collect(Collectors.toList());
                                        }
                                        dataTableList.add(psersonList.get(psersonList.size()-1));
                                    }
                                }else {
                                    dataTableList.add(scheduleList.get(0));
                                }
                            }

                        }
                    }else {
                        dataTableList = dataList;
                    }
//                    if (CheckBoxEnum.CHECKED.getKey().equals(showAll)){
//                        dataTableList.addAll(dataList);
//                        dataTableList.addAll(personGroupList);
//                        dataTableList.addAll(departmentList);
//                        dataTableList.addAll(subCompanyList);
//                    }else {
//                        for (SchedulingApproachEnum schedulingApproachEnum :SchedulingApproachEnum.values()){
//                            List<Map<String,Object>> resulstList = personCollect.get(schedulingApproachEnum.getKey());
//                            if (resulstList == null || resulstList.size() == 0){
//                                resulstList = personGroupCollect.get(schedulingApproachEnum.getKey());
//                                if (resulstList == null || resulstList.size() == 0){
//                                    resulstList = departmentCollect.get(schedulingApproachEnum.getKey());
//                                    if (resulstList == null || resulstList.size() == 0){
//                                        resulstList = subCompanyCollect.get(schedulingApproachEnum.getKey());
//                                    }
//                                }
//                            }
//                            if (resulstList != null && resulstList.size() != 0){
//                                dataTableList.addAll(resulstList);
//                            }
//                        }
//                    }
                }else if ("1".equals(pblx)){
                    List<Object> param = Lists.newArrayList();
                    param.addAll(Dateparam);
                    //人员分组
                    conditions += " and pbdxryfz = ? order by bcrq";
                    sql +=conditions;
                    param.add(pbdx);
                    dataTableList = DbTools.getSqlToList(sql,param.toArray());

                }else if ("2".equals(pblx)){
                    List<Object> param = Lists.newArrayList();
                    param.addAll(Dateparam);
                    //部门
                    //部门递归查、部门、分部
                    String querySqlbyPbdx = sql +conditions + " and pbdxbm = ? order by bcrq";
                    param.add(pbdx);
                    List<Map<String,Object>> departmentList = DbTools.getSqlToList(querySqlbyPbdx,param.toArray());
                    Map<String,List<Map<String,Object>>> departmentCollect = departmentList.stream().collect(Collectors.groupingBy(e->e.get("pbtj").toString()));
                    String querySubCompanySql = "select subcompanyid1 from hrmdepartment where id=?";
                    Map<String,Object> departMentMap = DbTools.getSqlToMap(querySubCompanySql,pbdx);

                    //分部分部数据
                    querySqlbyPbdx = sql +conditions + " and pbdxfb = ? order by bcrq";
                    log.debug("递归查询部门-分部节点，sql:{},pdeptids:{}",querySqlbyPbdx,departMentMap.get("subcompanyid1"));
                    param.clear();
                    param.addAll(Dateparam);
                    param.add(departMentMap.get("subcompanyid1"));
                    List<Map<String,Object>> subcompanyList = DbTools.getSqlToList(querySqlbyPbdx,param.toArray());
                    Map<String,List<Map<String,Object>>> subcompanyCollect = subcompanyList.stream().collect(Collectors.groupingBy(e->e.get("pbtj").toString()));


                    //排班枚举集合
                    if (CheckBoxEnum.CHECKED.getKey().equals(showAll)){
                        dataTableList.addAll(departmentList);
                        dataTableList.addAll(subcompanyList);
                    }else {
                        for (SchedulingApproachEnum schedulingApproachEnum :SchedulingApproachEnum.values()){
                            List<Map<String,Object>> resulstList = departmentCollect.get(schedulingApproachEnum.getKey());
                            if (resulstList == null || resulstList.size() == 0){
                                resulstList = subcompanyCollect.get(schedulingApproachEnum.getKey());
                            }
                            if (resulstList != null && resulstList.size() != 0){
                                dataTableList.addAll(resulstList);
                            }
                        }
                    }

                }else if ("3".equals(pblx)){
                    List<Object> param = Lists.newArrayList();
                    param.addAll(Dateparam);
                    //分部
                    conditions += " and pbdxfb = ? order by bcrq";
                    sql +=conditions;
                    param.add(pbdx);
                    dataTableList = DbTools.getSqlToList(sql,param.toArray());
                }

            }
        }catch (Exception e){
            log.error("catch error : {}",e);
        }
        resultMap.put("dataTableList",dataTableList);
        log.debug("dataTableList total size : {}",dataTableList.size());

        return resultMap;
    }


    /**
     * 递归查询人员
     * @return
     */
    public List<Map<String,Object>> getDataListPerson(String sql,String conditions,List<Object> Dateparam,String pbdx) throws Exception {

        List<Map<String,Object>> dataList = Lists.newArrayList();
        //查人员分组
        String currentTime = DateUtil.getCurrentDate();
        String queryryfz = "select a.mainid,a.empid,a.filters,a.bdate,a.edate,a.sqltj from uf_ryqz_dt1 a,(select pbdxryfz from uf_pbjg where dxlx=1 group by pbdxryfz) b where a.mainid =b.pbdxryfz and a.bdate <= '"+currentTime+"'";
        List<Map<String,Object>> personGroupData = DbTools.getSqlToList(queryryfz);
        Set<String> personnelGroupIds = PersongroupCommonUtil.getPersonnelGroupingByPerson(personGroupData,pbdx,null);
        String querySqlbyPbdx = sql +conditions + " and pbdxryfz in (";
        log.debug("递归查询人员-人员分组节点，sql:{},personnelGroupIds:{}",querySqlbyPbdx,personnelGroupIds);
        if(personnelGroupIds.size() > 0){
            querySqlbyPbdx = querySqlbyPbdx + String.join(",",personnelGroupIds)+") order by bcrq";
            log.debug("递归查询人员-人员分组节点，sql:{}",querySqlbyPbdx);
            dataList = DbTools.getSqlToList(querySqlbyPbdx,Dateparam.toArray());
        }
        if (dataList.size() == 0){
            //查询人员部门
            String queryDepartmentidAndSubcompanyid = "select id,departmentid,subcompanyid1 from hrmresource where id =?";
            Map<String,Object> dataMap = DbTools.getSqlToMap(queryDepartmentidAndSubcompanyid,pbdx);
            String pdeptids = "";
            pdeptids = new DepartmentComInfo().getAllParentDepartId(Util.null2String(dataMap.get("departmentid")), pdeptids);
            pdeptids = Util.null2String(dataMap.get("departmentid")) + pdeptids;
            log.debug("pdeptids : [{}]",pdeptids);
            querySqlbyPbdx = sql + conditions + " and pbdxbm in (";
            log.debug("递归查询人员-部门节点，sql:{},pdeptids:{}",querySqlbyPbdx,pdeptids);
            querySqlbyPbdx = querySqlbyPbdx + pdeptids+") order by bcrq";
            dataList = DbTools.getSqlToList(querySqlbyPbdx,Dateparam.toArray());
            if (dataList.size() == 0){
                //查询人员分部
                querySqlbyPbdx = sql + conditions + " and pbdxfb = ? order by bcrq";
                log.debug("递归查询人员-分部节点，sql:{},pdeptids:{}",querySqlbyPbdx,dataMap.get("subcompanyid1"));
                List<Object> param = Lists.newArrayList();
                param.clear();
                param.addAll(Dateparam);
                param.add(dataMap.get("subcompanyid1"));
                dataList = DbTools.getSqlToList(querySqlbyPbdx,param.toArray());
            }
        }
        return dataList;
    }

}
