package com.yeejoin.precontrol.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
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.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yeejoin.amos.boot.module.common.api.dto.CreatExamDto;
import com.yeejoin.amos.boot.module.common.api.feign.AmosTrainingFeignClient;
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.DepartmentModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.amos.feign.privilege.model.UserOrgTreeModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import com.yeejoin.precontrol.common.constant.Constant;
import com.yeejoin.precontrol.common.dto.CommonPageableDto;
import com.yeejoin.precontrol.common.dto.StatisticsDto;
import com.yeejoin.precontrol.common.dto.feign.CreateIntegralDto;
import com.yeejoin.precontrol.common.entity.*;
import com.yeejoin.precontrol.common.entity.fegin.TreeModel;
import com.yeejoin.precontrol.common.entity.platform.PlatformRole;
import com.yeejoin.precontrol.common.entity.publics.CommonPageable;
import com.yeejoin.precontrol.common.enums.*;
import com.yeejoin.precontrol.common.exception.BaseException;
import com.yeejoin.precontrol.common.exception.CommonException;
import com.yeejoin.precontrol.common.feign.IntegralFeign;
import com.yeejoin.precontrol.common.mapper.*;
import com.yeejoin.precontrol.common.param.PersonParam;
import com.yeejoin.precontrol.common.param.PersonStatisticParam;
import com.yeejoin.precontrol.common.param.VerityPersonParam;
import com.yeejoin.precontrol.common.publish.MessageEventPublish;
import com.yeejoin.precontrol.common.publish.TranslateEventPublish;
import com.yeejoin.precontrol.common.service.*;
import com.yeejoin.precontrol.common.utils.*;
import com.yeejoin.precontrol.common.vo.*;
import com.yeejoin.precontrol.common.ws.WebSocket;
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.util.CollectionUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 人员基本信息 服务实现类
 *
 * @author duanwei
 * @date 2020-06-30
 */
@Service
public class PersonServiceImpl extends ServiceImpl<PersonMapper, Person> implements IPersonService {

	private final int platformSuccessCode = 200;

	@Autowired
	private PersonMapper personMapper;

	@Autowired
	private PersonContractMapper contractMapper;

	@Autowired
	private PersonAscriptionMapper ascriptionMapper;

	@Autowired
	TranslateEventPublish translateEventPublish;

	@Autowired
	private DistrictsMapper districtsMapper;

	@Autowired
	private IPersonAscriptionService iPersonAscriptionService;

	@Autowired
	IPersonClockService iPersonClockService;

	@Autowired
	IPersonService iPersonService;

	@Autowired
	ICompanyService iCompanyService;

	@Autowired
	IPersonSkillEducationService skillEducationService;

	@Autowired
	IPersonQualificationsService qualificationService;

	@Autowired
	IPersonQualificationsAttachmentService qualificAttachService;

	@Autowired
	IPersonContractService contractService;

	@Autowired
	IPersonContractAttachmentService contractAttachService;

	@Autowired
	IPersonExaminationService examinnationService;

	@Autowired
	IPersonExaminationAttachmentService examinatiAttachService;

	@Autowired
	IPersonInsuranceService insuranceService;

	@Autowired
	IPersonInsuranceAttachmentService insuranceAttachService;

	@Autowired
	PlatformUtils platformUtils;

	@Autowired
	IProjectService iProjectService;

	@Autowired
	StatisticsMapper statisticsMapper;
	@Autowired
	IUserRegistrationService iUserRegistrationService;

	@Autowired
	MsgCodeUtil msgCodeUtil;

	@Autowired
	AmosTrainingFeignClient examFeign;

	@Autowired
	ITaskKnowledgeShareService taskKnowledgeShareService;

	@Autowired
	IProjectClockService iProjectClockService;

	@Autowired
	IProjectCompanyService iProjectCompanyService;

	@Autowired
	IProjectHistoryService iProjectHistoryService;

	@Autowired
	IPersonConditionService iPersonConditionService;

	@Autowired
	IProjectQrcodeService iProjectQrcodeService;

	@Autowired
	MessageEventPublish messageEventPublish;

	@Autowired
	AppMenuConfigServiceImpl appMenuConfigService;

	@Autowired
	PersonMessageServiceImpl personMessageService;

	@Autowired
	IProjectDeviceService iProjectDeviceService;

	@Autowired
	IPersonQualificationsService iPersonQualificationsService;

	@Autowired
	IPersonExamService personExamService;

	@Autowired
	private IPersonAscriptionService personAscriptionService;

	@Autowired
	private ICompanyDepartmentService iCompanyDepartmentService;

	/**
	 * 文件服务器地址
	 */
	@Value("${person.information.complete}")
	boolean personInfoComplete;

	/**
	 * 3级安全考试,数据来源平台字典行业类型，约定写死
	 */
	private final String THREE_LEVEL_EXAM = "THREE_LEVEL_EXAM";

	/**
	 * POST_NAME (app审核人员使用)
	 */
	private final String POST_NAME = "POST_NAME";

	final static Logger log = LoggerFactory.getLogger(PersonServiceImpl.class);

	@Autowired
	IStatisticsService statisticsService;

	@Autowired
	IntegralFeign integralFeign;

	@Value("${amos.secret.key}")
	private String secretKey;

	@Value("${jxdj.id}")
	private Long jxdjId;

	@Override
	public Page pageInfo(PersonParam personParam, CommonPageableDto pageable) {
		if (pageable.getIsAll() == 1) {
			pageable.setPageNumber(0);
			pageable.setPageSize(Integer.MAX_VALUE);
		}
		Page<PersonVo> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		int count = personMapper.pageInfoCount(personParam);
		page.setTotal(count);
		CommonPageable commonPage = new CommonPageable(
				pageable.getPageNumber() - 1 < 0 ? 0 : pageable.getPageNumber() - 1, pageable.getPageSize());
		List<PersonVo> pageInfo = personMapper.pageInfo(personParam, commonPage);
//		pageInfo.forEach(p -> {
//			String nativePlaceStr = p.getNativePlace();
//			if (nativePlaceStr != null) {
//				p.setNativePlace(districtsMapper.selectLabelByIds(nativePlaceStr.split(",")));
//			}
//		});
		page.setRecords(pageInfo);
		return page;
	}

	@Override
	public Person queryByIdNumber(String idNumber) {
		QueryWrapper<Person> wrapper = new QueryWrapper<>();
		wrapper.eq("ID_Number", idNumber);
		return personMapper.selectOne(wrapper);
	}

	@Override
	public void departureByPersonId(Long id) {
		// 归属信息
		PersonAscription ascription = ascriptionMapper
				.selectOne(new QueryWrapper<PersonAscription>().eq("person_id", id));
		if (ascription != null) {
			ascriptionMapper.deleteById(ascription.getId());
		}
		// 合同信息
		PersonContract contract = contractMapper.selectOne(
				new QueryWrapper<PersonContract>().eq("person_id", id).eq("useful", ContractUsefulEum.生效.getValue()));
		if (contract != null) {
			contract.setUseful(ContractUsefulEum.作废.getValue());
			contract.setDepartureTime(new Date());
			contractMapper.updateById(contract);
		}
	}

	@Override
	public List<PersonExcelVo> exportExcel(PersonParam param) {
		return personMapper.exportExcel(param);
	}

	/**
	 * 只支持一个资质信息导入
	 */
	@Transactional
	@Override
	public synchronized void importExcel(List<PersonExcelVo> list) {
		List<String> idNumbers = list.stream().map(PersonExcelVo::getIdNumber).collect(Collectors.toList());
		idNumbers.removeAll(Collections.singleton(null));
		idNumbers.removeAll(Collections.singleton(""));
		Set<String> setIdNumbers = new HashSet<>(idNumbers);
		if (idNumbers.size() != setIdNumbers.size()) {
			throw new BaseException("Excel用户身份证号信息重复！");
		}

		List<String> phones = list.stream().map(PersonExcelVo::getPhone).collect(Collectors.toList());
		phones.removeAll(Collections.singleton(null));
		phones.removeAll(Collections.singleton(""));
		Set<String> setPhones = new HashSet<>(phones);
		if (phones.size() != setPhones.size()) {
			throw new BaseException("Excel用户电话信息重复！");
		}
		list.forEach(p -> {
			Person person = new Person();
			PersonAscription ascription = new PersonAscription();
			PersonContract contract = new PersonContract();
			PersonExamination examination = new PersonExamination();
			PersonInsurance insurance = new PersonInsurance();
			PersonQualifications qualifications = new PersonQualifications();
			PersonSkillEducation skillEducation = new PersonSkillEducation();

			BeanUtils.copyProperties(p, person);
			if (p.getSex() != null && !"null".equals(p.getSex())) {
				person.setSex(Long.valueOf(p.getSex()));
			}
			if (p.getIdType() != null && !"null".equals(p.getIdType())) {
				person.setIdType(Long.valueOf(p.getIdType()));
			}

			BeanUtils.copyProperties(p, ascription);
			BeanUtils.copyProperties(p, examination);
			BeanUtils.copyProperties(p, insurance);
			BeanUtils.copyProperties(p, qualifications);
			BeanUtils.copyProperties(p, skillEducation);
			BeanUtils.copyProperties(p, contract);

//			BeanUtils.copyProperties(person, p);
//			BeanUtils.copyProperties(ascription, p);
//			BeanUtils.copyProperties(examination, p);
//			BeanUtils.copyProperties(insurance, p);
//			BeanUtils.copyProperties(qualifications, p);
//			BeanUtils.copyProperties(skillEducation, p);
//			BeanUtils.copyProperties(contract, p);

			Person oldPerson = iPersonService.getOne(new LambdaQueryWrapper<Person>()
					.eq(Person::getPhone, person.getPhone()).eq(Person::getName, person.getName()));
			if (oldPerson == null) {
				return;
			}
			person.setId(oldPerson.getId());
			// person.setNativePlace(DistrictsUtils.findByName(p.getNativePlaceName()));
			// person.setEmployPlace(DistrictsUtils.findByName(p.getEmployPlaceName()));
			if (null != person.getIdNumber()) {
				int idCount = iPersonService
						.count(new LambdaQueryWrapper<Person>().eq(Person::getIdNumber, person.getIdNumber()));
				List<Person> personListByIdNumber = iPersonService.list(new LambdaQueryWrapper<Person>()
						.eq(Person::getIdNumber, person.getIdNumber()).notLike(Person::getName, person.getName()));
				// 判断导入的身份证号是否除了本人之外还有其他的重复值
				if (idCount > 0 && null != personListByIdNumber && personListByIdNumber.size() > 0) {
					throw new BaseException("无法导入" + person.getName() + "，人员身份证号重复");
				}
			}

			if (person.getIdNumber() != null) {
				if (!IdNumberUtil.isValid(person.getIdNumber())) {
					throw new BaseException("身份证格式不正确: " + person.getName());
				} else {
					person.setAge(Long.valueOf(IdNumberUtil.getAge(person.getIdNumber())));
					person.setBirthday(IdNumberUtil.getBirthdayDate(person.getIdNumber()));
				}
			}

			iPersonService.updateById(person);
			Long personId = person.getId();
			ascription.setPersonId(personId);
			examination.setPersonId(personId);
			insurance.setPersonId(personId);
			qualifications.setPersonId(personId);
			contract.setPersonId(personId);
			skillEducation.setPersonId(personId);
//				ascriptionMapper.insert(ascription);
//				examinationMapper.insert(examination);
//				insuranceMapper.insert(insurance);
//				qualificationsMapper.insert(qualifications);
//				skillEducationMapper.insert(skillEducation);
//				contractMapper.insert(contract);

			if (iPersonAscriptionService.getOne(
					new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, personId)) != null) {
				iPersonAscriptionService.update(ascription,
						new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, personId));
			} else {
				iPersonAscriptionService.save(ascription);
			}

			// 如果是江西电建人员不做后面处理
			if (oldPerson.getIsJxdj() == TypeKeyEnum.JXDJ.getLongType()) {
				return;
			}

			if (examinnationService.getOne(
					new LambdaQueryWrapper<PersonExamination>().eq(PersonExamination::getPersonId, personId)) != null) {
				examinnationService.update(examination,
						new LambdaQueryWrapper<PersonExamination>().eq(PersonExamination::getPersonId, personId));
			} else {
				examinnationService.save(examination);
			}

			// 分割人员保险信息中的保障期限字段，分别进行保存
			if (StringUtil.isNotEmpty(insurance.getInsurePeriod())) {
				String[] split = insurance.getInsurePeriod().split("~");
				insurance.setInsurePeriodStart(split[0]);
				insurance.setInsurePeriodEnd(split[1]);
			}

			if (insuranceService.getOne(
					new LambdaQueryWrapper<PersonInsurance>().eq(PersonInsurance::getPersonId, personId)) != null) {
				insuranceService.update(insurance,
						new LambdaQueryWrapper<PersonInsurance>().eq(PersonInsurance::getPersonId, personId));
			} else {
				insuranceService.save(insurance);
			}

			LambdaUpdateWrapper<PersonQualifications> personQualificationsLambdaQueryWrapper = new LambdaUpdateWrapper<>();
			// 如果资质信息为无或者null时，则不导人所有资质相关信息
			if (StringUtils.isEmpty(qualifications.getCertificateTypeKey())
					|| ("无").equals(qualifications.getCertificateTypeKey())) {
				// 新增用的实体
				qualifications = new PersonQualifications();
				qualifications.setPersonId(personId);

				// 更新用的实体
				personQualificationsLambdaQueryWrapper.set(PersonQualifications::getCertificateLevel, null);
				personQualificationsLambdaQueryWrapper.set(PersonQualifications::getCertificateNameKey, null);
				personQualificationsLambdaQueryWrapper.set(PersonQualifications::getCertificateNumber, null);
				personQualificationsLambdaQueryWrapper.set(PersonQualifications::getCertificateProject, null);
				personQualificationsLambdaQueryWrapper.set(PersonQualifications::getIssuingAuthority, null);
				personQualificationsLambdaQueryWrapper.set(PersonQualifications::getCertificateObtainTime, null);
				personQualificationsLambdaQueryWrapper.set(PersonQualifications::getExpireDate, null);
				personQualificationsLambdaQueryWrapper.set(PersonQualifications::getCertificateTypeKey, "无");
			}
			if (qualificationService.getOne(new LambdaQueryWrapper<PersonQualifications>()
					.eq(PersonQualifications::getPersonId, personId).last("LIMIT 1")) != null) {
				qualificationService.update(qualifications,
						personQualificationsLambdaQueryWrapper.eq(PersonQualifications::getPersonId, personId));
			} else {
				qualificationService.save(qualifications);
			}
			// 劳动合同主体单位 保存id 需要根据导入的公司名称进行查询
			if (StringUtil.isNotEmpty(contract.getContractCompanyName())) {
				Company company = iCompanyService.getOne(
						new LambdaQueryWrapper<Company>().eq(Company::getName, contract.getContractCompanyName()));
				if (null != company) {
					contract.setContractCompanyId(company.getId());
				}
			}
			if (contractService
					.getOne(new LambdaQueryWrapper<PersonContract>().eq(PersonContract::getPersonId, personId)
							.eq(PersonContract::getUseful, ContractUsefulEum.生效.getValue()).last("LIMIT 1")) != null) {
				contractService.update(contract,
						new LambdaQueryWrapper<PersonContract>().eq(PersonContract::getPersonId, personId));
			} else {
				contract.setUseful(ContractUsefulEum.生效.getValue());
				contractService.save(contract);
			}
			// 人员技能和学历is_special_work字段置空，防止报错
			if (1L == oldPerson.getIsJxdj()) {
				skillEducation.setIsSpecialWork(null);
			}
			if (skillEducationService.getOne(new LambdaQueryWrapper<PersonSkillEducation>()
					.eq(PersonSkillEducation::getPersonId, personId)) != null) {
				skillEducationService.update(skillEducation,
						new LambdaQueryWrapper<PersonSkillEducation>().eq(PersonSkillEducation::getPersonId, personId));
			} else {
				skillEducationService.save(skillEducation);
			}

		});

	}

	@Override
	public List<HashMap<Long, String>> nationSelect() {
		return personMapper.nationSelect();
	}

	@Override
	public PersonVo getPersonVoByAccountNumber(String accountNum) {
		return personMapper.getPersonVoByAccountNumber(accountNum);
	}

	@Override
	public JSONObject getQrCodeColorByPersonId(Long personId) {
		Person person = personMapper.selectById(personId);
		Long colorStatus = person.getColor();
		JSONObject color;
		if (colorStatus == 0) {
			color = SmallProQrColorEum.red.getCode();
		} else if (colorStatus == 1) {
			color = SmallProQrColorEum.yellow.getCode();
		} else if (colorStatus == 2) {
			color = SmallProQrColorEum.green.getCode();
		} else {
			// 状态没有值 绿码
			log.info("人员没有二维码状态,默认绿码 人员id:{}", personId);
			color = SmallProQrColorEum.green.getCode();
		}
		return color;
	}

	@Override
	public HashMap<String, Object> statistical() {
		int statisticalByProject = personMapper.statisticalByProject();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String day = dateFormat.format(new Date());
		String start = day + " 00:00:00";
		String end = day + " 23:59:59";
		int statisticalByIn = personMapper.statisticalByIn(null, start, end);
		int statisticalByQualified = personMapper.statisticalByQualified();
		HashMap<String, Object> statistical = new HashMap<>();
		statistical.put("projectPersonNum", statisticalByProject);
		statistical.put("inPersonNum", statisticalByIn);
		statistical.put("qualifiedPersonNum", statisticalByQualified);
		return statistical;
	}

	@Override
	public HashMap<String, Object> personByProjectId(Long projectId) {
		String orgCode = platformUtils.getOrgCode();
		StatisticsDto statisticsDto = new StatisticsDto(orgCode, projectId);
		HashMap<String, Object> statistical = new HashMap<>();
		statistical.put("projectPersonNum", 0);
		statistical.put("inPersonNum", 0);
		statistical.put("qualifiedPersonNum", 0);
//		LambdaQueryWrapper<PersonAscription> personAscriptionLambdaQueryWrapper = new LambdaQueryWrapper<>();
//		if (projectId == null) {
//			personAscriptionLambdaQueryWrapper.isNotNull(PersonAscription::getProjectId);
//		} else {
//			personAscriptionLambdaQueryWrapper.eq(PersonAscription::getProjectId, projectId);
//		}
//
//		if (StringUtils.isNotEmpty(orgCode)) {
//			personAscriptionLambdaQueryWrapper.likeRight(PersonAscription::getOrgCode, orgCode);
//		}
//		List<PersonAscription> personAscriptionList = iPersonAscriptionService.list(personAscriptionLambdaQueryWrapper);
//
//		if (StringUtil.isNotEmpty(personAscriptionList)) {
//			statistical.put("projectPersonNum", personAscriptionList.size());
//		}
		// 入场人数
//		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//		String day = dateFormat.format(new Date());
//		String start = day + " 00:00:00";
//		String end = day + " 23:59:59";
//
//		if (StringUtil.isNotEmpty(personAscriptionList)) {
//			Set<Long> personIds = personAscriptionList.stream().map(r -> r.getPersonId()).collect(Collectors.toSet());
//			// 查找到今日打卡人员
//			List<PersonClock> personClockList = iPersonClockService
//					.list(new LambdaQueryWrapper<PersonClock>().select(PersonClock::getPersonId)
//							.in(PersonClock::getPersonId, personIds).between(PersonClock::getClockTime, start, end)
//							.eq(PersonClock::getInOrOut, 0).groupBy(PersonClock::getPersonId));
//			if (StringUtil.isNotEmpty(personClockList)) {
//				// 再次过滤入场中已经离场的人 查询入场人
//				List<Long> inPersonIds = personClockList.stream().map(personClock -> personClock.getPersonId())
//						.collect(Collectors.toList());
//				// 根据入场人 进行查询是否离场
//				List<PersonClock> outPerson = iPersonClockService.list(new LambdaQueryWrapper<PersonClock>()
//						.select(PersonClock::getPersonId).in(PersonClock::getPersonId, inPersonIds)
//						.between(PersonClock::getClockTime, start, end).eq(PersonClock::getInOrOut, 1)
//						.groupBy(PersonClock::getPersonId));
//				if (StringUtil.isNotEmpty(outPerson)) {
//					List<Long> outPersonIds = outPerson.stream().map(person -> person.getPersonId())
//							.collect(Collectors.toList());
//					List<Long> collect = inPersonIds.stream().filter(inPerson -> !outPersonIds.contains(inPerson))
//							.collect(Collectors.toList());
//					statistical.put("inPersonNum", collect.size());
//				} else {
//					statistical.put("inPersonNum", personClockList.size());
//				}
//			} else {
//				statistical.put("inPersonNum", 0);s
//			}
//		}
		int projectPersonNum = statisticsMapper.projectPersonCount(statisticsDto, TypeKeyEnum.COMPANY.getLongType(),
				null, null);
		statistical.put("projectPersonNum", projectPersonNum);

		int inPersonNum = statisticsMapper.inPersonCount(statisticsDto, false, null, false);
		statistical.put("inPersonNum", inPersonNum);

		// 项目的合格人数
		Integer personListNum = personMapper.isOk(projectId, orgCode);
		statistical.put("qualifiedPersonNum", personListNum);
		return statistical;
	}

	@Override
	public Map<String, Object> personSituational(Long projectId, Long companyId, String orgCode) {
		Map<String, Object> map = new HashMap<>();
		StatisticsDto statisticsDto = new StatisticsDto(orgCode, projectId, companyId);
		map.put("red", statisticsMapper.projectPersonCount(statisticsDto, TypeKeyEnum.COMPANY.getLongType(), null,
				SmallProQrColorEum.red.getSqlCode()));
		map.put("yellow", statisticsMapper.projectPersonCount(statisticsDto, TypeKeyEnum.COMPANY.getLongType(), null,
				SmallProQrColorEum.yellow.getSqlCode()));
		map.put("green", statisticsMapper.projectPersonCount(statisticsDto, TypeKeyEnum.COMPANY.getLongType(), null,
				SmallProQrColorEum.green.getSqlCode()));
		map.put("number",
				statisticsMapper.projectPersonCount(statisticsDto, TypeKeyEnum.COMPANY.getLongType(), null, null));
//		LambdaQueryWrapper<Project> projectWrapper = new LambdaQueryWrapper<>();
//		if (projectId != null) {
//			projectWrapper = projectWrapper.eq(Project::getId, projectId);
//		}
//		if (orgCode != null) {
//			projectWrapper.like(Project::getOrgCode, orgCode);
//		}
//		List<Project> projectList = iProjectService.list(projectWrapper);
//		LambdaQueryWrapper<PersonAscription> ascriptionWrapper = new LambdaQueryWrapper<>();
//		if (companyId != null) {
//			ascriptionWrapper = ascriptionWrapper.eq(PersonAscription::getCompanyId, companyId);
//		}
//		if (projectId == null) {
//			ascriptionWrapper = ascriptionWrapper.isNotNull(PersonAscription::getProjectId);
//		}
//		List<Long> idList = projectList.stream().map(l -> l.getId()).collect(Collectors.toList());
//		List<PersonAscription> list = null;
//		if (StringUtil.isNotEmpty(idList)) {
//			ascriptionWrapper.in(PersonAscription::getProjectId, idList);
//			list = iPersonAscriptionService.list(ascriptionWrapper);
//		}
//		if (StringUtil.isNotEmpty(list)) {
//			Set<Long> userIds = list.stream().map(personAscription -> personAscription.getPersonId())
//					.collect(Collectors.toSet());
//			Collection<Person> userList = iPersonService.listByIds(userIds);
//			// 计算红 黄 绿
//			AtomicReference<Integer> red = new AtomicReference<Integer>(0);
//			AtomicReference<Integer> yellow = new AtomicReference<>(0);
//			AtomicReference<Integer> green = new AtomicReference<>(0);
//
//			// 成绩中获得红码人数
//			userList.forEach(user -> {
//				if (user.getColor().intValue() == 0) {
//					red.updateAndGet(v -> v + 1);
//				} else if (user.getColor().intValue() == 1) {
//					yellow.updateAndGet(v -> v + 1);
//				} else if (user.getColor().intValue() == 2) {
//					green.updateAndGet(v -> v + 1);
//				}
//			});
//			map.put("red", red.get());
//			map.put("yellow", yellow.get());
//			map.put("green", green.get());
//			map.put("number", red.get() + yellow.get() + green.get());
//		}

		return map;
	}

	@Override
	public IPage<PersonStatisticVo> statisticInPersonlistPage(PersonStatisticParam personStatisticParam,
			CommonPageableDto pageable) {
		if (pageable.getIsAll() == 1) {
			pageable.setPageNumber(0);
			pageable.setPageSize(Integer.MAX_VALUE);
		}
		Page<PersonStatisticVo> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		IPage<PersonStatisticVo> pageData = personMapper.statisticInPersonlistPage(page, personStatisticParam);
		List<PersonStatisticVo> records = pageData.getRecords();
		formatPersonInfo(records);
		return pageData;
	}

	@Override
	public IPage<PersonStatisticVo> statisticPageInfo(PersonStatisticParam personStatisticParam,
			CommonPageableDto pageable) {
		if (pageable.getIsAll() == 1) {
			pageable.setPageNumber(0);
			pageable.setPageSize(Integer.MAX_VALUE);
		}
		Page<PersonStatisticVo> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		IPage<PersonStatisticVo> pageData = personMapper.listByPage(page, personStatisticParam);
		List<PersonStatisticVo> records = pageData.getRecords();
//		if (StringUtil.isNotEmpty(records)) {
//			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//			String day = dateFormat.format(new Date());
//			String start = day + " 00:00:00";
//			String end = day + " 23:59:59";
//			if (personStatisticParam.getInOrOut() != null) {
//				if (0 == personStatisticParam.getInOrOut()) {
//					Set<Long> userIds = records.stream().map(r -> r.getId()).collect(Collectors.toSet());
//					List<PersonClock> personClockList = iPersonClockService.list(new LambdaQueryWrapper<PersonClock>()
//							.select(PersonClock::getPersonId).in(PersonClock::getPersonId, userIds)
//							.between(PersonClock::getClockTime, start, end).eq(PersonClock::getInOrOut, 0)
//							.groupBy(PersonClock::getPersonId));
//					// 根据打卡人 过滤人员数据
//					if (StringUtil.isNotEmpty(personClockList)) {
//						Set<Long> clockUserIds = personClockList.stream().map(personClock -> personClock.getPersonId())
//								.collect(Collectors.toSet());
//						// 打卡人中离场的人
//						List<PersonClock> outPerson = iPersonClockService.list(new LambdaQueryWrapper<PersonClock>()
//								.select(PersonClock::getPersonId).in(PersonClock::getPersonId, clockUserIds)
//								.between(PersonClock::getClockTime, start, end).eq(PersonClock::getInOrOut, 1)
//								.groupBy(PersonClock::getPersonId));
//						if (StringUtil.isNotEmpty(outPerson)) {
//							List<Long> outPersonIds = outPerson.stream().map(person -> person.getPersonId())
//									.collect(Collectors.toList());
//							// 打了入场卡也没有离场的人
//							List<Long> collect = clockUserIds.stream()
//									.filter(inPerson -> !outPersonIds.contains(inPerson)).collect(Collectors.toList());
//							records = records.stream().filter(p -> collect.contains(p.getId()))
//									.collect(Collectors.toList());
//							formatPersonInfo(records);
//							// 方法内操作records似乎存在作用域问题 需要再次设置
//							pageData.setRecords(records);
//							pageData.setTotal(records.size());
//						} else {
//							records = records.stream().filter(p -> clockUserIds.contains(p.getId()))
//									.collect(Collectors.toList());
//							formatPersonInfo(records);
//							// 方法内操作records似乎存在作用域问题 需要再次设置
//							pageData.setRecords(records);
//							pageData.setTotal(records.size());
//						}
//					} else {
//						// 没人打卡
//						List<PersonStatisticVo> personStatisticVos = new ArrayList<>();
//						pageData.setRecords(personStatisticVos);
//						pageData.setTotal(0);
//						return pageData;
//					}
//				}
//			}
		formatPersonInfo(records);
//		}
		return pageData;
	}

	/**
	 * 根据人员数据修改状态
	 *
	 * @param records
	 */
	private void formatPersonInfo(List<PersonStatisticVo> records) {
		records.forEach(r -> {
			if (r.getColor() == 0) {
				r.setColorName("红码");
			} else if (r.getColor() == 1) {
				r.setColorName("黄码");
			} else if (r.getColor() == 2) {
				r.setColorName("绿码");
			}
			if (r.getProjectId() != null) {
				r.setInOutStatusName("在岗");
			} else {
				r.setInOutStatusName("不在岗");
			}
		});
	}

	@Override
	public List<String> selectBindUserSeqs() {
		return personMapper.selectBindUserSeqs();
	}

	@SuppressWarnings("unchecked")
	@Override
	public void syncPerson(JSONObject jsonObject) {
		JSONObject result = jsonObject.getJSONObject("result");
		String methodName = jsonObject.getString("methodName");
		String operUserId = jsonObject.getString("userId");
		//String orgCode = platformUtils.getOrgCode(operUserId);

//		// 平台添加用户
//		if ("create".equals(methodName)) {
//			JSONObject object = result.getJSONObject("result");
//			int count = this.count(new LambdaQueryWrapper<Person>().eq(Person::getId, object.getLong("sequenceNbr")));
//			if (count > 0) {
//				return;
//			}
//			AgencyUserModel userModel = platformUtils.getSyncPlatformUser(object.getString("userId"));
//			Long companyId = (userModel.getCompanys() != null && userModel.getCompanys().get(0) != null)
//					? userModel.getCompanys().get(0).getSequenceNbr()
//					: null;
//			Long departmentId = null;
//			String departmentOrgCode = null;
//			List<DepartmentModel> departmentList = null;
//			String departmentName = null;
//			Map<Long, List<DepartmentModel>> companyDepartments = userModel.getCompanyDepartments();
//			if (null != companyDepartments) {
//				departmentList = userModel.getCompanyDepartments().get(companyId);
//			}
//			if (departmentList != null && departmentList.get(0) != null) {
//				departmentId = departmentList.get(0).getSequenceNbr();
//				departmentOrgCode = departmentList.get(0).getOrgCode();
//				departmentName = departmentList.get(0).getDepartmentName();
//			}
//
//			Person person = new Person();
//			person.setId(object.getLong("sequenceNbr"));
//			person.setAccountName(object.getString("userName"));
//			person.setUserId(object.getLong("userId"));
//			person.setName(object.getString("realName"));
//			person.setPhone(object.getString("mobile"));
//			person.setColor(SmallProQrColorEum.green.getSqlCode());
//			person.setActiveStatus(0L);
//			// 新加--驻场开发
//			fillHeadPhoto(person);
//			// 判断是否是江西电建归属的人 如果是orgcode存自身 如果不是orgcode存操作人的 如果是江西电建公共部门 则orgcode=null
//			String currentOrgCode = null;
//			String companyOrgCode = (userModel.getCompanys() != null && userModel.getCompanys().get(0) != null)
//					? userModel.getCompanys().get(0).getOrgCode()
//					: null;
//			if (companyOrgCode != null) {
//				if (!companyOrgCode.contains("*")) {
//					person.setIsJxdj(1L);
//					person.setActiveStatus(1L);
//					person.setDeptType(DeptTypeEnum.PUBLIC.getLabel());
//					if (!platformUtils.isBelongDept(departmentId, companyId, "public")) {
//						person.setDeptType(DeptTypeEnum.PROJECT.getLabel());
//						boolean hasChild = platformUtils.hasChild(departmentId);
//						currentOrgCode = hasChild ? departmentOrgCode
//								: departmentOrgCode.substring(0, departmentOrgCode.lastIndexOf("*"));
//					}
//				} else {
//					person.setDeptType(DeptTypeEnum.FBS.getLabel());
//					currentOrgCode = orgCode;
//				}
//			}
//			Map<Long, List<Long>> roleMap = userModel.getOrgRoleSeqs();
//			Map<Long, String> orgRoleName = userModel.getOrgRoleName();
//
//			String roles = null;
//			if (departmentId != null) {
//				roles = roleMap.get(departmentId) != null ? Arrays.toString(roleMap.get(departmentId).toArray()) : null;
//			} else {
//				roles = roleMap.get(companyId) != null ? Arrays.toString(roleMap.get(companyId).toArray()) : null;
//			}
//
//			// 角色权限名称
//			setRoleName(person, roles);
//			person.setRoles(roles);
//			person.setOrgCode(currentOrgCode);
//			person.setQualifiedStage(QualifiedStageEnum.NONE.getValue());
//			UserRegistration userRegistration = this.getUserRegistration(person.getAccountName(), null);
//			// 新加--驻场开发 如果注册表则先不加入的person表
//			if (userRegistration != null) {
//				// 同步注册录入的三级安全考试分数，与是否合格，身份证正面，身份证反面
//				person.setExamineScore(userRegistration.getExamineScore());
//				person.setQualified(userRegistration.getQualified() != null && userRegistration.getQualified() > 0);
//				person.setFrontCertificatePhoto(userRegistration.getIdCardHead());
//				person.setBackCertificatePhoto(userRegistration.getIdCardNational());
//			}
//			Person oldPerson = this.getById(person.getId());
//			if (oldPerson != null) {
//				return;
//			}
//			this.save(person);
//			translateEventPublish.publish(person);
//			PersonAscription personAscription = new PersonAscription();
//			personAscription.setDepartmentId(departmentId);
//			personAscription.setPersonId(person.getId());
//			personAscription.setOrgCode(currentOrgCode);
//			personAscription.setDepartmentName(departmentName);
//			// 新加--驻场开发
//			personAscription.setProjectId(userRegistration != null ? userRegistration.getProjectId() : null);
//			personAscription.setCompanyId(userRegistration != null ? userRegistration.getCompanyId() : null);
//			// 平台创建账户时
//			if (!StringUtil.isNotEmpty(userRegistration)) {
//				personAscription.setCompanyId(companyId);
//			}
//			iPersonAscriptionService.save(personAscription);
//			PersonQualifications personQualifications = new PersonQualifications();
//			personQualifications.setPersonId(person.getId());
//			qualificationService.save(personQualifications);
//
//			// 分包商
//			if (DeptTypeEnum.FBS.getLabel().equals(person.getDeptType())) {
//				// 发考试
//				UserRegistration userRegistrationExam = new UserRegistration();
//				userRegistrationExam.setUserId(Long.valueOf(object.getString("userId")));
//				this.passOutThreeLevelExam(userRegistrationExam);
//			}
//
//			// 更新推送
//			statisticsService.initWs(currentOrgCode, Constant.WS_REDORGREENCODE);
//
//			// 更新积分
//			integralFeign.save(new CreateIntegralDto("REGISTER", null, person.getUserId(), null));
//
//		}
//		// 平台编辑用户
//		else if ("update".equals(methodName)) {
//			JSONObject object = result.getJSONObject("result");
//			AgencyUserModel userModel = platformUtils.getSyncPlatformUser(object.getString("userId"));
//			Long companyId = (userModel.getCompanys() != null && userModel.getCompanys().get(0) != null)
//					? userModel.getCompanys().get(0).getSequenceNbr()
//					: null;
//			Long departmentId = null;
//			String departmentOrgCode = null;
//			List<DepartmentModel> departmentList = null;
//			String departmentName = null;
//			Map<Long, List<DepartmentModel>> companyDepartments = userModel.getCompanyDepartments();
//			if (null != companyDepartments) {
//				departmentList = userModel.getCompanyDepartments().get(companyId);
//			}
//			if (departmentList != null && departmentList.get(0) != null) {
//				departmentId = departmentList.get(0).getSequenceNbr();
//				departmentOrgCode = departmentList.get(0).getOrgCode();
//				departmentName = departmentList.get(0).getDepartmentName();
//			}
//			Person person = new Person();
//			person.setId(object.getLong("sequenceNbr"));
//			person.setAccountName(object.getString("userName"));
//			person.setUserId(object.getLong("userId"));
//			person.setName(object.getString("realName"));
//			person.setPhone(object.getString("mobile"));
//			// 新加--驻场开发
//			fillHeadPhoto(person);
//
//			Map<Long, List<Long>> roleMap = userModel.getOrgRoleSeqs();
//			String roles = null;
//			if (departmentId != null) {
//				roles = roleMap.get(departmentId) != null ? Arrays.toString(roleMap.get(departmentId).toArray()) : null;
//			} else {
//				roles = roleMap.get(companyId) != null ? Arrays.toString(roleMap.get(companyId).toArray()) : null;
//			}
//			// 角色权限名称
//			setRoleName(person, roles);
//			// person.setRoleName(roleName);
//			person.setRoles(roles);
//			if (this.getById(person) == null) {
//				person.setColor(SmallProQrColorEum.green.getSqlCode());
//			}
//			// 判断是否是江西电建归属的人 如果是orgcode存自身 如果不是orgcode存操作人的 如果是江西电建公共部门 则orgcode=null
//			String currentOrgCode = null;
//			String companyOrgCode = (userModel.getCompanys() != null && userModel.getCompanys().get(0) != null)
//					? userModel.getCompanys().get(0).getOrgCode()
//					: null;
//			if (companyOrgCode != null) {
//				if (!companyOrgCode.contains("*")) {
//					person.setIsJxdj(1L);
//					person.setActiveStatus(1L);
//					person.setDeptType(DeptTypeEnum.PUBLIC.getLabel());
//					if (!platformUtils.isBelongDept(departmentId, companyId, "public")) {
//						person.setDeptType(DeptTypeEnum.PROJECT.getLabel());
//						boolean hasChild = platformUtils.hasChild(departmentId);
//						currentOrgCode = hasChild ? departmentOrgCode
//								: departmentOrgCode.substring(0, departmentOrgCode.lastIndexOf("*"));
//					}
//				} else {
//					person.setIsJxdj(0L);
//					person.setDeptType(DeptTypeEnum.FBS.getLabel());
//					currentOrgCode = orgCode;
//				}
//			}
//			person.setOrgCode(currentOrgCode);
//			UserRegistration userRegistration = this.getUserRegistration(person.getPhone(), null);
//			// 新加--驻场开发 如果注册表则从注册表取数据
//			if (userRegistration != null
//					&& userRegistration.getVerifyStatus() == PersonCheckStatus.INITED.getStatus()) {
//				person.setIdNumber(userRegistration.getIdNumber());
//				person.setIdType(userRegistration.getIdType());
//				// 同步注册录入的三级安全考试分数，与是否合格，身份证正面，身份证反面
//				person.setExamineScore(userRegistration.getExamineScore());
//				person.setQualified(userRegistration.getQualified() != null && userRegistration.getQualified() > 0);
//				person.setFrontCertificatePhoto(userRegistration.getIdCardHead());
//				person.setBackCertificatePhoto(userRegistration.getIdCardNational());
//				if (IdNumberUtil.isValid(userRegistration.getIdNumber())) {
//					person.setBirthday(IdNumberUtil.getBirthdayDate((userRegistration.getIdNumber())));
//					person.setAge(Long.valueOf(IdNumberUtil.getAge(userRegistration.getIdNumber())));
//				}
//				person.setHeadPhoto(userRegistration.getProfile());
//				// 手机注册人默认红码
//				person.setColor(0L);
//				Project project = iProjectService.getById(userRegistration.getProjectId());
//				if (project != null) {
//					person.setOrgCode(project.getOrgCode());
//				}
//
//				// 同步门禁人脸数据
//				List<ProjectDevice> list = iProjectDeviceService.list(new LambdaQueryWrapper<ProjectDevice>()
//						.eq(ProjectDevice::getProjectId, userRegistration.getProjectId()));
//				List<String> sessonNames = list.stream().map(ProjectDevice::getNumber).collect(Collectors.toList());
//				if (StringUtil.isNotEmpty(sessonNames)) {
//					WebSocket.addPerson(person, sessonNames);
//				}
//			} else if (userRegistration != null
//					&& userRegistration.getVerifyStatus() == PersonCheckStatus.WAIT_REGISTER.getStatus()) {
//				return;
//			}
//			this.saveOrUpdate(person);
//			if (currentOrgCode == null) {
//				personMapper.clearOrgCode(person);
//			}
//			PersonAscription personAscription = iPersonAscriptionService
//					.getOne(new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, person.getId())
//							.last("limit 1"));
//			Long oldCompanyId = personAscription != null ? personAscription.getCompanyId() : null;
//			// 更换公司 如果是之前有 现在没有 认为是离职
//			if (oldCompanyId != null && companyId == null) {
//				PersonContract contract = new PersonContract();
//				contract.setUseful(ContractUsefulEum.作废.getValue());
//				contract.setDepartureTime(new Date());
//				contractService.update(contract,
//						new LambdaQueryWrapper<PersonContract>().eq(PersonContract::getPersonId, person.getId())
//								.eq(PersonContract::getUseful, ContractUsefulEum.生效.getValue()));
//			}
//			// 如果之前没有 现在有 认为是入职
//			else if (oldCompanyId == null && companyId != null) {
//				PersonContract contract = new PersonContract();
//				contract.setPersonId(person.getId());
//				contract.setUseful(ContractUsefulEum.生效.getValue());
//				contract.setContractCompanyId(companyId);
//				contract.setStartTime(new Date());
//				contractService.save(contract);
//			}
//			// 如果之前有 现在companyId变更 认为是离职后 再入职
//			else if (oldCompanyId != null && companyId != null && !oldCompanyId.equals(companyId)) {
//				PersonContract contract = new PersonContract();
//				contract.setUseful(ContractUsefulEum.作废.getValue());
//				contract.setDepartureTime(new Date());
//				contractService.update(contract,
//						new LambdaQueryWrapper<PersonContract>().eq(PersonContract::getPersonId, person.getId())
//								.eq(PersonContract::getUseful, ContractUsefulEum.生效.getValue()));
//				PersonContract newContract = new PersonContract();
//				newContract.setPersonId(person.getId());
//				newContract.setUseful(ContractUsefulEum.生效.getValue());
//				newContract.setContractCompanyId(companyId);
//				newContract.setStartTime(new Date());
//				contractService.save(newContract);
//			}
//			if (personAscription != null) {
//				personAscription.setDepartmentId(departmentId);
//				personAscription.setPersonId(person.getId());
//				personAscription.setOrgCode(currentOrgCode);
//				personAscription.setDepartmentName(departmentName);
//				personAscription.setCompanyId(companyId);
//				// 新加--驻场开发
//				if (userRegistration != null
//						&& userRegistration.getVerifyStatus() == PersonCheckStatus.INITED.getStatus()) {
//					personAscription.setProjectId(userRegistration != null ? userRegistration.getProjectId() : null);
//					personAscription
//							.setCompanyId(userRegistration != null ? userRegistration.getCompanyId() : companyId);
//					personAscription
//							.setPostNameKey(userRegistration != null ? userRegistration.getPostNameKey() : null);
//					personAscription.setStatus(userRegistration != null ? 1 : 0);
//					personAscription.setPostName(userRegistration != null ? userRegistration.getPostName() : null);
//				}
//				iPersonAscriptionService.update(personAscription,
//						new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, person.getId()));
//			} else {
//				personAscription = new PersonAscription();
//				personAscription.setDepartmentId(departmentId);
//				personAscription.setPersonId(person.getId());
//				personAscription.setOrgCode(currentOrgCode);
//				personAscription.setDepartmentName(departmentName);
//				personAscription.setCompanyId(companyId);
//				// 新加--驻场开发
//				if (userRegistration != null
//						&& userRegistration.getVerifyStatus() == PersonCheckStatus.INITED.getStatus()) {
//					personAscription.setProjectId(userRegistration != null ? userRegistration.getProjectId() : null);
//					personAscription
//							.setCompanyId(userRegistration != null ? userRegistration.getCompanyId() : companyId);
//					personAscription
//							.setPostNameKey(userRegistration != null ? userRegistration.getPostNameKey() : null);
//					personAscription.setStatus(userRegistration != null ? 1 : 0);
//					personAscription.setPostName(userRegistration != null ? userRegistration.getPostName() : null);
//				}
//				iPersonAscriptionService.save(personAscription);
//			}
//
//			int count = qualificationService.count(new LambdaQueryWrapper<PersonQualifications>()
//					.eq(PersonQualifications::getPersonId, person.getId()));
//			if (count == 0) {
//				PersonQualifications personQualifications = new PersonQualifications();
//				personQualifications.setPersonId(person.getId());
//				qualificationService.save(personQualifications);
//			}
//
//			if (userRegistration != null
//					&& userRegistration.getVerifyStatus() == PersonCheckStatus.INITED.getStatus()) {
//				iProjectQrcodeService.projectClock(person.getId(), userRegistration.getProjectId(), "");
//				userRegistration.setVerifyStatus(PersonCheckStatus.DONE.getStatus());
//				iUserRegistrationService.updateById(userRegistration);
//
//			}
//			translateEventPublish.publish(person);
//
//			// 更新推送
//			statisticsService.initWs(currentOrgCode, Constant.WS_REDORGREENCODE);
//
//			// 更新积分
//			integralFeign.save(new CreateIntegralDto("REGISTER", null, person.getUserId(), null));
//
//		}
		// 平台删除用户
		// else
		if ("multDeleteUser".equals(methodName)) {
			JSONArray array = result.getJSONArray("result");
			List<Object> userIds = array.stream().collect(Collectors.toList());
			List<Person> list = this.list(new LambdaQueryWrapper<Person>().in(Person::getUserId, userIds));
			List<Long> ids = list.stream().map(Person::getId).collect(Collectors.toList());
			List<String> orgCodes = list.stream().map(Person::getOrgCode).collect(Collectors.toList());
			// 门禁删除人
			WebSocket.delPerson(userIds);
			if (ids.isEmpty()) {
				return;
			}
			// 删除归属
			iPersonAscriptionService
					.remove(new LambdaQueryWrapper<PersonAscription>().in(PersonAscription::getPersonId, ids));
			// 删除节能学历
			skillEducationService
					.remove(new LambdaQueryWrapper<PersonSkillEducation>().in(PersonSkillEducation::getPersonId, ids));
			// 删除资质附件
			List<Long> qualificationIds = qualificationService
					.list(new LambdaQueryWrapper<PersonQualifications>().in(PersonQualifications::getPersonId, ids))
					.stream().map(PersonQualifications::getId).collect(Collectors.toList());
			if (qualificationIds.size() > 0) {
				qualificAttachService.remove(new LambdaQueryWrapper<PersonQualificationsAttachment>()
						.in(PersonQualificationsAttachment::getPersonQualificationsId, qualificationIds));
			}
			// 删除资质
			qualificationService
					.remove(new LambdaQueryWrapper<PersonQualifications>().in(PersonQualifications::getPersonId, ids));
			// 删除合同附件

			List<Long> contractIds = contractService
					.list(new LambdaQueryWrapper<PersonContract>().in(PersonContract::getPersonId, ids)).stream()
					.map(PersonContract::getId).collect(Collectors.toList());
			if (contractIds.size() > 0) {
				contractAttachService.remove(new LambdaQueryWrapper<PersonContractAttachment>()
						.in(PersonContractAttachment::getPersonContractId, contractIds));
			}
			// 删除合同
			contractService.remove(new LambdaQueryWrapper<PersonContract>().in(PersonContract::getPersonId, ids));
			// 删除体检附件
			List<Long> examinnationIds = examinnationService
					.list(new LambdaQueryWrapper<PersonExamination>().in(PersonExamination::getPersonId, ids)).stream()
					.map(PersonExamination::getId).collect(Collectors.toList());
			if (examinnationIds.size() > 0) {
				examinatiAttachService.remove(new LambdaQueryWrapper<PersonExaminationAttachment>()
						.in(PersonExaminationAttachment::getPersonExaminationId, examinnationIds));
			}
			// 删除体检
			examinnationService
					.remove(new LambdaQueryWrapper<PersonExamination>().in(PersonExamination::getPersonId, ids));
			// 删除保险附件
			List<Long> insuranceIds = insuranceService
					.list(new LambdaQueryWrapper<PersonInsurance>().in(PersonInsurance::getPersonId, ids)).stream()
					.map(PersonInsurance::getId).collect(Collectors.toList());
			if (insuranceIds.size() > 0) {
				insuranceAttachService.remove(new LambdaQueryWrapper<PersonInsuranceAttachment>()
						.in(PersonInsuranceAttachment::getPersonInsuranceId, insuranceIds));
			}
			// 删除保险
			insuranceService.remove(new LambdaQueryWrapper<PersonInsurance>().in(PersonInsurance::getPersonId, ids));
			// 删除人
			this.removeByIds(ids);
			List<String> phones = list.stream().map(Person::getAccountName).collect(Collectors.toList());
			QueryWrapper<UserRegistration> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().in(UserRegistration::getPhoneNo, phones);
			List<UserRegistration> registrationList = iUserRegistrationService.list(queryWrapper);
			// 新加--驻场开发
			if (!CollectionUtils.isEmpty(registrationList)) {
				iUserRegistrationService.removeByIds(
						registrationList.stream().map(UserRegistration::getId).collect(Collectors.toList()));
			}

			// 删除小程序首页配置信息
			appMenuConfigService.remove(new LambdaQueryWrapper<AppMenuConfig>().in(AppMenuConfig::getUserId, ids));

			// 更新推送
			orgCodes.forEach(i -> {
				statisticsService.initWs(i, Constant.WS_REDORGREENCODE);
			});
		}
	}

	private UserRegistration getUserRegistration(String accountName, Integer status) {
		QueryWrapper<UserRegistration> wrapper = new QueryWrapper<>();
		wrapper.lambda().eq(UserRegistration::getPhoneNo, accountName);
		if (status != null) {
			wrapper.lambda().eq(UserRegistration::getVerifyStatus, status);
		}
		return iUserRegistrationService.getOne(wrapper);
	}

	private void fillHeadPhoto(Person person) {
		QueryWrapper<UserRegistration> wrapper = new QueryWrapper<>();
		wrapper.lambda().eq(UserRegistration::getPhoneNo, person.getAccountName());
		UserRegistration userRegistration = iUserRegistrationService.getOne(wrapper);
		if (userRegistration != null) {
			person.setHeadPhoto(userRegistration.getProfile());
		}
	}

	@Override
	public void updatePhoto(Person person) {
		personMapper.updatePhoto(person);
	}

	/**
	 * 根据项目部判断是否可以加入当前项目
	 *
	 * @param personId
	 * @return
	 */
	@Override
	public boolean canJoinProject(Long personId, Long projectId) {
		Person person = this.getOne(new LambdaQueryWrapper<Person>().eq(Person::getId, personId));
		if (person.getIsJxdj().equals(0L) || person.getOrgCode() == null) {
			return true;
		} else {
			Project project = iProjectService.getById(projectId);
			if (project != null && project.getOrgCode() != null && project.getOrgCode().contains(person.getOrgCode())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 递归获取上级部门 直到项目部 否则返回null
	 *
	 * @param deptId
	 * @param companyId
	 * @return
	 */
	private Long recursiveProjectDeptId(Long deptId, Long companyId) {
		FeignClientResult<DepartmentModel> result = Privilege.departmentClient.seleteOne(deptId);
		DepartmentModel dept = result.getResult();
		if (dept != null) {
			if ("project".equals(dept.getLevel())) {
				return deptId;
			}
		}
		FeignClientResult<Collection<DepartmentModel>> resultList = Privilege.departmentClient.treeByUser(deptId,
				companyId);
		List<DepartmentModel> list = new ArrayList<DepartmentModel>(resultList.getResult());
		if (list != null && list.size() != 0) {
			if ("project".equals(list.get(0).getLevel())) {
				return list.get(0).getSequenceNbr();
			} else {
				// recursiveProjectDeptId(list.get(0).getSequenceNbr(), companyId);
				return null;
			}
		}
		return null;
	}

	/**
	 * 根据权限反查平台角色信息
	 *
	 * @param roles
	 * @return
	 */
	public void setRoleName(Person person, String roles) {
		String roleName = "";
		String roleKey = "";
		if (StringUtils.isNotEmpty(roles)) {
			// 去除[]
			roles = roles.substring(1, roles.length() - 1);
			// 去除空格
			roles = roles.replaceAll(" ", "");
			platformUtils.setPlatFormAccess();
			FeignClientResult<List<RoleModel>> listFeignClientResult = Privilege.roleClient.queyrForMult(roles);
			List<RoleModel> result1 = listFeignClientResult.getResult();
			if (StringUtil.isNotEmpty(result1)) {
				for (RoleModel roleModel : result1) {
					String roleDesc = roleModel.getRoleDesc();
					roleName += roleDesc + ",";
					roleKey += roleModel.getRoleName() + ",";
				}
				if (roleName.lastIndexOf(",") > 0) {
					roleName = roleName.substring(0, roleName.length() - 1);
				}
				if (roleKey.lastIndexOf(",") > 0) {
					roleKey = roleKey.substring(0, roleKey.length() - 1);
				}
			}
			person.setRoleKey(roleKey);
			person.setRoles(roles);
			person.setRoleName(roleName);
		}
	}

	@Override
	public IPage<PersonVo> period(CommonPageableDto pageable, PersonParam personParam, Date start, Date end) {
		if (pageable.getIsAll() == 1) {
			pageable.setPageNumber(0);
			pageable.setPageSize(Integer.MAX_VALUE);
		}
		Page<PersonVo> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		IPage<PersonVo> iPageData = personMapper.period(page, personParam, start, end);
		return iPageData;
	}

	@Override
	public void syncCommonPerson(JSONObject jsonObject) {
		JSONObject result = jsonObject.getJSONObject("result");
		String methodName = jsonObject.getString("methodName");
		// 平台添加用户
		if ("create".equals(methodName)) {
			JSONObject object = result.getJSONObject("result");
			int count = this.count(new LambdaQueryWrapper<Person>().eq(Person::getId, object.getLong("sequenceNbr")));
			if (count > 0) {
				return;
			}
			AgencyUserModel userModel = platformUtils.getSyncPlatformUser(object.getString("userId"));
			Long companyId = (userModel.getCompanys() != null && userModel.getCompanys().get(0) != null)
					? userModel.getCompanys().get(0).getSequenceNbr()
					: null;
			Long departmentId = null;
			List<DepartmentModel> departmentList = null;
			String departmentOrgCode = null;
			String departmentName = null;
			Map<Long, List<DepartmentModel>> companyDepartments = userModel.getCompanyDepartments();
			if (null != companyDepartments) {
				departmentList = userModel.getCompanyDepartments().get(companyId);
			}
			if (departmentList != null && departmentList.get(0) != null) {
				departmentId = departmentList.get(0).getSequenceNbr();
				departmentOrgCode = departmentList.get(0).getOrgCode();
				departmentName = departmentList.get(0).getDepartmentName();
			}
			Person person = new Person();
			person.setId(object.getLong("sequenceNbr"));
			person.setAccountName(object.getString("userName"));
			person.setUserId(object.getLong("userId"));
			person.setName(object.getString("realName"));
			person.setPhone(object.getString("mobile"));
			person.setColor(SmallProQrColorEum.green.getSqlCode());
			Map<Long, List<Long>> roleMap = userModel.getOrgRoleSeqs();
			Map<Long, String> orgRoleName = userModel.getOrgRoleName();

			String roles = null;
			if (departmentId != null) {
				roles = roleMap.get(departmentId) != null ? Arrays.toString(roleMap.get(departmentId).toArray()) : null;
			} else {
				roles = roleMap.get(companyId) != null ? Arrays.toString(roleMap.get(companyId).toArray()) : null;
			}

			// 角色权限名称
			setRoleName(person, roles);
			person.setRoles(roles);
			person.setOrgCode(departmentOrgCode);

			// 同步注册录入的三级安全考试分数，与是否合格，身份证正面，身份证反面
			QueryWrapper<UserRegistration> queryWrapper = new QueryWrapper<UserRegistration>().eq("user_id",
					object.getLong("userId"));
			UserRegistration userRegistration = iUserRegistrationService.getOne(queryWrapper);
			if (userRegistration != null) {
				person.setExamineScore(userRegistration.getExamineScore());
				person.setQualified(userRegistration.getQualified() != null && userRegistration.getQualified() > 0);
				person.setFrontCertificatePhoto(userRegistration.getIdCardHead());
				person.setBackCertificatePhoto(userRegistration.getIdCardNational());
			}
			this.save(person);

			translateEventPublish.publish(person);

			PersonAscription personAscription = new PersonAscription();
			personAscription.setDepartmentId(departmentId);
			personAscription.setCompanyId(companyId);
			personAscription.setPersonId(person.getId());
			personAscription.setDepartmentName(departmentName);
			iPersonAscriptionService.save(personAscription);

			PersonQualifications personQualifications = new PersonQualifications();
			personQualifications.setPersonId(person.getId());
			qualificationService.save(personQualifications);
		}
		// 平台编辑用户
		else if ("update".equals(methodName)) {
			JSONObject object = result.getJSONObject("result");
			AgencyUserModel userModel = platformUtils.getSyncPlatformUser(object.getString("userId"));
			Long companyId = (userModel.getCompanys() != null && userModel.getCompanys().get(0) != null)
					? userModel.getCompanys().get(0).getSequenceNbr()
					: null;
			Long departmentId = null;
			List<DepartmentModel> departmentList = null;
			String departmentOrgCode = null;
			String departmentName = null;
			Map<Long, List<DepartmentModel>> companyDepartments = userModel.getCompanyDepartments();
			if (null != companyDepartments) {
				departmentList = userModel.getCompanyDepartments().get(companyId);
			}
			if (departmentList != null && departmentList.get(0) != null) {
				departmentId = departmentList.get(0).getSequenceNbr();
				departmentOrgCode = departmentList.get(0).getOrgCode();
				departmentName = departmentList.get(0).getDepartmentName();
			}
			Person person = new Person();
			person.setId(object.getLong("sequenceNbr"));
			person.setAccountName(object.getString("userName"));
			person.setUserId(object.getLong("userId"));
			person.setName(object.getString("realName"));
			person.setPhone(object.getString("mobile"));
			// 同步注册录入的三级安全考试分数，与是否合格，身份证正面，身份证反面
			QueryWrapper<UserRegistration> queryWrapper = new QueryWrapper<UserRegistration>().eq("user_id",
					object.getLong("userId"));
			UserRegistration userRegistration = iUserRegistrationService.getOne(queryWrapper);
			if (userRegistration != null) {
				person.setExamineScore(userRegistration.getExamineScore());
				person.setQualified(userRegistration.getQualified() != null && userRegistration.getQualified() > 0);
				person.setFrontCertificatePhoto(userRegistration.getIdCardHead());
				person.setBackCertificatePhoto(userRegistration.getIdCardNational());
			}
			Map<Long, List<Long>> roleMap = userModel.getOrgRoleSeqs();
			String roles = null;
			if (departmentId != null) {
				roles = roleMap.get(departmentId) != null ? Arrays.toString(roleMap.get(departmentId).toArray()) : null;
			} else {
				roles = roleMap.get(companyId) != null ? Arrays.toString(roleMap.get(companyId).toArray()) : null;
			}
			// 角色权限名称
			setRoleName(person, roles);
			person.setRoles(roles);
			if (this.getById(person) == null) {
				person.setColor(SmallProQrColorEum.green.getSqlCode());
			}
			person.setOrgCode(departmentOrgCode);
			this.saveOrUpdate(person);
			PersonAscription personAscription = iPersonAscriptionService
					.getOne(new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, person.getId())
							.last("limit 1"));
			Long oldCompanyId = personAscription != null ? personAscription.getCompanyId() : null;
			// 更换公司 如果是之前有 现在没有 认为是离职
			if (oldCompanyId != null && companyId == null) {
				PersonContract contract = new PersonContract();
				contract.setUseful(ContractUsefulEum.作废.getValue());
				contract.setDepartureTime(new Date());
				contractService.update(contract,
						new LambdaQueryWrapper<PersonContract>().eq(PersonContract::getPersonId, person.getId())
								.eq(PersonContract::getUseful, ContractUsefulEum.生效.getValue()));
			}
			// 如果之前没有 现在有 认为是入职
			else if (oldCompanyId == null && companyId != null) {
				PersonContract contract = new PersonContract();
				contract.setPersonId(person.getId());
				contract.setUseful(ContractUsefulEum.生效.getValue());
				contract.setContractCompanyId(companyId);
				contract.setStartTime(new Date());
				contractService.save(contract);
			}
			// 如果之前有 现在companyId变更 认为是离职后 再入职
			else if (oldCompanyId != null && companyId != null && !oldCompanyId.equals(companyId)) {
				PersonContract contract = new PersonContract();
				contract.setUseful(ContractUsefulEum.作废.getValue());
				contract.setDepartureTime(new Date());
				contractService.update(contract,
						new LambdaQueryWrapper<PersonContract>().eq(PersonContract::getPersonId, person.getId())
								.eq(PersonContract::getUseful, ContractUsefulEum.生效.getValue()));
				PersonContract newContract = new PersonContract();
				newContract.setPersonId(person.getId());
				newContract.setUseful(ContractUsefulEum.生效.getValue());
				newContract.setContractCompanyId(companyId);
				newContract.setStartTime(new Date());
				contractService.save(newContract);
			}
			if (personAscription != null) {
				personAscription.setDepartmentId(departmentId);
				personAscription.setCompanyId(companyId);
				personAscription.setPersonId(person.getId());
				personAscription.setDepartmentName(departmentName);
				iPersonAscriptionService.update(personAscription,
						new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, person.getId()));
			} else {
				personAscription = new PersonAscription();
				personAscription.setDepartmentId(departmentId);
				personAscription.setCompanyId(companyId);
				personAscription.setPersonId(person.getId());
				personAscription.setDepartmentName(departmentName);
				iPersonAscriptionService.save(personAscription);
			}
			translateEventPublish.publish(person);

		}
		// 平台删除用户
		else if ("multDeleteUser".equals(methodName)) {
			JSONArray array = result.getJSONArray("result");
			List<Object> userIds = array.stream().collect(Collectors.toList());
			List<Person> list = this.list(new LambdaQueryWrapper<Person>().in(Person::getUserId, userIds));
			List<Long> ids = list.stream().map(Person::getId).collect(Collectors.toList());
			if (ids.isEmpty()) {
				return;
			}
			// 删除归属
			iPersonAscriptionService
					.remove(new LambdaQueryWrapper<PersonAscription>().in(PersonAscription::getPersonId, ids));
			// 删除节能学历
			skillEducationService
					.remove(new LambdaQueryWrapper<PersonSkillEducation>().in(PersonSkillEducation::getPersonId, ids));
			// 删除资质附件
			List<Long> qualificationIds = qualificationService
					.list(new LambdaQueryWrapper<PersonQualifications>().in(PersonQualifications::getPersonId, ids))
					.stream().map(PersonQualifications::getId).collect(Collectors.toList());
			if (qualificationIds.size() > 0) {
				qualificAttachService.remove(new LambdaQueryWrapper<PersonQualificationsAttachment>()
						.in(PersonQualificationsAttachment::getPersonQualificationsId, qualificationIds));
			}
			// 删除资质
			qualificationService
					.remove(new LambdaQueryWrapper<PersonQualifications>().in(PersonQualifications::getPersonId, ids));
			// 删除合同附件

			List<Long> contractIds = contractService
					.list(new LambdaQueryWrapper<PersonContract>().in(PersonContract::getPersonId, ids)).stream()
					.map(PersonContract::getId).collect(Collectors.toList());
			if (contractIds.size() > 0) {
				contractAttachService.remove(new LambdaQueryWrapper<PersonContractAttachment>()
						.in(PersonContractAttachment::getPersonContractId, contractIds));
			}
			// 删除合同
			contractService.remove(new LambdaQueryWrapper<PersonContract>().in(PersonContract::getPersonId, ids));
			// 删除体检附件
			List<Long> examinnationIds = examinnationService
					.list(new LambdaQueryWrapper<PersonExamination>().in(PersonExamination::getPersonId, ids)).stream()
					.map(PersonExamination::getId).collect(Collectors.toList());
			if (examinnationIds.size() > 0) {
				examinatiAttachService.remove(new LambdaQueryWrapper<PersonExaminationAttachment>()
						.in(PersonExaminationAttachment::getPersonExaminationId, examinnationIds));
			}
			// 删除体检
			examinnationService
					.remove(new LambdaQueryWrapper<PersonExamination>().in(PersonExamination::getPersonId, ids));
			// 删除保险附件
			List<Long> insuranceIds = insuranceService
					.list(new LambdaQueryWrapper<PersonInsurance>().in(PersonInsurance::getPersonId, ids)).stream()
					.map(PersonInsurance::getId).collect(Collectors.toList());
			if (insuranceIds.size() > 0) {
				insuranceAttachService.remove(new LambdaQueryWrapper<PersonInsuranceAttachment>()
						.in(PersonInsuranceAttachment::getPersonInsuranceId, insuranceIds));
			}
			// 删除保险
			insuranceService.remove(new LambdaQueryWrapper<PersonInsurance>().in(PersonInsurance::getPersonId, ids));

			// 删除人
			this.removeByIds(ids);
		}

	}

	@Override
	public IPage<PersonVo> redPerson(CommonPageableDto pageable, Long companyId) {
		if (pageable.getIsAll() == 1) {
			pageable.setPageNumber(0);
			pageable.setPageSize(Integer.MAX_VALUE);
		}
		Page<PersonVo> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		IPage<PersonVo> data = personMapper.redPerson(page, companyId, true);
		return data;
	}

	@Override
	public Page<ApprovalPersonVo> verityPageList(int pageSize, int pageNumber, String name, Long companyId,
			Long projectId, Person person) {
		Page<ApprovalPersonVo> page = new Page<>(pageNumber, pageSize);
		Map<String, Object> param = new HashMap<>();
		param.put("name", name);
		param.put("projectId", projectId);
		String roleKey = person.getRoleKey();
		if (roleKey != null) {
			if (roleKey.contains("fbs")) {
				param.put("companyId", companyId);
				param.put("verifyStatus", PersonCheckStatus.WAIT_REGISTER.getStatus());
			} else {
				param.put("verifyStatus", PersonCheckStatus.CHECK_PASS.getStatus());
			}
		}
		return personMapper.pageListByVerify(page, param);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean verityPersonInfo(VerityPersonParam param, Person verifyPerson) {
		if (log.isInfoEnabled()) {
			log.info("用户审核参数：{}", JSON.toJSONString(param));
		}
		// 1.更新人员临时表
		UserRegistration userRegistration = iUserRegistrationService.getById(param.getId());
		if (userRegistration == null) {
			throw new CommonException(600001, "人员信息不存在");
		}
		Long verifyPersonId = verifyPerson.getId();
		if (param.getStatus() == PersonCheckStatus.CHECK_PASS.getStatus()) {
			// 分包商审核通过需更新的数据
			userRegistration.setPostName(param.getPostName());
			userRegistration.setPostNameKey(param.getPostNameKey());
			userRegistration.setDepartmentId(param.getDepartmentId());
			userRegistration.setRoleId(param.getRoleId());
			userRegistration.setRoleName(param.getRoleName());
			userRegistration.setVerifyStatus(param.getStatus());
			userRegistration.setFbsVerityId(verifyPersonId);
		} else if (param.getStatus() == PersonCheckStatus.INITED.getStatus()) {
			// 项目部审核通过需更新的数据
			userRegistration.setExamineScore(param.getExamScore());
			userRegistration.setQualified(param.getIsQualified());
			userRegistration.setVerifyStatus(param.getStatus());
			userRegistration.setProjectDepartVerityId(verifyPersonId);
		} else {
			// 驳回
			userRegistration.setVerifyStatus(param.getStatus());
		}
		boolean b = iUserRegistrationService.saveOrUpdate(userRegistration);
		if (b && param.getStatus() == PersonCheckStatus.CHECK_PASS.getStatus()) {
			// 分包商审核通过
			// 消息通知--项目部进行人员审核
			// 查询项目部的HR进行消息推送
			
			List<Person> personList = personMapper.getProjectDepartmentPersonByRolekey("hr");
			List<Person> secList = personMapper.getProjectDepartmentPersonByRolekey("security");
			personList.addAll(secList);
			List<Long> directorIdList = Lists.transform(personList, Person::getId);
			JSONArray array = new JSONArray();
			directorIdList.forEach(id -> {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put(MessageAttributeEnum.MSG_TYPE.getName(), MessageTypeEnum.AUDIT.getType());
				jsonObject.put(MessageAttributeEnum.MSG_SUB_TYPE.getName(), MessageSubTypeEnum.AUDIT_MSG.getType());
				jsonObject.put(MessageAttributeEnum.PERSON_ID.getName(), id);
				jsonObject.put(MessageAttributeEnum.CONTENT.getName(), MessageSubTypeEnum.AUDIT_MSG.getTip());
				array.add(jsonObject);
			});
			JSONObject data = new JSONObject();
			data.put("param", array);
			messageEventPublish.publish(data);
		} else if (b && param.getStatus() == PersonCheckStatus.INITED.getStatus()) {
			// 2.项目部 审核通过，调用平台更新用户信息，部门角色
			// 2.1 给人员发布考试
			Long examId = passOutExam(userRegistration);
			// 2.2 给审核通过人员发布知识
			DictionarieValueModel dict = getWorkTypeByName(userRegistration.getPostNameKey());
			Long knowledgeTaskId = taskKnowledgeShareService.saveOneByPostName(userRegistration, dict.getDictDataDesc(),
					dict.getDictDataValue(), verifyPersonId);
			// 2.3保存人员条件信息
			iPersonConditionService.saveOne(userRegistration, examId, knowledgeTaskId);
			// 2.4 保存成绩
			if (userRegistration.getExamineScore() != null) {
				personExamService.saveExam(userRegistration);
			}
			// 同步平台数据
			try {
				AgencyUserModel user = iPersonService.updatePlatformUser(userRegistration);
				// 业务数据保存
				this.initPrecontrolPerson(userRegistration, user);
			} catch (Exception e) {
				e.printStackTrace();
				throw new BaseException("平台更新用户失败");
			}

		} else {
			try {
				String roleKey = verifyPerson.getRoleKey();
				if (roleKey != null) {
					if (roleKey.contains("fbs")) {
						// 分包商 驳回 给注册人发短信
						msgCodeUtil.checkRejectMsgSend(userRegistration.getPhoneNo());
					} else {
						// 项目部驳回 给分包商审核人 发消息通知
						JSONArray array = new JSONArray();
						JSONObject jsonObject = new JSONObject();
						jsonObject.put(MessageAttributeEnum.MSG_TYPE.getName(), MessageTypeEnum.AUDIT.getType());
						jsonObject.put(MessageAttributeEnum.MSG_SUB_TYPE.getName(),
								MessageSubTypeEnum.AUDIT_MSG.getType());
						jsonObject.put(MessageAttributeEnum.PERSON_ID.getName(), userRegistration.getFbsVerityId());
						jsonObject.put(MessageAttributeEnum.CONTENT.getName(), MessageSubTypeEnum.AUDIT_MSG.getTip());
						array.add(jsonObject);
						JSONObject data = new JSONObject();
						data.put("param", array);
						messageEventPublish.publish(data);
					}
				}
			} catch (Exception e) {
				if (log.isErrorEnabled()) {
					log.error("短信发送失败:{}", e.getMessage());
				}
				throw new CommonException(600001, "短信发送失败");
			}

		}
		return b;
	}

	@Override
	public AgencyUserModel updatePlatformUser(UserRegistration userRegistration) {
		FeignClientResult<AgencyUserModel> result = Privilege.agencyUserClient
				.queryByUserId(userRegistration.getUserId().toString());
		if (result.getStatus() == platformSuccessCode) {
			userRegistration.setPersonId(result.getResult().getSequenceNbr());
			Project project = iProjectService.getById(userRegistration.getProjectId());
			FeignClientResult<DepartmentModel> department = Privilege.departmentClient
					.queryByOrgcode(project.getOrgCode());
			FeignClientResult<Collection<DepartmentModel>> result1 = Privilege.departmentClient
					.querySubAgencyTree(department.getResult().getSequenceNbr());
			// Collection<DepartmentModel> depts = department.getResult().getChildren();
			Collection<DepartmentModel> depts = result1.getResult();
			DepartmentModel fbsDept = null;
			for (DepartmentModel dept : depts) {
				if ("fbs".equals(dept.getLevel())) {
					fbsDept = dept;
					break;
				}
			}
			if (fbsDept == null) {
				log.error("请先在平台项目部下创建分包商部门:{}", department.getResult().getDepartmentName());
				throw new CommonException(600001, "请先在平台项目部下创建分包商部门:" + department.getResult().getDepartmentName());
			}
			AgencyUserModel userModel = result.getResult();
			Map<Long, List<Long>> orgRoleSeqs = new HashMap<>();
			orgRoleSeqs.put(fbsDept.getSequenceNbr(), Collections.singletonList(userRegistration.getRoleId()));
			userModel.setOrgRoleSeqs(orgRoleSeqs);
			if (log.isInfoEnabled()) {
				log.info("调用平台进行用户信息更新参数：{}", JSON.toJSONString(userModel));
			}
			FeignClientResult<AgencyUserModel> updateResult = Privilege.agencyUserClient.update(userModel,
					userRegistration.getUserId().toString());
			if (updateResult.getStatus() != platformSuccessCode) {
				if (log.isErrorEnabled()) {
					log.error("调用平台更新用户信息失败:{}", updateResult.getDevMessage());
				}
			}
			return updateResult.getResult();

		} else {
			if (log.isErrorEnabled()) {
				log.error("调用平台查询用户信息失败:{}", result.getDevMessage());
			}
			throw new CommonException(600001, "查询用户信息失败");
		}

	}

	/**
	 * 根据岗位名称获取工种key (从平台岗位名称字典的描述字段获取)
	 *
	 * @param postNameKey
	 * @return
	 */
	private DictionarieValueModel getWorkTypeByName(String postNameKey) {
		// 根据人员岗位 匹配工种
		FeignClientResult<List<DictionarieValueModel>> resultDict = Systemctl.dictionarieClient.dictValues(POST_NAME);
		if (StringUtil.isNotEmpty(resultDict)) {
			DictionarieValueModel dictModel = resultDict.getResult().stream()
					.filter(dict -> dict.getDictDataKey().equals(postNameKey)).findFirst().get();
			if (StringUtil.isNotEmpty(dictModel)) {
				return dictModel;
			}
		}
		return new DictionarieValueModel();
	}

	/**
	 * 对审核通过的人员下发三级安全考试、按人员工种下发对应考试
	 *
	 * @param userRegistration
	 */
	public Long passOutExam(UserRegistration userRegistration) {
		Long examId = null;
		String userId = userRegistration.getUserId().toString();
		// 1 按工种考试发题
		String workType = getWorkTypeByName(userRegistration.getPostNameKey()).getDictDataDesc();
		if (StringUtil.isNotEmpty(workType)) {
			ResponseModel<List<Map<String, Object>>> res = examFeign.getTemplateInSubjectBankType(workType);
			examId = passOutRandomExam(userId, res);
		}
		// 如果注册时录入成绩则不进行三级安全考试下发
		Long examineScore = userRegistration.getExamineScore();
		if (examineScore == null) {
			passOutThreeLevelExam(userRegistration);
		}
		return examId;
	}

	/**
	 * 三级安全考试发题
	 *
	 * @param userRegistration
	 */
	@Override
	public Long passOutThreeLevelExam(UserRegistration userRegistration) {
		String userId = userRegistration.getUserId().toString();
		log.info("start userId----------------------------------->" + userId);
		// 2 三级安全考试发题
		ResponseModel<List<Map<String, Object>>> res = examFeign.getTemplateInSubjectBankType(THREE_LEVEL_EXAM);
		log.info("end userId----------------------------------->" + JSON.toJSONString(res));
		return passOutRandomExam(userId, res);
	}

	/**
	 * 随机考试
	 *
	 * @param userId
	 * @param res
	 */
	private Long passOutRandomExam(String userId, ResponseModel<List<Map<String, Object>>> res) {
		if (StringUtil.isNotEmpty(res) && StringUtil.isNotEmpty(res.getResult())) {
			List<Map<String, Object>> templateList = res.getResult();
			int randomIndex = RandomUtils.getRandomIndex(templateList.size() - 1);
			// 根据随机考试模板发题
			Long templateId = Long.parseLong((String) templateList.get(randomIndex).get("id"));
			CreatExamDto creatExamDto = new CreatExamDto();
			creatExamDto.setId(templateId);
			creatExamDto.setIsAgain(1);
			creatExamDto.setIsMiniApp(false);
			creatExamDto.setUserIds(userId);
			creatExamDto.setBusinessKey(null);
			creatExamDto.setExaminationId(null);
			ResponseModel<Long> response = examFeign.doTemplateExam(creatExamDto);
			return response.getResult();
		}
		return null;
	}

	@Override
	public List<Person> listAllSecurityPerson(Long projectId) {
		QueryWrapper<Person> personQueryWrapper = new QueryWrapper<>();
		personQueryWrapper.lambda().like(Person::getRoleKey, Constant.SECURITY).notLike(Person::getRoleKey, "fbs_");
		Project project = iProjectService.getById(projectId);
		if (project != null && project.getOrgCode() != null) {
			personQueryWrapper.lambda().like(Person::getOrgCode, project.getOrgCode());
		}
		return this.baseMapper.selectList(personQueryWrapper);
	}

	@Override
	public List<Person> listAllTechnicianPerson(Long projectId) {
		QueryWrapper<Person> personQueryWrapper = new QueryWrapper<>();
		personQueryWrapper.lambda().like(Person::getRoleKey, Constant.TECHNICINA).notLike(Person::getRoleKey, "fbs_");
		Project project = iProjectService.getById(projectId);
		if (project != null && project.getOrgCode() != null) {
			personQueryWrapper.lambda().like(Person::getOrgCode, project.getOrgCode());
		}
		return this.baseMapper.selectList(personQueryWrapper);
	}

	/**
	 * @param id
	 * @Description 檢查人員信息是否完成
	 * @Return Boolean
	 * @Date 2021/4/8 15:08
	 */
	@Override
	public Boolean checkPersonMessageIsFinish(Long id) {
		if (!personInfoComplete) {
			return Boolean.TRUE;
		}
		Person person = this.getById(id);
		PersonAscription personAscription = iPersonAscriptionService
				.getOne(new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, id));
		List<PersonQualifications> personQualifications = iPersonQualificationsService
				.list(new LambdaQueryWrapper<PersonQualifications>().eq(PersonQualifications::getPersonId, id));
		if (person.getIsJxdj() == 1) {
			// 姓名
			if (StringUtils.isBlank(person.getName())) {
				return Boolean.FALSE;
			}
			// 性別
			if (person.getSex() == null) {
				return Boolean.FALSE;
			}
			// 證件編號
			if (StringUtils.isBlank(person.getIdNumber())) {
				return Boolean.FALSE;
			}
			// 證件類型
			if (person.getIdType() == null) {
				return Boolean.FALSE;
			}
			// 生日
			if (person.getBirthday() == null) {
				return Boolean.FALSE;
			}
			// 年齡
			if (person.getAge() == null) {
				return Boolean.FALSE;
			}
			// 電話
			if (StringUtils.isBlank(person.getPhone())) {
				return Boolean.FALSE;
			}
			// 工号
			if (StringUtils.isBlank(person.getJobNumber())) {
				return Boolean.FALSE;
			}
			// 岗位
			if (StringUtils.isBlank(personAscription.getPostName())) {
				return Boolean.FALSE;
			}
			// 人員頭像
			if (StringUtils.isBlank(person.getHeadPhoto())) {
				return Boolean.FALSE;
			}
		} else {
			// 姓名
			if (StringUtils.isBlank(person.getName())) {
				return Boolean.FALSE;
			}
			// 性別
			if (person.getSex() == null) {
				return Boolean.FALSE;
			}
			// 生日
			if (person.getBirthday() == null) {
				return Boolean.FALSE;
			}
			// 年齡
			if (person.getAge() == null) {
				return Boolean.FALSE;
			}
			// 名族
			if (StringUtils.isBlank(person.getFolkKey())) {
				return Boolean.FALSE;
			}
			// 電話
			if (StringUtils.isBlank(person.getPhone())) {
				return Boolean.FALSE;
			}
			// 應急電話
			if (StringUtils.isBlank(person.getEmergencyPhone())) {
				return Boolean.FALSE;
			}
			// 政治面貌
			if (StringUtils.isBlank(person.getPoliticCountenance())) {
				return Boolean.FALSE;
			}
			// 證件編號
			if (StringUtils.isBlank(person.getIdNumber())) {
				return Boolean.FALSE;
			}
			// 證件類型
			if (person.getIdType() == null) {
				return Boolean.FALSE;
			}
			// 户籍地址
			if (StringUtils.isBlank(person.getAddress())) {
				return Boolean.FALSE;
			}
			// 現住址
			if (StringUtils.isBlank(person.getPresentAddress())) {
				return Boolean.FALSE;
			}
			// 參加工作時間
			if (person.getWorkTime() == null) {
				return Boolean.FALSE;
			}
			// 人員頭像
			if (StringUtils.isBlank(person.getHeadPhoto())) {
				return Boolean.FALSE;
			}
			// 证件照片正面
			if (StringUtils.isBlank(person.getFrontCertificatePhoto())) {
				return Boolean.FALSE;
			}
			// 证件照片反面
			if (StringUtils.isBlank(person.getBackCertificatePhoto())) {
				return Boolean.FALSE;
			}
			// 进入本单位工作时间
			if (personAscription.getCompanyWorkTime() == null) {
				return Boolean.FALSE;
			}
			// 所在单位id
			if (personAscription.getCompanyId() == null) {
				return Boolean.FALSE;
			}
			// 所在单位id
			if (personAscription.getCompanyId() == null) {
				return Boolean.FALSE;
			}
			// 部門班組
			if (personAscription.getDepartmentId() == null) {
				return Boolean.FALSE;
			}
			// 工作所在地key
			if (StringUtils.isBlank(personAscription.getWorkPlaceKey())) {
				return Boolean.FALSE;
			}
			// 岗位
			if (StringUtils.isBlank(personAscription.getPostName())) {
				return Boolean.FALSE;
			}
			if (StringUtil.isEmpty(personQualifications)) {
				return Boolean.FALSE;
			} else {
				PersonQualifications personQualification = personQualifications.get(0);
				if (StringUtils.isNotBlank(personQualification.getCertificateTypeKey())
						&& !personQualification.getCertificateTypeKey().equals("无")) {
					// 证件名称key
					if (StringUtils.isBlank(personQualification.getCertificateNameKey())) {
						return Boolean.FALSE;
					}
					// 取证项目
					if (StringUtils.isBlank(personQualification.getCertificateProject())) {
						return Boolean.FALSE;
					}
					// 发证机关
					if (StringUtils.isBlank(personQualification.getIssuingAuthority())) {
						return Boolean.FALSE;
					}
					// 证书编号
					if (StringUtils.isBlank(personQualification.getCertificateNumber())) {
						return Boolean.FALSE;
					}
					// 取证时间
					if (personQualification.getCertificateObtainTime() == null) {
						return Boolean.FALSE;
					}
					// 有效期限（年）
					if (StringUtils.isBlank(personQualification.getExpireDate())) {
						return Boolean.FALSE;
					}
					// 证书等级
					if (StringUtils.isBlank(personQualification.getCertificateLevel())) {
						return Boolean.FALSE;
					}
				}
			}

		}
		return Boolean.TRUE;
	}

	/**
	 * @param userId
	 * @Author songLei
	 * @Version 1.0
	 * @Description // 积分系统提供 人员信息
	 * @Return PersonMsgVo
	 * @Date 2021/6/22 16:10
	 */
	@Override
	public PersonMsgVo personMsg(Long userId) {
		PersonAscription pa = personAscriptionService
				.getOne(new QueryWrapper<PersonAscription>().lambda().eq(PersonAscription::getPersonId, userId));
		PersonMsgVo personMsgVo = new PersonMsgVo();
		if (pa != null) {
			Project project = iProjectService.getById(pa.getProjectId());
			Person person = iPersonService.getById(userId);
			Company company = iCompanyService.getById(pa.getCompanyId());
			personMsgVo.setProjectId(project != null ? project.getId() : null);
			personMsgVo.setProjectName(project != null ? project.getName() : null);
			personMsgVo.setOrgCode(project != null ? project.getOrgCode() : null);
			personMsgVo.setCompanyName(company.getName());
			personMsgVo.setRealName(person.getName());
		}
		return personMsgVo;
	}

	/**
	 * 用户树
	 *
	 * @param userId
	 * @return
	 */
	@Override
	public Object personTree(String userId) {
		FeignClientResult<java.util.Collection<UserOrgTreeModel>> ojb = Privilege.userOrgRoleClient
				.queryTreeByCompanyId(null, null);
		Collection<UserOrgTreeModel> tree = ojb.getResult();
		Person person = this.getOne(new QueryWrapper<Person>().lambda().eq(Person::getUserId, userId));
		if (StringUtils.isNotBlank(person.getOrgCode())) {
			return projectCompany(person.getOrgCode(), tree.stream().findFirst().get().getId(), tree);
		} else {
			return tree;
		}
	}

	public Collection<UserOrgTreeModel> projectCompany(String orgCode, String id, Collection<UserOrgTreeModel> tree) {
		List<Project> projects = iProjectService
				.list(new QueryWrapper<Project>().lambda().like(Project::getOrgCode, orgCode));
		List<Long> ids = new ArrayList<>();
		if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(projects)) {
			projects.stream().forEach(item -> {
				ids.add(item.getId());
			});
		}
		List<Long> cids = new ArrayList<>();
		if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(ids)) {
			List<ProjectCompany> projectCompanies = iProjectCompanyService
					.list(new QueryWrapper<ProjectCompany>().lambda().in(ProjectCompany::getProjectId, ids));
			if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(projectCompanies)) {
				projectCompanies.stream().forEach(item -> {
					cids.add(item.getCompanyId());
				});
			}
		}
		if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(cids)) {
			Collection<UserOrgTreeModel> children = tree.stream().findFirst().get().getChildren();
			UserOrgTreeModel firstChildren = children.stream()
					.filter(x -> orgCode.startsWith(
							JSON.parseObject(JSON.toJSONString(x.getObject()), TreeModel.class).getOrgCode()))
					.findFirst().get();
			Collection<UserOrgTreeModel> orgTreeModels = firstChildren.getChildren();
			if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(orgTreeModels)) {
				for (UserOrgTreeModel orm : orgTreeModels) {
					TreeModel treeModel = JSON.parseObject(JSON.toJSONString(orm.getObject()), TreeModel.class);
					if (treeModel.getOrgCode() != null && orgCode.startsWith(treeModel.getOrgCode())) {
						UserOrgTreeModel a = orm;
						Collection<UserOrgTreeModel> uom = new ArrayList<>();
						uom.add(a);
						firstChildren.setChildren(uom);
					}
				}
			}
			tree.stream().findFirst().get().setChildren(new ArrayList<>());
			tree.stream().findFirst().get().getChildren().add(firstChildren);
			/*
			 * cids.stream().distinct().collect(Collectors.toList()).forEach(item -> {
			 * FeignClientResult<java.util.Collection<UserOrgTreeModel>> obj =
			 * Privilege.userOrgRoleClient .queryTre(item, null); if
			 * (org.apache.commons.collections4.CollectionUtils.isNotEmpty(obj.getResult()))
			 * { obj.getResult().stream().forEach(t -> { t.setParentId(id); }); }
			 * tree.stream().findFirst().get().getChildren().addAll(obj.getResult()); });
			 */
		}
		return tree;
	}

	@Override
	@Transactional
	public Boolean savePersonNew(PersonAccount personAccount) {
		// 创建账号
		AgencyUserModel userModel = new AgencyUserModel();
		userModel.setRealName(personAccount.getName());
		userModel.setPassword(DesUtil.encode(personAccount.getPassword(), secretKey));
		userModel.setRePassword(DesUtil.encode(personAccount.getConfirmPassword(), secretKey));
		userModel.setUserName(personAccount.getAccount());
		userModel.setMobile(personAccount.getPhone());
		userModel.setLockStatus("UNLOCK");
		userModel.setAppCodes(personAccount.getApplicationList());
		Map<Long, List<Long>> map = new HashMap<>();
		map.put(personAccount.getPlatformDepartmentId(), personAccount.getRoleIdList());
		userModel.setOrgRoleSeqs(map);
		FeignClientResult<AgencyUserModel> createResult = null;
		try {
			createResult = Privilege.agencyUserClient.create(userModel);
		} catch (Exception e) {
			log.error(e.getMessage());
			System.out.println(e.getMessage());
			e.printStackTrace();
			throw new BaseException(e.getMessage());
		}

		// 基本信息
		Person person = new Person();
		person.setId(createResult.getResult().getSequenceNbr());
		person.setAccountName(personAccount.getAccount());
		person.setPhone(personAccount.getPhone());
		person.setName(personAccount.getName());
		person.setIsJxdj(personAccount.getCompanyId() == null ? 1L : 0);
		person.setUserId(Long.valueOf(createResult.getResult().getUserId()));
		person.setRoles(Arrays.toString(personAccount.getRoleIdList().toArray()));
		setNewRoleName(person, personAccount.getRoleList());
		person.setDeptType(personAccount.getPlatformDepartmentType());
		String orgCode = getCurrentCode(personAccount.getPlatformDepartmentId().toString());
		person.setColor(personAccount.getCompanyId() == null ?SmallProQrColorEum.green.getSqlCode():SmallProQrColorEum.red.getSqlCode());
		person.setOrgCode(orgCode);
		this.save(person);

		// 归属信息
		PersonAscription personAscription = new PersonAscription();

		personAscription.setPersonId(person.getId());
		Company company;
		if (personAccount.getCompanyId() == null) {
			company = iCompanyService
					.getOne(new LambdaQueryWrapper<Company>().eq(Company::getTypeKey, TypeKeyEnum.JXDJ.getType()));
			if (company == null) {
				throw new BaseException("所属公司不存在");
			}
			personAscription.setCompanyId(company.getId());
			personAscription.setCompanyName(company.getName());
			personAscription.setDepartmentId(personAccount.getPlatformDepartmentId());
			personAscription.setDepartmentName(personAccount.getPlatformDepartmentName());
		} else {
			company = iCompanyService.getById(personAccount.getCompanyId());
			if (company == null) {
				throw new BaseException("所属公司不存在");
			}
			personAscription.setCompanyId(company.getId());
			personAscription.setCompanyName(company.getName());
			CompanyDepartment companyDepartment = iCompanyDepartmentService.getById(personAccount.getDepartmentId());
			if (companyDepartment == null) {
				throw new BaseException("所属部门不存在");
			}
			personAscription.setDepartmentId(personAccount.getDepartmentId());
			personAscription.setDepartmentName(companyDepartment.getName());
		}
		iPersonAscriptionService.save(personAscription);

		// 资质信息
		PersonQualifications personQualifications = new PersonQualifications();
		personQualifications.setPersonId(person.getId());
		qualificationService.save(personQualifications);

		// 新合同生效
		PersonContract contract = new PersonContract();
		contract.setPersonId(person.getId());
		contract.setUseful(ContractUsefulEum.生效.getValue());
		contract.setContractCompanyId(personAccount.getCompanyId());
		contract.setStartTime(new Date());
		contractService.save(contract);

		// 分包商主管发考试
		if (person.getRoleKey().contains(RoleEnum.FBS_DIRECTOR.getValue())) {
			UserRegistration userRegistration = new UserRegistration();
			userRegistration.setUserId(person.getUserId());
			Long examId = passOutThreeLevelExam(userRegistration);
		}
		return true;
	}

	private String getCurrentCode(String platformDepartmentId) {
		String orgcode = null;
		System.out.println(RequestContext.getToken());
		FeignClientResult<List> deptResult = Privilege.departmentClient.queryDeptByIds(platformDepartmentId.toString());
		if (deptResult.getResult() != null && deptResult.getResult().size() > 0
				&& deptResult.getResult().get(0) != null) {
			Map deptModel = (Map) deptResult.getResult().get(0);
			Object obj = deptModel.get("orgCode");
			if (obj != null) {
				if ("public".equals(String.valueOf(deptModel.get("level")))) {

				} else if ("project".equals(String.valueOf(deptModel.get("level")))) {
					orgcode = obj.toString();
				} else {
					Object parentId = deptModel.get("parentId");
					if (parentId != null&&!"1".equals(parentId)) {
						orgcode = getCurrentCode(parentId.toString());
					}else 
					{
						orgcode = obj.toString();
					}
				}
			}
		}
		return orgcode;
	}

	/**
	 * 根据权限反查平台角色信息
	 *
	 * @param roles
	 * @return
	 */
	public void setNewRoleName(Person person, List<PlatformRole> roles) {
		StringBuffer roleName = new StringBuffer();
		StringBuffer roleKey = new StringBuffer();
		if (StringUtil.isNotEmpty(roles)) {
			roles.forEach(i -> {
				roleName.append(i.getRoleDesc()).append(",");
				roleKey.append(i.getRoleName()).append(",");
			});
			if (roleName.length() > 0) {
				roleName.deleteCharAt(roleName.length() - 1);
			}
			if (roleKey.length() > 0) {
				roleKey.deleteCharAt(roleKey.length() - 1);
			}
			person.setRoleKey(roleKey.toString());
			person.setRoleName(roleName.toString());
		}
	}

	private void initPrecontrolPerson(UserRegistration userRegistration, AgencyUserModel userModel) {
		Person person = new Person();
		person.setId(userRegistration.getPersonId());
		person.setAccountName(userRegistration.getPhoneNo());
		person.setUserId(userRegistration.getUserId());
		person.setName(userRegistration.getRealName());
		person.setPhone(userRegistration.getPhoneNo());
		person.setColor(SmallProQrColorEum.red.getSqlCode());
		person.setRoleName(userRegistration.getRoleName());
		person.setHeadPhoto(userRegistration.getProfile());
		person.setIdNumber(userRegistration.getIdNumber());
		if (person.getIdNumber() != null) {
			if (!IdNumberUtil.isValid(person.getIdNumber())) {
				throw new BaseException("身份证格式不正确: " + person.getName());
			} else {
				person.setAge(Long.valueOf(IdNumberUtil.getAge(person.getIdNumber())));
				person.setBirthday(IdNumberUtil.getBirthdayDate(person.getIdNumber()));
			}
		}
		Map<Long, List<Long>> roleMap = userModel.getOrgRoleSeqs();
		String roles = null;
		for (Long key : roleMap.keySet()) {
			roles = roleMap.get(key) != null ? Arrays.toString(roleMap.get(key).toArray()) : null;
		}
		// 角色权限名称
		setRoleName(person, roles);
		person.setRoles(roles);
		Project project = iProjectService.getById(userRegistration.getProjectId());
		String orgcode = project == null ? null : project.getOrgCode();
		person.setOrgCode(orgcode);
		person.setExamineScore(userRegistration.getExamineScore());
		person.setQualified(userRegistration.getQualified() != null && userRegistration.getQualified() > 0);
		person.setFrontCertificatePhoto(userRegistration.getIdCardHead());
		person.setBackCertificatePhoto(userRegistration.getIdCardNational());
		this.saveOrUpdate(person);

		translateEventPublish.publish(person);
		PersonAscription personAscription = new PersonAscription();
		personAscription.setDepartmentId(userRegistration.getDepartmentId());
		personAscription.setCompanyId(userRegistration.getCompanyId());
		personAscription.setPersonId(person.getId());
		personAscription.setPostName(userRegistration.getPostName());
		personAscription.setPostNameKey(userRegistration.getPostNameKey());
		CompanyDepartment companyDepartment = iCompanyDepartmentService.getById(userRegistration.getDepartmentId());
		personAscription.setDepartmentName(companyDepartment == null ? null : companyDepartment.getName());
		PersonAscription oldPersonAscription = iPersonAscriptionService
				.getOne(new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, person.getId()));
		if (oldPersonAscription != null) {
			iPersonAscriptionService.update(personAscription,
					new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, person.getId()));
		} else {
			iPersonAscriptionService.save(personAscription);
		}

		PersonQualifications personQualifications = new PersonQualifications();
		personQualifications.setPersonId(person.getId());
		qualificationService.save(personQualifications);

		// 新合同生效
		PersonContract contract = new PersonContract();
		contract.setPersonId(person.getId());
		contract.setUseful(ContractUsefulEum.生效.getValue());
		contract.setContractCompanyId(userRegistration.getCompanyId());
		contract.setStartTime(new Date());
		contractService.save(contract);

		iProjectQrcodeService.projectClock(person.getId(), userRegistration.getProjectId(), "");
		translateEventPublish.publish(person);
		// 更新推送
		statisticsService.initWs(orgcode, Constant.WS_REDORGREENCODE);

		// 更新积分
		integralFeign.save(new CreateIntegralDto("REGISTER", null, person.getUserId(), null));

	}

	@Override
	public void inOccupation(PersonAccount personAccount) {
		String userId = personAccount.getUserId();
		FeignClientResult<AgencyUserModel> agencyUserModelFeignClientResult = Privilege.agencyUserClient
				.queryByUserId(personAccount.getUserId());
		FeignClientResult<DepartmentModel> deptResult = Privilege.departmentClient
				.seleteOne(personAccount.getPlatformDepartmentId());
		AgencyUserModel userModel = agencyUserModelFeignClientResult.getResult();
		userModel.setAppCodes(personAccount.getApplicationList());
		Map<Long, List<Long>> map = new HashMap<>();
		map.put(personAccount.getPlatformDepartmentId(), personAccount.getRoleIdList());
		userModel.setOrgRoleSeqs(map);
		userModel.setLockStatus("UNLOCK");
		Person person = iPersonService
				.getOne(new LambdaQueryWrapper<Person>().eq(Person::getUserId, personAccount.getUserId()));
		//person.setRoles(Arrays.toString(personAccount.getRoleIdList().toArray()));
		setRoleName(person, Arrays.toString(personAccount.getRoleIdList().toArray()));
		//iPersonService.setNewRoleName(person, personAccount.getRoleList());
		person.setDeptType(personAccount.getPlatformDepartmentType());
		person.setIsJxdj(personAccount.getCompanyId() == null ? 1L : 0);
		String orgCode = getCurrentCode(personAccount.getPlatformDepartmentId().toString());
		person.setOrgCode(orgCode);
		FeignClientResult<AgencyUserModel> result = new FeignClientResult<>();
		try {
			result = Privilege.agencyUserClient.update(userModel, userId);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			throw new BaseException("平台更新账户失败");
		}
		int status = result.getStatus();
		if (status == 200) {
			// sequenceNbr代表我们系统的userId
			Long sequenceNbr = result.getResult().getSequenceNbr();
			if (sequenceNbr != null) {
				PersonAscription personAscription = iPersonAscriptionService.getOne(
						new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, person.getId()));
				if (personAccount.getCompanyId() == null) {
					Company company = iCompanyService
							.getOne(new LambdaQueryWrapper<Company>().eq(Company::getTypeKey, 1));
					personAscription.setCompanyId(company.getId());
					personAscription.setCompanyName(company.getName());
					personAscription.setDepartmentId(personAccount.getPlatformDepartmentId());
					personAscription.setDepartmentName(personAccount.getPlatformDepartmentName());

				} else {
					personAscription.setCompanyId(personAccount.getCompanyId());
					Company company = iCompanyService.getById(personAccount.getCompanyId());
					personAscription.setCompanyName(company.getName());
					personAscription.setDepartmentId(personAccount.getDepartmentId());
					CompanyDepartment department = iCompanyDepartmentService.getById(personAccount.getDepartmentId());
					personAscription.setDepartmentName(department.getName());
				}
				if(orgCode==null) 
				{
					iPersonService.update(new LambdaUpdateWrapper<Person>().set(Person::getOrgCode, null).eq(Person::getId, person.getId()));
				}
				iPersonService.updateById(person);
				iPersonAscriptionService.updateById(personAscription);
				// 新合同生效
				PersonContract contract = new PersonContract();
				contract.setPersonId(sequenceNbr);
				contract.setUseful(ContractUsefulEum.生效.getValue());
				contract.setContractCompanyId(personAccount.getCompanyId());
				contract.setStartTime(new Date());
				contractService.save(contract);
			}

		}

	}

	@Override
	public Boolean updateDept(PersonAccount personAccount) {
		Person person = iPersonService
				.getOne(new LambdaQueryWrapper<Person>().eq(Person::getUserId, personAccount.getUserId()));
		PersonAscription personAscription = iPersonAscriptionService
				.getOne(new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, person.getId()));
		if (personAscription.getProjectId() != null) {
			throw new BaseException("人员在岗中,请先离岗");
		}
		FeignClientResult<AgencyUserModel> agencyUserModelFeignClientResult = Privilege.agencyUserClient
				.queryByUserId(personAccount.getUserId());
		AgencyUserModel userModel = agencyUserModelFeignClientResult.getResult();
		Map<Long, List<Long>> map = new HashMap<>();
		map.put(personAccount.getPlatformDepartmentId(), personAccount.getRoleIdList());
		userModel.setOrgRoleSeqs(map);
		FeignClientResult<AgencyUserModel> result = new FeignClientResult<>();
		try {
			platformUtils.setPlatFormAccess();
			result = Privilege.agencyUserClient.update(userModel, personAccount.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			throw new BaseException("平台更新账户失败");
		}
		int status = result.getStatus();
		if (status == 200) {

			Map<Long, List<Long>> roleMap = userModel.getOrgRoleSeqs();
			String roles = null;
			for (Long key : roleMap.keySet()) {
				roles = roleMap.get(key) != null ? Arrays.toString(roleMap.get(key).toArray()) : null;
			}
			// 角色权限名称
			setRoleName(person, roles);
			person.setRoles(roles);
			String orgCode = getCurrentCode(personAccount.getPlatformDepartmentId().toString());

			person.setOrgCode(orgCode);
			iPersonService.updateById(person);
			if(orgCode==null) 
			{
				iPersonService.update(new LambdaUpdateWrapper<Person>().set(Person::getOrgCode, null).eq(Person::getId, person.getId()));
			}
			personAscription.setDepartmentId(personAccount.getPlatformDepartmentId());
			personAscription.setDepartmentName(personAccount.getPlatformDepartmentName());
			iPersonAscriptionService.updateById(personAscription);
		}
		return true;
	}
}
