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

import ch.qos.logback.core.net.SyslogOutputStream;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
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.interceptors.PermissionInterceptorContext;
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.feign.AmosTrainingFeignClient;
import com.yeejoin.amos.boot.module.common.api.mapper.DynamicFormInstanceMapper;
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 freemarker.core.ReturnInstruction.Return;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import javax.annotation.Resource;

import static org.hamcrest.CoreMatchers.nullValue;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

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

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

	private final Logger logger = LoggerFactory.getLogger(OrgUsrServiceImpl.class);

	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";
	private static final String COMPANY_VALUE = "COMPANY";

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

	@Autowired
	DynamicFormInstanceMapper dynamicFormInstanceMapper;

	@Autowired
	AmosTrainingFeignClient amosTrainingFeignClient;

	@Value("${auth-key-org-user:org_user_info}")
	private String authKey;

	@Autowired
	OrgUsrServiceImpl iOrgUsrService;

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

		List<OrgMenuDto> menuList = list.stream()
				.map(o -> new OrgMenuDto(o.getSequenceNbr(), o.getBizOrgName(),
						ObjectUtils.isEmpty(o.getParentId()) ? 0L : Long.parseLong(o.getParentId()), o.getBizOrgType(),
						false, o.getBizOrgCode()).setTotal(o.getTotal()))
				.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.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;
	}

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

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

	@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"));
		}
		if (req!=null&&req.containsKey("company") && !ObjectUtils.isEmpty(req.get("company"))) {
			req.put("company", req.get("company"));
		}

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

		// 新加
		if (!ObjectUtils.isEmpty(req)&&req.containsKey("OrgCode") && req.get("OrgCode") != null && !req.get("OrgCode").equals("")) {
			map.put("bizOrgCode", req.get("OrgCode"));
			req.remove("OrgCode");
		}

		/* BUG2680 查询部门人员错误 传递参数类型不正确 修改为string 2021-09-14 陈召 开始 */
		if (!req.isEmpty()&&req.containsKey("amosOrgId") && !ObjectUtils.isEmpty(req.get("amosOrgId"))) {
			map.put("amosOrgCode", req.get("amosOrgId"));// 当时给前端给的key名字错了，以为是传Id过来，现在传名字，那就将错就错吧
		}

		req.remove("bizOrgName");
		req.remove("pageSize");
		req.remove("pageNum");
		req.remove("parentId");
		req.remove("amosOrgId");
		req.remove("company");
		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());
				}
				String chargePersonId = iOrgUsrService.getIdNumberByAmosId(t.get("amosOrgId").toString());
				t.put("chargePersonId", chargePersonId);
			} else {
				t.put("chargePersonId", null);
			}

		});
		/* 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 OrgUsrDto saveOrgUsrDynamicFormInstance(OrgUsr orgUsr, List<DynamicFormInstance> alertFromValuelist) {
		orgUsr.setRecDate(new Date());
		AgencyUserModel user = Privilege.agencyUserClient.getme().getResult();
		orgUsr.setRecUserName(user.getRealName());
		orgUsr.setRecUserId(user.getUserId());
		OrgUsrDto orgUsrDto = new OrgUsrDto();
		BeanUtils.copyProperties(orgUsr, orgUsrDto);
		// 单位新增情况
		OrgUsrDto model = createWithModel(orgUsrDto);
		// save(orgUsr);
		// 填充主键
		alertFromValuelist.stream().forEach(alertFromValue -> {
			if (OrgPersonEnum.公司.getKey().equals(orgUsrDto.getBizOrgType())) {
				alertFromValue.setGroupCode(OrgPersonEnum.公司.getCode());
			} else if (OrgPersonEnum.部门.getKey().equals(orgUsrDto.getBizOrgType())) {
				alertFromValue.setGroupCode(OrgPersonEnum.部门.getCode());
			}
			alertFromValue.setInstanceId(orgUsrDto.getSequenceNbr());
		});
		// 保存动态表单数据
		alertFormValueServiceImpl.saveBatch(alertFromValuelist);
		model.setDynamicFormValue(alertFromValuelist);
		return model;
	}

	@Override
	public void updateDynamicFormInstance(Long instanceId, List<DynamicFormInstance> fromValueList) {
		if (ValidationUtil.isEmpty(fromValueList)) {
			return;
		}
		// 填充主键
		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.forEach(form -> {
			resourceMap.put(form.getFormColumnId(), form);
		});

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

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

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

		resourceMap.keySet().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 Map<String, Object> selectForShowByIduser(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<>();
		result = Bean.BeantoMap(orgUsr);
		// 放入所有动态表单数据
		for (DynamicFormColumn alertForm : alertForms) {
			result.put(alertForm.getFieldCode(), null);
		}

		result.put("parenName", orgUsr.getParentId() != null ? getByIduser(orgUsr.getParentId()).getBizOrgName() : "");

		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 OrgUsrDto 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());
		}
		OrgUsrDto orgUsrDto = saveOrgUsrDynamicFormInstance(orgUsr, OrgUsrVo.getDynamicFormValue());
		orgUsr.setSequenceNbr(orgUsrDto.getSequenceNbr());
		/**
		 * 同步保存ES
		 */
		eSOrgUsrService.saveAlertCalledToES(orgUsr);

		syncCompany2Supervision(Lists.newArrayList(orgUsrDto.getSequenceNbr()));
		return orgUsrDto;
	}

	@Override
	public OrgUsrDto 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());
		}

		return 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());
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public OrgUsrDto updateByIdOrgUsr(OrgUsrDto orgUsrVo, Long id) throws Exception {
		// 修改单位信息
		OrgUsr orgUsr = new OrgUsr();
		OrgUsr oriOrgUsr = getById(id);
		BeanUtils.copyProperties(orgUsrVo, orgUsr);
		// 判断是否修改所属单位
		if (!(oriOrgUsr.getParentId() != null ? oriOrgUsr.getParentId() : "").equals(orgUsrVo.getParentId())) {

			/* 单位编辑后 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 陈召 结束  */8888
			orgUsrMapper.updatelistByParentId(orgUsr.getBizOrgCode(), oriOrgUsr.getBizOrgCode());
		}
		updateById(orgUsr);

		// saveOrgUsr(orgUsr, oriOrgUsr);

		// 保存动态表单数据
		updateDynamicFormInstance(orgUsr.getSequenceNbr(), orgUsrVo.getDynamicFormValue());
		/**
		 * 同步保存ES
		 */
		eSOrgUsrService.saveAlertCalledToES(orgUsr);
		orgUsrVo.setBizOrgCode(orgUsr.getBizOrgCode());

		syncCompany2Supervision(Lists.newArrayList(orgUsr.getSequenceNbr()));
		return orgUsrVo;
	}

	@Override
	public OrgPersonDto updateByIdOrgPerson(OrgPersonDto OrgPersonVo, Long id) throws Exception {
		try {
			updatePersonNumber(id, OrgPersonVo);
		} catch (Exception e) {
			logger.info("同步修改培训计划中的人员编号：---------------" + id);
		}
		// 修改人员信息
		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());
		if (orgUsr.getBizOrgCode() != null) {
			OrgPersonVo.setBizOrgCode(orgUsr.getBizOrgCode());
		}
		return OrgPersonVo;
	}

	void updatePersonNumber(Long id, OrgPersonDto OrgPersonVo) {
		String oldNumber = null;
		String newNumber = null;
		List<DynamicFormInstanceDto> list = alertFormValueServiceImpl.listByCalledId(id);
		for (DynamicFormInstanceDto dynamicFormInstanceDto : list) {
			if (dynamicFormInstanceDto.getFieldCode().equals("personNumber")) {
				oldNumber = dynamicFormInstanceDto.getFieldValue();
			}
		}
		for (DynamicFormInstance dynamicForm : OrgPersonVo.getDynamicFormValue()) {
			if (dynamicForm.getFieldCode().equals("personNumber")) {
				newNumber = dynamicForm.getFieldValue();
			}
		}
		amosTrainingFeignClient.updOperationNumber(newNumber, oldNumber);
	}

	@Override
	public OrgUsrFormDto selectCompanyById(Long id) throws Exception {
		OrgUsr orgUsr = getById(id);

		// 动态表单数据
		List<FormValue> formValue = getFormValue(id);
		// bug 2580 返回值改为具体名称 chenzhao 2021-09-27 start
		// bug 2797 前端要求先改回code值。
		/*
		 * 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);
		Map<String, String> Xfaq = orgUsrMapper.selectPersonone("消防安全负责人", id);
		Map<String, String> Xfgl = orgUsrMapper.selectPersonone("消防安全管理人", id);
		Map<String, String> Dwfz = orgUsrMapper.selectPersonone("法定代表人", id);
		orgUsrFormVo.setXfaq(Xfaq != null ? Xfaq.get("name") : "");
		orgUsrFormVo.setXfgl(Xfgl != null ? Xfgl.get("name") : "");
		orgUsrFormVo.setDwfz(Dwfz != null ? Dwfz.get("name") : "");
		if (orgUsr.getParentId() != null) {
			orgUsrFormVo.setParentName(getById(orgUsr.getParentId()).getBizOrgName());
		}
		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) {
		List<Long> companyIdList = Lists.newArrayList();
		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);
			OrgUsrDto orgUsrDto = saveOrgUsrDynamicFormInstance(orgUsr, OrgUsrVo.get(i).getDynamicFormValue());
			companyIdList.add(orgUsrDto.getSequenceNbr());
		}
		syncCompany2Supervision(companyIdList);
	}

	@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 OrgUsrDto 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());
		}
		return saveOrgUsrDynamicFormInstance(orgUsr, OrgDepartmentVo.getDynamicFormValue());
	}

	@Override
	public OrgDepartmentDto 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 陈召 结束 */
		orgUsrMapper.updatelistByParentId(orgUsr.getBizOrgCode(), oriOrgUsr.getBizOrgCode());
//        saveOrgUsr(orgUsr, oriOrgUsr);
		// 保存动态表单数据

		updateById(orgUsr);
		updateDynamicFormInstance(orgUsr.getSequenceNbr(), OrgDepartmentVo.getDynamicFormValue());
		OrgDepartmentVo.setBizOrgCode(orgUsr.getBizOrgCode());
		return OrgDepartmentVo;
	}

	@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<Map<String, Object>> selectForShowByListIdUser(List<Long> ids) throws Exception {
		List<Map<String, Object>> personResult = new ArrayList<>();
		for (int i = 0; i < ids.size(); i++) {
			OrgUsr orgUsr = getByIduser(ids.get(i));
			Map<String, Object> result = selectForShowByIduser(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 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) {
		LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(BaseEntity::getIsDelete, false);
		wrapper.eq(OrgUsr::getAmosOrgId, amosOrgId);
		List<OrgUsr> orgUsrs = orgUsrMapper.selectList(wrapper);

		String parentId = null;
		if (orgUsrs.size() >= 1) {
			parentId = orgUsrs.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(Map par) {
		String parentId = par.containsKey("parentId") ? par.get("parentId").toString() : null;
		String bizOrgCode = par.containsKey("bizOrgCode") ? par.get("bizOrgCode").toString() : null;
		String internalPositionCode = par.containsKey("internalPositionCode")
				? par.get("internalPositionCode").toString()
				: null;
		String positionType = par.containsKey("positionType") ? par.get("positionType").toString() : null;
		return orgUsrMapper.exportToExcel(parentId, bizOrgCode, internalPositionCode, positionType);
	}

	@Override
	public UserUnitDto getUserUnit(String userId) {
		String[] typeArr = TYPE.split(",");
		// 业主单位人员
		List<UserUnitDto> list = orgUsrMapper.getUserUnit(userId, typeArr[0], null);
		// 维保单位人员
		List<MaintenanceCompany> maintenancePersons = maintenanceCompanyService.findPersonByAmosOrgId(typeArr[0],
				userId);
		if (!CollectionUtils.isEmpty(list) && !CollectionUtils.isEmpty(maintenancePersons)) {
			throw new RuntimeException("人员绑定单位重复！");
		}
		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("人员绑定业主单位不唯一！");
		}
		if (!CollectionUtils.isEmpty(maintenancePersons)) {
			if (maintenancePersons.size() == 1) {
				MaintenanceCompany person = maintenancePersons.get(0);
				MaintenanceCompany maintenanceCompany = maintenanceCompanyService.getOne(person.getParentId());
				UserUnitDto unitDto = new UserUnitDto();
				unitDto.setIdentityType(UserUnitTypeEnum.MAINTENANCE_COMPANY.getValue());
				unitDto.setPersonSeq(String.valueOf(person.getSequenceNbr()));
				unitDto.setPersonName(person.getName());
				unitDto.setCompanyId(String.valueOf(maintenanceCompany.getSequenceNbr()));
				unitDto.setCompanyName(maintenanceCompany.getName());
				return unitDto;
			}
			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<OrgMenuDto> companyTreeByUserAndType(ReginParams reginParams, String type) {
		Map<String, Object> param = new HashMap<>();
		param.put("bizOrgCode", reginParams.getPersonIdentity().getBizOrgCode());
		param.put("type", type);
		List<OrgUsr> list = orgUsrMapper.companyTreeByUserAndType(param);
		return buildTreeParallel(list);
	}

	@Override
	public List<OrgUsr> companyTreeByUserAndTypeNoTree(ReginParams reginParams, String type) {
		Map<String, Object> param = new HashMap<>();
		param.put("bizOrgCode", reginParams.getPersonIdentity().getBizOrgCode());
		param.put("type", type);
		List<OrgUsr> list = orgUsrMapper.companyTreeByUserAndType(param);
		return list;
	}

	public List<OrgUsr> equipCompanyExport(ReginParams reginParams, String type) {

		List<OrgUsr> list = orgUsrMapper.equipCompanyExport(reginParams.getPersonIdentity().getBizOrgCode());
		/*LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(BaseEntity::getIsDelete,0);
		wrapper.likeRight(OrgUsr::getBizOrgCode,reginParams.getPersonIdentity().getBizOrgCode());
		wrapper.eq(OrgUsr::getBizOrgType,"DEPARTMENT").or().eq(OrgUsr::getBizOrgType,"COMPANY");
		List<OrgUsr> list = baseMapper.selectList(wrapper);*/
		return list;
	}

	@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())
						&& orgUsr.getBizOrgCode().length() == TreeParser.CODE_LENGTH * 2) {// 树节点一级单位
					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.stream().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);
				}
				System.out.println(value.getSequenceNbr()+"---------------------------------------");
				// 只查出一级单位，顶级为西部机场集团
				if (value.getBizOrgCode() !=null && value.getBizOrgType().equals(OrgPersonEnum.公司.getKey())
						&& value.getBizOrgCode().length() == TreeParser.CODE_LENGTH * 2) {
					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
	 */
	@Override
	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);
	}

	/**
	 * 查询组织机构下面的人员信息
	 *
	 * @param id
	 * @return
	 */
	@Override
	public List<OrgUsr> getPersonListByParentIds(List<String> ids) {
		LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<OrgUsr>();
		wrapper.eq(OrgUsr::getIsDelete, false);
		wrapper.in(OrgUsr::getParentId, ids);
		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 OrgUsr getByIduser(Serializable id) {
		OrgUsr orgUser = this.baseMapper.selectById(id);
		return orgUser;
	}

	public Object amosIdExist(String amosId) {
		int num = orgUsrMapper.amosIdExist(amosId);
		if (num > 0) {
			return false;
		}
		return true;
	}

	public Object amosIdExistTeam(String amosId) {
		int num = orgUsrMapper.amosIdExistTeam(amosId);
		if (num > 0) {
			return false;
		}
		return true;
	}

	/**
	 * 获取对应公司组下面的人员信息
	 *
	 * @param ids
	 * @return
	 */
	@Override
	/*
	 * public List<Map<String, Object>> getPersonDetailByCompanyIds(List<String>
	 * ids) {
	 * 
	 * List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	 * LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<OrgUsr>();
	 * wrapper.eq(OrgUsr::getIsDelete, false); wrapper.eq(OrgUsr::getBizOrgType,
	 * OrgPersonEnum.人员.getKey()); wrapper.in(OrgUsr::getParentId, ids);
	 * List<OrgUsr> orgPersonList = this.baseMapper.selectList(wrapper);
	 * 
	 * List<String> fireStationSimpleList = new ArrayList<String>();
	 * ids.forEach(id-> { List<Map<String, Object>> maps = fireStationServiceImpl
	 * .queryForFireStationListByCompanyId(Long.parseLong(id));
	 * maps.stream().forEach(i -> { String tagertString = i.get("name").toString() +
	 * "@" + i.get("sequence_nbr").toString();
	 * fireStationSimpleList.add(tagertString); }); });
	 * 
	 * for (OrgUsr orgUsr : orgPersonList) { Map<String, Object> map = new
	 * HashMap<String, Object>(); List<DynamicFormInstanceDto> dyList =
	 * alertFormValueServiceImpl.queryByCalledId(orgUsr.getSequenceNbr()); if
	 * (ObjectUtils.isEmpty(dyList)) { continue; } for (DynamicFormInstanceDto dto :
	 * dyList) { if ("positionType".equals(dto.getFieldCode())) {
	 * map.put("postType", dto.getFieldValue()); map.put("postTypeName",
	 * dto.getFieldValueLabel()); break; } } if (!map.containsKey("postType") ||
	 * map.get("postType") == null ||
	 * StringUtils.isBlank(map.get("postType").toString())) { continue; }
	 * map.put("userName", orgUsr.getBizOrgName()); map.put("userId",
	 * orgUsr.getSequenceNbr().toString()); LambdaQueryWrapper<OrgUsr> wrapper1 =
	 * new LambdaQueryWrapper<OrgUsr>(); wrapper1.eq(OrgUsr::getIsDelete, false);
	 * wrapper1.eq(OrgUsr::getBizOrgType, OrgPersonEnum.公司.getKey());
	 * wrapper1.eq(OrgUsr::getSequenceNbr, Long.parseLong(orgUsr.getParentId()));
	 * OrgUsr orgCompany = this.baseMapper.selectOne(wrapper1); if
	 * (ObjectUtils.isEmpty(orgCompany)) { continue; } map.put("teamName",
	 * orgCompany.getBizOrgName()); map.put("teamId",
	 * orgCompany.getSequenceNbr().toString()); List<Map<String, Object>>
	 * fireStationList = fireStationServiceImpl
	 * .queryForFireStationListByCompanyId(Long.parseLong(orgUsr.getParentId())); if
	 * (ObjectUtils.isEmpty(fireStationList)) { continue; } if
	 * (!map.containsKey("fireStation")){ map.put("fireStation",
	 * fireStationSimpleList); } list.add(map); } return list; }
	 */

	public List<Map<String, Object>> getPersonDetailByCompanyIds(List<String> ids) {

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<OrgUsr>();
		wrapper.eq(OrgUsr::getIsDelete, false);
		wrapper.eq(OrgUsr::getBizOrgType, OrgPersonEnum.人员.getKey());
		wrapper.in(OrgUsr::getParentId, ids);
		List<OrgUsr> orgPersonList = this.baseMapper.selectList(wrapper);

		List<String> fireStationSimpleList = new ArrayList<String>();
		ids.forEach(id -> {
			List<Map<String, Object>> maps = fireStationServiceImpl
					.queryForFireStationListByCompanyId(Long.parseLong(id));
			maps.stream().forEach(i -> {
				String tagertString = i.get("name").toString() + "@" + i.get("sequence_nbr").toString();
				fireStationSimpleList.add(tagertString);
			});
		});

		for (OrgUsr orgUsr : orgPersonList) {
			Map<String, Object> map = new HashMap<String, Object>();
			List<DynamicFormInstanceDto> dyList = alertFormValueServiceImpl.queryByCalledId(orgUsr.getSequenceNbr());
			if (ObjectUtils.isEmpty(dyList)) {
				continue;
			}
			for (DynamicFormInstanceDto dto : dyList) {
				if ("positionType".equals(dto.getFieldCode())) {
					map.put("postType", dto.getFieldValue());
					map.put("postTypeName", dto.getFieldValueLabel());
					break;
				}
			}
			if (!map.containsKey("postType") || map.get("postType") == null
					|| StringUtils.isBlank(map.get("postType").toString())) {
				continue;
			}
			map.put("userName", orgUsr.getBizOrgName());
			map.put("userId", orgUsr.getSequenceNbr().toString());
			LambdaQueryWrapper<OrgUsr> wrapper1 = new LambdaQueryWrapper<OrgUsr>();
			wrapper1.eq(OrgUsr::getIsDelete, false);
			wrapper1.in(OrgUsr::getBizOrgType, OrgPersonEnum.公司.getKey(), OrgPersonEnum.部门.getKey());
			wrapper1.eq(OrgUsr::getSequenceNbr, Long.parseLong(orgUsr.getParentId()));
			OrgUsr orgCompany = this.baseMapper.selectOne(wrapper1);
			if (ObjectUtils.isEmpty(orgCompany)) {
				continue;
			}
			map.put("teamName", orgCompany.getBizOrgName());
			map.put("teamId", orgCompany.getSequenceNbr().toString());

			if (!map.containsKey("fireStation")) {
				map.put("fireStation", fireStationSimpleList);
			}
			list.add(map);
		}
		return list;
	}

	@Override
	public List<OrgUsr> selectCompanyUsers(Long orgUnitId) {
		OrgUsr orgUsr = this.getById(orgUnitId);
		if (null == orgUnitId) {
			return null;
		}
		LambdaQueryWrapper<OrgUsr> queryWrapper = new LambdaQueryWrapper();
		queryWrapper.like(OrgUsr::getBizOrgCode, orgUsr.getBizOrgCode());
		queryWrapper.eq(OrgUsr::getBizOrgType, CommonConstant.BIZ_ORG_TYPE_PERSON);
		queryWrapper.eq(OrgUsr::getIsDelete, false);
		List<OrgUsr> list = this.list(queryWrapper);
		return list;
	}

	@Override
	public OrgUsr selectByAmosOrgId(Long id) {

		QueryWrapper<OrgUsr> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("amos_org_id", id);
		OrgUsr orgUsr = orgUsrMapper.selectOne(queryWrapper);

		return orgUsr;
	}

	@Override
	public AgencyUserModel getAmosIdByOrgUserId(String orgUserId) throws Exception {
		OrgUsr orgUsr = this.baseMapper
				.selectOne(new LambdaQueryWrapper<OrgUsr>().eq(OrgUsr::getSequenceNbr, orgUserId));
		if (ValidationUtil.isEmpty(orgUsr)) {
			throw new Exception("账号不存在");
		}
		AgencyUserModel amosUser = Privilege.agencyUserClient.queryByUserId(orgUsr.getAmosOrgId()).getResult();
		if (ValidationUtil.isEmpty(amosUser)) {
			throw new Exception("账号不存在");
		}
		return amosUser;
	}

	@Override
	public List<String> getAmosIdListByOrgUserId(String orgUserIds) throws Exception {
		if (ValidationUtil.isEmpty(orgUserIds)) {
			throw new Exception("账号不存在");
		}
		List<String> orgUserIdList = Lists.newArrayList(orgUserIds.split(","));
		List<OrgUsr> orgUsrList = this.baseMapper
				.selectList(new LambdaQueryWrapper<OrgUsr>().in(OrgUsr::getSequenceNbr, orgUserIdList));
		if (ValidationUtil.isEmpty(orgUsrList)) {
			throw new Exception("账号不存在");
		}
		List<AgencyUserModel> amosUserList = Privilege.agencyUserClient.queryByIds(
				Joiner.on(",").join(orgUsrList.stream().map(OrgUsr::getAmosOrgId).collect(Collectors.toList())), false)
				.getResult();
		if (ValidationUtil.isEmpty(amosUserList)) {
			throw new Exception("账号不存在");
		}

		return amosUserList.stream().map(AgencyUserModel::getUserId).collect(Collectors.toList());
	}

	@Override
	public List<OrgUsrFormDto> getUnSyncOrgCompanyList(List<Long> companyIdList) {
		LambdaQueryWrapper<OrgUsr> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.notIn(OrgUsr::getSequenceNbr, companyIdList).eq(OrgUsr::getIsDelete, false)
				.eq(OrgUsr::getBizOrgType, "COMPANY");
		List<OrgUsr> unSyncCompanyList = this.baseMapper.selectList(queryWrapper);
		List<OrgUsrFormDto> allUnSyncCompanyList = Lists.newArrayList();
		if (!ValidationUtil.isEmpty(unSyncCompanyList)) {
			unSyncCompanyList.forEach(company -> {
				try {
					OrgUsrFormDto orgUsrFormDto = this.selectCompanyById(company.getSequenceNbr());
					allUnSyncCompanyList.add(orgUsrFormDto);
				} catch (Exception e) {
					logger.info(e.getMessage());
				}
			});
		}
		return allUnSyncCompanyList;
	}

	@Override
	public OrgUsr getDetailById(Long id) {
		LambdaQueryWrapper<OrgUsr> queryWrapper = new LambdaQueryWrapper<OrgUsr>();
		queryWrapper.eq(OrgUsr::getIsDelete, false);
		queryWrapper.eq(OrgUsr::getSequenceNbr, id);
		return this.baseMapper.selectOne(queryWrapper);
	}

	public List<Map<String, String>> getPersonSimpleDetail() {
		return orgUsrMapper.getPersonSimpleDetail();
	}

	public Map<String, Integer> getDeptCountByCompanyIds(List<String> companyIdList) {
		Map<String, Integer> resultMap = Maps.newHashMap();
		List<Map<String, Long>> companyDeptCountMapList;
		if (!ValidationUtil.isEmpty(companyIdList)) {
			companyDeptCountMapList = this.baseMapper.countDeptByCompanyId(companyIdList);
			if (!ValidationUtil.isEmpty(companyDeptCountMapList)) {
				companyDeptCountMapList.forEach(c -> {
					resultMap.put(c.get("sequence_nbr").toString(), Integer.valueOf(c.get("count").intValue()));
				});
			}
		}

		return resultMap;
	}

	public List<Map<String, Object>> queryCompanyId(String bizOrgName, List<String> codes) {

		return orgUsrMapper.queryCompanyId(bizOrgName, codes);
	}

	public List<Map<String, Object>> queryCompanyIdNew(String bizOrgName) {

		return orgUsrMapper.queryCompanyIdNew(bizOrgName);
	}

	public List<Map<String, Object>> getuserDetail(Long departmentId, List<Map<String, Object>> resulLists) {
		OrgUsr resulList = this.baseMapper.selectById(departmentId);
		if (resulList.getParentId() != null) {
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("departmentId", resulList.getSequenceNbr());
			resulLists.add(resultMap);
			return getuserDetail(Long.parseLong(resulList.getParentId()), resulLists);
		} else {
			return resulLists;
		}
	}

	public List<AgencyUserModel> getAmosUserByOrgUser(String orgUserIds) throws Exception {
		if (ValidationUtil.isEmpty(orgUserIds)) {
			throw new Exception("账号不存在");
		}
		List<String> orgUserIdList = Lists.newArrayList(orgUserIds.split(","));
		List<OrgUsr> orgUsr = this.baseMapper
				.selectList(new LambdaQueryWrapper<OrgUsr>().in(OrgUsr::getSequenceNbr, orgUserIdList));
		if (ValidationUtil.isEmpty(orgUsr)) {
			throw new Exception("账号不存在");
		}
		String userIds = Joiner.on(",").join(Lists.transform(orgUsr, OrgUsr::getAmosOrgId));
		List<AgencyUserModel> amosUser = Privilege.agencyUserClient.queryByIds(userIds, false).getResult();
		if (ValidationUtil.isEmpty(amosUser)) {
			throw new Exception("账号不存在");
		}
		return amosUser;
	}

	/**
	 * 查询组织机构下面的人员列表信息
	 *
	 * @param id
	 * @return
	 */
	public List<OrgUsr> getPersonListByCompanyId(String id) {
		OrgUsr company = this.getById(id);
		if (ValidationUtil.isEmpty(company)) {
			return null;
		}
		LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<OrgUsr>();
		wrapper.eq(OrgUsr::getIsDelete, false);
		wrapper.eq(OrgUsr::getBizOrgType, OrgPersonEnum.人员.getKey());
		wrapper.likeRight(OrgUsr::getBizOrgCode, company.getBizOrgCode());
		return this.baseMapper.selectList(wrapper);
	}

	@Override
	public List<OrgMenuDto> getTreeFlc(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, "getParentId", OrgTypeMethodName));
		}
		return resultList;
	}

	@Override
	public OrgUsrDto saveOrgPersonFlc(OrgPersonDto OrgPersonVo) throws Exception {
		OrgUsr orgUsr = new OrgUsr();
		BeanUtils.copyProperties(OrgPersonVo, orgUsr);
		orgUsr.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_PERSON);
		// orgCode 前端调用接口生成 不再后台生成orgCode
		/*
		 * if (OrgPersonVo.getParentId() != null) {OrgUsrMapper OrgUsr parent =
		 * getById(OrgPersonVo.getParentId()); if (parent != null &&
		 * ObjectUtils.isEmpty(OrgPersonVo.getBizOrgCode())) {
		 * orgUsr.setBizOrgCode(parent.getBizOrgCode() + getOrgCodeStr()); } } else {
		 * orgUsr.setBizOrgCode(getOrgCodeStr()); }
		 */
		OrgUsrDto result = new OrgUsrDto();
		if (orgUsr.getSequenceNbr() != null) { // 走更新方法
			this.updateById(orgUsr);
			BeanUtils.copyProperties(orgUsr, result);
		} else {
			result = saveOrgUsrDynamicFormInstance(orgUsr, OrgPersonVo.getDynamicFormValue());
		}
//	}*/
//    OrgUsrDto result = new OrgUsrDto();
//    if (orgUsr.getSequenceNbr() != null) { // 走更新方法
//        this.updateById(orgUsr);
//        BeanUtils.copyProperties(orgUsr, result);
//    } else {
//        if(OrgPersonVo.getDynamicFormValue() == null || OrgPersonVo.getDynamicFormValue().size() == 0) {
//            throw new BadRequest("人员动态表单信息未填写");
//        }
//        result = saveOrgUsrDynamicFormInstance(orgUsr, OrgPersonVo.getDynamicFormValue());
//    }
		return result;
	}

	/**
	 * 同步单位信息到防火监督point表
	 *
	 * @param companyIdList
	 */
	protected void syncCompany2Supervision(List<Long> companyIdList) {
		if (ValidationUtil.isEmpty(companyIdList)) {
			return;
		}
		String token = RequestContext.getToken();
		String appKey = RequestContext.getAppKey();
		String product = RequestContext.getProduct();
		new Thread(() -> companyIdList.forEach(id -> {
			try {
				RequestContext.setAppKey(appKey);
				RequestContext.setToken(token);
				RequestContext.setProduct(product);
				OrgUsrFormDto formDto = this.selectCompanyById(id);
				if (!ValidationUtil.isEmpty(formDto) && OrgPersonEnum.公司.getKey().equals(formDto.getBizOrgType())) {
					emqKeeper.getMqttClient().publish(airportAddTopic, JSON.toJSONString(formDto).getBytes(), 2, false);
				}
			} catch (Exception e) {
				logger.debug("syncCompany2Supervision error:", e.getMessage());
				e.printStackTrace();
			}
		})).start();
	}

	/**
	 * 查询多个组织机构下面的所有人员列表信息
	 *
	 * @param companyIdList
	 * @return
	 */
	public List<OrgUsr> getPersonListByCompanyIdList(List<String> companyIdList) {
		if (ValidationUtil.isEmpty(companyIdList)) {
			return Lists.newArrayList();
		}

		return this.baseMapper.selectPersonListByCompanyIdList(companyIdList);
	}

	/**
	 * 根据bizOrgCode查询详情
	 *
	 * @param bizOrgCode
	 * @return
	 */
	public OrgUsrDto getCompanyByBizOrgCodeList(String bizOrgCode) {

		LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(OrgUsr::getBizOrgCode, bizOrgCode);
		wrapper.eq(BaseEntity::getIsDelete, false);
		OrgUsr orgUsr = baseMapper.selectOne(wrapper);
		OrgUsrDto orgUsrDto = new OrgUsrDto();
		if (!orgUsr.getBizOrgType().equals(COMPANY_VALUE)) {
			for (int i = 0; i < 10; i++) {
				OrgUsr result = baseMapper.selectById(orgUsr.getParentId());
				if (result.getBizOrgType().equals(COMPANY_VALUE)) {
					BeanUtils.copyProperties(result, orgUsrDto);
					break;
				}
			}
		} else {
			BeanUtils.copyProperties(orgUsr, orgUsrDto);
		}
		return orgUsrDto;
	}

	public OrgUsr getCompanyByUserId(Long userId) {
		LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<OrgUsr>();
		wrapper.eq(OrgUsr::getIsDelete, false);
		wrapper.eq(OrgUsr::getAmosOrgId, userId);
		wrapper.eq(OrgUsr::getBizOrgType, CommonConstant.BIZ_ORG_TYPE_PERSON);
		OrgUsr orgUsr = baseMapper.selectOne(wrapper);
		return getCompanyByParentId(orgUsr.getParentId());
	}

	public OrgUsr getCompanyByParentId(String parentId) {
		LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<OrgUsr>();
		wrapper.eq(OrgUsr::getIsDelete, false);
		wrapper.eq(OrgUsr::getSequenceNbr, parentId);
		OrgUsr orgUsr1 = baseMapper.selectOne(wrapper);
		if (!orgUsr1.getBizOrgType().equals(CommonConstant.BIZ_ORG_TYPE_COMPANY)) {
			return getCompanyByParentId(orgUsr1.getParentId());
		}
		return orgUsr1;
	}

//			orgUsr.setBizOrgCode(getOrgCodeStr());
//		
//
//
//        return result;
//    }

	@Override
	public void updateByIdOrgPersonFlc(OrgPersonDto OrgPersonVo, Long id) throws Exception {
		// 修改人员信息
		OrgUsr orgUsr = new OrgUsr();
		OrgUsr oriOrgUsr = getById(id);
		BeanUtils.copyProperties(OrgPersonVo, orgUsr);
		orgUsr.setSequenceNbr(id);
		updateById(orgUsr);
		// 保存动态表单数据
		updateDynamicFormInstance(orgUsr.getSequenceNbr(), OrgPersonVo.getDynamicFormValue());
	}

	@Override
	public JSONObject selectPersonByUserId(Long userId) throws Exception {
		OrgUsr orgUsr = orgUsrMapper.queryByUserId(userId);
		// 动态表单数据
		List<FormValue> formValue = getFormValue(orgUsr.getSequenceNbr());
		OrgPersonFormDto orgPersonFormVo = new OrgPersonFormDto(formValue);
		BeanUtils.copyProperties(orgUsr, orgPersonFormVo);
		OrgUsr parent = getById(orgUsr.getParentId());
		if (!ObjectUtils.isEmpty(parent)) {
			orgPersonFormVo.setParentName(parent.getBizOrgName());
		}
		List<FormValue> dynamicFormAlert = orgPersonFormVo.getDynamicFormAlert();
		Map<String, String> collect = dynamicFormAlert.stream().collect(HashMap::new,
				(map, item) -> map.put(item.getKey(), item.getValue()), HashMap::putAll);
		JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(orgPersonFormVo));
		jsonObject.put("map", collect);
		return jsonObject;
	}

	@Override
	public UserDto getUserParentInfo(String userId) {
		OrgUsr orgUsr = orgUsrMapper.queryByUserId(Long.parseLong(userId));
		if (null != orgUsr) {
			UserDto userDto = new UserDto();
			String parentId = orgUsr.getParentId();
			userDto.setPersonSeq(String.valueOf(orgUsr.getSequenceNbr()));
			userDto.setPersonName(orgUsr.getBizOrgName());
			OrgUsr bizOrg = orgUsrMapper.queryBySequenceNbr(parentId);
			if (!ObjectUtils.isEmpty(bizOrg)) {
				userDto.setBizOrgType(bizOrg.getBizOrgType());
				userDto.setBizOrgCode(bizOrg.getBizOrgCode());
				userDto.setCompanyId(String.valueOf(bizOrg.getSequenceNbr()));
				userDto.setCompanyName(bizOrg.getBizOrgName());
			} else {
				throw new RuntimeException("人员所在公司不存在");
			}
			return userDto;
		} else {
			return new UserDto();
		}
	}

	public Object getOrgUserByAmosUserId(String amosUserId) throws Exception {
		LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<OrgUsr>();
		wrapper.eq(OrgUsr::getIsDelete, false);
		wrapper.eq(OrgUsr::getBizOrgType, CommonConstant.BIZ_ORG_TYPE_PERSON);
		wrapper.like(StringUtils.isNotBlank(amosUserId), OrgUsr::getAmosOrgId, amosUserId);
		return this.baseMapper.selectList(wrapper);
	}

	@Override
	public List<OrgUsr> getListByBizOrgTypeCode(String orgTypes, String orgCode) {
		List<String> orgTypeList = new ArrayList<>();
		if (StringUtils.isNotBlank(orgTypes)) {
			orgTypeList = Arrays.asList(orgTypes.split(","));
		}
		return this.getBaseMapper().listByOrgTypes(orgTypeList, orgCode);
	}

	@Override
	public List<OrgMenuDto> companyTreeByUserNumber(ReginParams reginParams) {
		Map<String, Object> param = new HashMap<>();
		// 权限处理
		PermissionInterceptorContext.setDataAuthRule(authKey);
		param.put("bizOrgCode", reginParams.getPersonIdentity().getBizOrgCode());
		List<OrgUsr> list = orgUsrMapper.companyDeptListWithPersonCount(param);
		return buildTreeParallel(list);
	}

	@Override
	public List<OrgMenuDto> companyTreeByUser(ReginParams reginParams) {
		Map<String, Object> param = new HashMap<>();
		// 权限处理
		PermissionInterceptorContext.setDataAuthRule(authKey);
		LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(OrgUsr::getBizOrgCode,reginParams.getPersonIdentity().getBizOrgCode());
		wrapper.eq(BaseEntity::getIsDelete,false);
		wrapper.isNull(OrgUsr::getParentId);
		OrgUsr orgUsr = baseMapper.selectOne(wrapper);

		List<OrgUsr> list = new ArrayList<>();

		if (ValidationUtil.isEmpty(orgUsr)){
			 list = orgUsrMapper.companyTreeByUser(reginParams.getPersonIdentity().getBizOrgCode());
		}else {
			LambdaQueryWrapper<OrgUsr> queryWrapper= new LambdaQueryWrapper<>();
			wrapper.likeRight(OrgUsr::getBizOrgCode,reginParams.getPersonIdentity().getBizOrgCode());
			wrapper.eq(BaseEntity::getIsDelete,false);
			wrapper.eq(OrgUsr::getBizOrgType,"DEPARTMENT");
			baseMapper.selectList(queryWrapper);

		}

		 list = orgUsrMapper.companyTreeByUser(reginParams.getPersonIdentity().getBizOrgCode());
		return buildTreeParallel(list);
	}
//    /**
//     * 同步单位信息到防火监督point表
//     *
//     * @param companyIdList
//     */
//    protected void syncCompany2Supervision(List<Long> companyIdList) {
//        if (ValidationUtil.isEmpty(companyIdList)) {
//            return;
//        }
//        String token = RequestContext.getToken();
//        String appKey = RequestContext.getAppKey();
//        String product = RequestContext.getProduct();
//        new Thread(() -> companyIdList.forEach(id -> {
//            try {
//                RequestContext.setAppKey(appKey);
//                RequestContext.setToken(token);
//                RequestContext.setProduct(product);
//                OrgUsrFormDto formDto = this.selectCompanyById(id);
//                if (!ValidationUtil.isEmpty(formDto) && OrgPersonEnum.公司.getKey().equals(formDto.getBizOrgType())) {
//                    emqKeeper.getMqttClient().publish(airportAddTopic, JSON.toJSONString(formDto).getBytes(), 2, false);
//                }
//            } catch (Exception e) {
//                logger.debug("syncCompany2Supervision error:", e.getMessage());
//                e.printStackTrace();
//            }
//        })).start();
//    }

	public String getIdNumberByAmosId(String amosId) {
		LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(OrgUsr::getIsDelete, false);
		wrapper.eq(OrgUsr::getAmosOrgId, amosId);
		wrapper.eq(OrgUsr::getBizOrgType, OrgPersonEnum.人员.getKey());
		OrgUsr orgUsr = this.baseMapper.selectOne(wrapper);
		if (orgUsr == null) {
			return null;
		}
		List<DynamicFormInstanceDto> list = alertFormValueServiceImpl.listByCalledId(orgUsr.getSequenceNbr());
		String certificateTypeValueString = null;
		String certificatesNumberValueString = null;
		if (list != null && list.size() > 0) {
			for (DynamicFormInstanceDto dynamicFormInstanceDto : list) {
				if ("certificatesTypeCode".equals(dynamicFormInstanceDto.getFieldCode())) {
					certificateTypeValueString = dynamicFormInstanceDto.getFieldValue();
					continue;
				}
				if ("certificatesNumber".equals(dynamicFormInstanceDto.getFieldCode())) {
					certificatesNumberValueString = dynamicFormInstanceDto.getFieldValue();
					continue;
				}
			}
			if (certificateTypeValueString != null && "120".equals(certificateTypeValueString)) {
				return certificatesNumberValueString;
			}
		}
		return null;
	}


	public List<OrgUsr>	getByAmosId(List<String> amosIds) {
		if (ValidationUtil.isEmpty(amosIds)) {
			return null;
		}
		LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
		wrapper.in(OrgUsr::getAmosOrgId, amosIds);
		wrapper.eq(OrgUsr::getBizOrgType, OrgPersonEnum.人员.getKey());
		return this.baseMapper.selectList(wrapper).stream().collect(Collectors.toList());
	}

	public List<OrgUsr>	getByOrgCode(String bizOrgCode) {
		if (StringUtils.isEmpty(bizOrgCode)) {
			return null;
		}
		LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
		wrapper.likeRight(OrgUsr::getBizOrgCode,bizOrgCode);
		wrapper.isNotNull(OrgUsr::getBizOrgCode);
		wrapper.eq(BaseEntity::getIsDelete,false);
		wrapper.eq(OrgUsr::getBizOrgType, CommonConstant.BIZ_ORG_TYPE_DEPARTMENT)
				.or().eq(OrgUsr::getBizOrgType, CommonConstant.BIZ_ORG_TYPE_COMPANY);
		return this.baseMapper.selectList(wrapper).stream().collect(Collectors.toList());
	}

}