package com.engine.jucailinkq.common.cmd;

import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.jucailinkq.attendance.component.persongroup.commonutil.PersongroupCommonUtil;
import com.engine.jucailinkq.attendance.enums.ApplicableOrganizationEnum;
import com.engine.jucailinkq.common.util.DateUtil;
import com.engine.jucailinkq.common.util.DbTools;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import weaver.general.Util;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 获得modeid下所有的适用组织的人
 */
public class GetPersonBySuitOrganzationCmd extends AbstractCommonCommand<Map<String,Object>> {

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

    @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=? order by id desc";
        //适用组织所有值集合
        List<Map<String,Object>> organzationList = DbTools.getSqlToList(sql,modeId);

        //人力资源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();


        for (Map<String,Object> organzation:organzationList){
            String dx = Util.null2String(organzation.get("dx")).split("-")[0];
            String dataid = Util.null2String(organzation.get("dataid"));
            String aqjb = Util.null2String(organzation.get("aqjb"));
            String dxlx = Util.null2String(organzation.get("dxlx"));
            if ("".equals(dx)){
                continue;
            }
            if (ApplicableOrganizationEnum.PERSONNEL.getKey().equals(dxlx)){
                personMap.put(dx,dataid);
            }else if (ApplicableOrganizationEnum.PERSONNEL_GROUP.getKey().equals(dxlx)){
                personOrganzationMap.put(dx,dataid);
            }else if (ApplicableOrganizationEnum.DEPARTMENT.getKey().equals(dxlx)){
                departMentMap.put(dx+"&"+aqjb,dataid);
            }else if (ApplicableOrganizationEnum.SUBCOMPANY.getKey().equals(dxlx)){
                subCompanyMap.put(dx+"&"+aqjb,dataid);
            }
        }
        if (personOrganzationMap.size() > 0){
            sql = "select a.list_type,b.mainid,b.empid,b.filters,b.bdate,b.edate,b.sqltj from uf_ryqz a left join uf_ryqz_dt1 b on a.id=b.mainid  where a.id=?";
            for (Map.Entry<String,Object> entrySet: personOrganzationMap.entrySet()){
                List<Map<String,Object>> personnelGrouping = DbTools.getSqlToList(sql,entrySet.getKey());
                Set<String> userIds = PersongroupCommonUtil.getUserIdsByPersonnelGrouping(personnelGrouping, DateUtil.getCurrentDate());
                for (String userId:userIds){
                    if (personMap.get(userId) == null){
                        personMap.put(userId,entrySet.getValue());
                    }
                }
            }
        }
        if (departMentMap.size() > 0){
            Set<String> departMentIds = Sets.newHashSet();
            for (Map.Entry<String,Object> entrySet: departMentMap.entrySet()){
                departMentIds.add(entrySet.getKey().split("&")[0]);
            }
            sql = "select id,seclevel,departmentid from hrmresource where departmentid in ("+String.join(",",departMentIds)+")";
            List<Map<String,Object>> dataList = DbTools.getSqlToList(sql);
            Map<String,List<Map<String,Object>>> dataCollect = dataList.stream().collect(Collectors.groupingBy(e->e.get("departmentid").toString()));
            for (Map.Entry<String,Object> entrySet: departMentMap.entrySet()){
                String departmentid = entrySet.getKey().split("&")[0];
                String aqjb = entrySet.getKey().split("&")[1];
                List<Map<String,Object>> userIdsQuerybyDepartment = dataCollect.get(departmentid);
                if (userIdsQuerybyDepartment == null){
                    continue;
                }
                userIdsQuerybyDepartment = userIdsQuerybyDepartment.stream().filter(e->"-1".equals(e.get("seclevel")) || "".equals(aqjb) || "-".equals(aqjb) || (Integer.valueOf(aqjb.split("-")[0]) <= Integer.valueOf(e.get("seclevel").toString()) &&
                        Integer.valueOf(aqjb.split("-")[1]) >= Integer.valueOf(e.get("seclevel").toString()))).collect(Collectors.toList());
                for (Map<String,Object> userMap :userIdsQuerybyDepartment){
                    if (personMap.get(userMap.get("id").toString()) == null){
                        personMap.put(userMap.get("id").toString(),entrySet.getValue());
                    }
                }
            }
        }
        if (subCompanyMap.size() > 0){
            Set<String> subCompanyIds = Sets.newHashSet();
            for (Map.Entry<String,Object> entrySet: subCompanyMap.entrySet()){
                subCompanyIds.add(entrySet.getKey().split("&")[0]);
            }
            sql = "select id,seclevel,subcompanyid1 from hrmresource where subcompanyid1 in ("+String.join(",",subCompanyIds)+")";
            List<Map<String,Object>> dataList = DbTools.getSqlToList(sql);
            Map<String,List<Map<String,Object>>> dataCollect = dataList.stream().collect(Collectors.groupingBy(e->e.get("subcompanyid1").toString()));
            for (Map.Entry<String,Object> entrySet: subCompanyMap.entrySet()){
                String subcompanyid1 = entrySet.getKey().split("&")[0];
                String aqjb = entrySet.getKey().split("&")[1];
                List<Map<String,Object>> userIdsQuerybySubcompany = dataCollect.get(subcompanyid1);
                if (userIdsQuerybySubcompany == null){
                    continue;
                }
                userIdsQuerybySubcompany = userIdsQuerybySubcompany.stream().filter(e->"-1".equals(e.get("seclevel")) || "".equals(aqjb) || "-".equals(aqjb) || (Integer.valueOf(aqjb.split("-")[0]) <= Integer.valueOf(e.get("seclevel").toString()) &&
                        Integer.valueOf(aqjb.split("-")[1]) >= Integer.valueOf(e.get("seclevel").toString()))).collect(Collectors.toList());
                for (Map<String,Object> userMap :userIdsQuerybySubcompany){
                    if (personMap.get(userMap.get("id").toString()) == null){
                        personMap.put(userMap.get("id").toString(),entrySet.getValue());
                    }
                }
            }
        }

        return personMap;
    }
}
