package com.sys.bus.jx.service;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Enhancer;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.sys.bus.hr.model.Person;
import com.sys.bus.hr.service.HrService;
import com.sys.bus.jx.vo.DeptDto;
import com.sys.bus.jx.vo.DeptManagerDto;
import com.sys.bus.model.Org;
import com.sys.bus.model.PersonManager;
import com.sys.bus.model.SysCode;
import com.sys.bus.sys.model.DtBean;
import com.sys.bus.syscode.service.SysCodeService;
import com.sys.core.model.PageBean;
import com.sys.core.utils.SessionUtil;
import com.sys.core.utils.ShrOsf;
import com.sys.core.utils.Tool;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class PersonManagerService {
    Log log = LogFactory.getLog(this.getClass());
    static HrService hrService = Enhancer.enhance(HrService.class);
    static SysCodeService codeService = Enhancer.enhance(SysCodeService.class);
    static OrgService orgService = Enhancer.enhance(OrgService.class);
    static boolean syncFlag = false;//防重复调用

    /**
     * @param pageNumber
     * @param pageSize
     * @param personName
     * @param managerName
     * @return
     */
    public PageBean getPersonManagerQueryList(Integer pageNumber, Integer pageSize, String personName,String managerName,String hrSame) {

        String sqlCount  =
                "select  count(1)  from ct_jx_personmanager dm  " +
                        " left join t_bd_person p on dm.personmanager_id = p.fid "
                        +" LEFT JOIN T_ORG_PositionMember pp ON p.fid = pp.FPERSONID and pp.FISPRIMARY=1 "
                        +" LEFT JOIN T_ORG_Position po ON po.fid = pp.FPOSITIONID "
                        +" LEFT JOIN t_org_admin org ON org.FID = po.FADMINORGUNITID "
                       +  " where personmanager_status='1'  " ;


        String sqlPara  =
                " select  dm.*,p.fname_l2||'_'||p.fnumber personmanager_personname,sp.fname_l2 superName,org.fname_l2 personmanager_deptname ,org.fdisplayname_l2 personmanager_deptlongname   from ct_jx_personmanager dm " +
                        " left join t_bd_person p on dm.personmanager_id = p.fid "
                        +" left join t_bd_person sp on sp.fid = p.cfleaderid"
                        +" LEFT JOIN T_ORG_PositionMember pp ON p.fid = pp.FPERSONID and pp.FISPRIMARY=1 "
                        +" LEFT JOIN T_ORG_Position po ON po.fid = pp.FPOSITIONID "
                        +" LEFT JOIN t_org_admin org ON org.FID = po.FADMINORGUNITID "
                        +"  where personmanager_status='1'   " ;

        String whereBy = "";
        if(!StringUtils.isBlank(personName)){
            whereBy += " and  (p.fname_l2 like '%"+personName+"%'  or  p.fnumber like '%"+personName+"%' )";
        }
        if(!StringUtils.isBlank(managerName)){
            whereBy += " and  (dm.personmanager_pname1 like '%"+managerName+"%'  or dm.personmanager_pname2 like '%"+managerName+"%'  or dm.personmanager_pname3 like '%"+managerName+"%' "
            +" or dm.personmanager_hrpname1 like '%"+managerName+"%'  or dm.personmanager_hrpname2 like '%"+managerName+"%'  or dm.personmanager_hrpname3 like '%"+managerName+"%' )"  ;
        }
        if(!StringUtils.isBlank(hrSame)){
            whereBy += " and personmanager_hrsame='"+hrSame+"' "  ;
        }

        if(SessionUtil.isAdmin()){//绩效管理员
        }else{//绩效专员
            Person person = SessionUtil.getCurrentPerson();
            List<Org> orgList = orgService.getOrgList(person.getId());
            if(orgList.size() > 0){
                String subWhere = " and (";
                for(int i=0;i<orgList.size();i++){
                    Org org = orgList.get(i);
                    if(i>0)subWhere += " or ";
                    subWhere += " org.fdisplayname_l2 like '" +org.get("fdisplayname_l2") +"%' ";
                }
                subWhere += " )";
                whereBy += subWhere;
            }else{
                //没有任何组织授权的绩效专员  看不到任何数据
                whereBy += " and org.fdisplayname_l2='111' ";
            }

        }

        sqlCount += whereBy;
        sqlPara += whereBy;

        sqlPara += "order by personmanager_lock desc, org.fdisplayname_l2";//
        PageBean pageBean = new PageBean();
        Page<PersonManager> page = new PersonManager().dao().paginateByFullSql(pageNumber, pageSize, sqlCount, sqlPara);
        pageBean.setCount(page.getTotalRow());
        List<PersonManager> list = page.getList();
        setLongDept(list);

        Map<String, PersonManager> shrPersonManagerMap = this.getShrPersonManagerMap();
        for(PersonManager personManager : list){
            String pid = personManager.getPersonManagerId();
            PersonManager shrPersonManager = shrPersonManagerMap.get(pid);
            if(shrPersonManager == null){
                personManager.setPersonManagerHrpname1("");
                personManager.setPersonManagerHrpname2("");
                personManager.setPersonManagerHrpname3("");
                personManager.setPersonManagerHrpid1("");
                personManager.setPersonManagerHrpid2("");
                personManager.setPersonManagerHrpid3("");
                personManager.setPersonManagerHrSuperName("");
            }else{
                personManager.setPersonManagerHrpname1(shrPersonManager.getPersonManagerHrpname1());
                personManager.setPersonManagerHrpname2(shrPersonManager.getPersonManagerHrpname2());
                personManager.setPersonManagerHrpname3(shrPersonManager.getPersonManagerHrpname3());
                personManager.setPersonManagerHrpid1(shrPersonManager.getPersonManagerHrpid1());
                personManager.setPersonManagerHrpid2(shrPersonManager.getPersonManagerHrpid2());
                personManager.setPersonManagerHrpid3(shrPersonManager.getPersonManagerHrpid3());
                personManager.setPersonManagerHrSuperName(shrPersonManager.getPersonManagerHrSuperName());
            }
            personManager.setPersonManagerHrsame(this.isSameManager(personManager)?"1":"2");
        }

        pageBean.setData(list);

        return pageBean;
    }
    private void setLongDept(List<PersonManager> list){
        if(list == null || list.size()==0)return;
        String startName= "刀锋集团_刀锋互娱_";
        int startLen = startName.length();
        for(PersonManager dm : list){
            String deptname = dm.getStr("personmanager_deptlongname");
            if(deptname == null || !deptname.startsWith(startName)){
                continue;
            }
            deptname = deptname.substring(startLen);
            for (int i = 0; i <10 ; i++) {
                int len = deptname.length();
                if(deptname.replace("_","").length()>= len-2){
                    dm.put("personmanager_deptname",deptname);
                    break;
                }
                deptname = deptname.substring(deptname.indexOf("_")+1);
            }
        }
    }
    @Before(Tx.class)
    /**
     * 修改保存上级数据  返回same
     */
    public String updatePersonManager(String personId,String type, String managerId,String managerName) {
        PersonManager personManager = PersonManager.dao.findById(personId);
        return this.updatePersonManager(personManager,type, managerId, managerName);
    }
    /**
     * 删除上级数据  返回same
     */
    public String deletePersonManager(String personId,String type) {
        PersonManager personManager = PersonManager.dao.findById(personId);
        return this.deletePersonManager(personManager,type);
    }

    public String deletePersonManager(PersonManager personManager,String type){

        if("1".equals(type)){
            personManager.setPersonManagerPid1(null);
            personManager.setPersonManagerPname1(null);
        }
        if("2".equals(type)){
            personManager.setPersonManagerPid2(null);
            personManager.setPersonManagerPname2(null);
        }
        if("3".equals(type)){
            personManager.setPersonManagerPid3(null);
            personManager.setPersonManagerPname3(null);
        }
        boolean sameManager = isSameManager(personManager);
        personManager.setPersonManagerHrsame(sameManager?"1":"2");
        personManager.setPersonManagerUpdatetime(Tool.getCurrTime());
        personManager.setPersonManagerUpdate("2");
        personManager.update();
        return personManager.getPersonManagerHrsame();
    }

    /**
     *  修改保存上级数据  返回same
     */
    @Before(Tx.class)
    public String updatePersonManager(PersonManager personManager,String type, String managerId,String managerName){

        if("1".equals(type)){
            personManager.setPersonManagerPid1(managerId);
            personManager.setPersonManagerPname1(managerName);
        }
        if("2".equals(type)){
            personManager.setPersonManagerPid2(managerId);
            personManager.setPersonManagerPname2(managerName);
        }
        if("3".equals(type)){
            personManager.setPersonManagerPid3(managerId);
            personManager.setPersonManagerPname3(managerName);
        }
        boolean sameManager = isSameManager(personManager);
        personManager.setPersonManagerHrsame(sameManager?"1":"2");
        personManager.setPersonManagerUpdatetime(Tool.getCurrTime());
        personManager.setPersonManagerUpdate("2");
        boolean suc = personManager.update();
        if(!suc){
            throw new RuntimeException("修改异常！");
        }
        return personManager.getPersonManagerHrsame();
    }
    public boolean  isSameManager(PersonManager personManager){
        String managerId1 = personManager.getPersonManagerPid1();
        String managerId2 = personManager.getPersonManagerPid2();
        String managerId3 = personManager.getPersonManagerPid3();

        String hrManagerId1 = personManager.getPersonManagerHrpid1();
        String hrManagerId2 = personManager.getPersonManagerHrpid2();
        String hrManagerId3 = personManager.getPersonManagerHrpid3();

        if(!isSame(managerId1,hrManagerId1)){
            return false;
        }
        if(!isSame(managerId2,hrManagerId2)){
            return false;
        }
        if(!isSame(managerId3,hrManagerId3)){
            return false;
        }
        return true;
    }

    private boolean isSame(String str1,String str2){
        if(str1 == null && str2 == null){
            return true;
        }
        if((str1 == null )!= (str2 == null)){
            return false;
        }
        return str1.equals(str2);
    }
    @Before(Tx.class)
    public void syncPersonManager(boolean syncAll){
        if(syncFlag){
            log.error("正在同步中。。请稍后再试！");
            return;
        }
        syncFlag = true;
        try{
            List<PersonManager> personManagers = new PersonManager().dao().find(" select * from ct_jx_personmanager ");
            Map<String, PersonManager> personManagerMap = personManagers.stream().collect(Collectors.toMap(PersonManager::getPersonManagerId, personManager -> personManager));
            String currTime = Tool.getCurrTime();
            Map<String, PersonManager> shrPersonManagerMap = this.getShrPersonManagerMap();
            for(String personId : shrPersonManagerMap.keySet()){
                PersonManager shrPersonManager = shrPersonManagerMap.get(personId);
                if(!personManagerMap.containsKey(personId)){//新人员信息
                    shrPersonManager.setPersonManagerStatus("1");
                    shrPersonManager.setPersonManagerCreatetime(currTime);
                    shrPersonManager.save();
                    continue;
                }

                //已有配置信息
                PersonManager personManager = personManagerMap.get(personId);
                String status = personManager.getPersonManagerStatus();
                String hrSame = personManager.getPersonManagerHrsame();
                String update = personManager.getPersonManagerUpdate();

                String oldCreatetime = personManager.getPersonManagerCreatetime();


                boolean lock =false;
                if("2".equals(personManager.getPersonManagerLock())){
                    lock =true;
                }
                if(syncAll && !lock){//全量同步
                    shrPersonManager.setPersonManagerStatus("1");
                    shrPersonManager.setPersonManagerUpdatetime(currTime);
                    shrPersonManager.setPersonManagerCreatetime(oldCreatetime);
                    shrPersonManager.update();
                    continue;
                }
                if(syncAll && lock){//全量同步
                    personManager.setPersonManagerHrpid1(shrPersonManager.getPersonManagerHrpid1());
                    personManager.setPersonManagerHrpid2(shrPersonManager.getPersonManagerHrpid2());
                    personManager.setPersonManagerHrpid3(shrPersonManager.getPersonManagerHrpid3());
                    personManager.setPersonManagerHrpname1(shrPersonManager.getPersonManagerHrpname1());
                    personManager.setPersonManagerHrpname2(shrPersonManager.getPersonManagerHrpname2());
                    personManager.setPersonManagerHrpname3(shrPersonManager.getPersonManagerHrpname3());
                    personManager.setPersonManagerHrSuperId(shrPersonManager.getPersonManagerHrSuperId());
                    personManager.setPersonManagerHrSuperName(shrPersonManager.getPersonManagerHrSuperName());

                    boolean sameManager = isSameManager(personManager);
                    personManager.setPersonManagerHrsame(sameManager?"1":"2");
                    personManager.setPersonManagerUpdatetime(currTime);
                    //personManager.setPersonManagerUpdate("1");
                    personManager.setPersonManagerStatus("1");
                    personManager.update();
                    continue;
                }
//                //增量同步
//                if("2".equals(status)){//禁用的，直接启用新的
//                    shrPersonManager.update();
//                }else if("1".equals(hrSame) || !"2".equals(update)){//正常状态、配置相同或未手工更新的 ,直接按新数据更新
//                    shrPersonManager.update();
//                }else{//shrPersonManager
//
//                }
            }
            for(String personId : personManagerMap.keySet()){// 不存在的进行禁用处理
                if(!shrPersonManagerMap.containsKey(personId)){
                    PersonManager personManager = personManagerMap.get(personId);
                    personManager.setPersonManagerStatus("2");
                    personManager.setPersonManagerUpdatetime(Tool.getCurrTime());
                    personManager.update();
                }
            }
        }catch (Exception e){
           throw e;
        }finally {
            syncFlag = false;
        }


    }

    private Map<String, PersonManager> getShrPersonManagerMap(){
        // String shrUrl = PropKit.get("shrUrl");
        String shrUrl = codeService.getSysCodeName("金蝶shr登录路径").getSyscodeValue();
        SysCode sysCode = codeService.getSysCodeName("shr-osf Url");
        if(sysCode!=null && StringUtils.isNotBlank(sysCode.getSyscodeValue())){
            shrUrl =sysCode.getSyscodeValue();
        }

        Object data =  ShrOsf.callOSF(shrUrl,"inteOAGetAdminOrgDataServiceExt", new HashMap<String,Object>());
        if(data==null){
            throw new RuntimeException("获取shr组织二开接口异常！");
        }
        if(data.toString().indexOf("\"error\":")>=0){
            throw new RuntimeException("获取shr组织二开接口异常！"+data.toString());
        }
        JSONArray jsonArray = JSON.parseArray(data.toString());
        if(jsonArray.size()<10){
            throw new RuntimeException("获取shr组织二开接口异常！(组织个数小于10个)");
        }
        Map<String,DeptManagerDto> deptManagerMap = new HashMap<>();
        Map<String,PersonManager> personManagerMap = new HashMap<>();
        List<Person> allEnablePerson = hrService.getAllEnablePerson2();
        Map<String, Person> personMap = allEnablePerson.stream().collect(Collectors.toMap(Person::getId, person -> person));
        String currTime = Tool.getCurrTime();
        //部门配置转换
        for(int i=0;i<jsonArray.size();i++) {
            JSONObject deptJson = (JSONObject)jsonArray.get(i);
            DeptDto deptDto = JSONUtil.toBean(deptJson.toJSONString(),DeptDto.class);
            String deptId = deptDto.getEasdept_id();
            DeptManagerDto deptManager = new DeptManagerDto();
            deptManager.setDeptId(deptId);
            setDeptManager(deptManager,deptDto,personMap);
            deptManagerMap.put(deptId,deptManager);
        }
        Map<String, String> personId2SuperIdMap = getPersonId2SuperIdMap();//HR上级
        for(Person person : allEnablePerson){
            PersonManager personManager = new PersonManager();
            String personId = person.getId();
            personManagerMap.put(person.getId(),personManager);
            personManager.setPersonManagerId(person.getId());
            String deptId = person.getDeptId();
            DeptManagerDto deptManagerDto = deptManagerMap.get(deptId);
            if(deptManagerDto == null){
                continue;
            }
            personManager.setPersonManagerHrpid1(deptManagerDto.getDeptManagerHrpid1());
            personManager.setPersonManagerHrpname1(deptManagerDto.getDeptManagerHrpname1());
            personManager.setPersonManagerHrpid2(deptManagerDto.getDeptManagerHrpid2());
            personManager.setPersonManagerHrpname2(deptManagerDto.getDeptManagerHrpname2());
            personManager.setPersonManagerHrpid3(deptManagerDto.getDeptManagerHrpid3());
            personManager.setPersonManagerHrpname3(deptManagerDto.getDeptManagerHrpname3());

            personManager.setPersonManagerPid1(deptManagerDto.getDeptManagerPid1());
            personManager.setPersonManagerPname1(deptManagerDto.getDeptManagerPname1());
            personManager.setPersonManagerPid2(deptManagerDto.getDeptManagerPid2());
            personManager.setPersonManagerPname2(deptManagerDto.getDeptManagerPname2());
            personManager.setPersonManagerPid3(deptManagerDto.getDeptManagerPid3());
            personManager.setPersonManagerPname3(deptManagerDto.getDeptManagerPname3());

            personManager.setPersonManagerHrsame(deptManagerDto.isSame()?"1":"2");
            personManager.setPersonManagerLock("1");
            personManager.setPersonManagerCreatetime(currTime);
            String superId = personId2SuperIdMap.get(personId);
            personManager.setPersonManagerHrSuperId(superId);
            if(StringUtils.isNotBlank(superId) && personMap.containsKey(superId)){
                personManager.setPersonManagerHrSuperName(personMap.get(superId).getName());
            }

        }
        return personManagerMap;
    }

    private Map<String,String> getPersonId2SuperIdMap(){
        Map<String,String> map = new HashMap<>();
        List<DtBean> list = new DtBean().dao().find("select fid,cfleaderid from t_bd_person ");
        for(DtBean bean :list){
            map.put(bean.getStr("fid"),bean.getStr("cfleaderid"));
        }
        return map;
    }

    private void setDeptManager(DeptManagerDto deptManager,DeptDto dept,Map<String, Person> personMap){
        String groupLeaders = dept.getGroupLeaders();
        String directors = dept.getDirectors();
        String managers = dept.getManagers();
        boolean  hrSame = true;
        if(StringUtils.isNotEmpty(groupLeaders)){
            String[] ids = groupLeaders.split(",");
            deptManager.setDeptManagerPid1(ids[0]);
            deptManager.setDeptManagerHrpid1(groupLeaders);
            String names = "";
            if(ids.length>1)hrSame=false;
            for (int i = 0; i < ids.length; i++) {
                Person person = personMap.get(ids[i]);
                if(i == 0){
                    deptManager.setDeptManagerPname1(person==null?"异常数据":person.getName()+"_"+person.getNumber());
                    names += person==null?"异常数据":person.getName();
                }else{
                    names += ";"+(person==null?"异常数据":person.getName());
                }
            }
            deptManager.setDeptManagerHrpname1(names);
        }
        if(StringUtils.isNotEmpty(directors)){
            String[] ids = directors.split(",");
            deptManager.setDeptManagerPid2(ids[0]);
            deptManager.setDeptManagerHrpid2(directors);
            String names = "";
            if(ids.length>1)hrSame=false;
            for (int i = 0; i < ids.length; i++) {
                Person person = personMap.get(ids[i]);
                if(i == 0){
                    deptManager.setDeptManagerPname2(person==null?"异常数据":person.getName()+"_"+person.getNumber());
                    names += person==null?"异常数据":person.getName();
                }else{
                    names += ";"+(person==null?"异常数据":person.getName());
                }
            }
            deptManager.setDeptManagerHrpname2(names);
        }
        if(StringUtils.isNotEmpty(managers)){
            String[] ids = managers.split(",");
            deptManager.setDeptManagerPid3(ids[0]);
            deptManager.setDeptManagerHrpid3(managers);
            String names = "";
            if(ids.length>1)hrSame=false;
            for (int i = 0; i < ids.length; i++) {
                Person person = personMap.get(ids[i]);
                if(i == 0){
                    deptManager.setDeptManagerPname3(person==null?"异常数据":person.getName()+"_"+person.getNumber());
                    names += person==null?"异常数据":person.getName();
                }else{
                    names += ";"+(person==null?"异常数据":person.getName());
                }
            }
            deptManager.setDeptManagerHrpname3(names);
        }
        deptManager.setSame(hrSame);
    }

    public Person getManager(String personId,int level){

        PersonManager personManager = PersonManager.dao.findById(personId);
        return getManager(personManager,level);
    }

    /**
     * 获取上级
     * @param personManager
     * @param level
     * @return
     */
    public Person getManager(PersonManager personManager,int level){
        if(personManager == null){
            return null;
        }
        if(level>3){
            return null;
        }
        String pid1 = personManager.getPersonManagerPid1();
        String pid2 = personManager.getPersonManagerPid2();
        String pid3 = personManager.getPersonManagerPid3();
        String[] pids = new String[]{pid1,pid2,pid3};
        String pid = pids[level-1];
        if(personManager.getPersonManagerId().equals(pid)){//上级为本人
            if(level <3){
                return getManager(personManager,level+1);
            }else{
                return hrService.getEnableDfSuperPersonById(personManager.getPersonManagerId());//3级为本人取hr上级
            }
        }
        Person person = null;
        if(StringUtils.isNotBlank(pid)){
            person = hrService.getEnablePersonById(pid);
        }
        if(person != null){
            return person;
        }

        return getManager(personManager,level+1);
    }
    /**
     * 获取人员 领导+实际层级
     * @param personId
     * @param level
     * @return
     */
    public Object[] getManagerAndLv(String personId,int level){

        PersonManager personManager = PersonManager.dao.findById(personId);
        return getManagerAndLv(personManager,level);
    }

    public boolean isManager(String personId,String pid){
        PersonManager personManager = PersonManager.dao.findById(personId);
        String pid1 = personManager.getPersonManagerPid1();
        String pid2 = personManager.getPersonManagerPid2();
        String pid3 = personManager.getPersonManagerPid3();
        if(pid.equals(pid1) || pid.equals(pid2) || pid.equals(pid3)){
            return true;
        }
        return false;
    }
    /**
     * 获取人员 领导+实际层级
     * @param personManager
     * @param level
     * @return
     */
    public Object[] getManagerAndLv(PersonManager personManager,int level){
        if(personManager == null){
            return null;
        }
        //3层都没找到领导  找hr直属领导
        if(level== 4 && StringUtils.isNotBlank(personManager.getPersonManagerHrSuperId())){
            return new Object[]{hrService.getEnableDfSuperPersonById(personManager.getPersonManagerId()),3};
        }
        if(level>3){
            return null;
        }
        String pid1 = personManager.getPersonManagerPid1();
        String pid2 = personManager.getPersonManagerPid2();
        String pid3 = personManager.getPersonManagerPid3();
        String[] pids = new String[]{pid1,pid2,pid3};

        LinkedHashMap<Integer, Person> lvManagerPersons = getLvManagerPerson(pids, level);
        Integer managerLv = null;
        Person manager = null;
        for (Integer lv : lvManagerPersons.keySet()) {
            if(personManager.getPersonManagerId().equals(lvManagerPersons.get(lv).getId())){//上级为员工自己
                continue;
            }
            if(managerLv == null){
                managerLv = lv;
                manager = lvManagerPersons.get(managerLv);
                continue;
            }
            //判断后一位领导是否和前一位相同
            if(lvManagerPersons.get(lv).getId().equals(manager.getId())){
                managerLv = lv;
            }else{
                break;
            }
        }
        if(manager == null ){
            return new Object[]{hrService.getEnableDfSuperPersonById(personManager.getPersonManagerId()),3};
        }
        return new Object[]{manager,managerLv};
    }
    private LinkedHashMap<Integer,Person> getLvManagerPerson(String[] pids,Integer lv){
        LinkedHashMap<Integer,Person> map = new LinkedHashMap<>();
        return getLvManagerPerson(pids,lv,map);
    }
    private LinkedHashMap<Integer,Person> getLvManagerPerson(String[] pids,Integer lv,LinkedHashMap<Integer,Person> map){
        if(map == null)map = new LinkedHashMap<Integer,Person>();
        if(lv>3){
            return map;
        }
        String pid = pids[lv-1];
        Person person = null;
        if(StringUtils.isNotBlank(pid)){
            person = hrService.getEnablePersonById(pid);
        }
        if(person!=null)map.put(lv,person);

       return getLvManagerPerson(pids,lv+1,map);
    }

    public Person getManager(String personId,int level,Map<String,Person> personMap){

        PersonManager personManager = PersonManager.dao.findById(personId);
        return getManager(personManager,level,personMap);
    }
    public Person getManager(PersonManager personManager,int level,Map<String,Person> personMap){
        if(personManager == null){
            return null;
        }
        if(level>3){
            return null;
        }
        String pid1 = personManager.getPersonManagerPid1();
        String pid2 = personManager.getPersonManagerPid2();
        String pid3 = personManager.getPersonManagerPid3();
        String[] pids = new String[]{pid1,pid2,pid3};
        String pid = pids[level-1];
        if(personManager.getPersonManagerId().equals(pid)){//上级为本人
            if(level <3){
                return getManager(personManager,level+1,personMap);
            }else{
                return hrService.getEnableDfSuperPersonById(personManager.getPersonManagerId());//3级为本人取hr上级
            }
        }
        Person person = null;
        if(StringUtils.isNotBlank(pid)){
            person = personMap.get(pid);
        }

        if(person != null){
            return person;
        }

        return getManager(personManager,level+1,personMap);
    }


//    public Object[] getManagerAndLv(String deptId,int level){
//        PersonManager personManager = PersonManager.dao.findById(deptId);
//        if(personManager == null){
//            return null;
//        }
//        int lv = 0;
//        String pid = personManager.getPersonManagerPid1();
//        if(StringUtils.isNotBlank(pid)){
//            lv ++;
//            if(lv == level){
//                return hrService.getPersonById(pid);
//            }
//        }
//        pid = personManager.getPersonManagerPid2();
//        if(StringUtils.isNotBlank(pid)){
//            lv ++;
//            if(lv == level){
//                return hrService.getPersonById(pid);
//            }
//        }
//        pid = personManager.getPersonManagerPid3();
//        if(StringUtils.isNotBlank(pid)){
//            lv ++;
//            if(lv == level){
//                return hrService.getPersonById(pid);
//            }
//        }
//
//
//    }

}