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

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

import com.engine.common.util.DateUtil;
import com.engine.common.util.DbTools;
import com.engine.core.interceptor.CommandContext;
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.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 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.info("递归查询人员-人员节点，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 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,null);
                    querySqlbyPbdx = sql +conditions + " and pbdxryfz in (";
                    log.info("递归查询人员-人员分组节点，sql:{},personnelGroupIds:{}",querySqlbyPbdx,personnelGroupIds);
                    if(personnelGroupIds.size() > 0){
                        querySqlbyPbdx = querySqlbyPbdx + String.join(",",personnelGroupIds)+") order by bcrq";
                        log.info("递归查询人员-人员分组节点，sql:{}",querySqlbyPbdx);
                        personGroupList = DbTools.getSqlToList(querySqlbyPbdx,Dateparam.toArray());
                    }
                    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.info("pdeptids : [{}]",pdeptids);
                    querySqlbyPbdx = sql + conditions + " and pbdxbm in (";
                    log.info("递归查询人员-部门节点，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.info("递归查询人员-分部节点，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()));



                    //排班途径枚举集合
                    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.info("递归查询部门-分部节点，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()));


                    //排班枚举集合
                    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.info("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 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,null);
        String querySqlbyPbdx = sql +conditions + " and pbdxryfz in (";
        log.info("递归查询人员-人员分组节点，sql:{},personnelGroupIds:{}",querySqlbyPbdx,personnelGroupIds);
        if(personnelGroupIds.size() > 0){
            querySqlbyPbdx = querySqlbyPbdx + String.join(",",personnelGroupIds)+") order by bcrq";
            log.info("递归查询人员-人员分组节点，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.info("pdeptids : [{}]",pdeptids);
            querySqlbyPbdx = sql + conditions + " and pbdxbm in (";
            log.info("递归查询人员-部门节点，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.info("递归查询人员-分部节点，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;
    }

}
