package com.yeejoin.amos.boot.module.common.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.constants.CommonConstant;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.biz.common.utils.TreeParser;
import com.yeejoin.amos.boot.module.common.api.dto.*;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormColumn;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormInstance;
import com.yeejoin.amos.boot.module.common.api.entity.MaintenanceCompany;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.api.enums.OrgPersonEnum;
import com.yeejoin.amos.boot.module.common.api.enums.UserRolesEnum;
import com.yeejoin.amos.boot.module.common.api.enums.UserUnitTypeEnum;
import com.yeejoin.amos.boot.module.common.api.mapper.OrgUsrMapper;
import com.yeejoin.amos.boot.module.common.api.service.IMaintenanceCompanyService;
import com.yeejoin.amos.boot.module.common.api.service.IOrgUsrService;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import javax.annotation.Resource;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 机构/部门/人员表 服务实现类
 *
 * @author tb
 * @date 2021-06-18
 */

@Service
public class OrgUsrServiceImpl extends BaseService<OrgUsrDto, OrgUsr, OrgUsrMapper> implements IOrgUsrService {

    private static final String TYPE = "PERSON,COMPANY";

    private static final String CODE = "amosAccount";

    private static final String FIELD_CODE = "telephone";

    private static final String COMPANY_FIELD_CODE = "companyLocation,longitude,latitude";

    @Autowired
    DynamicFormInstanceServiceImpl alertFormValueServiceImpl;
    @Autowired
    FirefightersServiceImpl firefightersService;
    @Autowired
    DynamicFormColumnServiceImpl alertFormServiceImpl;
    @Resource
    OrgUsrMapper orgUsrMapper;
    @Autowired
    EmqKeeper emqKeeper;
    @Value("${jcs.company.topic.add}")
    private String airportAddTopic;
    @Autowired
    ESOrgUsrService eSOrgUsrService;
    @Autowired
    IMaintenanceCompanyService maintenanceCompanyService;

    @Override
    public String selectUpUnitByParam(String id) {
        return this.baseMapper.selectUpUnitByParam(id);
    }

    public static List<OrgMenuDto> buildTreeParallel(List<OrgUsr> list) {

        List<OrgMenuDto> menuList = list.stream().map(o -> {
            OrgMenuDto menu = new OrgMenuDto(o.getSequenceNbr(), o.getBizOrgName(),
                    ObjectUtils.isEmpty(o.getParentId()) ? 0L : Long.valueOf(o.getParentId()), o.getBizOrgType(), false,
                    o.getBizOrgCode());
            return menu;
        }).collect(Collectors.toList());

        List<OrgMenuDto> result = new ArrayList<>();
        Map<Long, OrgMenuDto> map = new HashMap<>(menuList.size());
        menuList.forEach(e -> map.put(e.getKey(), e));
        Set<? extends Map.Entry<Long, ? extends OrgMenuDto>> entries = map.entrySet();
        //此处多线程，会value 出现null 的情况
        //entries.parallelStream().forEach(entry -> {
            entries.stream().forEach(entry -> {
            OrgMenuDto value = entry.getValue();
            if (value != null) {
                OrgMenuDto treeDto = map.get(value.getParentId());
                if (treeDto != null) {
                    List<OrgMenuDto> children = treeDto.getChildren();
                    if (children == null) {
                        children = new ArrayList<>();
                        treeDto.setChildren(children);
                    }

                    children.add(value);
                } else {
                    result.add(value);
                }
            }
        });
        return result;
    }

    @Override
    public List<OrgMenuDto> getTree(Long topId, Collection entityList, String packageURL, String IDMethodName,
                                    int IDHierarchy, String NAMEMethodName, String PARENTIDMethodName, String OrgTypeMethodName)
            throws Exception {
        List<OrgMenuDto> resultList = new ArrayList<>();
        Class<?> clazz = Class.forName(packageURL);
        Method IDMethodNameme = null;
        switch (IDHierarchy) {
            case 1:
                IDMethodNameme = clazz.getDeclaredMethod(IDMethodName);
                break;
            case 2:
                IDMethodNameme = clazz.getSuperclass().getDeclaredMethod(IDMethodName);
                break;
            case 3:
                IDMethodNameme = clazz.getSuperclass().getSuperclass().getDeclaredMethod(IDMethodName);
                break;
            default:
                IDMethodNameme = clazz.getDeclaredMethod(IDMethodName);
                break;
        }

        Method NAMEMethodNameme = clazz.getDeclaredMethod(NAMEMethodName);
        Method PARENTIDMethodNameme = clazz.getDeclaredMethod(PARENTIDMethodName);
        Method OrgTypeMethodNameme = clazz.getDeclaredMethod(OrgTypeMethodName);
        // 获取顶层元素集合
        Long parentId;
        for (Object ob : entityList) {

            Object entity = clazz.cast(ob);

            parentId = !ObjectUtils.isEmpty(PARENTIDMethodNameme.invoke(entity))
                    ? Long.valueOf(String.valueOf(PARENTIDMethodNameme.invoke(entity)))
                    : null;
//			if (parentId == null || topId ==parentId ) {
//				OrgMenuDto menu = new OrgMenuDto(Long.valueOf(String.valueOf(IDMethodNameme.invoke(entity))),
//						String.valueOf(NAMEMethodNameme.invoke(entity)), parentId,
//						String.valueOf(OrgTypeMethodNameme.invoke(entity)), false);
//				resultList.add(menu);
//			}
            /*	*******************topId与parentId的等值判断，修改人陈浩 on 2021/07/21---start******************************/
            if (parentId == null) {//topId与parentId的等值判断，修改人陈浩 on 2021/07/21
                OrgMenuDto menu = new OrgMenuDto(Long.valueOf(String.valueOf(IDMethodNameme.invoke(entity))),
                        String.valueOf(NAMEMethodNameme.invoke(entity)), parentId,
                        String.valueOf(OrgTypeMethodNameme.invoke(entity)), false);
                resultList.add(menu);
            } else if (topId != null && topId.longValue() == parentId.longValue()) {
                OrgMenuDto menu = new OrgMenuDto(Long.valueOf(String.valueOf(IDMethodNameme.invoke(entity))),
                        String.valueOf(NAMEMethodNameme.invoke(entity)), parentId,
                        String.valueOf(OrgTypeMethodNameme.invoke(entity)), false);
                resultList.add(menu);
            }
            /*	*******************topId与parentId的等值判断，修改人陈浩 on 2021/07/21---end******************************/
        }
        // 获取每个顶层元素的子数据集合
        for (OrgMenuDto entity : resultList) {
            entity.setChildren(getSub(entity.getKey(), entityList, packageURL, IDMethodName, IDHierarchy,
                    NAMEMethodName, PARENTIDMethodName, OrgTypeMethodName));
        }
        return resultList;
    }

    @Override
    public List<OrgMenuDto> getSub(Long topId, @SuppressWarnings("rawtypes") Collection entityList, String packageURL,
                                   String IDMethodName, int IDHierarchy, String NAMEMethodName, String PARENTIDMethodName,
                                   String OrgTypeMethodName) throws Exception {
        List<OrgMenuDto> childList = new ArrayList<>();
        Class clazz = Class.forName(packageURL);
        Method IDMethodNameme = null;
        switch (IDHierarchy) {
            case 1:
                IDMethodNameme = clazz.getDeclaredMethod(IDMethodName);
                break;
            case 2:
                IDMethodNameme = clazz.getSuperclass().getDeclaredMethod(IDMethodName);
                break;
            case 3:
                IDMethodNameme = clazz.getSuperclass().getSuperclass().getDeclaredMethod(IDMethodName);
                break;
            default:
                IDMethodNameme = clazz.getDeclaredMethod(IDMethodName);
                break;
        }
        Method OrgTypeMethodNameme = clazz.getDeclaredMethod(OrgTypeMethodName);
        Method NAMEMethodNameme = clazz.getDeclaredMethod(NAMEMethodName);
        Method PARENTIDMethodNameme = clazz.getDeclaredMethod(PARENTIDMethodName);

        Long parentId;
        // 子集的直接子对象
        for (Object ob : entityList) {
            Object entity = clazz.cast(ob);

            parentId = !ObjectUtils.isEmpty(PARENTIDMethodNameme.invoke(entity))
                    ? Long.valueOf(String.valueOf(PARENTIDMethodNameme.invoke(entity)))
                    : null;

            if (parentId == null) {
                if (topId == parentId) {
                    OrgMenuDto menu = new OrgMenuDto(Long.valueOf(String.valueOf(IDMethodNameme.invoke(entity))),
                            String.valueOf(NAMEMethodNameme.invoke(entity)), parentId,
                            String.valueOf(OrgTypeMethodNameme.invoke(entity)));
                    childList.add(menu);
                }
            } else {
                if (topId.longValue() == parentId.longValue()) {
                    OrgMenuDto menu = new OrgMenuDto(Long.valueOf(String.valueOf(IDMethodNameme.invoke(entity))),
                            String.valueOf(NAMEMethodNameme.invoke(entity)), parentId,
                            String.valueOf(OrgTypeMethodNameme.invoke(entity)));
                    childList.add(menu);
                }
            }

        }

        // 子集的间接子对象
        for (OrgMenuDto entity : childList) {
            entity.setChildren(getSub(entity.getKey(), entityList, packageURL, IDMethodName, IDHierarchy,
                    NAMEMethodName, PARENTIDMethodName, OrgTypeMethodName));
            if (entity.getChildren() != null) {
                entity.setLeaf(false);
            }
        }

        // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }

        return childList;
    }

    @Override
    public List<Map<String, Object>> returnCompanyPersonMsg(List<Long> ids) throws Exception {
        List<Map<String, Object>> companyPersonMsg = new ArrayList<>();
        for (int i = 0; i < ids.size(); i++) {
            Map<String, Object> resultMap = new HashMap<>();
            // 查询出单位基本信息
            OrgUsr company = getById(ids.get(i));
            resultMap.put("id", company.getSequenceNbr());
            // 上级单位
            resultMap.put("upUnit", selectUpUnitByParam(company.getSequenceNbr() + ""));
            // 当前单位
            resultMap.put("currentUnit", company.getBizOrgName());
            // 下级单位
            Map<String, Object> downUnitColumnMap = new HashMap<>();
            downUnitColumnMap.put("is_delete", CommonConstant.IS_DELETE_00);
            downUnitColumnMap.put("biz_org_type", CommonConstant.BIZ_ORG_TYPE_COMPANY);
            downUnitColumnMap.put("parent_id", company.getSequenceNbr());
            QueryWrapper<OrgUsr> downUnitWrapper = new QueryWrapper<OrgUsr>();
            downUnitWrapper.allEq(downUnitColumnMap);
            List<OrgUsr> downList = list(downUnitWrapper);
            if (downList.size() == 0) {
                resultMap.put("downUnit", false);
            } else {
                resultMap.put("downUnit", true);
            }
            // 人员数量
            Map<String, Object> countPerson = new HashMap<>();
            countPerson.put("parent_id", company.getSequenceNbr());
            countPerson.put("biz_org_type", CommonConstant.BIZ_ORG_TYPE_PERSON);
            QueryWrapper<OrgUsr> personNumWrapper = new QueryWrapper<OrgUsr>();
            personNumWrapper.allEq(countPerson);
            int personNum = count(personNumWrapper);
            resultMap.put("personNum", personNum);
            if (0 == personNum) {
                continue;
            }
            List<Map<String, Object>> personList = new ArrayList<>();
            // 查询动态表单Phone
            Map<String, Object> phone = new HashMap<>();
            phone.put("instance_id", company.getSequenceNbr());
            phone.put("field_code", "companyPhone");
            QueryWrapper<DynamicFormInstance> phoneWrapper = new QueryWrapper<DynamicFormInstance>();
            phoneWrapper.allEq(phone);
            DynamicFormInstance phoneValue = alertFormValueServiceImpl.getOne(phoneWrapper);
            if (phoneValue == null) {
                resultMap.put("tel", "");
            } else {
                resultMap.put("tel", phoneValue.getFieldValue());
            }

            // 获取单位人员列表信息
            personList = listPerson(company.getSequenceNbr() + "").stream().map(p -> {
                Map<String, Object> person = new HashMap<>();
                person.put("tel", getValue(p.get("telephone"), null));
                person.put("img", getValue(p.get("personImg"), null));
                person.put("id", getValue(p.get("sequenceNbr"), null));
                person.put("name", getValue(p.get("bizOrgName"), null));
                person.put("zhiwei", getValue(p.get("administrativePositionCode"), null));
                person.put("unit", getValue(p.get("fireManagementPostCode"), null));
                return person;
            }).collect(Collectors.toList());
            resultMap.put("children", personList);
            companyPersonMsg.add(resultMap);
        }
        return companyPersonMsg;
    }

    private Object getValue(Object obj, Object defaultValue) {
        return ObjectUtils.isEmpty(obj) ? defaultValue : obj;
    }

    public List<Map<String, Object>> listPerson(String parentId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("fields", alertFormServiceImpl.queryListByFormId(OrgPersonEnum.人员.getCode()));
        map.put("bizOrgType", OrgPersonEnum.人员.getKey());
        map.put("parentId", parentId);
        List<Map<String, Object>> list = this.baseMapper.selectPersonAllList(map);
        return list == null ? new ArrayList<Map<String, Object>>() : list;
    }

    public IPage<Map<String, Object>> pagePerson(String pageNum, String pageSize, Map<String, Object> req) {
        IPage<Map<String, Object>> pageBean = null;
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        Map<String, Object> map = new HashMap<>();
        /*Bug2652 根据名字和工号模糊查询失效 已添加模糊匹配 2021-09-01 陈召 开始*/
        map.put("bizOrgType", OrgPersonEnum.人员.getKey());
        if (!ObjectUtils.isEmpty(req.get("bizOrgName"))) {
            map.put("bizOrgName", req.get("bizOrgName"));
        }

        if (!ObjectUtils.isEmpty(req.get("personNumber"))) {
            map.put("personNumber", req.get("personNumber"));
        }
        /*BUG2680 查询部门人员错误 传递参数类型不正确 修改为string 2021-09-14 陈召 开始*/
        if (req.get("parentId") != null && req.get("parentId") != "") {
            OrgUsr parent = this.getById(req.get("parentId").toString());
            map.put("bizOrgCode", ObjectUtils.isEmpty(parent) ? null : parent.getBizOrgCode());
        }
        /*BUG2680 查询部门人员错误 传递参数类型不正确 修改为string 2021-09-14 陈召 开始*/

        req.remove("bizOrgName");
        req.remove("pageSize");
        req.remove("pageNum");
        req.remove("parentId");

        map.put("fieldsValue", req);
        map.put("fields", alertFormServiceImpl.queryListByFormId(OrgPersonEnum.人员.getCode()));
        pageBean.setTotal(this.baseMapper.selectPersonListCount(map));
        map.put("pageNum", (pageBean.getCurrent() - 1) * pageBean.getSize());
        map.put("pageSize", pageBean.getSize());
        List<Map<String, Object>> list = this.baseMapper.selectPersonList(map);
        list.stream().forEach(t -> {
            // BUG2886 因为前期沟通 人员code 可能会发生改变 所以 现在接口code 不再保存，查询数据时通过接口重新赋值 by kongfm 2021-09-16
            if (null != t.get("amosOrgId") && StringUtils.isNotEmpty(t.get("amosOrgId").toString())) {
                FeignClientResult<AgencyUserModel> result1 = Privilege.agencyUserClient.queryByUserId(t.get("amosOrgId").toString());
                if (null != result1.getResult()) {
                    t.put("amosOrgCode", result1.getResult().getRealName());
                }
            }

        });
        /*Bug2652 根据名字和工号模糊查询失效 已添加模糊匹配 2021-09-01 陈召 结束*/
        pageBean.setRecords(list);
        return pageBean;
    }

    @Override
    public List<FormValue> getFormValue(Long id) throws Exception {
        // 动态表单数据

        List<DynamicFormInstanceDto> list = alertFormValueServiceImpl.listByCalledId(id);
        List<FormValue> formValue = new ArrayList<>();
        for (DynamicFormInstanceDto alertFormValue : list) {
            /*修改为动态表单返回的数据参数量 2021-09-08 陈浩 开始 */
//            if (alertFormValue.getFieldValueLabel() != null) {
//                FormValue value = new FormValue(alertFormValue.getFieldCode(), alertFormValue.getFieldName(),
//                        alertFormValue.getFieldType(), alertFormValue.getFieldValueLabel(), alertFormValue.getBlock());
//                formValue.add(value);
//            } else {
            FormValue value = new FormValue(alertFormValue.getFieldCode(), alertFormValue.getFieldName(),
                    alertFormValue.getFieldType(), alertFormValue.getFieldValue(), alertFormValue.getBlock(), alertFormValue.getFieldValueLabel());
            formValue.add(value);
            /*修改为动态表单返回的数据参数量 2021-09-08 陈浩 结束 */
//            }
            /*BUG2580 返回值为code值 修改为类型名称 2021-08-31 陈召 开始 */
        }
        return formValue;

    }

    public List<FormValue> getFormValueDetail(Long id) throws Exception {
        // 动态表单数据
        List<DynamicFormInstanceDto> list = alertFormValueServiceImpl.listByCalledId(id);
        List<FormValue> formValue = new ArrayList<>();
        for (DynamicFormInstanceDto alertFormValue : list) {
            FormValue value = new FormValue(alertFormValue.getFieldCode(), alertFormValue.getFieldName(),
                    alertFormValue.getFieldType(), alertFormValue.getFieldValue(), alertFormValue.getBlock(), alertFormValue.getFieldValueLabel());//陈浩 添加getFieldValueLabel的属性值 2021-09-08
            formValue.add(value);
        }
        return formValue;
    }

    @Override
    public void saveOrgUsr(OrgUsr orgUsr, OrgUsr oriOrgUsr) throws Exception {

        if (oriOrgUsr.getParentId() != oriOrgUsr.getParentId()) {
            OrgUsr parent = getById(orgUsr.getParentId());
            if (parent != null && !ObjectUtils.isEmpty(parent.getBizOrgCode())) {
                orgUsr.setBizOrgCode(parent.getBizOrgCode() + getOrgCodeStr());
            }
            updateChildOrgCode(oriOrgUsr.getBizOrgCode(), orgUsr.getBizOrgCode());
            orgUsr.setParentId(oriOrgUsr.getParentId());
        }
        AgencyUserModel me = Privilege.agencyUserClient.getme().getResult();
        orgUsr.setRecDate(new Date());
        orgUsr.setRecUserId(me.getUserId());
        orgUsr.setRecUserName(me.getRealName());
        updateById(orgUsr);
    }

    private void updateChildOrgCode(String oriOrgCode, String targetOrgCode) {
        List<OrgUsr> list = queryOrgUsrList(oriOrgCode);
        if (!ObjectUtils.isEmpty(list)) {
            list.forEach(action -> {
                action.setBizOrgCode(action.getBizOrgCode().replace(oriOrgCode, targetOrgCode));
                updateById(action);
            });
        }
    }

    public List<OrgUsr> queryOrgUsrList(String bizOrgCode) {
        return this.baseMapper.queryOrgUsrListByBizOrgCode(bizOrgCode);
    }

    @Override
    public void saveOrgUsrDynamicFormInstance(OrgUsr orgUsr, List<DynamicFormInstance> alertFromValuelist) throws Exception {
        orgUsr.setRecDate(new Date());
        AgencyUserModel user = Privilege.agencyUserClient.getme().getResult();
        orgUsr.setRecUserName(user.getRealName());
        orgUsr.setRecUserId(user.getUserId());
        // 单位新增情况
        save(orgUsr);
        // 填充主键
        alertFromValuelist.stream().forEach(alertFromValue -> {
            if (OrgPersonEnum.公司.getKey().equals(orgUsr.getBizOrgType())) {
                alertFromValue.setGroupCode(OrgPersonEnum.公司.getCode());
            } else if (OrgPersonEnum.部门.getKey().equals(orgUsr.getBizOrgType())) {
                alertFromValue.setGroupCode(OrgPersonEnum.部门.getCode());
            }
            alertFromValue.setInstanceId(orgUsr.getSequenceNbr());
        });
        // 保存动态表单数据
        alertFormValueServiceImpl.saveBatch(alertFromValuelist);
        OrgUsrFormDto formDto = this.selectCompanyById(orgUsr.getSequenceNbr());
        if (OrgPersonEnum.公司.getKey().equals(orgUsr.getBizOrgType())) {
            try {
                emqKeeper.getMqttClient().publish(airportAddTopic, JSON.toJSONString(formDto).getBytes(), 2, false);
            } catch (Exception e) {
                e.getMessage();
            }
        }
    }

    @Override
    public void updateDynamicFormInstance(Long instanceId, List<DynamicFormInstance> fromValueList) {
        // 填充主键
        fromValueList.forEach(alertFromValue -> {
            alertFromValue.setInstanceId(instanceId);
        });
        List<DynamicFormInstanceDto> formList = alertFormValueServiceImpl.queryByCalledId(instanceId);

        Map<Long, DynamicFormInstanceDto> resourceMap = new HashMap<>();
        Map<Long, DynamicFormInstance> newResourceMap = new HashMap<>();
        formList.parallelStream().forEach(form -> {
            resourceMap.put(form.getFormColumnId(), form);
        });

        List<DynamicFormInstance> updateList = new ArrayList<>();
        List<DynamicFormInstance> addList = new ArrayList<>();
        List<Long> deleteList = new ArrayList<>();

        fromValueList.parallelStream().forEach(submitFormItem -> {
            if (resourceMap.containsKey(submitFormItem.getFormColumnId())) {
                DynamicFormInstanceDto oldForm = resourceMap.get(submitFormItem.getFormColumnId());
                submitFormItem.setSequenceNbr(oldForm.getSequenceNbr());
                updateList.add(submitFormItem);
            } else {
                addList.add(submitFormItem);
            }
            newResourceMap.put(submitFormItem.getFormColumnId(), submitFormItem);
        });


        newResourceMap.keySet().parallelStream().forEach(form -> {
            resourceMap.remove(form);
        });

        resourceMap.keySet().parallelStream().forEach(action -> {
            deleteList.add(resourceMap.get(action).getSequenceNbr());
        });

        if (deleteList.size() > 0) {
            alertFormValueServiceImpl.deleteBatchSeq(deleteList);
        }

        if (updateList.size() > 0) {
            alertFormValueServiceImpl.updateBatchById(updateList);
        }

        if (addList.size() > 0) {
            alertFormValueServiceImpl.saveBatch(addList);
        }
    }

    @Override
    public Map<String, Object> selectForShowById(OrgUsr orgUsr, Long id) throws Exception {
        QueryWrapper<DynamicFormColumn> queryWrapper = new QueryWrapper<DynamicFormColumn>();
        queryWrapper.eq("group_code", OrgPersonEnum.人员.getCode());
        List<DynamicFormColumn> alertForms = alertFormServiceImpl.list(queryWrapper);
        // 动态表单数据
        List<DynamicFormInstanceDto> list = alertFormValueServiceImpl.listByCalledId(id);
        Map<String, Object> result = new HashMap<>();

        // 机场人员AMOS角色丢失修正, by litw start 2021年9月10日
        if (StringUtils.isNotEmpty(orgUsr.getAmosOrgId())) {
            FeignClientResult<AgencyUserModel> result1 = Privilege.agencyUserClient.queryByUserId(orgUsr.getAmosOrgId());
            if (null != result1.getResult()) {
                orgUsr.setAmosOrgCode(result1.getResult().getRealName());
            }
        }
        // 机场人员AMOS角色丢失修正, by litw end  2021年9月10日
        result = Bean.BeantoMap(orgUsr);
        /*bug 2869 部门为空人员详情报空指针 2021-09-15 陈召 开始*/
        if (orgUsr.getParentId() != null) {
            result.put("parenName", getById(orgUsr.getParentId()).getBizOrgName());
        }
        /*bug 2869 部门为空人员详情报空指针 2021-09-15 陈召 结束*/
        // 放入所有动态表单数据
        for (DynamicFormColumn alertForm : alertForms) {
            result.put(alertForm.getFieldCode(), null);
        }
        for (DynamicFormInstanceDto alertFormValue : list) {
            result.put(alertFormValue.getFieldCode(),
                    ObjectUtils.isEmpty(alertFormValue.getFieldValueLabel()) ? alertFormValue.getFieldValue()
                            : alertFormValue.getFieldValueLabel());
        }
        return result;
    }

    @Override
    public List<OrgUsr> selectCompanyDepartmentMsg() {
        List<OrgUsr> list = this.baseMapper.selectCompanyDepartmentMsg();
        if (list == null) {
            return new ArrayList<>();
        }
        list = list.stream().filter(o -> !ObjectUtils.isEmpty(o)).collect(Collectors.toList());
        return list;
    }

    public List<OrgUsr> selectCompanyList() {
        List<OrgUsr> list =
                list(new LambdaQueryWrapper<OrgUsr>().eq(OrgUsr::getIsDelete, false).eq(OrgUsr::getBizOrgType,
                        "COMPANY"));
        if (list == null) {
            return new ArrayList<>();
        }
        list = list.stream().filter(o -> !ObjectUtils.isEmpty(o)).collect(Collectors.toList());
        return list;
    }

    @Override
    public void saveOrgUsr(OrgUsrDto OrgUsrVo) throws Exception {
        OrgUsr orgUsr = new OrgUsr();
        BeanUtils.copyProperties(OrgUsrVo, orgUsr);
        orgUsr.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_COMPANY);
        if (OrgUsrVo.getParentId() != null) {
            OrgUsr parent = getById(OrgUsrVo.getParentId());
            if (parent != null && ObjectUtils.isEmpty(OrgUsrVo.getBizOrgCode())) {
                orgUsr.setBizOrgCode(parent.getBizOrgCode() + getOrgCodeStr());
            }
        } else {
            orgUsr.setBizOrgCode(getOrgCodeStr());
        }
        saveOrgUsrDynamicFormInstance(orgUsr, OrgUsrVo.getDynamicFormValue());

        /**
         * 同步保存ES
         */
        eSOrgUsrService.saveAlertCalledToES(orgUsr);
    }

    @Override
    public void saveOrgPerson(OrgPersonDto OrgPersonVo) throws Exception {
        OrgUsr orgUsr = new OrgUsr();
        BeanUtils.copyProperties(OrgPersonVo, orgUsr);
        orgUsr.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_PERSON);
        if (OrgPersonVo.getParentId() != null) {
            OrgUsr parent = getById(OrgPersonVo.getParentId());
            if (parent != null && ObjectUtils.isEmpty(OrgPersonVo.getBizOrgCode())) {
                orgUsr.setBizOrgCode(parent.getBizOrgCode() + getOrgCodeStr());
            }
        } else {
            orgUsr.setBizOrgCode(getOrgCodeStr());
        }

        saveOrgUsrDynamicFormInstance(orgUsr, OrgPersonVo.getDynamicFormValue());
    }


    public void saveOrgPersonExcel(OrgUsrExcelDto OrgPersonVo) throws Exception {
        OrgUsr orgUsr = new OrgUsr();
        BeanUtils.copyProperties(OrgPersonVo, orgUsr);
        orgUsr.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_PERSON);
        if (OrgPersonVo.getParentId() != null) {
            OrgUsr parent = getById(OrgPersonVo.getParentId());
            if (parent != null && ObjectUtils.isEmpty(OrgPersonVo.getBizOrgCode())) {
                orgUsr.setBizOrgCode(parent.getBizOrgCode() + getOrgCodeStr());
            }
        } else {
            orgUsr.setBizOrgCode(getOrgCodeStr());
        }


        if (!ObjectUtils.isEmpty(OrgPersonVo.getAmosOrgId())) {
            AgencyUserModel user = Privilege.agencyUserClient.queryByUserId(OrgPersonVo.getAmosOrgId()).getResult();
            OrgPersonVo.setAmosOrgCode(user.getRealName());
        }

        saveOrgUsrDynamicFormInstance(orgUsr, OrgPersonVo.getDynamicFormValue());
    }

    @Override
    public void updateByIdOrgUsr(OrgUsrDto OrgUsrVo, Long id) throws Exception {
        // 修改单位信息
        OrgUsr orgUsr = new OrgUsr();
        OrgUsr oriOrgUsr = getById(id);
        BeanUtils.copyProperties(OrgUsrVo, orgUsr);
        /*单位编辑后 code值也应做出修改 2021-09-09 陈召 开始 */
        OrgUsr parent = getById(OrgUsrVo.getParentId());
        if (parent != null) {
            orgUsr.setBizOrgCode(parent.getBizOrgCode() + getOrgCodeStr());
        }
        orgUsr.setSequenceNbr(id);
        // 查询机构下的所有部门单位人员数据，进行bizOrgCode的统一修改  BUG 2880  by litw start 2021年9月16日
        String oriOrgCode = oriOrgUsr.getBizOrgCode();
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("bizOrgCode", oriOrgCode);
        List<OrgUsr> list = orgUsrMapper.selectAllChildrenList(columnMap);
        list.stream().forEach(e -> {
            e.setBizOrgCode(e.getBizOrgCode().replace(oriOrgCode, orgUsr.getBizOrgCode()));
        });
        this.updateBatchById(list);

        /*单位编辑后 code值也应做出修改 2021-09-09 陈召 结束  */
        saveOrgUsr(orgUsr, oriOrgUsr);
        // 保存动态表单数据
        updateDynamicFormInstance(orgUsr.getSequenceNbr(), OrgUsrVo.getDynamicFormValue());
        /**
         * 同步保存ES
         */
        eSOrgUsrService.saveAlertCalledToES(orgUsr);
    }

    @Override
    public void updateByIdOrgPerson(OrgPersonDto OrgPersonVo, Long id) throws Exception {
        // 修改人员信息
        OrgUsr orgUsr = new OrgUsr();
        OrgUsr oriOrgUsr = getById(id);
        BeanUtils.copyProperties(OrgPersonVo, orgUsr);
        /* Bug 2647  编辑用户所属单位后按单位筛选人员结果错误  增加了 638 639 两行代码 根据修改的部门调整部门code 2021-09-03 陈召  开始*/
        OrgUsr parent = getById(OrgPersonVo.getParentId());
        if (parent != null) {
            orgUsr.setBizOrgCode(parent.getBizOrgCode() + getOrgCodeStr());
        }
        /* Bug 2647  编辑用户所属单位后按单位筛选人员结果错误  增加了 638 639 两行代码 根据修改的部门调整部门code 2021-09-03 陈召  结束*/
        orgUsr.setSequenceNbr(id);
        if (!ObjectUtils.isEmpty(OrgPersonVo.getAmosOrgId())) {
            AgencyUserModel user = Privilege.agencyUserClient.queryByUserId(OrgPersonVo.getAmosOrgId()).getResult();
            // oriOrgUsr.setAmosOrgCode(user.getRealName());  去掉AmosOrgCode by litw 2021年9月10日
            oriOrgUsr.setAmosOrgId(user.getUserId());
            //orgUsr.setAmosOrgCode(user.getRealName()); 去掉AmosOrgCode by litw 2021年9月10日
            orgUsr.setAmosOrgId(user.getUserId());
        }

        saveOrgUsr(orgUsr, oriOrgUsr);
        // 保存动态表单数据
        updateDynamicFormInstance(orgUsr.getSequenceNbr(), OrgPersonVo.getDynamicFormValue());
    }

    @Override
    public OrgUsrFormDto selectCompanyById(Long id) throws Exception {
        OrgUsr orgUsr = getById(id);
        // 动态表单数据
        List<FormValue> formValue = getFormValue(id);
        //bug 2580 返回值改为具体名称  chenzhao  2021-09-27 start
        for (FormValue value : formValue) {
            if (value.getValueName() != null && !value.getValueName() .equals(" ")){
                value.setValue(value.getValueName());
            }
        }
        //bug 2580 返回值改为具体名称  chenzhao  2021-09-27 end
        OrgUsrFormDto orgUsrFormVo = new OrgUsrFormDto();
        orgUsrFormVo.setDynamicFormAlert(formValue);
        BeanUtils.copyProperties(orgUsr, orgUsrFormVo);
        return orgUsrFormVo;
    }

    @Override
    public IPage<OrgUsr> bizOrgTypeListPage(String pageNum, String pageSize, String bizOrgType) throws Exception {

        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("is_delete", CommonConstant.IS_DELETE_00);
        columnMap.put("biz_org_type", bizOrgType);
        Page<OrgUsr> pageBean = new Page<OrgUsr>();
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        QueryWrapper<OrgUsr> queryWrapper = new QueryWrapper<OrgUsr>();
        queryWrapper.allEq(columnMap);
        queryWrapper.orderByAsc("sequence_nbr");
        return page(pageBean, queryWrapper);
    }

    @Override
    public void saveDepartment(List<OrgDepartmentDto> OrgDepartmentVo, Long id) throws Exception {
        for (int i = 0; i < OrgDepartmentVo.size(); i++) {
            // 导入部门信息的前提条件：单位信息已经存在
            if (getById(id) != null) {
                OrgUsr orgUsr = new OrgUsr();
                BeanUtils.copyProperties(OrgDepartmentVo.get(i), orgUsr);
                orgUsr.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_DEPARTMENT);
                saveOrgUsrDynamicFormInstance(orgUsr, OrgDepartmentVo.get(i).getDynamicFormValue());
            }
        }
    }

    @Override
    public void saveCompany(List<OrgUsrDto> OrgUsrVo) throws Exception {
        for (int i = 0; i < OrgUsrVo.size(); i++) {
            OrgUsr orgUsr = new OrgUsr();
            BeanUtils.copyProperties(OrgUsrVo.get(i), orgUsr);
            orgUsr.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_COMPANY);
            saveOrgUsrDynamicFormInstance(orgUsr, OrgUsrVo.get(i).getDynamicFormValue());
        }
    }

    @Override
    public OrgPersonFormDto selectPersonById(Long id) throws Exception {
        OrgUsr orgUsr = getById(id);
        // 动态表单数据
        List<FormValue> formValue = getFormValue(id);
        OrgPersonFormDto orgPersonFormVo = new OrgPersonFormDto(formValue);
        BeanUtils.copyProperties(orgUsr, orgPersonFormVo);
        OrgUsr parent = getById(orgUsr.getParentId());
        if (!ObjectUtils.isEmpty(parent)) {
            orgPersonFormVo.setParentName(parent.getBizOrgName());
        }

        return orgPersonFormVo;
    }

    @Override
    public OrgPersonFormDto selectPersonByIdDetail(Long id) throws Exception {
        OrgUsr orgUsr = getById(id);

        // 动态表单数据
        List<FormValue> formValue = getFormValueDetail(id);
        OrgPersonFormDto orgPersonFormVo = new OrgPersonFormDto(formValue);
        BeanUtils.copyProperties(orgUsr, orgPersonFormVo);

        /*bug 2869 部门为空人员详情报空指针 2021-09-15 陈召 开始*/
        if (orgUsr.getParentId() != null) {
            orgPersonFormVo.setParentName(getById(orgUsr.getParentId()).getBizOrgName());
        }
        /*bug 2869 部门为空人员详情报空指针 2021-09-15 陈召 结束*/

        return orgPersonFormVo;
    }

    @Override
    public List<OrgMenuDto> selectPersonTree() throws Exception {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("is_delete", CommonConstant.IS_DELETE_00);
        columnMap.put("biz_org_type", CommonConstant.BIZ_ORG_TYPE_PERSON);
        Collection<OrgUsr> list = listByMap(columnMap);
//        list.stream().forEach(t-> {
//            // BUG2886 因为前期沟通 人员code 可能会发生改变 所以 现在接口code 不再保存，查询数据时通过接口重新赋值 by kongfm 2021-09-16
//            if(StringUtils.isNotEmpty(t.getAmosOrgId())) {
//                FeignClientResult<AgencyUserModel> result1 = Privilege.agencyUserClient.queryByUserId(t.getAmosOrgId());
//                if(null !=result1.getResult()) {
//                    t.setAmosOrgCode(result1.getResult().getRealName());
//                }
//            }
//        });
        return getTree(null, list, OrgUsr.class.getName(), "getSequenceNbr", 2, "getBizOrgName", "getParentId",
                "getBizOrgType");
    }

    @Override
    public void savePersonList(List<OrgPersonDto> OrgPersonVo) throws Exception {
        for (int i = 0; i < OrgPersonVo.size(); i++) {
            OrgUsr orgUsr = new OrgUsr();
            BeanUtils.copyProperties(OrgPersonVo.get(i), orgUsr);
            orgUsr.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_PERSON);
            saveOrgUsrDynamicFormInstance(orgUsr, OrgPersonVo.get(i).getDynamicFormValue());
        }
    }

    @Override
    public void saveOrgDepartment(OrgDepartmentDto OrgDepartmentVo) throws Exception {
        OrgUsr orgUsr = new OrgUsr();
        BeanUtils.copyProperties(OrgDepartmentVo, orgUsr);
        orgUsr.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_DEPARTMENT);
        if (OrgDepartmentVo.getParentId() != null) {
            OrgUsr parent = getById(OrgDepartmentVo.getParentId());
            if (parent != null && ObjectUtils.isEmpty(OrgDepartmentVo.getBizOrgCode())) {
                orgUsr.setBizOrgCode(parent.getBizOrgCode() + getOrgCodeStr());
            }
        } else {
            orgUsr.setBizOrgCode(getOrgCodeStr());
        }
        saveOrgUsrDynamicFormInstance(orgUsr, OrgDepartmentVo.getDynamicFormValue());
    }

    @Override
    public void updateByIdOrgDepartment(OrgDepartmentDto OrgDepartmentVo, Long id) throws Exception {
        // 修改部门信息
        OrgUsr orgUsr = new OrgUsr();
        OrgUsr oriOrgUsr = getById(id);
        BeanUtils.copyProperties(OrgDepartmentVo, orgUsr);
        /*部门编辑后 code值也应做出修改 2021-09-09 陈召 开始 */
        OrgUsr parent = getById(OrgDepartmentVo.getParentId());
        if (parent != null) {
            orgUsr.setBizOrgCode(parent.getBizOrgCode() + getOrgCodeStr());
        }
        orgUsr.setSequenceNbr(id);
        /*部门编辑后 code值也应做出修改 2021-09-09 陈召 结束  */

        saveOrgUsr(orgUsr, oriOrgUsr);
        // 保存动态表单数据
        updateDynamicFormInstance(orgUsr.getSequenceNbr(), OrgDepartmentVo.getDynamicFormValue());
    }

    @Override
    public OrgDepartmentFormDto selectDepartmentById(Long id) throws Exception {
        OrgUsr orgUsr = getById(id);
        // 动态表单数据
        List<FormValue> formValue = getFormValue(id);
        OrgDepartmentFormDto orgDepartmentFormVo = new OrgDepartmentFormDto(formValue);
        BeanUtils.copyProperties(orgUsr, orgDepartmentFormVo);
        return orgDepartmentFormVo;
    }

    @Override
    public List<Map<String, Object>> selectForShowByListId(List<Long> ids) throws Exception {
        List<Map<String, Object>> personResult = new ArrayList<>();
        for (int i = 0; i < ids.size(); i++) {
            OrgUsr orgUsr = getById(ids.get(i));
            Map<String, Object> result = selectForShowById(orgUsr, ids.get(i));
            personResult.add(result);
        }
        return personResult;
    }


    @Override
    public List<CompanyDto> listContractDto(Integer pageNum, Integer pageSize, RequestData requestData) {
        if (null == pageNum || null == pageSize) {
            pageNum = 1;
            pageSize = Integer.MAX_VALUE;
        } else {
            pageNum = (pageNum - 1) * pageSize;
        }
        return orgUsrMapper.listContractDto(pageNum, pageSize, requestData);
    }

    @Override
    public Integer listContractDtoCount(RequestData par) {
        return orgUsrMapper.listContractDtoCount(par);
    }


    public static String getOrgCodeStr() {
        return TreeParser.genTreeCode();
    }

    public void importByExcel(List<OrgPersonExcelDto> list) {
        list.forEach(item -> {
            OrgPersonDto orgPersonDto = new OrgPersonDto();
            orgPersonDto = Bean.toPo(item, orgPersonDto);
            List<DynamicFormInstance> alertFormValueList = new ArrayList<>();
            if (item.getPersonNumber() != null) {
                DynamicFormInstance alertFormValue = new DynamicFormInstance(102L, OrgPersonEnum.人员.getCode(), "员工编号",
                        "personNumber", item.getPersonNumber(), null, false);
                alertFormValueList.add(alertFormValue);
            }
            if (item.getCertificatesType() != null) {
                String certificatesType = item.getCertificatesType();
                String[] split = certificatesType.split("@");
                DynamicFormInstance alertFormValue = new DynamicFormInstance(23L, OrgPersonEnum.人员.getCode(), "证件类型",
                        "certificatesTypeCode", split[0], split[1], false);
                alertFormValueList.add(alertFormValue);
            }
            if (item.getGender() != null) {
                String gender = item.getGender();
                String[] split = gender.split("@");
                DynamicFormInstance alertFormValue = new DynamicFormInstance(22L, OrgPersonEnum.人员.getCode(), "性别",
                        "gender", split[0], split[1], false);
                alertFormValueList.add(alertFormValue);
            }
            if (item.getCertificatesNumber() != null) {
                DynamicFormInstance alertFormValue = new DynamicFormInstance(100L, OrgPersonEnum.人员.getCode(), "证件号码",
                        "certificatesNumber", item.getCertificatesNumber(), null, false);
                alertFormValueList.add(alertFormValue);
            }
            if (item.getTelephone() != null) {
                DynamicFormInstance alertFormValue = new DynamicFormInstance(24L, OrgPersonEnum.人员.getCode(), "联系电话",
                        "telephone", item.getTelephone(), null, false);
                alertFormValueList.add(alertFormValue);
            }
            if (item.getState() != null) {
                String state = item.getState();
                String[] split = state.split("@");
                DynamicFormInstance alertFormValue = new DynamicFormInstance(25L, OrgPersonEnum.人员.getCode(), "人员状态",
                        "stateCode", split[0], split[1], false);
                alertFormValueList.add(alertFormValue);
            }
            if (item.getSafetyTraining() != null) {
                String safetyTraining = item.getSafetyTraining();
                String[] split = safetyTraining.split("@");
                DynamicFormInstance alertFormValue = new DynamicFormInstance(29L, OrgPersonEnum.人员.getCode(),
                        "是否进行安全培训", "safetyTraining", split[0], split[1], false);
                alertFormValueList.add(alertFormValue);
            }
            if (item.getAdministrativePosition() != null) {
                String administrativePosition = item.getAdministrativePosition();
                String[] split = administrativePosition.split("@");
                DynamicFormInstance alertFormValue = new DynamicFormInstance(28L, OrgPersonEnum.人员.getCode(), "行政职务",
                        "administrativePositionCode", split[0], split[1], false);
                alertFormValueList.add(alertFormValue);
            }
            if (item.getInternalPosition() != null) {
                String internalPosition = item.getInternalPosition();
                String[] split = internalPosition.split("@");
                DynamicFormInstance alertFormValue = new DynamicFormInstance(26L, OrgPersonEnum.人员.getCode(),
                        "消防管理组织机构内部职务", "internalPositionCode", split[0], split[1], false);
                alertFormValueList.add(alertFormValue);
            }
            if (item.getFireManagementPost() != null) {
                String fireManagementPost = item.getFireManagementPost();
                String[] split = fireManagementPost.split("@");
                DynamicFormInstance alertFormValue = new DynamicFormInstance(27L, OrgPersonEnum.人员.getCode(), "消防管理岗位",
                        "fireManagementPostCode", split[0], split[1], false);
                alertFormValueList.add(alertFormValue);
            }
            if (item.getPositionType() != null) {
                String positionType = item.getPositionType();
                String[] split = positionType.split("@");
                DynamicFormInstance alertFormValue = new DynamicFormInstance(30L, OrgPersonEnum.人员.getCode(), "岗位类型",
                        "positionType", split[0], split[1], false);
                alertFormValueList.add(alertFormValue);
            }
            if (item.getCertificateType() != null) {
                String certificateType = item.getCertificateType();
                String[] split = certificateType.split("@");
                DynamicFormInstance alertFormValue = new DynamicFormInstance(31L, OrgPersonEnum.人员.getCode(), "持证类别",
                        "certificateType", split[0], split[1], false);
                alertFormValueList.add(alertFormValue);
            }
            if (item.getHoldingTime() != null) {
                DynamicFormInstance alertFormValue = new DynamicFormInstance(32L, OrgPersonEnum.人员.getCode(), "持证时间",
                        "holdingTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item.getHoldingTime()), null,
                        false);
                alertFormValueList.add(alertFormValue);
            }
            if (item.getAuditCycle() != null) {
                String auditCycle = item.getAuditCycle();
                String[] split = auditCycle.split("@");
                DynamicFormInstance alertFormValue = new DynamicFormInstance(33L, OrgPersonEnum.人员.getCode(), "审核周期",
                        "auditCycle", split[0], split[1], false);
                alertFormValueList.add(alertFormValue);
            }
            if (item.getPersonImg() != null) {
                DynamicFormInstance alertFormValue = new DynamicFormInstance(34L, OrgPersonEnum.人员.getCode(), "人员照片",
                        "personImg", item.getPersonImg(), null, false);
                alertFormValueList.add(alertFormValue);
            }
            if (item.getCertificateImg() != null) {
                DynamicFormInstance alertFormValue = new DynamicFormInstance(101L, OrgPersonEnum.人员.getCode(),
                        "重点工种资质证书", "certificateImg", item.getCertificateImg(), null, false);
                alertFormValueList.add(alertFormValue);
            }
            try {
                orgPersonDto.setDynamicFormValue(alertFormValueList);
                this.saveOrgPerson(orgPersonDto);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public List<OrgPersonExcelDto> queryOrgPersonDtoList(boolean isDelete) {

        List<OrgPersonExcelDto> excelOrgPersonDtoList = orgUsrMapper.queryOrgPersonDtoList(isDelete);

        return excelOrgPersonDtoList;
    }

    /**
     * 根据id查询当前单位下的所有子单位、部门
     *
     * @param orgUserId
     * @return
     */
    public List<OrgUsr> listOrgUserById(Long orgUserId) {
        return this.baseMapper.listOrgUserById(orgUserId);
    }

    public List<CompanyPerson> returnCompanyPerson(List<Long> ids) {
        if (ObjectUtils.isEmpty(ids)) {
            return null;
        }
        List<CompanyPerson> tempList = new ArrayList<CompanyPerson>();
        for (Long tempId : ids) {
            // BUG 2740 机场单位主键varchar 导致 通过主键搜索返回多条数据  2021 - 09 - 09by kongfm
            OrgUsr org = getById(tempId.toString());
            if (ObjectUtils.isEmpty(org)) {
                continue;
            }
            CompanyPerson company = new CompanyPerson();
            BeanUtils.copyProperties(org, company);
            company.setPersons(this.queryForListByParentIdAndOrgType(org.getSequenceNbr(), OrgPersonEnum.人员.getKey()));
            tempList.add(company);
        }
        return tempList;
    }

    // BUG 2736 人员导出过滤已经删除的数据by kongfm
    // 该方法使用时参数有问题 会有下标越界问题，现在更改为public List<OrgUsrDto> queryForListByParentIdAndOrgType(Long parentId, String bizOrgType) 2021-09-13 by kongfm
    public List<OrgUsrDto> queryForListByParentIdAndOrgType(Long parentId, String bizOrgType, Boolean isDelete) {
        return this.queryForList(null, false, parentId, bizOrgType, isDelete);
    }

    public List<OrgUsrDto> queryForListByParentIdAndOrgType(Long parentId, String bizOrgType) {
        // BUG 2843 过滤没有绑定关联账户的user by kongfm 2021-09-16
        List<OrgUsr> tempUserList = this.list(new LambdaQueryWrapper<OrgUsr>().eq(OrgUsr::getIsDelete, false).eq(OrgUsr::getParentId, parentId).eq(OrgUsr::getBizOrgType, bizOrgType).isNotNull(OrgUsr::getAmosOrgId));
        tempUserList.stream().forEach(m -> {
            if (StringUtils.isNotEmpty(m.getAmosOrgId())) {
                FeignClientResult<AgencyUserModel> result1 = Privilege.agencyUserClient.queryByUserId(m.getAmosOrgId());
                if (null != result1.getResult()) {
                    m.setAmosOrgCode(result1.getResult().getRealName());
                }
            }
        });
        return Bean.toModels(tempUserList, this.getModelClass());
    }

    public OrgUsrDto getOrg(String amosUserId) {
        OrgUsrDto person = queryForListByParentIdAndOrgType(amosUserId);
        if (ObjectUtils.isEmpty(person)) {
            return null;
        }
        return this.queryBySeq(Long.valueOf(person.getParentId()));
    }

    public String getParentId(String amosOrgId) {
        List<OrgUsrDto> orgUsrDtos = queryForList("", false, amosOrgId);
        String parentId = null;
        if (orgUsrDtos.size() >= 1) {
            parentId = orgUsrDtos.get(0).getParentId();
        } else {
            return null;
        }
        return parentId;
    }


    public OrgUsrDto queryForListByParentIdAndOrgType(String amosOrgId) {
        return this.queryModelByParams(amosOrgId);
    }

    @Override
    public List<OrgUsrzhDto> getOrgUsrzhDto(String name) {
        // TODO Auto-generated method stub
        List<OrgUsrzhDto> list = orgUsrMapper.getOrgUsrzhDto(name);
        return list;
    }

    @Override
    public List<ESOrgUsrDto> selectByIddata(String name) {
        //获取所有单位
        QueryWrapper<OrgUsr> wrapper = new QueryWrapper<>();

        wrapper.in("biz_org_type", "DEPARTMENT", "COMPANY");
        wrapper.eq("is_delete", 0);
        if (name != null && !"".equals(name)) {
            wrapper.like("biz_org_name", name);
        }

        List<OrgUsr> list = this.list(wrapper);
        List<ESOrgUsrDto> lidataDtos = new ArrayList();
        list.forEach(orgUsr -> {
            ESOrgUsrDto data = new ESOrgUsrDto();
            data.setSequenceNbr(orgUsr.getSequenceNbr());
            data.setBizOrgName(orgUsr.getBizOrgName());
            lidataDtos.add(data);
        });
        return lidataDtos;
    }

    @Override
    public List<Map<String, Object>> getparent() {
        return orgUsrMapper.getparent();
    }

    @Override
    public List<OrgUsrExcelDto> exportToExcel() {
        return orgUsrMapper.exportToExcel();
    }

    @Override
    public UserUnitDto getUserUnit(String userId) {
        if (StringUtils.isNotBlank(userId)) {
            String[] typeArr = TYPE.split(",");
            //	业主单位
            List<UserUnitDto> list = orgUsrMapper.getUserUnit(userId, typeArr[0], null);
            //     维保单位
            List<DynamicFormInstance> instanceList = alertFormValueServiceImpl.getInstanceByCodeAndValue(CODE, userId);
            if (!CollectionUtils.isEmpty(list) && !CollectionUtils.isEmpty(instanceList)) {
                throw new RuntimeException("人员绑定单位重复！");
            } else {
                if (!CollectionUtils.isEmpty(list)) {
                    if (list.size() == 1) {
                        UserUnitDto userUnitDto = list.get(0);
                        String codeVal = userUnitDto.getCompanyId().substring(0, 5);
                        if (StringUtils.isNotBlank(codeVal)) {
                            List<UserUnitDto> dtoList = orgUsrMapper.getUserUnit(null, typeArr[1], codeVal);
                            if (!CollectionUtils.isEmpty(dtoList)) {
                                UserUnitDto dto = dtoList.get(0);
                                userUnitDto.setCompanyId(dto.getPersonSeq());
                                userUnitDto.setCompanyName(dto.getPersonName());
                                return userUnitDto;
                            }
                        }
                        throw new RuntimeException("未获取人员业主单位！");
                    }
                    throw new RuntimeException("人员绑定业主单位不唯一！");
                } else {
                    if (!CollectionUtils.isEmpty(instanceList)) {
                        if (instanceList.size() == 1) {
                            Long instanceId = instanceList.get(0).getInstanceId();
                            List<MaintenanceCompany> maintenanceCompanyList = maintenanceCompanyService.findByInstanceIdAndType(instanceId, typeArr[0]);
                            if (!CollectionUtils.isEmpty(maintenanceCompanyList)) {
                                if (maintenanceCompanyList.size() == 1) {
                                    MaintenanceCompany person = maintenanceCompanyList.get(0);
                                    UserUnitDto unitDto = new UserUnitDto();
                                    unitDto.setIdentityType(UserUnitTypeEnum.MAINTENANCE_COMPANY.getValue());
                                    unitDto.setPersonSeq(String.valueOf(person.getSequenceNbr()));
                                    unitDto.setPersonName(person.getName());
                                    String codeVal = person.getCode().substring(0, 5);
                                    if (StringUtils.isNotBlank(codeVal)) {
                                        List<MaintenanceCompany> companyList = maintenanceCompanyService.findByCodeAndType(codeVal, typeArr[1]);
                                        if (!CollectionUtils.isEmpty(companyList)) {
                                            MaintenanceCompany company = companyList.get(0);
                                            unitDto.setCompanyId(String.valueOf(company.getSequenceNbr()));
                                            unitDto.setCompanyName(company.getName());
                                            return unitDto;
                                        }
                                    }
                                    throw new RuntimeException("未获取人员维保单位！");
                                }
                                throw new RuntimeException("人员绑定维保单位不唯一！");
                            }
                        }
                        throw new RuntimeException("人员绑定维保单位不唯一！");
                    }
                }
            }
            throw new RuntimeException("人员未绑定任何单位！");
        }
        throw new RuntimeException("参数必传且不为空！");
    }

    @Override
    public List<UserDto> getUserInfo(String userId) {
        List<UserDto> userDtoList = new ArrayList<>();
        if (StringUtils.isNotBlank(userId)) {
            String[] typeArr = TYPE.split(",");
            //	业主单位
            List<UserDto> list = orgUsrMapper.getUserInfo(userId, typeArr[0], null, FIELD_CODE.split(","));
            if (!CollectionUtils.isEmpty(list)) {
                if (list.size() == 1) {
                    userDtoList.addAll(list);
                    UserDto userDto = list.get(0);
                    String codeVal = userDto.getBizOrgCode().substring(0, 5);
                    if (StringUtils.isNotBlank(codeVal)) {
                        List<UserDto> dtoList = orgUsrMapper.getUserInfo(null, typeArr[1], codeVal, COMPANY_FIELD_CODE.split(","));
                        if (!CollectionUtils.isEmpty(dtoList)) {
                            userDtoList.addAll(dtoList);
                        }
                    }
                    return userDtoList;
                }
                throw new RuntimeException("人员绑定业主单位不唯一！");
            }
            throw new RuntimeException("人员未绑定任何单位！");
        }
        throw new RuntimeException("参数必传且不为空！");
    }


    public List<OrgUsr> getCompanyDetailTree() {
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<OrgUsr>();
        wrapper.eq(OrgUsr::getBizOrgType, "COMPANY");
        wrapper.eq(OrgUsr::getIsDelete, false);
        return this.baseMapper.selectList(wrapper);
    }

    @Override
    public List<OrgMenuDto> companyUserTreeByUser(AgencyUserModel user) {
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<OrgUsr>();
        wrapper.eq(OrgUsr::getIsDelete, false);
        List<OrgUsr> companyDepartmentMsgList = this.baseMapper.selectList(wrapper);
        return gettTreeByUser(user, companyDepartmentMsgList);
    }

    @Override
    public List<OrgMenuDto> companyTreeByUser(AgencyUserModel user) {
        List<OrgUsr> companyDepartmentMsgList = selectCompanyDepartmentMsg();
        return gettTreeByUser(user, companyDepartmentMsgList);
    }

    ;

    @Override
    public List<CheckObjectDto> companyListByUser(AgencyUserModel user) {
        List<CheckObjectDto> list = new ArrayList<>();
        // 需要角色为机场单位或管理员，其余角色返回空
        String code = UserRolesEnum.AIRPORTUNIT.getCode();
        String codeAdmin = UserRolesEnum.ADMIN.getCode();
        String roles = getRoles(user, code);

        if (!StringUtils.isEmpty(roles)) {
            List<CheckObjectDto> companyList = this.baseMapper.getCompanyAndKeySite(null);
            if (roles.equals(codeAdmin)) {
                // 返回全部单位列表
                return companyAndKeySiteList(companyList);
            } else if (roles.equals(code)) {
//			} else  {
                // 人员与多个部门/公司关联
                List<OrgUsr> orgUsrList = orgUsrList(user);
                if (ObjectUtils.isEmpty(orgUsrList)) {
                    return list;
                }
                Set<Long> set = new HashSet<>();
                orgUsrList.forEach(orgUsr -> {
                    if (!StringUtils.isEmpty(orgUsr.getParentId())) {
                        Long parent = Long.parseLong(orgUsr.getParentId());
                        if (set.add(parent)) {
                            Long companyIdByDto = getCompanyIdByDto(parent, companyList);
                            List<CheckObjectDto> orgUsrTreeDtoList = this.baseMapper.getCompanyAndKeySite(companyIdByDto);
                            list.addAll(companyAndKeySiteList(orgUsrTreeDtoList));
                        }
                    }
                });
                // 返回所在用户单位列表
                return list.stream().distinct().collect(Collectors.toList());
            }
        }
        return list;
    }

    /**
     * 获取登陆人所在公司
     */
    private Long getCompanyIdByDto(Long parentId, List<CheckObjectDto> companyDepartmentMsgList) {
        Long pid = null;
        for (CheckObjectDto orgUsr : companyDepartmentMsgList) {
            if (orgUsr.getSequenceNbr().equals(parentId)) {
                if (orgUsr.getBizOrgType().equals(OrgPersonEnum.公司.getKey()) && ObjectUtils.isEmpty(orgUsr.getParentId())) {
                    return orgUsr.getSequenceNbr();
                } else {
                    if (!StringUtils.isEmpty(orgUsr.getParentId())) {
                        pid = getCompanyIdByDto(Long.parseLong(orgUsr.getParentId()), companyDepartmentMsgList);
                    }
                }
            }
        }
        return pid;
    }

    /**
     * 查询单位列表
     */
    private List<CheckObjectDto> companyAndKeySiteList(List<CheckObjectDto> companyList) {
        List<CheckObjectDto> list = new ArrayList<>();
        if (ObjectUtils.isEmpty(companyList)) {
            return list;
        }
        Map<Long, CheckObjectDto> map = new HashMap<>(companyList.size());
        companyList.forEach(e -> map.put(e.getSequenceNbr(), e));
        Set<? extends Map.Entry<Long, ? extends CheckObjectDto>> entries = map.entrySet();
        entries.parallelStream().forEach(entry -> {
            CheckObjectDto value = entry.getValue();
            if (!ObjectUtils.isEmpty(value)) {
                Long parent = ObjectUtils.isEmpty(value.getParentId()) ? 0L : Long.parseLong(value.getParentId());
                CheckObjectDto orgUsrTreeDto = map.get(parent);
                if (!ObjectUtils.isEmpty(orgUsrTreeDto)) {
                    int num = orgUsrTreeDto.getNum() + value.getNum();
                    orgUsrTreeDto.setNum(num);
                } else {
                    if (value.getBizOrgType().equals(OrgPersonEnum.公司.getKey())) {
                        list.add(value);
                    }
                }
            }
        });
        return list;
    }

    /**
     * 获取树
     */
    private List<OrgMenuDto> gettTreeByUser(AgencyUserModel user, List<OrgUsr> list) {
        List<OrgMenuDto> treeList = new ArrayList<>();
        // 需要角色为机场单位或管理员，其余角色返回空
        String code = UserRolesEnum.AIRPORTUNIT.getCode();
        String codeAdmin = UserRolesEnum.ADMIN.getCode();
        String roles = getRoles(user, code);
        if (!StringUtils.isEmpty(roles)) {
//			treeList = getDepartmentTreeByUser(user,list);
            if (roles.equals(codeAdmin)) {
                // 返回全量树
                treeList = buildTreeParallel(list);
            } else if (roles.equals(code)) {
                // 获取当前用户所在部门树
                treeList = getDepartmentTreeByUser(user, list);
            }
        }
        return treeList;
    }

    /**
     * 根基登陆人获取指定角色/最高角色,默认最高角色
     */
    private String getRoles(AgencyUserModel user, String code) {
        String type = null;
        Map<Long, List<RoleModel>> orgRolesMap = user.getOrgRoles();
        if (ObjectUtils.isEmpty(orgRolesMap)) {
            return null;
        }
        for (Long key : orgRolesMap.keySet()) {
            if (!ObjectUtils.isEmpty(orgRolesMap.get(key))) {
                for (RoleModel roleModel : orgRolesMap.get(key)) {
                    String roleType = roleModel.getRoleType();
                    if (roleType.equals(code)) {
                        type = code;
                    }
                    if (roleType.equals(UserRolesEnum.ADMIN.getCode())) {
                        return roleType;
                    }
                }
            }
        }
        return type;
    }

    /**
     * 获取当前用户所在部门/用户树
     */
    private List<OrgMenuDto> getDepartmentTreeByUser(AgencyUserModel user, List<OrgUsr> companyDepartmentMsgList) {

        List<OrgMenuDto> list = new ArrayList<>();
        if (ObjectUtils.isEmpty(companyDepartmentMsgList)) {
            return list;
        }

        // 1.获取当前登陆用户关联人员
        List<OrgUsr> orgUsrList = orgUsrList(user);
        if (ObjectUtils.isEmpty(orgUsrList)) {
            return list;
        }

        // 2.查询人员所属部门
        List<OrgMenuDto> treeList = buildTreeParallel(companyDepartmentMsgList);
        Set<Long> set = new HashSet<>();
        orgUsrList.forEach(orgUsr -> {
            if (!StringUtils.isEmpty(orgUsr.getParentId())) {
                Long parentId = Long.parseLong(orgUsr.getParentId());
                getTreeChildre(list, treeList, parentId, set, companyDepartmentMsgList);
            }
        });
        return list;
    }

    /**
     * 获取登陆人关联账号
     */
    private List<OrgUsr> orgUsrList(AgencyUserModel user) {
        String userId = user.getUserId();
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr::getIsDelete, false);
        wrapper.eq(OrgUsr::getAmosOrgId, userId);
        wrapper.eq(OrgUsr::getBizOrgType, OrgPersonEnum.人员.getKey());
        List<OrgUsr> orgUsrList = this.baseMapper.selectList(wrapper);
        return orgUsrList;
    }

    /**
     * 组装树
     */
    private void getTreeChildre(List<OrgMenuDto> list, List<OrgMenuDto> treeList, Long parentId, Set<Long> set, List<OrgUsr> companyDepartmentMsgList) {
        if (ObjectUtils.isEmpty(treeList) && ObjectUtils.isEmpty(companyDepartmentMsgList)) {
            return;
        }

        // 获取登陆人所在公司
        Long pid = getCompanyId(parentId, companyDepartmentMsgList);
        if (set.add(pid)) {
            List<OrgMenuDto> list1 = treeList.stream().filter(orgMenuDto -> !ObjectUtils.isEmpty(orgMenuDto) && pid.equals(orgMenuDto.getKey())).collect(Collectors.toList());
            list.addAll(list1);
        }
    }

    /**
     * 获取登陆人所在公司
     */
    private Long getCompanyId(Long parentId, List<OrgUsr> companyDepartmentMsgList) {
        Long pid = null;
        for (OrgUsr orgUsr : companyDepartmentMsgList) {
            if (orgUsr.getSequenceNbr().equals(parentId)) {
                if (orgUsr.getBizOrgType().equals(OrgPersonEnum.公司.getKey()) && ObjectUtils.isEmpty(orgUsr.getParentId())) {
                    return orgUsr.getSequenceNbr();
                } else {
                    if (!StringUtils.isEmpty(orgUsr.getParentId())) {
                        pid = getCompanyId(Long.parseLong(orgUsr.getParentId()), companyDepartmentMsgList);
                    }
                }
            }
        }
        return pid;
    }

    /**
     * 查询组织机构下面的人员信息
     *
     * @param id
     * @return
     */
    public List<OrgUsr> getPersonListByParentId(Long id) {
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<OrgUsr>();
        wrapper.eq(OrgUsr::getIsDelete, false);
        wrapper.eq(OrgUsr::getParentId, id);
        wrapper.eq(OrgUsr::getBizOrgType, OrgPersonEnum.人员.getKey());
        return this.baseMapper.selectList(wrapper);
    }

    @Override
    public List<OrgUsrExcelDto> exportPersonToExcelByParentId(Long parentId) {
        return orgUsrMapper.exportPersonToExcelByParentId(parentId);
    }


    @Override
    public List<Map<String, Object>> getLoginUserDetails(String userId, AgencyUserModel user) {

        // 获取登陆人关联账号
        List<OrgUsr> orgUsrs = getUsrList(userId);
        List<Map<String, Object>> list = new ArrayList<>();
        if (!ObjectUtils.isEmpty(orgUsrs)) {
            orgUsrs.forEach(orgUsr -> {
                Map<String, Object> map = new HashMap<>();
                map.put(OrgPersonEnum.人员.getKey(), orgUsr);
                // 获取关联账号所在部门/公司
                LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(OrgUsr::getIsDelete, false);
                wrapper.eq(BaseEntity::getSequenceNbr, orgUsr.getParentId());
                OrgUsr one = this.getOne(wrapper);
                map.put(OrgPersonEnum.部门.getKey(), one);
                map.put("AMOSUSER", user);
                list.add(map);
            });

        }
        return list;
    }

    /**
     * 获取登陆人关联账号
     */
    private List<OrgUsr> getUsrList(String userId) {
        // 获取登陆人角色
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr::getIsDelete, false);
        wrapper.eq(OrgUsr::getAmosOrgId, userId);
        wrapper.eq(OrgUsr::getBizOrgType, OrgPersonEnum.人员.getKey());
        List<OrgUsr> orgUsrList = this.baseMapper.selectList(wrapper);
        return orgUsrList;
    }

    /**
     * 重写getByid 方法 因为前期沟通 人员code 可能会发生改变 所以 现在接口code 不再保存，查询数据时通过接口重新赋值 by kongfm 2021-09-16
     *
     * @param id
     * @return
     */
    @Override
    public OrgUsr getById(Serializable id) {
        OrgUsr orgUser = this.baseMapper.selectById(id);
        // BUG2886 因为前期沟通 人员code 可能会发生改变 所以 现在接口code 不再保存，查询数据时通过接口重新赋值 by kongfm 2021-09-16
        if (orgUser != null && StringUtils.isNotEmpty(orgUser.getAmosOrgId())) {
            FeignClientResult<AgencyUserModel> result1 = Privilege.agencyUserClient.queryByUserId(orgUser.getAmosOrgId());
            if (null != result1.getResult()) {
                orgUser.setAmosOrgCode(result1.getResult().getRealName());
            }
        }
        return orgUser;
    }
    public Object amosIdExist(String amosId){
        List<OrgUsr> orgUsrs = orgUsrMapper.amosIdExist(amosId);
        if (orgUsrs.size() > 0){
            return false;
        }
        return true;
    }

}


	