package com.engine.common.cmd;

import com.engine.attendance.enums.ApplicableOrganizationEnum;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.common.util.DbTools;
import com.engine.core.interceptor.CommandContext;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import weaver.general.Util;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 获得modeid下所有适用组织人
 */
@Slf4j
public class GetPersonDateBySuitOrganzation extends AbstractCommonCommand<Map<String,Object>> {
    @Override
    public BizLogContext getLogContext() {
        return null;
    }


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

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        String modeId = Util.null2String(params.get("modeId"));
        String sql = "select dxlx,aqjb,dataid,dx from uf_jcl_syzz where modeid=?";
        //假期额度适用组织所有值集合
        List<Map<String,Object>> organzationList = DbTools.getSqlToList(sql,modeId);
        sql = "select a.id dataid,b.id detailid,a.*,b.* from uf_jcl_kq_jqed a left join uf_jcl_kq_jqed_dt1 b on a.id=b.mainid where (gzzt is null or  gzzt <> '1')";
        //所有假期额度生成规则值
        List<Map<String,Object>> vacationList = DbTools.getSqlToList(sql);
        //人力资源id，（假别，规则id）
        Map<String,Object> personMap = Maps.newHashMap();
        //人员分组id，（假别，规则id）
        Map<String,Object> personOrganzationMap = Maps.newHashMap();
        //部门id，（假别，规则id）
        Map<String,Object> departMentMap = Maps.newHashMap();
        //分部id，（假别，规则id）
        Map<String,Object> subCompanyMap = Maps.newHashMap();


        //规则id-对象id，安全级别
        Map<String,String> organzationByMap = Maps.newHashMap();
        for (Map<String,Object> map : organzationList){
            String dataid = Util.null2String(map.get("dataid"));
            String aqjb = Util.null2String(map.get("aqjb"));
            String dx = Util.null2String(map.get("dx")).split("-")[0];
            String key = dataid+"-"+dx;
            String oldvalue = organzationByMap.get(key);
            if (oldvalue == null){
                organzationByMap.put(key,aqjb);
            }else {
                oldvalue = oldvalue+","+aqjb;
                organzationByMap.put(key,oldvalue);
            }

        }


        //以假期额度生成规则id分割的假期额度生成规则值集合
        Map<String,String> vacationMap = Maps.newHashMap();
        for (Map<String,Object> vocation:vacationList){
            vacationMap.put(vocation.get("dataid").toString(),vocation.get("jb").toString());
        }


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


        Set<String> personOrganzationIds = Sets.newHashSet();
        Set<String> departMentIds = Sets.newHashSet();
        Set<String> subCompanyIds = Sets.newHashSet();
        for (Map<String,Object> organzation:organzationList){
            String dx = Util.null2String(organzation.get("dx")).split("-")[0];
            String dataid = Util.null2String(organzation.get("dataid"));
            String jb = vacationMap.get(dataid);
            if (ApplicableOrganizationEnum.PERSONNEL.getKey().equals(organzation.get("dxlx"))){
                Map<String,String> psersonSet = (Map<String,String>)personMap.get(dx);
                if (psersonSet == null){
                    psersonSet = Maps.newHashMap();
                    personMap.put(dx,psersonSet);
                }
                psersonSet.put(jb,dataid);
            }else if (ApplicableOrganizationEnum.PERSONNEL_GROUP.getKey().equals(organzation.get("dxlx"))){
                personOrganzationIds.add(dx);

                Map<String,String> personOrganzationSet = (Map<String,String>)personOrganzationMap.get(dx);
                if (personOrganzationSet == null){
                    personOrganzationSet = Maps.newHashMap();
                    personOrganzationMap.put(dx,personOrganzationSet);
                }
                personOrganzationSet.put(jb,dataid);
            }else if (ApplicableOrganizationEnum.DEPARTMENT.getKey().equals(organzation.get("dxlx"))){
                departMentIds.add(dx);

                Map<String,String> departMentSet = (Map<String,String>)departMentMap.get(dx);
                if (departMentSet == null){
                    departMentSet = Maps.newHashMap();
                    departMentMap.put(dx,departMentSet);
                }
                departMentSet.put(jb,dataid);
            }else if (ApplicableOrganizationEnum.SUBCOMPANY.getKey().equals(organzation.get("dxlx"))){
                subCompanyIds.add(dx);

                Map<String,String> subCompanySet = (Map<String,String>)subCompanyMap.get(dx);
                if (subCompanySet == null){
                    subCompanySet = Maps.newHashMap();
                    subCompanyMap.put(dx,subCompanySet);
                }
                subCompanySet.put(jb,dataid);
            }
        }
        sql = "select id,departmentid,subcompanyid1,seclevel from hrmresource where 1=1";
        if (departMentIds.size() > 0){
            sql = sql+ " and departmentid in ("+String.join(",",departMentIds)+")";
        }
        if (subCompanyIds .size() >0 && departMentIds.size() > 0){
            sql = sql+ " or subcompanyid1 in ("+String.join(",",subCompanyIds)+")";
        }else if (subCompanyIds .size() >0 && departMentIds.size() == 0){
            sql = sql+ " and subcompanyid1 in ("+String.join(",",subCompanyIds)+")";
        }


        List<Map<String,Object>> hrmListByDepartAndSubCompanyIds = DbTools.getSqlToList(sql);
        //部门id-人员id集合
        Map<String,List<Map<String,Object>>> hrmListGroupByDepart = hrmListByDepartAndSubCompanyIds.stream().collect(Collectors.groupingBy(e->Util.null2String(e.get("departmentid"))));
        log.info("hrmListGroupByDepart : [{}]",hrmListGroupByDepart);
        //分部id-人员id集合
        Map<String,List<Map<String,Object>>> hrmListGroupBySubCompany = hrmListByDepartAndSubCompanyIds.stream().collect(Collectors.groupingBy(e->Util.null2String(e.get("subcompanyid1"))));
        log.info("hrmListGroupBySubCompany : [{}]",hrmListGroupBySubCompany);
        //人员分组id-人员id集合
        if (personOrganzationIds.size() >0){
            //人员分组id-（假别，假期规则id）
            Map<String,Set<String>> personGroupUserIds = getPersonGroupUserIds(personOrganzationIds);
            log.info("personGroupUserIds : [{}]",personGroupUserIds);
            log.info("personOrganzationMap : [{}]",personOrganzationMap);
            for (Map.Entry<String,Object> entry : personOrganzationMap.entrySet()){
                String personGroupId = entry.getKey();
                //人员分组（假别，假期规则id）
                Map<String,String> personGroupHolidayMap = (Map<String,String>)entry.getValue();
                Set<String> userIds = personGroupUserIds.get(personGroupId);
                for (String userId :userIds){
                    //人力资源原本已有的假期，（假别，规则id）
                    Map<String,String> psersonSet = personMap.get(userId) == null?null:(Map<String,String>)personMap.get(userId);
                    if (psersonSet == null) {
                        personMap.put(userId,personGroupHolidayMap);
                    }else {
                        for (Map.Entry<String,String> personGroupHolidayEntry :personGroupHolidayMap.entrySet()){
                            if (psersonSet.get(personGroupHolidayEntry.getKey()) == null){
                                psersonSet.put(personGroupHolidayEntry.getKey(),personGroupHolidayEntry.getValue());
                            }
                        }
                        personMap.put(userId,psersonSet);
                    }
                }
            }
        }

        log.info("before personMap : [{}]",personMap);
        //部门id
        log.info("departMentMap : [{}]",departMentMap);
        for (Map.Entry<String,Object> entry : departMentMap.entrySet()){
            String departMentId = entry.getKey();
            //部门（假别，假期规则id）
            Map<String,String> departMentHolidayMap = (Map<String,String>)entry.getValue();
            List<Map<String,Object>> userIds = hrmListGroupByDepart.get(departMentId);
            for (Map<String,Object> userIdMap :userIds){
                //人力资源原本已有的假期，（假别，规则id）
                String userId = Util.null2String(userIdMap.get("id"));
                Map<String,String> psersonSet = personMap.get(userId) == null?null:(Map<String,String>)personMap.get(userId);
                if (psersonSet == null) {
                    personMap.put(userId,departMentHolidayMap);
                }else {
                    for (Map.Entry<String,String> personGroupHolidayEntry :departMentHolidayMap.entrySet()){
                        if (psersonSet.get(personGroupHolidayEntry.getKey()) == null){
                            psersonSet.put(personGroupHolidayEntry.getKey(),personGroupHolidayEntry.getValue());
                        }
                    }
                    personMap.put(userId,psersonSet);
                }
            }
        }
        //分部id
        log.info("subCompanyMap : [{}]",subCompanyMap);
        for (Map.Entry<String,Object> entry : subCompanyMap.entrySet()){
            String subCompanyId = entry.getKey();
            //分部（假别，假期规则id）
            Map<String,String> subCompanyHolidayMap = (Map<String,String>)entry.getValue();
            List<Map<String,Object>> userIds = hrmListGroupBySubCompany.get(subCompanyId);
            for (Map<String,Object> userIdMap :userIds){
                //人力资源原本已有的假期，（假别，规则id）
                String userId = Util.null2String(userIdMap.get("id"));
                Map<String,String> psersonSet = personMap.get(userId) == null?null:(Map<String,String>)personMap.get(userId);
                if (psersonSet == null) {
                    personMap.put(userId,subCompanyHolidayMap);
                }else {
                    for (Map.Entry<String,String> personGroupHolidayEntry :subCompanyHolidayMap.entrySet()){
                        if (psersonSet.get(personGroupHolidayEntry.getKey()) == null){
                            psersonSet.put(personGroupHolidayEntry.getKey(),personGroupHolidayEntry.getValue());
                        }
                    }
                    personMap.put(userId,psersonSet);
                }
            }
        }
        log.info("personMap : [{}]",personMap);
        Map<String,Object> newpersonMap = Maps.newHashMap();
        for (Map.Entry<String,Object> entry :personMap.entrySet()){
            String userId = entry.getKey();
            Map<String, String> vocationMap = (Map<String, String>)entry.getValue();
            Map<String,Object> dataMap = Maps.newHashMap();
            for (Map.Entry<String,String> vocationEntry :vocationMap.entrySet()){
                String jb = vocationEntry.getKey();
                String dataId = vocationEntry.getValue();
                if (jb != null && !"".equals(jb) && vacationGroupByDataIdMap.get(dataId) !=null){
                    dataMap.put(jb,vacationGroupByDataIdMap.get(dataId));
                }
            }
            newpersonMap.put(userId,dataMap);
        }
        return newpersonMap;
    }

    /**
     * 获得人员分组下面的人员集合
     * @param personOrganzationIds
     * @return人员分组id-人员id集合
     */
    public Map<String,Set<String>> getPersonGroupUserIds(Set<String> personOrganzationIds){
        String sql = "select b.mainid,b.empid,b.filters,b.bdate,b.edate,a.list_type from uf_ryqz a left join uf_ryqz_dt1 b on a.id=b.mainid where  mainid in ("+String.join(",",personOrganzationIds)+")";

        List<Map<String,Object>> personGroupDataList = DbTools.getSqlToList(sql);

        Map<String,Set<String>> personGroupUserIds = Maps.newHashMap();
        for (Map<String,Object> personGroupData :personGroupDataList){
            String id = Util.null2String(personGroupData.get("mainid"));
            String empid = Util.null2String(personGroupData.get("empid"));
            String filters = Util.null2String(personGroupData.get("filters"));
            String list_type = Util.null2String(personGroupData.get("list_type"));

            Set<String> userIds = personGroupUserIds.get(id);
            if (userIds == null){
                userIds = Sets.newHashSet();
                personGroupUserIds.put(id,userIds);
            }

            if ("0".equals(list_type) && !"".equals(empid)){
                //人员清单
                userIds.add(empid);

            }else if ("1".equals(list_type) && !"".equals(filters)){
                //条件清单
                sql = "select id,seclevel from hrmresource where 1=1 ";
                if (filters.contains("field")){
                    sql = "select a.id,a.seclevel from hrmresource a left join cus_fielddata b on a.id=b.id where scope='HrmCustomFieldByInfoType' and scopeid=-1 and "+filters;
                }else {
                    filters = filters.replace("ａｎｄ","and");
                    filters = filters.replace("ｏｒ","or");
                    sql = sql+ " and "+filters;
                }
                log.info("getPersonnelGroupingByPerson filter sql : {}",sql);
                List<Map<String,Object>> dataList = DbTools.getSqlToList(sql);
                for (Map<String,Object> dataMap :dataList){
                    String hrmId = Util.null2String(dataMap.get("id"));
                    String seclevel = Util.null2String(dataMap.get("seclevel"));
                    userIds.add(hrmId);
                }
            }
        }

        return personGroupUserIds;
    }
}
