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

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.conditions.update.UpdateWrapper;
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.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.interceptors.PermissionInterceptorContext;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
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.*;
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.FireTeamMapper;
import com.yeejoin.amos.boot.module.common.api.mapper.FirefightersJacketMapper;
import com.yeejoin.amos.boot.module.common.api.mapper.OrgUsrMapper;
import com.yeejoin.amos.boot.module.common.api.service.IDataSyncService;
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.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.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.component.emq.EmqKeeper;
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 javax.annotation.Resource;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.ParseException;
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 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";

	private static final String FIREFIGHTERSID ="firefighters_id";

	@Value("${logic}")
	Boolean logic;

	@Autowired
	DynamicFormInstanceServiceImpl alertFormValueServiceImpl;
	@Autowired
	FirefightersServiceImpl firefightersService;
	@Autowired
	DynamicFormColumnServiceImpl alertFormServiceImpl;
	@Resource
	OrgUsrMapper orgUsrMapper;
	@Autowired
	EmqKeeper emqKeeper;
	@Autowired
	ESOrgUsrService eSOrgUsrService;
	@Autowired
	IMaintenanceCompanyService maintenanceCompanyService;
	@Autowired
	FireStationServiceImpl fireStationServiceImpl;
	@Autowired
	FireCompanyInfoServiceImpl fireCompanyInfoServiceImpl;
	@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;


	@Value("${jcs.company.topic.delete:jcs/company/topic/delete}")
	private String airportDeleteTopic;

	@Autowired
	FireTeamMapper fireTeamMapper;

	@Autowired
	FirefightersThoughtServiceImpl iFirefightersThoughtService;
	@Autowired
	FirefightersContractServiceImpl iFirefightersContractService;

	@Autowired
	FirefightersJacketMapper firefightersJacketMapper;

	@Autowired
	FireTeamServiceImpl iFireTeamService;

	@Autowired
	DynamicFormInstanceServiceImpl dynamicFormInstanceService;

	@Autowired
	DynamicFormColumnServiceImpl dynamicFormColumnServiceImpl;

	@Autowired
	FirefightersServiceImpl iFirefightersService;

	@Autowired
	FirefightersPostServiceImpl iFirefightersPostService;

	@Autowired
	FirefightersEducationServiceImpl ifirefightersEducationService;

	@Autowired
	FirefightersWorkexperienceServiceImpl ifirefightersWorkexperienceService;

	@Autowired
	DataDictionaryServiceImpl dataDictionaryService;

	@Autowired
	FirefightersContactsServiceImpl firefightersContactsService;

	@Autowired
	FirefightersContactsServiceImpl ifirefightersContactsService;

	@Autowired
	private IDataSyncService dataSyncService;

	@Autowired
	RedisUtils redisUtils;

	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(), o.getCode()).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.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;

			/*
			 * *******************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> getCompanyTree(Long topId, Collection entityList, String packageURL, String IDMethodName,
										   int IDHierarchy, String NAMEMethodName, String PARENTIDMethodName, String OrgTypeMethodName, String OrgCodeMethodName)
			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);
		Method OrgCodeMethodNameme = clazz.getDeclaredMethod(OrgCodeMethodName);
		// 获取顶层元素集合
		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) {
				OrgMenuDto menu = new OrgMenuDto(Long.valueOf(String.valueOf(IDMethodNameme.invoke(entity))),
						String.valueOf(NAMEMethodNameme.invoke(entity)), parentId,
						String.valueOf(OrgTypeMethodNameme.invoke(entity)), false, String.valueOf(OrgCodeMethodNameme.invoke(entity)));
				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, String.valueOf(OrgCodeMethodNameme.invoke(entity)));
				resultList.add(menu);
			}
		}
		// 获取每个顶层元素的子数据集合
		for (OrgMenuDto entity : resultList) {
			entity.setChildren(getCompanySub(entity.getKey(), entityList, packageURL, IDMethodName, IDHierarchy,
					NAMEMethodName, PARENTIDMethodName, OrgTypeMethodName, OrgCodeMethodName));
		}
		return resultList;
	}

	@Override
	public List<OrgMenuDto> getCompanySub(Long topId, @SuppressWarnings("rawtypes") Collection entityList, String packageURL,
										  String IDMethodName, int IDHierarchy, String NAMEMethodName, String PARENTIDMethodName,
										  String OrgTypeMethodName, String OrgCodeMethodName) 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);
		Method OrgCodeMethodNameme = clazz.getDeclaredMethod(OrgCodeMethodName);

		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)), String.valueOf(OrgCodeMethodNameme.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)), String.valueOf(OrgCodeMethodNameme.invoke(entity)));
					childList.add(menu);
				}
			}

		}

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

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

		return childList;
	}

	@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);
			map.put("bizOrgCode", req.get("bizOrgCode"));
			req.remove("bizOrgCode");
		}
		/* 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过来，现在传名字，那就将错就错吧
		}
		String positionType = "";
		if(req.containsKey("positionType")) {
			positionType = req.get("positionType").toString();
			map.put("positionType", positionType);
		}

		List<String> fireManagementPost;
		if(req.containsKey("fireManagementPost")) {
			if(StringUtils.isNotEmpty(req.get("fireManagementPost").toString())) {
				fireManagementPost = Arrays.asList(req.get("fireManagementPost").toString().split(","));
				map.put("fireManagementPost", fireManagementPost);
			}
		}

		String peopleType = "";
		if(req.containsKey("peopleType")) {
			peopleType = req.get("peopleType").toString();
			map.put("peopleType", peopleType);
		}

		String personStatus = "";
		if(req.containsKey("personStatus")) {
			personStatus = req.get("personStatus").toString();
			map.put("personStatus", personStatus);
		}

		req.remove("pageSize");
		req.remove("pageNum");
		req.remove("parentId");
		req.remove("amosOrgId");
		req.remove("company");
		req.remove("positionType");
		req.remove("peopleType");
		req.remove("bizOrgName");
		req.remove("fireManagementPost");
		req.remove("personStatus");
		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<String> amosIds = new ArrayList<>();
		list.forEach(t -> {
			// BUG2886 因为前期沟通 人员code 可能会发生改变 所以 现在接口code 不再保存，查询数据时通过接口重新赋值 by kongfm
			// 2021-09-16
			if (null != t.get("amosOrgId") && StringUtils.isNotEmpty(t.get("amosOrgId").toString())) {
				amosIds.add(t.get("amosOrgId").toString());
				if (!ObjectUtils.isEmpty(t.get("certificateTypeValue"))  && "120".equals(t.get("certificateTypeValue").toString())) {
					t.put("chargePersonId", t.get("certificatesNumber"));
				}
			} else {
				t.put("chargePersonId", null);
			}
		});
		List<DataDictionary> dictList = dataDictionaryService.getByType("RYZT");
		Map<String, String> dictMap = dictList.stream().collect(Collectors.toMap(DataDictionary::getCode, DataDictionary::getName));

		Map<String, AgencyUserModel> collect = new HashMap<>();
		if (CollectionUtils.isNotEmpty(amosIds)) {
			String join = String.join(",", amosIds);
			List<AgencyUserModel> amosUser = Privilege.agencyUserClient.queryByIds(join, false).getResult();
			collect = amosUser.stream().collect(Collectors.toMap(AgencyUserModel::getUserId, t -> t));
		}
		Map<String, AgencyUserModel> finalCollect = collect;
		list.forEach(t -> {
			if (!ObjectUtils.isEmpty(finalCollect) && null != t.get("amosOrgId") && StringUtils.isNotEmpty(t.get("amosOrgId").toString()) && finalCollect.containsKey(t.get("amosOrgId").toString())) {
				t.put("amosOrgCode", finalCollect.get(t.get("amosOrgId").toString()).getRealName());
			}
			if (!ObjectUtils.isEmpty(t.get("state"))) {
				t.put("stateName", dictMap.getOrDefault(t.get("state").toString(), t.get("state").toString()));
			}
		});
		if(!positionType.equals("")) {
			String positionTypeFine = positionType;
			list = list.stream().filter(e-> !ObjectUtils.isEmpty(e.get("positionType")) && String.valueOf(e.get("positionType")).contains(positionTypeFine)).collect(Collectors.toList());
		}
		/* Bug2652 根据名字和工号模糊查询失效 已添加模糊匹配 2021-09-01 陈召 结束 */
		pageBean.setRecords(list);

		return pageBean;
	}

	public IPage<Map<String, Object>> listAllByCurrentUser(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<String> amosIds = new ArrayList<>();
		list.forEach(t -> {
			// BUG2886 因为前期沟通 人员code 可能会发生改变 所以 现在接口code 不再保存，查询数据时通过接口重新赋值 by kongfm
			// 2021-09-16
			if (null != t.get("amosOrgId") && StringUtils.isNotEmpty(t.get("amosOrgId").toString())) {
				amosIds.add(t.get("amosOrgId").toString());
				if (!ObjectUtils.isEmpty(t.get("certificateTypeValue"))  && "120".equals(t.get("certificateTypeValue").toString())) {
					t.put("chargePersonId", t.get("certificatesNumber"));
				}
			} else {
				t.put("chargePersonId", null);
			}
		});
		List<DataDictionary> dictList = dataDictionaryService.getByType("RYZT");
		Map<String, String> dictMap = dictList.stream().collect(Collectors.toMap(DataDictionary::getCode, DataDictionary::getName));

		Map<String, AgencyUserModel> collect = new HashMap<>();
		if (CollectionUtils.isNotEmpty(amosIds)) {
			String join = String.join(",", amosIds);
			List<AgencyUserModel> amosUser = Privilege.agencyUserClient.queryByIds(join, false).getResult();
			collect = amosUser.stream().collect(Collectors.toMap(AgencyUserModel::getUserId, t -> t));
		}
		Map<String, AgencyUserModel> finalCollect = collect;
		list.forEach(t -> {
				if (!ObjectUtils.isEmpty(finalCollect) && null != t.get("amosOrgId") && StringUtils.isNotEmpty(t.get("amosOrgId").toString()) && finalCollect.containsKey(t.get("amosOrgId").toString())) {
					t.put("amosOrgCode", finalCollect.get(t.get("amosOrgId").toString()).getRealName());
				}
				if (!ObjectUtils.isEmpty(t.get("state"))) {
					t.put("stateName", dictMap.getOrDefault(t.get("state").toString(), t.get("state").toString()));
				}
			});
		/* Bug2652 根据名字和工号模糊查询失效 已添加模糊匹配 2021-09-01 陈召 结束 */
		pageBean.setRecords(list);
		return pageBean;
	}

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

		List<DynamicFormInstanceDto> list = alertFormValueServiceImpl.listByCalledId(id);
		List<FormValue> formValue = new ArrayList<>();
		for (DynamicFormInstanceDto alertFormValue : list) {
			/* 修改为动态表单返回的数据参数量 2021-09-08 陈浩 开始 */

			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;

	}

	@Override
	public String getPersonImg(String id) {
		Long userId = Long.valueOf(id);
		OrgUsr orgUsr = this.baseMapper.queryByUserId(userId);
		return orgUsr.getPersonImg();
	}

	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 oldOrgUsr) throws Exception {

		if (!orgUsr.getParentId().equals(oldOrgUsr.getParentId())) {
			OrgUsr parent = getById(orgUsr.getParentId());
			if (parent != null && !ObjectUtils.isEmpty(parent.getBizOrgCode())) {
				orgUsr.setBizOrgCode(parent.getBizOrgCode() + getOrgCodeStr());
			}
			updateChildOrgCode(oldOrgUsr.getBizOrgCode(), orgUsr.getBizOrgCode());
		}
		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 List<Map<String, Object>> selectStatic(String bizOrgCode, String type) {
		List<Map<String,Object>> listMap;
		if("1601".equals(type)) {
			listMap = this.baseMapper.selectStaticFire(bizOrgCode);
		} else {
			listMap = this.baseMapper.selectStaticYw(bizOrgCode);
		}
		return listMap;
	}

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

		QueryWrapper<FirefightersPost> queryWrapperf = new QueryWrapper<>();
		queryWrapperf.eq("org_usr_id", id);
		FirefightersPost firefightersPost = iFirefightersPostService.getOne(queryWrapperf);
		if (!ObjectUtils.isEmpty(result.get("stateCode"))) {
			DataDictionary gwmc = dataDictionaryService.getByCode(result.get("stateCode").toString(), "RYZT");
			if (!ObjectUtils.isEmpty(gwmc)) {
				result.put("state", gwmc.getName());
			} else {
				result.put("state", result.get("stateCode"));
			}
		}
		if (!ObjectUtils.isEmpty(firefightersPost)) {
			result.put("fireManagementPostCode",firefightersPost.getFireManagementPost());
			result.put("internalPositionCode", firefightersPost.getInternalPosition());
			result.put("positionType", firefightersPost.getJobTitle());
			result.put("certificateType", firefightersPost.getCertificateType());
		}
		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());
				orgUsr.setParentName(parent.getBizOrgName());
			}
		} else {
			orgUsr.setBizOrgCode(getOrgCodeStr());
		}
		OrgUsrDto orgUsrDto = saveOrgUsrDynamicFormInstance(orgUsr, OrgUsrVo.getDynamicFormValue());
		orgUsr.setSequenceNbr(orgUsrDto.getSequenceNbr());
		// 储存公司消防信息
		CompanyInfo info = saveFireCompanyInfo(orgUsr, OrgUsrVo.getFireCompanyInfoDto());
		orgUsrDto.setCompanyInfo(info);
		/**
		 * 同步保存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 OrgUsrDto 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());
		}
//已在前面对此字段赋值 废弃


		return 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);
		orgUsrVo.setBizOrgCode(oriOrgUsr.getBizOrgCode());
		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日

//            /*单位编辑后 code值也应做出修改 2021-09-09 陈召 结束  */8888
			orgUsrMapper.updatelistByParentId(orgUsr.getBizOrgCode(), oriOrgUsr.getBizOrgCode());
		}else {
			orgUsr.setBizOrgCode(oriOrgUsr.getBizOrgCode());
		}
		updateById(orgUsr);
		// 更新公司消防信息
		CompanyInfo info = updateFireCompanyInfo(orgUsr, orgUsrVo.getFireCompanyInfoDto());
		orgUsrVo.setCompanyInfo(info);

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

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

	public CompanyInfo saveFireCompanyInfo(OrgUsr orgUsr, FireCompanyInfoDto fireCompanyInfoDto) {
		if (ValidationUtil.isEmpty(fireCompanyInfoDto)) {
			return null;
		}
		CompanyInfo companyInfo = new CompanyInfo();
		String indoor = "";
		String outdoor = "";
		if (!ValidationUtil.isEmpty(fireCompanyInfoDto.getIndoorPipeNetworkType()) && 0 < fireCompanyInfoDto.getIndoorPipeNetworkType().size()) {
			indoor = JSON.toJSONString(fireCompanyInfoDto.getIndoorPipeNetworkType());
		}
		if (!ValidationUtil.isEmpty(fireCompanyInfoDto.getOutdoorPipeNetworkType()) && 0 < fireCompanyInfoDto.getOutdoorPipeNetworkType().size()) {
			outdoor = JSON.toJSONString(fireCompanyInfoDto.getOutdoorPipeNetworkType());
		}
		BeanUtils.copyProperties(fireCompanyInfoDto, companyInfo);
		companyInfo.setIndoorPipeNetworkType(indoor);
		companyInfo.setOutdoorPipeNetworkType(outdoor);
		if (!ValidationUtil.isEmpty(fireCompanyInfoDto.getFireEquipFile())) {
			companyInfo.setFireEquipFile(fireCompanyInfoDto.getFireEquipFile().size() > 0 ?
					JSON.toJSONString(fireCompanyInfoDto.getFireEquipFile()) : "");
		}
		if (!ValidationUtil.isEmpty(fireCompanyInfoDto.getFireDesignCheckFile())) {
			companyInfo.setFireDesignCheckFile(fireCompanyInfoDto.getFireDesignCheckFile().size() > 0 ?
					JSON.toJSONString(fireCompanyInfoDto.getFireDesignCheckFile()) : "");
		}
		if (!ValidationUtil.isEmpty(fireCompanyInfoDto.getFireDesignAcceptanceFile())) {
			companyInfo.setFireDesignAcceptanceFile(fireCompanyInfoDto.getFireDesignAcceptanceFile().size() > 0 ?
					JSON.toJSONString(fireCompanyInfoDto.getFireDesignAcceptanceFile()) : "");
		}
		if (!ValidationUtil.isEmpty(fireCompanyInfoDto.getFireSafeCheckFile())) {
			companyInfo.setFireSafeCheckFile(fireCompanyInfoDto.getFireSafeCheckFile().size() > 0 ?
					JSON.toJSONString(fireCompanyInfoDto.getFireSafeCheckFile()) : "");
		}

		if (!ValidationUtil.isEmpty(fireCompanyInfoDto.getOthersFile())) {
			companyInfo.setOthersFile(fireCompanyInfoDto.getOthersFile().size() > 0 ?
					JSON.toJSONString(fireCompanyInfoDto.getOthersFile()) : "");
		}
		companyInfo.setInstanceId(orgUsr.getSequenceNbr());
		companyInfo.setRecUserId(String.valueOf(orgUsr.getSequenceNbr()));
		companyInfo.setRecUserName(orgUsr.getRecUserName());
		companyInfo.setRecDate(new Date());
		fireCompanyInfoServiceImpl.save(companyInfo);
		return companyInfo;
	}

	public CompanyInfo updateFireCompanyInfo(OrgUsr orgUsr, FireCompanyInfoDto fireCompanyInfoDto) {
		if (ValidationUtil.isEmpty(fireCompanyInfoDto)) {
			return null;
		}
		CompanyInfo companyInfo = new CompanyInfo();
		String indoor = "";
		String outdoor = "";
		if (!ValidationUtil.isEmpty(fireCompanyInfoDto.getIndoorPipeNetworkType()) && 0 < fireCompanyInfoDto.getIndoorPipeNetworkType().size()) {
			indoor = JSON.toJSONString(fireCompanyInfoDto.getIndoorPipeNetworkType());
		}
		if (!ValidationUtil.isEmpty(fireCompanyInfoDto.getOutdoorPipeNetworkType()) && 0 < fireCompanyInfoDto.getOutdoorPipeNetworkType().size()) {
			outdoor = JSON.toJSONString(fireCompanyInfoDto.getOutdoorPipeNetworkType());
		}
		BeanUtils.copyProperties(fireCompanyInfoDto, companyInfo);
		companyInfo.setIndoorPipeNetworkType(indoor);
		companyInfo.setOutdoorPipeNetworkType(outdoor);
		if (!ValidationUtil.isEmpty(fireCompanyInfoDto.getFireEquipFile())) {
			companyInfo.setFireEquipFile(fireCompanyInfoDto.getFireEquipFile().size() > 0 ?
					JSON.toJSONString(fireCompanyInfoDto.getFireEquipFile()) : "");
		}
		if (!ValidationUtil.isEmpty(fireCompanyInfoDto.getFireDesignCheckFile())) {
			companyInfo.setFireDesignCheckFile(fireCompanyInfoDto.getFireDesignCheckFile().size() > 0 ?
					JSON.toJSONString(fireCompanyInfoDto.getFireDesignCheckFile()) : "");
		}
		if (!ValidationUtil.isEmpty(fireCompanyInfoDto.getFireDesignAcceptanceFile())) {
			companyInfo.setFireDesignAcceptanceFile(fireCompanyInfoDto.getFireDesignAcceptanceFile().size() > 0 ?
					JSON.toJSONString(fireCompanyInfoDto.getFireDesignAcceptanceFile()) : "");
		}
		if (!ValidationUtil.isEmpty(fireCompanyInfoDto.getFireSafeCheckFile())) {
			companyInfo.setFireSafeCheckFile(fireCompanyInfoDto.getFireSafeCheckFile().size() > 0 ?
					JSON.toJSONString(fireCompanyInfoDto.getFireSafeCheckFile()) : "");
		}

		if (!ValidationUtil.isEmpty(fireCompanyInfoDto.getOthersFile())) {
			companyInfo.setOthersFile(fireCompanyInfoDto.getOthersFile().size() > 0 ?
					JSON.toJSONString(fireCompanyInfoDto.getOthersFile()) : "");
		}
		companyInfo.setInstanceId(orgUsr.getSequenceNbr());
		companyInfo.setRecUserId(String.valueOf(orgUsr.getSequenceNbr()));
		companyInfo.setRecUserName(orgUsr.getRecUserName());
		companyInfo.setRecDate(new Date());
		fireCompanyInfoServiceImpl.updateById(companyInfo);
		return companyInfo;
	}

	@Override
	public OrgPersonDto updateByIdOrgPerson(OrgPersonDto orgPersonDto, Long id) throws Exception {
		try {
			updatePersonNumber(id, orgPersonDto);
		} catch (Exception e) {
			logger.info("同步修改培训计划中的人员编号：---------------");
		}
		// 修改人员信息
		OrgUsr orgUsr = new OrgUsr();
		OrgUsr oldOrgUsr = getById(id);
		BeanUtils.copyProperties(orgPersonDto, orgUsr);
		/*
		 * Bug 2647 编辑用户所属单位后按单位筛选人员结果错误 增加了 638 639 两行代码 根据修改的部门调整部门code 2021-09-03 陈召
		 * 开始
		 */
		// 下面saveOrgUsr有处理逻辑，这段代码多余
//		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(orgPersonDto.getAmosOrgId())) {
			AgencyUserModel user = Privilege.agencyUserClient.queryByUserId(orgPersonDto.getAmosOrgId()).getResult();
			// oldOrgUsr.setAmosOrgCode(user.getRealName()); 去掉AmosOrgCode by litw
			// 2021年9月10日
			oldOrgUsr.setAmosOrgId(user.getUserId());
			// orgUsr.setAmosOrgCode(user.getRealName()); 去掉AmosOrgCode by litw 2021年9月10日
			orgUsr.setAmosOrgId(user.getUserId());
		}
		saveOrgUsr(orgUsr, oldOrgUsr);
		// 保存消防人员表数据
		QueryWrapper<Firefighters> firefightersQueryWrapper = new QueryWrapper<>();
		firefightersQueryWrapper.eq("org_usr_id", id);
		Firefighters fire = firefightersService.getOne(firefightersQueryWrapper);
		if(!ObjectUtils.isEmpty(fire)) {
			fire.setName(orgUsr.getBizOrgName());
			firefightersService.updateById(fire);
		}

		// 保存动态表单数据
		updateDynamicFormInstance(orgUsr.getSequenceNbr(), orgPersonDto.getDynamicFormValue());
		if (orgUsr.getBizOrgCode() != null) {
			orgPersonDto.setBizOrgCode(orgUsr.getBizOrgCode());
		}
//		if(redisUtils.get("userList")!= null){
//			redisUtils.del("userList");
//		}
		return orgPersonDto;
	}

	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);
		Map<String, String> Xfaq = null;
		Map<String, String> Xfgl = null;
		Map<String, String> Dwfz = null;
		List<OrgUsr> orgUsrs = getIdByOrgCode(orgUsr.getBizOrgCode(), id);
		List<Long> ids = orgUsrs.stream().map(x -> x.getSequenceNbr()).collect(Collectors.toList());
		if (CollectionUtils.isNotEmpty(ids)) {
			Xfaq = orgUsrMapper.getManagePerson("消防安全负责人", ids);
			Xfgl = orgUsrMapper.getManagePerson("消防安全管理人", ids);
			Dwfz = orgUsrMapper.getManagePerson("法定代表人", ids);
		}
		orgUsrFormVo.setXfaq(Xfaq != null ? Xfaq.get("uname") : "");
		orgUsrFormVo.setXfgl(Xfgl != null ? Xfgl.get("uname") : "");
		orgUsrFormVo.setDwfz(Dwfz != null ? Dwfz.get("uname") : "");
		if (orgUsr.getParentId() != null) {
			orgUsrFormVo.setParentName(getById(orgUsr.getParentId()).getBizOrgName());
		}
		CompanyInfo info = fireCompanyInfoServiceImpl.getOne(new QueryWrapper<CompanyInfo>().eq("instance_id", id).eq("is_delete", 0));
		orgUsrFormVo.setCompanyInfo(info);
		return orgUsrFormVo;
	}

	public OrgUsr selectParentOrgUsr(OrgUsr orgUsr){
		if (orgUsr.getBizOrgType().equals("COMPANY")){
			return orgUsr ;
		}
		LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(OrgUsr::getSequenceNbr,orgUsr.getParentId());
		wrapper.eq(BaseEntity::getIsDelete,false);
		orgUsr = orgUsrMapper.selectOne(wrapper);
		return selectParentOrgUsr(orgUsr);

	}

	@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));
			result.put("parentId",orgUsr.getParentId());
			orgUsr = getById(orgUsr.getParentId());
			result.put("bizOrgType",orgUsr.getBizOrgType() == "DEPARTMENT" ? 1 : 0);
			orgUsr  =iOrgUsrService.selectParentOrgUsr(orgUsr);
			result.put("companyId",orgUsr.getSequenceNbr());
			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>();
		//4.24优化 原有方法不断循环查库 接口太慢 将数据一次捞出由java层组装
		//获取指定单位
		LambdaQueryWrapper<OrgUsr> companyWrapper = new LambdaQueryWrapper<>();
		companyWrapper.in(BaseEntity::getSequenceNbr,ids);
		List<OrgUsr> companys = this.orgUsrMapper.selectList(companyWrapper);
		//获取指定单位下所有人员
		LambdaQueryWrapper<OrgUsr> personWrapper = new LambdaQueryWrapper<>();
		personWrapper.in(OrgUsr::getParentId,ids);
		personWrapper.eq(OrgUsr::getBizOrgType,OrgPersonEnum.人员.getKey());
		personWrapper.eq(BaseEntity::getIsDelete,false);
		List<OrgUsr> persons = this.orgUsrMapper.selectList(personWrapper);
		//将各单位人员数据组装
		companys.stream().forEach(e->{
			List<OrgUsr> list = persons.stream().filter(p -> p.getParentId().equals(e.getSequenceNbr().toString())).collect(Collectors.toList());
			CompanyPerson company = new CompanyPerson();
			BeanUtils.copyProperties(e, company);
			company.setPersons(Bean.toModels(list, this.getModelClass()));
			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));
		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);
	}

	public List<OrgMenuDto> companyTreeByUserAndType(ReginParams reginParams, String type, String station) {
		Map<String, Object> param = new HashMap<>();
		String bizOrgCode = reginParams.getPersonIdentity().getBizOrgCode();
		if ("dl".equals(station)){
			LambdaQueryWrapper<OrgUsr> lambda = new QueryWrapper<OrgUsr>().lambda();
			lambda.eq(OrgUsr::getBizOrgCode, bizOrgCode);
			lambda.eq(OrgUsr::getIsDelete, false);
			OrgUsr orgUsr = orgUsrMapper.selectList(lambda).get(0);
			if (!org.apache.commons.lang3.ObjectUtils.isEmpty(orgUsr.getBizOrgType()) && "COMPANY".equals(orgUsr.getBizOrgType())) {
				bizOrgCode = orgUsr.getBizOrgCode();
			} else {
				bizOrgCode = getCompanyNameById(orgUsr.getParentId());
			}
		}
		param.put("bizOrgCode", bizOrgCode);
		param.put("type", type);
		List<OrgUsr> list = orgUsrMapper.companyTreeByUserAndType(param);
		return buildTreeParallel(list);
	}

	private String getCompanyNameById(String id) {
		LambdaQueryWrapper<OrgUsr> lambda = new QueryWrapper<OrgUsr>().lambda();
		lambda.eq(OrgUsr::getSequenceNbr, id);
		lambda.eq(OrgUsr::getIsDelete, false);
		OrgUsr orgUsr = orgUsrMapper.selectList(lambda).get(0);
		if (!org.apache.commons.lang3.ObjectUtils.isEmpty(orgUsr.getBizOrgType()) && "COMPANY".equals(orgUsr.getBizOrgType())) {
			return orgUsr.getBizOrgCode();
		} else {
			return getCompanyNameById(orgUsr.getParentId());
		}

	}

	@Override
	public List<OrgMenuDto> companyTreeAll(String type) {
		Map<String, Object> param = new HashMap<>();
		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,String bizOrgCode) {
		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)) {

				// 人员与多个部门/公司关联
				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));
						}
					}
				});
				// 返回所在用户单位列表
				List<CheckObjectDto> lists = list.stream().distinct().collect(Collectors.toList());
				return lists.stream().filter(i-> !i.getBizOrgCode().equals(bizOrgCode)).collect(Collectors.toList());
			}
		}
		return	list.stream().filter(i-> !i.getBizOrgCode().equals(bizOrgCode)).collect(Collectors.toList());
	}

	/**
	 * 获取登陆人所在公司
	 */
	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);
				}
				// 只查出一级单位，顶级为西部机场集团
				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)) {
			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 ids
	 * @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::getAmosOrgId, userId);
		wrapper.eq(OrgUsr::getBizOrgType, OrgPersonEnum.人员.getKey()).and(rapper->
				rapper.eq(OrgUsr::getIsDelete, false).or().eq(OrgUsr::getOrgExpandAttr8, "1")
		);
		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, String orgUsrId) {
		// 增加逻辑：orgUsrId不为空时（编辑逻辑），进行筛选，解决自己页面编辑成自己，导致校验不通过
		int num = orgUsrMapper.amosIdExist(amosId,orgUsrId);
		return num <= 0;
	}

	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.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.isNotNull(OrgUsr::getAmosOrgId);
		wrapper.ne(OrgUsr::getAmosOrgId, "");
		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;

			/*
			 * *******************topId与parentId的等值判断，修改人陈浩 on 2021/07/21---start
			 ******************************/
			if (parentId == null) {// topId与parentId的等值判断，修改人陈浩 on 2021/07/21

			} 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

		OrgUsrDto result = new OrgUsrDto();
		if (orgUsr.getSequenceNbr() != null) { // 走更新方法
			this.updateById(orgUsr);
			BeanUtils.copyProperties(orgUsr, result);
		} else {
			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)) {
			//查询当前登录人所属单位/部门
			orgUsr = orgUsrMapper.selectById(orgUsr.getParentId());
			//判断登陆人是否已经是顶级节点单位
			if (orgUsr.getParentId() != null ){
				orgUsr  =iOrgUsrService.selectParentOrgUsr(orgUsr);

			}
		}
		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());
		}
		List<DynamicFormInstanceDto>  tagerList=	dynamicFormInstanceMapper.selectListByCalledId(orgUsr1.getSequenceNbr());
		tagerList.stream().forEach(i->{
			if("managementType".equals(i.getFieldCode().toString())) {
				orgUsr1.setManagementType(i.getFieldValueLabel());
			}
		});
		return orgUsr1;
	}



	@Override
	public void updateByIdOrgPersonFlc(OrgPersonDto OrgPersonVo, Long id) throws Exception {
		// 修改人员信息
		OrgUsr orgUsr = new OrgUsr();
		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 = JSON.parseObject(JSON.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());
				if(bizOrg.getBizOrgType().equals("COMPANY")){
					userDto.setCompanyBizOrgCode(bizOrg.getBizOrgCode());
				}else{
					userDto.setCompanyBizOrgCode(getCompany(bizOrg));
				}
			} else {
				throw new RuntimeException("人员所在公司不存在");
			}
			return userDto;
		} else {
			return new UserDto();
		}
	}

	@Override
	public UserDto selectByIdUser(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());

				if(bizOrg.getBizOrgType().equals("COMPANY")){
					userDto.setCompanyBizOrgCode(bizOrg.getBizOrgCode());
				}else{
					userDto.setCompanyBizOrgCode(getCompany(orgUsr));
				}

			} else {
				throw new RuntimeException("人员所在公司不存在");
			}
			return userDto;
		} else {
			return new UserDto();
		}
	}

	@Override
	public List<OrgUsr> getListById(List<String> ids) {
		LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<OrgUsr>();
		wrapper.eq(OrgUsr::getIsDelete, false);
		wrapper.in(OrgUsr::getSequenceNbr, ids);
		wrapper.eq(OrgUsr::getBizOrgType, CommonConstant.BIZ_ORG_TYPE_PERSON);
		List<OrgUsr> orgUsr = baseMapper.selectList(wrapper);
		return orgUsr;
	}

	public String getCompany(OrgUsr userDto){
		if(userDto.getBizOrgType().equals("COMPANY")){
			return userDto.getBizOrgCode();
		}else{
			OrgUsr bizOrg = orgUsrMapper.queryBySequenceNbr(userDto.getParentId());
			return getCompany(bizOrg);
		}
	}

	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<>();
		String bizOrgCode = reginParams.getPersonIdentity().getBizOrgCode();
		// 权限处理
		if (!logic){
			OrgUsr orgUsr = orgUsrMapper.selectById(reginParams.getPersonIdentity().getCompanyId());
			//判断登陆人是否已经是顶级节点单位
			if (!ObjectUtils.isEmpty(orgUsr) && orgUsr.getParentId() != null) {
				orgUsr = this.selectParentOrgUsr(orgUsr);
				bizOrgCode = orgUsr.getBizOrgCode() != null? orgUsr.getBizOrgCode():bizOrgCode;
			}
		}
		PermissionInterceptorContext.setDataAuthRule(authKey);
		param.put("bizOrgCode",bizOrgCode);
		List<OrgUsr> list = orgUsrMapper.companyDeptListWithPersonCount(param);
		return buildTreeParallel(list);
	}

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

	public List<OrgMenuDto> companyTreeByUserNumberCurrentNew(ReginParams reginParams) {
		Map<String, Object> param = new HashMap<>();
		// 权限处理
		param.put("bizOrgCode", reginParams.getPersonIdentity().getBizOrgCode());
		List<OrgUsr> list = orgUsrMapper.companyDeptListWithPersonCountNew(param);
		list = list.stream().filter(e -> e.getBizOrgCode().equals(reginParams.getPersonIdentity().getBizOrgCode())).collect(Collectors.toList());
		return buildTreeParallel(list);
	}

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

		List<OrgUsr> list = null;
		list = orgUsrMapper.companyTreeByUser(reginParams.getPersonIdentity().getBizOrgCode());
		return buildTreeParallel(list);
	}


	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) {
		List<OrgUsr> da=null;
		if (ValidationUtil.isEmpty(amosIds)) {
			return da;
		}
		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) {
		List<OrgUsr> da=null;
		if (StringUtils.isEmpty(bizOrgCode)) {
			return da;
		}
		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());
	}

	private List<OrgUsr> getIdByOrgCode(String bizOrgCode, Long id) {
		List<OrgUsr> da=null;
		if (StringUtils.isEmpty(bizOrgCode)) {
			return da;
		}
		LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
		wrapper.likeRight(OrgUsr::getBizOrgCode,bizOrgCode);
		wrapper.isNotNull(OrgUsr::getBizOrgCode);
		wrapper.eq(BaseEntity::getIsDelete,false);
		wrapper.eq(OrgUsr::getParentId, id);
		wrapper.eq(OrgUsr::getBizOrgType, CommonConstant.BIZ_ORG_TYPE_PERSON);
		return this.baseMapper.selectList(wrapper).stream().collect(Collectors.toList());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public PeopleInfoDto peopleSave(PeopleInfoDto peopleInfoDto) {
		// 1.保存cb_org_usr表
		OrgUsr orgUsr = peopleSaveOrgUsr(peopleInfoDto.getFirefighters());

		// 2.保存cb_dynamic_form_instance表 人员基本信息
		OrgUsrDto orgUsrDto = saveDynamicformInstance(orgUsr, peopleInfoDto);
		Long sequenceNbr = orgUsrDto.getSequenceNbr();
		if (!ObjectUtils.isEmpty(sequenceNbr)) {
			peopleInfoDto.getFirefightersContacts().setOrgUsrId(sequenceNbr.toString());
			peopleInfoDto.getFirefighters().setOrgUsrId(sequenceNbr.toString());
			peopleInfoDto.getPostEduDtoObj().getFirefightersWorkexperience().setOrgUsrId(sequenceNbr.toString());
			peopleInfoDto.getPostEduDtoObj().getFirefightersEducation().setOrgUsrId(sequenceNbr.toString());
			peopleInfoDto.getPostEduDtoObj().getFirefightersPost().setOrgUsrId(sequenceNbr.toString());
			peopleInfoDto.getFirefighters().setSequenceNbr(sequenceNbr.toString());
		}

		if (peopleInfoDto.getFirefighters() != null && "1601".equals(peopleInfoDto.getFirefighters().getPeopleType())) {
			// 3.同步保存cb_firefighters消防人员基础信息
			saveFirefighters(peopleInfoDto);
		} else {
			// 保存联系人
			saveFirefightersContacts(peopleInfoDto);
		}
		// 4.保存岗位信息
		saveFirefightersPost(peopleInfoDto.getPostEduDtoObj(), orgUsrDto.getSequenceNbr());
		//  巡检站端与中心级数据同步
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
			@Override
			public void afterCommit() {
				// 事物提交后业务逻辑
				dataSyncService.OrgUsrSyncDtoDataSync(sequenceNbr);
			}
		});
		return peopleInfoDto;
	}

	public OrgUsr peopleSaveOrgUsr(PeopleBasicInfoDto peopleBasicInfoDto) {
		OrgUsr orgUsr = new OrgUsr();
		orgUsr.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_PERSON);
		if (ValidationUtil.isEmpty(peopleBasicInfoDto.getSequenceNbr())) { // 新增
			// cb_org_user表biz_org_code表示该资源自己的编码，同一单位下唯一。只用父单位bizOrgCode会引起bug6259，遂改为父单位bizOrgCode + getOrgCodeStr()
			orgUsr.setBizOrgCode(peopleBasicInfoDto.getBizOrgCode() + getOrgCodeStr());
		} else { // 编辑
			OrgUsr o = getById(peopleBasicInfoDto.getSequenceNbr());
			orgUsr.setBizOrgCode(o.getBizOrgCode());
		}
		orgUsr.setAmosOrgId(peopleBasicInfoDto.getAmosUserId());
		orgUsr.setAmosOrgCode(peopleBasicInfoDto.getAmosName());
		orgUsr.setBizOrgName(peopleBasicInfoDto.getName());
		orgUsr.setParentId(peopleBasicInfoDto.getCompany());
		orgUsr.setParentName(peopleBasicInfoDto.getBizOrgName());
		orgUsr.setPersonImg(peopleBasicInfoDto.getPersonImg());
		orgUsr.setIsDelete(false);
		return orgUsr;
	}

	private OrgUsrDto saveDynamicformInstance(OrgUsr orgUsr,PeopleInfoDto peopleInfoDto) {
		List<DynamicFormInstance> dynamicFormInstancelist = dynamicFormColumn(peopleInfoDto, true);
		return  saveOrgUsrDynamicFormInstance(orgUsr, dynamicFormInstancelist);
	}

	public List<DynamicFormInstance> dynamicFormColumn(PeopleInfoDto peopleInfoDto, boolean flag){
		// 动态字段填充
		List<DynamicFormInitDto> dynamicFormColumn = dynamicFormColumnServiceImpl.getFormlist("246");
		Map<String, Object> map = new HashMap<>();
		// 获取对象属性和值
		Field[] fields = peopleInfoDto.getFirefighters().getClass().getDeclaredFields();
		for (Field field : fields) {
			try{
				field.setAccessible(true);
				Object value = field.get(peopleInfoDto.getFirefighters());
				String name = field.getName();
				map.put(name, value);
			}	catch (Exception ex){
				logger.error("获取{}字段值失败, {}", field.getName(), ex);
			}
		}
		List<DynamicFormInstanceDto> dynamicFormValue = new ArrayList<>();
		List<DynamicFormInstance> dynamicFormInstancelist = new ArrayList<>();

		dynamicFormColumn.forEach(DynamicFormInitDto -> {
			dynamicFormValue.add(DynamicFormInitDto.getFormItemDescr());
		});

		FirefightersPost firefightersPost = peopleInfoDto.getPostEduDtoObj().getFirefightersPost();
		PeopleBasicInfoDto firefighters = peopleInfoDto.getFirefighters();
		String s2 = JSON.toJSONString(firefighters);
		Map map2 = JSON.parseObject(s2, Map.class);

		String s = JSON.toJSONString(firefightersPost);
		Map map1 = JSON.parseObject(s, Map.class);
		map1.putAll(map2);

		dynamicFormValue.forEach(dynamicFormInstanceDto -> {
			String key = dynamicFormInstanceDto.getFieldCode();
			Object value = map.get(key);
			if (value != null) {
				Object o = null;
				if (key.contains("Code")) {
					String code = key.substring(0, key.indexOf("Code"));
					o = map.get(code);
				}
				if (!ObjectUtils.isEmpty(o)) {
					dynamicFormInstanceDto.setFieldValue(value.toString());
					dynamicFormInstanceDto.setFieldValueLabel(o.toString());
				} else {
					if(flag) {
						dynamicFormInstanceDto.setFieldValue(value.toString());
					} else {
						if(!ValidationUtil.isEmpty(value)) {
							dynamicFormInstanceDto.setFieldValue(value.toString());
						}
					}
				}
				if ("birthdayTime".equals(key)) {
					SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					try {
						String date = ft.format(value);
						dynamicFormInstanceDto.setFieldValue(date);
					} catch (Exception e) {
						logger.error("日期转换失败");
					}
				}
			}
			DynamicFormInstance dynamicFormInstance = new DynamicFormInstance();
			BeanUtils.copyProperties(dynamicFormInstanceDto, dynamicFormInstance);
			if ("gender".equals(dynamicFormInstance.getFieldCode())){
				dynamicFormInstance.setFieldValueLabel("346".equals(String.valueOf(dynamicFormInstance.getFieldValue()))?"男":"女");
			}
			if ("peopleType".equals(dynamicFormInstance.getFieldCode()) && dynamicFormInstance.getFieldValue() != null){
				dynamicFormInstance.setFieldValueLabel(dataDictionaryService.getById(dynamicFormInstance.getFieldValue()).getName());
			}
			if ("positionType".equals(dynamicFormInstance.getFieldCode()) && peopleInfoDto.getFirefighters().getJobTitleCode() != null){
				dynamicFormInstance.setFieldValueLabel(peopleInfoDto.getFirefighters().getJobTitle());
			}
			if ("administrativePositionCode".equals(dynamicFormInstance.getFieldCode()) && firefightersPost.getAdministrativePositionCode() != null){
				dynamicFormInstance.setFieldValueLabel(dataDictionaryService.getById(map1.get("administrativePositionCode").toString()).getName());
			}
			String fieldCode = dynamicFormInstance.getFieldCode();
			if ("auditCycle".equals(dynamicFormInstance.getFieldCode())  && dynamicFormInstance.getFieldValue() != null){
				dynamicFormInstance.setFieldValue(map1.get(fieldCode).toString());
				dynamicFormInstance.setFieldValueLabel(dataDictionaryService.getById(dynamicFormInstance.getFieldValue()).getName());
			}
			if ("certificateType".equals(dynamicFormInstance.getFieldCode())){
				dynamicFormInstance.setFieldValue(map1.get(fieldCode) == null ? "" :map1.get(fieldCode).toString());
				dynamicFormInstance.setFieldValueLabel(map1.get("certificateTypeCode") == null ? "":map1.get("certificateTypeCode").toString());
			}
			if (map1.containsKey(fieldCode) && fieldCode.contains("Code") ){
				dynamicFormInstance.setFieldValue(map1.get(fieldCode) == null ? "" :map1.get(fieldCode).toString());
			}
			if (map1.containsKey(fieldCode.substring(0,fieldCode.length()-4))){
				dynamicFormInstance.setFieldValueLabel(map1.get(fieldCode.substring(0,fieldCode.length()-4)).toString());
			}
			// 动态表单存在默认值
			if ("birthdayTime".equals(dynamicFormInstance.getFieldCode()) && ObjectUtils.isEmpty(peopleInfoDto.getFirefighters().getBirthdayTime())){
				dynamicFormInstance.setFieldValue(null);
			}
			dynamicFormInstancelist.add(dynamicFormInstance);
		});

		return dynamicFormInstancelist;
	}

	public void saveFirefighters(PeopleInfoDto peopleInfoDto){
		/*3184 消防人员，编辑页面岗位选择子分类保存成功后，概要中岗位未修改 chenzhao start 2021-10-19*/

		PeopleBasicInfoDto firefighters = peopleInfoDto.getFirefighters();
		Firefighters firefightersNew = new Firefighters();
		BeanUtils.copyProperties(firefighters, firefightersNew);
		firefightersNew.setMobilePhone(firefighters.getTelephone());
		firefightersNew.setEmployeeNumber(firefighters.getPersonNumber());
		firefightersNew.setCertificateNumber(firefighters.getCertificatesNumber());
		firefightersNew.setAmosName(firefighters.getAmosName());
		firefightersNew.setPersonnelPhotos(firefighters.getPersonImg());
		FirefightersInfoDto firefightersInfoDto = new FirefightersInfoDto(firefightersNew, peopleInfoDto.getFirefightersContacts());

		if (!ObjectUtils.isEmpty(firefighters.getCertificatesTypeCode())) {
			DataDictionary gwmc = dataDictionaryService.getByCode(firefighters.getCertificatesTypeCode(), "RYZJLX");
			firefightersNew.setCertificatesType(gwmc.getName());
		}

		if (!ObjectUtils.isEmpty(firefighters.getStateCode())) {
			DataDictionary gwmc = dataDictionaryService.getByCode(firefighters.getStateCode(), "RYZT");
			firefightersNew.setState(gwmc.getName());
		}

		iFirefightersService.saveFirefighters(firefightersInfoDto);
		Long sequenceNbr = firefightersInfoDto.getFirefighters().getSequenceNbr();
		peopleInfoDto.getPostEduDtoObj().getFirefightersPost().setFirefightersId(sequenceNbr);
		peopleInfoDto.getPostEduDtoObj().getFirefightersEducation().setFirefightersId(sequenceNbr);
		peopleInfoDto.getPostEduDtoObj().getFirefightersWorkexperience().setFirefightersId(sequenceNbr);
	}

	public void saveFirefightersPost(FirefightersDataDto firefightersDataDto, Long id){
		QueryWrapper queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("org_usr_id", id);
		FirefightersPost firefightersPost = iFirefightersPostService.getOne(queryWrapper);

		/*bug3071 消防人员，专家领域选择子分类时概要信息中专家领域未显示 2021-10-09 chenzhao */
		if (firefightersDataDto.getFirefightersPost().getAreasExpertiseCode() != null){
			String areasExpertiseCode = firefightersDataDto.getFirefightersPost().getAreasExpertiseCode();
			DataDictionary zjly = dataDictionaryService.getByCode(areasExpertiseCode, "ZJLY");
			firefightersDataDto.getFirefightersPost().setAreasExpertise(zjly.getName());
		}
		/*bug3071 消防人员，专家领域选择子分类时概要信息中专家领域未显示 2021-10-09 chenzhao */
		if (firefightersPost == null) {
			firefightersDataDto.getFirefightersPost().setOrgUsrId(String.valueOf(id));
			iFirefightersPostService.save(firefightersDataDto.getFirefightersPost());
		} else {
			iFirefightersPostService.update(firefightersDataDto.getFirefightersPost(), queryWrapper);
		}

		FirefightersEducation firefightersEducation = ifirefightersEducationService.getOne(queryWrapper);
		if(firefightersEducation == null) {
			firefightersDataDto.getFirefightersEducation().setOrgUsrId(String.valueOf(id));
			ifirefightersEducationService.save(firefightersDataDto.getFirefightersEducation());
		}else {
			ifirefightersEducationService.update(firefightersDataDto.getFirefightersEducation(),queryWrapper);
		}

		FirefightersWorkexperience firefightersWorkexperience = ifirefightersWorkexperienceService.getOne(queryWrapper);
		if(firefightersWorkexperience == null) {
			firefightersDataDto.getFirefightersWorkexperience().setOrgUsrId(String.valueOf(id));
			ifirefightersWorkexperienceService.save(firefightersDataDto.getFirefightersWorkexperience());
		}else {
			ifirefightersWorkexperienceService.update(firefightersDataDto.getFirefightersWorkexperience(),queryWrapper);
		}
	}

	private void saveFirefightersContacts(PeopleInfoDto peopleInfoDto) {
		if(peopleInfoDto.getFirefightersContacts() != null){
			FirefightersContacts firefightersContact = peopleInfoDto.getFirefightersContacts();
			firefightersContactsService.save(firefightersContact);
			peopleInfoDto.setFirefightersContacts(firefightersContact);
		}
	}

	@Override
	public PeopleInfoDto selectPeopleById(Long id) {
		PeopleBasicInfoDto peopleBasicInfoDto = new PeopleBasicInfoDto();
		OrgUsr orgUsr = getById(id);
		// 动态表单数据
		List<FormValue> formValues = getFormValue(id);

		Map<String, Object> collect = formValues.stream().collect(Collectors.toMap(FormValue::getKey,
				formValue -> !ObjectUtils.isEmpty(formValue.getValue()) ? formValue.getValue() : ""));
		// 获取对象属性和值
		Field[] fields = peopleBasicInfoDto.getClass().getDeclaredFields();
		for (Field field : fields) {
			try{
				field.setAccessible(true);
				String name = field.getName();
				Object value = collect.get(name);
				String genericType = ((Class)field.getGenericType()).getSimpleName();
				if ("Date".equals(genericType)) {
					if (!ObjectUtils.isEmpty(value)) {
						Date date;
						SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

							date = ft.parse(value.toString());
							field.set(peopleBasicInfoDto, date);

					}
				} else {
					field.set(peopleBasicInfoDto, value);
				}
			} catch (Exception ex){
				logger.error("获取{}字段值失败, {}", field.getName(), ex);
			}
		}



		if (!ObjectUtils.isEmpty(orgUsr.getSequenceNbr())) {
			peopleBasicInfoDto.setName(orgUsr.getBizOrgName());
			peopleBasicInfoDto.setAmosUserId(orgUsr.getAmosOrgId());
			peopleBasicInfoDto.setAmosName(orgUsr.getAmosOrgCode());
			peopleBasicInfoDto.setSequenceNbr(orgUsr.getSequenceNbr().toString());
			peopleBasicInfoDto.setCompany(orgUsr.getParentId());
			peopleBasicInfoDto.setBizOrgName(orgUsr.getParentName());
			peopleBasicInfoDto.setBizOrgCode(orgUsr.getBizOrgCode());
			peopleBasicInfoDto.setCompanyCode(orgUsr.getParentId());
			peopleBasicInfoDto.setCompanyName(orgUsr.getParentName());
		}

		if ("1601".equals(peopleBasicInfoDto.getPeopleType())) {
			QueryWrapper<Firefighters> firefightersQueryWrapper = new QueryWrapper<>();
			Firefighters firefighters = iFirefightersService.getOne(firefightersQueryWrapper.eq("org_usr_id", id).eq("is_delete", 0));
			if (!ObjectUtils.isEmpty(firefighters)) {
				peopleBasicInfoDto.setState(firefighters.getState());
				peopleBasicInfoDto.setCompanyCode(firefighters.getCompanyCode());
				peopleBasicInfoDto.setCompany(firefighters.getCompany());
				peopleBasicInfoDto.setCompanyName(firefighters.getCompanyName());
				peopleBasicInfoDto.setBizOrgCode(firefighters.getBizOrgCode());
				peopleBasicInfoDto.setBizOrgName(firefighters.getBizOrgName());
				peopleBasicInfoDto.setFireTeamId(firefighters.getFireTeamId());
				peopleBasicInfoDto.setFireTeamName(firefighters.getFireTeamName());
				//10445 BUG
				peopleBasicInfoDto.setCertificatesType(firefighters.getCertificatesType());
			}
		}

		// 获取联系人
		QueryWrapper<FirefightersContacts> queryWrapper1 = new QueryWrapper<>();
		queryWrapper1.eq("org_usr_id", String.valueOf(id));
		FirefightersContacts firefightersContacts = ifirefightersContactsService.getOne(queryWrapper1);
		// 获取岗位标签
		QueryWrapper queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("org_usr_id", String.valueOf(id));
		FirefightersDataDto firefightersDataDto = new FirefightersDataDto(
				ifirefightersWorkexperienceService.getOne(queryWrapper),
				ifirefightersEducationService.getOne(queryWrapper), iFirefightersPostService.getOne(queryWrapper));

		return  new PeopleInfoDto(peopleBasicInfoDto, firefightersContacts, firefightersDataDto);
	}

	@Override
	public PeopleInfoDto selectPeopleByIdNoAuth(Long id) {
		PeopleBasicInfoDto peopleBasicInfoDto = new PeopleBasicInfoDto();
		OrgUsr orgUsr = this.baseMapper.selectById(id);
		QueryWrapper<OrgUsr> queryWrapper2 = new QueryWrapper<>();
		queryWrapper2.eq("sequence_nbr", orgUsr.getParentId());
		OrgUsr orgUsrParent = this.baseMapper.selectOne(queryWrapper2);
		// 动态表单数据
		List<FormValue> formValues = getFormValue(id);

		Map<String, Object> collect = formValues.stream().collect(Collectors.toMap(FormValue::getKey,
				formValue -> !ObjectUtils.isEmpty(formValue.getValue()) ? formValue.getValue() : ""));
		// 获取对象属性和值
		Field[] fields = peopleBasicInfoDto.getClass().getDeclaredFields();
		for (Field field : fields) {
			try{
				field.setAccessible(true);
				String name = field.getName();
				Object value = collect.get(name);
				String genericType = ((Class)field.getGenericType()).getSimpleName();
				if ("Date".equals(genericType)) {
					if (!ObjectUtils.isEmpty(value)) {
						Date date;
						SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

						date = ft.parse(value.toString());
						field.set(peopleBasicInfoDto, date);

					}
				} else {
					field.set(peopleBasicInfoDto, value);
				}
			} catch (Exception ex){
				logger.error("获取{}字段值失败, {}", field.getName(), ex);
			}
		}

		if (!ObjectUtils.isEmpty(orgUsr.getSequenceNbr())) {
			peopleBasicInfoDto.setName(orgUsr.getBizOrgName());
			peopleBasicInfoDto.setAmosUserId(orgUsr.getAmosOrgId());
			peopleBasicInfoDto.setAmosName(orgUsr.getAmosOrgCode());
			peopleBasicInfoDto.setSequenceNbr(orgUsr.getSequenceNbr().toString());
			peopleBasicInfoDto.setCompany(orgUsr.getParentId());
			peopleBasicInfoDto.setBizOrgName(orgUsr.getParentName());
			peopleBasicInfoDto.setBizOrgCode(orgUsrParent.getBizOrgCode());
			peopleBasicInfoDto.setCompanyCode(orgUsr.getParentId());
			peopleBasicInfoDto.setCompanyName(orgUsr.getParentName());
			peopleBasicInfoDto.setPersonStatus(orgUsr.getPersonStatus());
		}

		if ("1601".equals(peopleBasicInfoDto.getPeopleType())) {
			QueryWrapper<Firefighters> firefightersQueryWrapper = new QueryWrapper<>();
			Firefighters firefighters = iFirefightersService.getOne(firefightersQueryWrapper.eq("org_usr_id", id).eq("is_delete", 0));
			if (!ObjectUtils.isEmpty(firefighters)) {
				peopleBasicInfoDto.setState(firefighters.getState());
				peopleBasicInfoDto.setCompanyCode(firefighters.getCompanyCode());
				peopleBasicInfoDto.setCompany(firefighters.getCompany());
				peopleBasicInfoDto.setCompanyName(firefighters.getCompanyName());
				peopleBasicInfoDto.setBizOrgCode(firefighters.getBizOrgCode());
				peopleBasicInfoDto.setBizOrgName(firefighters.getBizOrgName());
				peopleBasicInfoDto.setFireTeamId(firefighters.getFireTeamId());
				peopleBasicInfoDto.setFireTeamName(firefighters.getFireTeamName());
				//10445 BUG
				peopleBasicInfoDto.setCertificatesType(firefighters.getCertificatesType());
			}
		}

		// 获取联系人
		QueryWrapper<FirefightersContacts> queryWrapper1 = new QueryWrapper<>();
		queryWrapper1.eq("org_usr_id", String.valueOf(id));
		FirefightersContacts firefightersContacts = ifirefightersContactsService.getOne(queryWrapper1);
		// 获取岗位标签
		QueryWrapper queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("org_usr_id", String.valueOf(id));
		FirefightersDataDto firefightersDataDto = new FirefightersDataDto(
				ifirefightersWorkexperienceService.getOne(queryWrapper),
				ifirefightersEducationService.getOne(queryWrapper), iFirefightersPostService.getOne(queryWrapper));

		return  new PeopleInfoDto(peopleBasicInfoDto, firefightersContacts, firefightersDataDto);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String deletePeopleById(Long id, String type, AgencyUserModel user) {

		if ("1601".equals(type)) {
			QueryWrapper<Firefighters> firefightersQueryWrapper = new QueryWrapper<>();
			Firefighters firefighters = iFirefightersService.getOne(firefightersQueryWrapper.eq("org_usr_id", id).eq("is_delete", 0));
			Long firefightersSequenceNbr = firefighters.getSequenceNbr();

			//BUG 2761 判断人员删除时的逻辑 如果被选为队伍联系人则无法被删除 bykongfm
			List fireTeam = iFireTeamService.list(new LambdaQueryWrapper<FireTeam>().eq(FireTeam::getIsDelete, false).eq(FireTeam::getContactUserId, id));
			if (fireTeam.size() > 0) {
				return "-1";
			}
			QueryWrapper<FirefightersJacket> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq(FIREFIGHTERSID, firefightersSequenceNbr);
			queryWrapper.eq("is_delete", 0);
			List<FirefightersJacket> firefightersJacket = firefightersJacketMapper.selectList(queryWrapper);
			if (firefightersJacket != null && firefightersJacket.size() > 0) {
				// BUG 2222 by litw start 2021年9月10日
				return "-2";
			}
		}

		// 1.删除单位人员

		// 删除时，只作逻辑删除
		// BUG 2741 首先判断是否为公司 如果公司底下有人员不可直接删除 bykongfm
		// bug 2882 判断是否为部门 如果部门底下有人员不可直接删除 chenzhao 2021-09-27 start
		OrgUsr tempOrg = iOrgUsrService.getById(id.toString());
		// 当前登录人不能删除自己
		if (tempOrg.getAmosOrgId() != null && tempOrg.getAmosOrgId().equals(user.getUserId())) {
			return "-3";
		}

		if (tempOrg.getBizOrgType().equals("COMPANY") || tempOrg.getBizOrgType().equals("DEPARTMENT")) {
			List<OrgUsr> tempList = iOrgUsrService
					.list(new LambdaQueryWrapper<OrgUsr>().eq(OrgUsr::getParentId, id).eq(OrgUsr::getIsDelete, false));
			/* bug3031 删除机场单位后，队伍所属单位字段数据未清空 2021-10-13 start */
			List<FireTeam> fireTeams = fireTeamMapper.byTeamId(id);
			if (tempList.size() > 0 || fireTeams.size() > 0) {
				return "-3";
			}
			/* bug3031 删除机场单位后，队伍所属单位字段数据未清空 2021-10-13 end */
		}
		// bug 2882 判断是否为部门 如果部门底下有人员不可直接删除 chenzhao 2021-09-27 end
		/* bug 2812 一次删除多条数据 传入类型修改为string 问题解决 2021-09-09 陈召 开始 */
		iOrgUsrService.update(new UpdateWrapper<OrgUsr>().eq("sequence_nbr", String.valueOf(id)).set("is_delete",
				CommonConstant.IS_DELETE_01));
		/* bug 2812 一次删除多条数据 传入类型修改为string 问题解决 2021-09-09 陈召 结束 */
		try {
			eSOrgUsrService.deleteById(id);
			emqKeeper.getMqttClient().publish(airportDeleteTopic, JSON.toJSONString(id).getBytes(), 2, false);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}

		// 2. 删除岗位页签
		deleteFirefightersPost(String.valueOf(id));

		// 3.根据type是否删除消防人员
		if ("1601".equals(type)) {
			deleteFirefighters(id);
		}

		// 4.解决人员更换岗位类型然后删除，App打卡还有脏数据问题
		firefightersService.update(new UpdateWrapper<Firefighters>().eq("org_usr_id", id).set("is_delete", 1));

		//  巡检站端与中心级数据同步
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
			@Override
			public void afterCommit() {
				// 事物提交后业务逻辑
				dataSyncService.OrgUsrSyncDtoDelDataSync(id);
			}
		});

		return "0";
	}

	public String deleteFirefighters(Long userId){
		QueryWrapper<Firefighters> firefightersQueryWrapper = new QueryWrapper<>();
		Firefighters firefighters = iFirefightersService.getOne(firefightersQueryWrapper.eq("org_usr_id", userId).eq("is_delete", 0));
		if(ObjectUtils.isEmpty(firefighters)){
			return "0";
		}
		Long id = firefighters.getSequenceNbr();

		//BUG 2761 判断人员删除时的逻辑 如果被选为队伍联系人则无法被删除 bykongfm
		List fireTeam = iFireTeamService.list(new LambdaQueryWrapper<FireTeam>().eq(FireTeam::getIsDelete, false).eq(FireTeam::getContactUserId, userId));
		if (!fireTeam.isEmpty()) {
			return "-1";
		}
		QueryWrapper<FirefightersJacket> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq(FIREFIGHTERSID, id);
		queryWrapper.eq("is_delete", 0);
		List<FirefightersJacket> firefightersJacket = firefightersJacketMapper.selectList(queryWrapper);
		if (!firefightersJacket.isEmpty()) {
			// BUG 2222 by litw start 2021年9月10日
			return "-2";
		}
		try {
			this.iFirefightersService.update(new UpdateWrapper<Firefighters>().eq("sequence_nbr", id).set("is_delete", 1));
			iFirefightersThoughtService
					.update(new UpdateWrapper<FirefightersThought>().eq(FIREFIGHTERSID, id).set("is_delete", 1));
			iFirefightersContractService
					.update(new UpdateWrapper<FirefightersContract>().eq(FIREFIGHTERSID, id).set("is_delete", 1));

			FirefightersJacket firefightersJacket1 = new FirefightersJacket();
			firefightersJacket1.setFirefightersId(id);
			firefightersJacket1.setIsDelete(true);
			firefightersJacketMapper.updateById(firefightersJacket1);
			// 删除缓存
			redisUtils.del(RedisKey.FIREFIGHTERS_ID + id, RedisKey.FIREFIGHTERS_LIST_ID + id);
			return "0";
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("删除失败！");
		}
	}

	public void deleteFirefightersPost(String id){
		iFirefightersPostService
				.update(new UpdateWrapper<FirefightersPost>().eq("org_usr_id", id).set("is_delete", 1));
		ifirefightersContactsService
				.update(new UpdateWrapper<FirefightersContacts>().eq("org_usr_id", id).set("is_delete", 1));
		ifirefightersEducationService
				.update(new UpdateWrapper<FirefightersEducation>().eq("org_usr_id", id).set("is_delete", 1));
		ifirefightersWorkexperienceService
				.update(new UpdateWrapper<FirefightersWorkexperience>().eq("org_usr_id", id).set("is_delete", 1));
	}

	@Override
	public boolean checkCertificatesNumber(String certificatesNumber, Long orgUserId) {
		List<DynamicFormInstance> list = orgUsrMapper.checkCertificatesNumber(certificatesNumber, orgUserId);
		return !list.isEmpty();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String deleteFirefighterPeopleById(Long id,String type) {
		String flag = deleteFirefighters(id);
		// 基础信息人员类型修改为非消防
		UpdateWrapper<DynamicFormInstance> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("instance_id", id);
		updateWrapper.eq("field_code", "peopleType");
		updateWrapper.set("field_value", type);
		if ("0".equals(flag)) {
			dynamicFormInstanceService.update(updateWrapper);
		}
		return flag;
	}

	public List<OrgUsr> personListByBizOrgCode(String bizOrgCode){
		QueryWrapper<OrgUsr> wrapper = new QueryWrapper<>();
		wrapper.eq("is_delete",false);
		wrapper.eq("biz_org_code",bizOrgCode);
		wrapper.eq("biz_org_type","PERSON");
		return 	baseMapper.selectList(wrapper);
	}

	public List<OrgUsr> personByBizOrgCode(String bizOrgCode){
		QueryWrapper<OrgUsr> wrapper = new QueryWrapper<>();
		wrapper.eq("is_delete",false);
		wrapper.like("biz_org_code",bizOrgCode);
		wrapper.eq("biz_org_type","PERSON");
		wrapper.isNotNull("amos_org_id");
		return 	baseMapper.selectList(wrapper);
	}

	public List<OrgUsr> getDetByCompanyId(String companyId){
		QueryWrapper<OrgUsr> wrapper = new QueryWrapper<>();
		wrapper.eq("is_delete",false);
		wrapper.eq("parent_id",companyId);
		wrapper.eq("biz_org_type","DEPARTMENT");
		return 	baseMapper.selectList(wrapper);
	}

	public List<OrgMenuDto> companyTreeByUserToPatrolRoute(ReginParams reginParams) {
		Map<String, Object> param = new HashMap<>();
		String bizOrgCode = reginParams.getPersonIdentity().getCompanyBizOrgCode();
		param.put("bizOrgCode", bizOrgCode);
		List<OrgUsr> list = orgUsrMapper.companyTreeByUserToPatrolRoute(param);
		return buildTreeParallel(list);
	}

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

	@Override
	public List<OrgMenuDto> companyUserTreeByUserAndTypeAll(String bizorgcode) {

		List<OrgUsr> list = orgUsrMapper.companyUserTreeByUserAndTypeALL(bizorgcode);
		return buildTreeParallel(list);
	}

	@Override
	public List<DynamicFormInstance> selectTelById(List<String> ids, String type) {
		LambdaQueryWrapper<DynamicFormInstance> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(DynamicFormInstance::getFieldCode, type);
		wrapper.in(DynamicFormInstance::getInstanceId, ids);
		return dynamicFormInstanceService.list(wrapper);
	}

	@Override
	public List<FirefightersPost> selectPostById(List<String> ids) {
		LambdaQueryWrapper<FirefightersPost> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(FirefightersPost::getOrgUsrId, ids);
		return iFirefightersPostService.list(queryWrapper);
	}

	@Override
	public RiskBizInfoVo getPersonInfo(String id, String type) {
		RiskBizInfoVo riskBizInfoVo = new RiskBizInfoVo();
		if ("personInfo".equals(type)) {
			PeopleInfoDto peopleInfoDto =iOrgUsrService.selectPeopleByIdNoAuth(Long.valueOf(id));
		   return getRiskBizInfo(riskBizInfoVo,peopleInfoDto, id);
		} else {
			LambdaQueryWrapper<OrgUsr> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(OrgUsr::getAmosOrgId,id);
			OrgUsr orgUsr = iOrgUsrService.getOne(queryWrapper);
			PeopleInfoDto peopleInfoDto =iOrgUsrService.selectPeopleByIdNoAuth(orgUsr.getSequenceNbr());
			return getRiskBizInfo(riskBizInfoVo,peopleInfoDto,String.valueOf(orgUsr.getSequenceNbr()));
		}
	}

	@Override
	public OrgUsr getPersonOne(String id) {
		OrgUsr orgUsr = orgUsrMapper.selectById(Long.valueOf(id));
		return orgUsr;
	}


	@Override
	public void updatePersonStatus(String status, String id) {
		orgUsrMapper.updatePersonStatus(status,id);
	}

	@Override
	public String reportResult(String startTime, String endTime, String bizOrgCode) {
		List<Map<String, Object>> stringObjectMap = orgUsrMapper.reportResult(startTime, endTime, bizOrgCode);
		return String.valueOf(stringObjectMap.size());
	}


	private RiskBizInfoVo getRiskBizInfo(RiskBizInfoVo riskBizInfoVo, PeopleInfoDto peopleInfoDto,String id) {
		Map<String, Object> map = new HashMap<>();
		riskBizInfoVo.setWarningObjectName(peopleInfoDto.getFirefighters().getName());
		riskBizInfoVo.setWarningObjectCode(id); // 存为cb_org_user 表id 返回给idx 为附码业务后续处理
		riskBizInfoVo.setSourceAttribution(peopleInfoDto.getFirefighters().getBizOrgCode());
		riskBizInfoVo.setSourceAttributionDesc(peopleInfoDto.getFirefighters().getBizOrgName());
		try {
			riskBizInfoVo.setWarningTime(DateUtils.dateFormat(new Date(), DateUtils.DATE_TIME_PATTERN));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		map.put("bizOrgName", peopleInfoDto.getFirefighters().getBizOrgName());
		map.put("bizOrgCode", peopleInfoDto.getFirefighters().getBizOrgCode());
		map.put("userName", peopleInfoDto.getFirefighters().getName());
		map.put("gender", peopleInfoDto.getFirefighters().getGender());
		map.put("phone", peopleInfoDto.getFirefighters().getMobilePhone());
		Map<String, Object> typeMap = orgUsrMapper.getPersonType(peopleInfoDto.getFirefighters().getPeopleType());
		map.put("userType", typeMap.get("peopleType"));
		map.put("jobType", peopleInfoDto.getFirefighters().getJobTitle());
		map.put("jobZz", peopleInfoDto.getPostEduDtoObj().getFirefightersPost().getPostQualification());

		List<RiskDynamicDetailsVo> detailsVos = new ArrayList<>();
		RiskDynamicDetailsVo dynamicDetailsVo = new RiskDynamicDetailsVo();
		dynamicDetailsVo.setTabName("人员基本信息");
		List<TableContentVo> contentVos = new ArrayList<>();
		for (DynamicLabelEnum u : DynamicLabelEnum.values()) {
			TableContentVo contentVo = new TableContentVo();
			contentVo.setKey(u.getCode());
			switch (u.getCode()) {
				case "name":
					contentVo.setLabel(u.getDescribe());
					contentVo.setValue(peopleInfoDto.getFirefighters().getName());
					contentVo.setType("text");
					break;
				case "personNumber":
					contentVo.setLabel(u.getDescribe());
					contentVo.setValue(peopleInfoDto.getFirefighters().getPersonNumber());
					contentVo.setType("text");
					break;
				case "bizOrgName":
					contentVo.setLabel(u.getDescribe());
					contentVo.setValue(peopleInfoDto.getFirefighters().getBizOrgName());
					contentVo.setType("text");
					break;
				case "peopleType":
					contentVo.setLabel(u.getDescribe());
					contentVo.setValue(peopleInfoDto.getFirefighters().getPeopleType());
					contentVo.setType("text");
					break;
				case "mobilePhone":
					contentVo.setLabel(u.getDescribe());
					contentVo.setValue(peopleInfoDto.getFirefighters().getMobilePhone());
					contentVo.setType("text");
					break;
				case "gender":
					contentVo.setLabel(u.getDescribe());
					contentVo.setValue(peopleInfoDto.getFirefighters().getGender());
					contentVo.setType("text");
					break;
				case "certificatesType":
					contentVo.setLabel(u.getDescribe());
					contentVo.setValue(peopleInfoDto.getFirefighters().getCertificatesType());
					contentVo.setType("text");
					break;
				case "certificatesNumber":
					contentVo.setLabel(u.getDescribe());
					contentVo.setValue(peopleInfoDto.getFirefighters().getCertificatesNumber());
					contentVo.setType("text");
					break;
				case "jobTitle":
					contentVo.setLabel(u.getDescribe());
					contentVo.setValue(peopleInfoDto.getPostEduDtoObj().getFirefightersPost().getJobTitle());
					contentVo.setType("text");
					break;
				case "postQualification":
					contentVo.setLabel(u.getDescribe());
					contentVo.setValue(peopleInfoDto.getPostEduDtoObj().getFirefightersPost().getPostQualification());
					contentVo.setType("text");
					break;
				case "fireManagementPost":
					contentVo.setLabel(u.getDescribe());
					contentVo.setValue(peopleInfoDto.getPostEduDtoObj().getFirefightersPost().getFireManagementPost());
					contentVo.setType("text");
					break;
				case "amosName":
					contentVo.setLabel(u.getDescribe());
					contentVo.setValue(peopleInfoDto.getFirefighters().getAmosName());
					contentVo.setType("text");
					break;
				case "state":
					contentVo.setLabel(u.getDescribe());
					contentVo.setValue(peopleInfoDto.getFirefighters().getState());
					contentVo.setType("text");
					break;
				case "birthdayTime":
					contentVo.setLabel(u.getDescribe());
					try {
						if(null != peopleInfoDto.getFirefighters().getBirthdayTime()) {
							contentVo.setValue(DateUtils.dateFormat(peopleInfoDto.getFirefighters().getBirthdayTime(), DateUtils.DATE_TIME_PATTERN));
						}
					} catch (ParseException e) {
						e.printStackTrace();
					}
					contentVo.setType("text");
					break;
				default:
					log.debug("方法参数错误 !!!");
					break;
			}
			contentVos.add(contentVo);
		}
		dynamicDetailsVo.setTabContent(contentVos);
		dynamicDetailsVo.setSpecialMap(map);
		detailsVos.add(dynamicDetailsVo);
		riskBizInfoVo.setDynamicDetails(detailsVos);
		return riskBizInfoVo;
	}


	public IPage<Map<String, Object>> getUserByPeopleType(String pageNum, String pageSize, Map<String, Object> map) {
		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));
		}
		pageBean.setTotal(orgUsrMapper.getUserByPeopleTypeCount(map));
		map.put("pageNum", (pageBean.getCurrent() - 1) * pageBean.getSize());
		map.put("pageSize", pageBean.getSize());

		List<Map<String, Object>> list = orgUsrMapper.getUserByPeopleType(map);
		pageBean.setRecords(list);
		return pageBean;
	}



}