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

import cn.hutool.core.util.DesensitizedUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yeejoin.amos.boot.biz.common.feign.AmosFeignService;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.jxiop.api.Enum.QrcodeColorEnum;
import com.yeejoin.amos.boot.module.jxiop.api.dto.*;
import com.yeejoin.amos.boot.module.jxiop.api.entity.PersonBasic;
import com.yeejoin.amos.boot.module.jxiop.api.entity.*;
import com.yeejoin.amos.boot.module.jxiop.api.feign.AgencyuserFeign;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.PersonAccountFedMapper;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.PersonBasicMapper;
import com.yeejoin.amos.boot.module.jxiop.api.service.IPersonBasicService;
import com.yeejoin.amos.boot.module.jxiop.api.util.Constants;
import com.yeejoin.amos.boot.module.jxiop.biz.activemq.QuerueProduce;
import com.yeejoin.amos.boot.module.jxiop.biz.amosprojectmapper.UserEmpowerMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.StdUserEmpower;
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.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.feign.privilege.model.LoginInfoModel;
import com.yeejoin.amos.feign.privilege.util.DesUtil;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 人员基本信息服务实现类
 *
 * @author system_generator
 * @date 2023-04-20
 */
@Slf4j
@Service
public class PersonBasicServiceImpl extends BaseService<PersonBasicDto, PersonBasic, PersonBasicMapper>
		implements IPersonBasicService {

	@Autowired
	PersonBasicMapper personBasicMapper;

	// 人员账号信息service
	@Autowired
	PersonAccountServiceImpl personAccountService;
	// 人员归属信息service
	@Autowired
	PersonAscriptionServiceImpl personAscriptionService;
	// 人员资质信息service
	@Autowired
	PersonCertificateServiceImpl personCertificateService;
	// 人员教育信息
	@Autowired
	PersonSkillEducationServiceImpl personSkillEducationService;
	@Value("${amos.secret.key}")
	String secretKey;
	@Autowired
	QuerueProduce querueProduce;

	@Autowired
	private AmosFeignService amosFeignService;

	@Autowired
	private RedisUtils redisUtils;

	@Autowired
	protected EmqKeeper emqKeeper;

	@Autowired
	private AgencyuserFeign agencyuserFeign;

	@Autowired
	private UserEmpowerMapper userEmpowerMapper;

	/**
	 * 人员赋码触发风险模型
	 */
	public static final String RYFM_DATA_MQTT_TOPIC = "ryfm/data/analysis";

	/**
	 * 人员红黄码恢复为绿码
	 */
	public static final String RYFM_GREEN = "ryfm/person/green";

	private String UPDATE = "UPDATE";
	private String INSERT = "INSERT";
	@Autowired
	PersonAccountFedMapper personAccountFedMapper;

	/**
	 * 分页查询
	 */
	public Page<PersonBasicDto> queryForPersonBasicPage(Page<PersonBasicDto> page) {
		return this.queryForPage(page, null, false);
	}

	/**
	 * 列表查询 示例
	 */
	public List<PersonBasicDto> queryForPersonBasicList() {
		return this.queryForList("", false);
	}

	public void addRedisPostAndCerInfo() {
		List<DictionarieValueModel> elevatorCategory = null;
		try {
			elevatorCategory = amosFeignService.listDictionaryByDictCode("YGZYJNJDZS");
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String, String> collect = elevatorCategory.stream().collect(
				Collectors.toMap(DictionarieValueModel::getDictDataKey, DictionarieValueModel::getDictDataDesc));
		redisUtils.set(Constants.JXIOP_DICT_POST, collect);

		List<DictionarieValueModel> elevator = null;
		try {
			elevator = amosFeignService.listDictionaryByDictCode("岗位资质鉴定证书");
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String, String> collect2 = elevator.stream().collect(
				Collectors.toMap(DictionarieValueModel::getDictDataKey, DictionarieValueModel::getDictDataDesc));
		redisUtils.set(Constants.JXIOP_DICT_CERTIFICATES, collect2);
	}

	public RiskBizInfoVo fetchData(PersonBasic personBasic, PersonAccount personAccount, String content) {
		RiskBizInfoVo riskBizInfoVo = new RiskBizInfoVo();
		riskBizInfoVo.setWarningObjectName(
				personAccount.getProjectName() + personBasic.getPostName() + personAccount.getName());
		riskBizInfoVo.setWarningObjectCode(String.valueOf(personBasic.getSequenceNbr()));
		riskBizInfoVo.setSourceAttribution(personBasic.getProjectOrgCode());
		riskBizInfoVo.setSourceAttributionDesc(personAccount.getProjectName());
		riskBizInfoVo.setWarningObjectType("RYFM");
		List<RiskDynamicDetailsVo> detailsVos = new ArrayList<>();
		RiskDynamicDetailsVo dynamicDetailsVo = new RiskDynamicDetailsVo();
		dynamicDetailsVo.setTabName("预警详情");
		detailsVos.add(dynamicDetailsVo);
		riskBizInfoVo.setDynamicDetails(detailsVos);
		CustomizeItems customizeItems = new CustomizeItems();
		customizeItems.setWarningContent(content);
		riskBizInfoVo.setCustomizeItems(customizeItems);
		return riskBizInfoVo;
	}

	/**
	 * 新增
	 */
	@Transactional
	public void addPerson(PersonDto model, HttpServletRequest httpServletRequest) throws Exception {
		if (!redisUtils.hasKey(Constants.JXIOP_DICT_POST) || !redisUtils.hasKey(Constants.JXIOP_DICT_CERTIFICATES)) {
			addRedisPostAndCerInfo();
		}
		// 岗位所需证书信息
		Map<String, String> postNameMap = (Map<String, String>) redisUtils.get(Constants.JXIOP_DICT_POST);
		// 证书临期信息
		Map<String, String> certificatesMap = (Map<String, String>) redisUtils.get(Constants.JXIOP_DICT_CERTIFICATES);

		// 获取人员基本信息数据
		PersonUser personUser = model.getPersonUser();
		// 获取人员账号信息
		PersonAccount personAccount = model.getPersonAccount();
		personUser.setPhone(personAccount.getPhoneNum());
		// 人员基础信息
		PersonBasic personBasic = new PersonBasic();
		BeanUtils.copyProperties(personUser, personBasic);
		// 默认红码
		personBasic.setQrcodeColor(QrcodeColorEnum.RED.getCode());
		personBasic.setQrcodeDesc("证书不全");
		// 该岗位应获得的证书
		List<String> list2 = new ArrayList<>();
		if (StringUtils.isNotEmpty(personUser.getPostName())) {
			String certificates = postNameMap.get(personUser.getPostName());
			if (!StringUtils.isEmpty(certificates)) {
				list2 = Arrays.asList(certificates.split(","));
			}
		}
		List<String> list = new ArrayList(list2);
		// 人员资质信息
		Integer isInMonth = 0;
		Integer isOver = 0;
		CertificationInfo personCertificate = model.getPersonCertificate();

		// 过期的证书
		List<String> overCertificateList = new ArrayList<>();
		// 临期证书
		List<String> inMonthCertificateList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(personCertificate.getCertificationInfo())) {
			for (PersonCertificate item : personCertificate.getCertificationInfo()) {
				if (StringUtils.isNotEmpty(item.getValidPeriod()) && !Objects.isNull(item.getCertificateTime())) {
					int validPeriod = StringUtils.isEmpty(item.getValidPeriod()) ? 3
							: Integer.parseInt(item.getValidPeriod());
					Date date = DateUtils.dateAddYears(item.getCertificateTime(), validPeriod);
					if (list.contains(item.getCertificateName()) && DateUtils.dateCompare(date, new Date()) == -1) {
						isOver = 1;
						overCertificateList.add(item.getCertificateName());
					}
					if (list.contains(item.getCertificateName())
							&& DateUtils.dateBetweenIncludeToday(new Date(), date) < Integer
									.valueOf(certificatesMap.get(item.getCertificateName()))
							&& DateUtils.dateCompare(date, new Date()) == 1) {
						isInMonth = 1;
						inMonthCertificateList.add(item.getCertificateName());
					}
				}
				list.remove(item.getCertificateName());
			}
		}
		// 缺证
		List<String> noCertificateList = new ArrayList<>(list);
		List<String> strings = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(overCertificateList)) {
			strings.add("过期证书：" + String.join("，", overCertificateList));
		}
		if (CollectionUtils.isNotEmpty(inMonthCertificateList)) {
			strings.add("临期证书：" + String.join("，", inMonthCertificateList));
		}
		if (CollectionUtils.isNotEmpty(noCertificateList)) {
			strings.add("缺少证书：" + String.join("，", noCertificateList));
		}
		String join = "";
		if (CollectionUtils.isNotEmpty(strings)) {
			join = String.join("；", strings);
		}
		personBasic.setMissingCertificate(join);

		if (CollectionUtils.isEmpty(list) && isInMonth == 0 && isOver == 0) {
			personBasic.setQrcodeColor(QrcodeColorEnum.GREEN.getCode());
			personBasic.setQrcodeDesc("证书齐全");
			personBasic.setQrcodeDate(new Date());
		} else if ((CollectionUtils.isEmpty(list) && isOver == 1) || (CollectionUtils.isNotEmpty(list))) {
			personBasic.setQrcodeColor(QrcodeColorEnum.RED.getCode());
			personBasic.setQrcodeDesc("证书不全");
			personBasic.setQrcodeDate(new Date());
		} else if (CollectionUtils.isEmpty(list) && isOver == 0 && isInMonth == 1) {
			personBasic.setQrcodeColor(QrcodeColorEnum.YELLOW.getCode());
			personBasic.setQrcodeDesc("证书临期");
			personBasic.setQrcodeDate(new Date());
		}
		CompanyModel companyModel = new CompanyModel();
		// 单位
		companyModel = this.getCompanyModel(personAccount.getProjectId());
		personBasic.setProjectOrgCode(companyModel.getOrgCode());

		if (personUser.getNativePlace() != null) {
			personBasic.setNativePlace(JSON.toJSONString(personUser.getNativePlace()));
		}
		this.baseMapper.insert(personBasic);

		if ("证书不全".equals(personBasic.getQrcodeDesc()) || "证书临期".equals(personBasic.getQrcodeDesc())) {
			personBasic.setProjectOrgCode(companyModel.getOrgCode());
			personAccount.setProjectName(companyModel.getCompanyName());
			BizMessage bizMessage = new BizMessage();
			bizMessage.setIndexKey("RYFM");
			bizMessage.setIndexValue(personBasic.getPostName() + personBasic.getQrcodeDesc());
			RiskBizInfoVo riskBizInfoVo = fetchData(personBasic, personAccount, join);
			bizMessage.setBizInfo(riskBizInfoVo);
			bizMessage.setTraceId(String.valueOf(personBasic.getSequenceNbr()));
			try {
				emqKeeper.getMqttClient().publish(RYFM_DATA_MQTT_TOPIC,
						JSON.toJSONString(bizMessage).getBytes(StandardCharsets.UTF_8), 2, false);
			} catch (MqttException e) {
				e.printStackTrace();
			}
		}
		if (CollectionUtils.isNotEmpty(personCertificate.getCertificationInfo())) {
			personCertificate.getCertificationInfo().forEach(item -> {
				item.setPersonId(personBasic.getSequenceNbr());
				personCertificateService.save(item);
			});
		}
		// 人员技能学历信息
		PersonSkillEducation personSkillEducation = new PersonSkillEducation();
		BeanUtils.copyProperties(personUser, personSkillEducation);
		personSkillEducation.setPersonId(personBasic.getSequenceNbr());
		personSkillEducationService.save(personSkillEducation);

		// 人员账号信息
		personAccount.setPersonId(personBasic.getSequenceNbr());
		personAccount.setPassword(DesUtil.encode(personAccount.getPassword(), secretKey));
		personAccount.setSecondaryPassword(DesUtil.encode(personAccount.getSecondaryPassword(), secretKey));
		personAccountService.save(personAccount);
		// 新增平台账号
		// 组装数据
		AgencyUserModel usd = new AgencyUserModel();
		// 应用
		usd.setAppCodes(personAccount.getApplication());
		// 手机号
		usd.setMobile(personUser.getPhone());
		// 角色
		Map<Long, List<Long>> map = new HashMap<>();
		List<Long> cdids = personAccount.getRoles().stream().map(s -> Long.parseLong(s.trim()))
				.collect(Collectors.toList()); // 测点数组
		if (personAccount.getDepartmentId() != null) {

			map.put(personAccount.getDepartmentId(), cdids);
		} else {
			map.put(personAccount.getProjectId(), cdids);
		}
		usd.setOrgRoleSeqs(map);
		// 密码
		usd.setPassword(personAccount.getPassword());
		// 二次密码
		usd.setRePassword(personAccount.getSecondaryPassword());
		// 用户名
		usd.setRealName(personAccount.getName());
		// 账号
		usd.setUserName(personAccount.getAccountName());
		usd.setLockStatus("UNLOCK");
		// 新增平台用户
		AgencyUserModel agencyUserModel = this.setcreateUser(usd);
		// 设置userID
		usd.setUserId(agencyUserModel.getUserId());
		// 设置工号
		usd.setUserName(personAccount.getJobNumber());
		// 创建支持工号登录
		this.createLoginInfo(usd);
		// 查询部门
		DepartmentModel departmentModel = null;
		if (personAccount.getDepartmentId() != null) {
			departmentModel = this.getdepartmentModel(personAccount.getDepartmentId());
		}

		if (departmentModel != null) {
			// personBasic.setProjectOrgCode(departmentModel.getOrgCode());
			personAccount.setProjectDepartmentName(departmentModel.getDepartmentName());
		}
//            personBasic.setProjectOrgCode(companyModel.getOrgCode());
//
//
//        if (personUser.getNativePlace()!=null) {
//            personBasic.setNativePlace(JSON.toJSONString(personUser.getNativePlace()));
//        }
		personAccount.setPuserId(agencyUserModel.getUserId());
		personAccount.setProjectName(companyModel.getCompanyName());
//        this.personBasicMapper.updateById(personBasic);
		this.personAccountService.updateById(personAccount);
		// ----------------------------权限表中新增数据-----------------------------
		StdUserEmpower stdUserEmpower = new StdUserEmpower();
		stdUserEmpower.setPermissionType("YTH");
		stdUserEmpower.setRecDate(new Date());
		stdUserEmpower.setAmosOrgCode(Arrays.asList(personAccount.getYthPermission()));
		stdUserEmpower.setAmosUserId(personAccount.getPuserId());
		userEmpowerMapper.insert(stdUserEmpower);

		// ----------------------------户用管理端区域公司---------------------------

		StdUserEmpower stdUserEmpowerhygf = new StdUserEmpower();
		List<CompanyModel> co = userEmpowerMapper.getCompanyBoList("region", null, null);
		List<String> re = personAccount.getRegionalCompaniesSeq();

		String flag = personAccount.getRegionalCompaniesSeqFlag();
		if (flag != null && !flag.isEmpty()) {
			if (flag.equals("all")) {
				List<String> all = new ArrayList<>();
				all.add("all");
				stdUserEmpowerhygf.setAmosOrgCode(all);
			} else {
				stdUserEmpowerhygf.setAmosOrgCode(re);
			}
		}
		List<String> exre = personAccount.getExternalRegionalCompaniesSeq();
//        if(exre!=null&&!exre.isEmpty()){
//            List<String> pexre=new ArrayList<>();
//            List<CompanyModel> exreco = co.stream().filter(product -> !"area".equals(product.getLevel())).collect(Collectors.toList());
//            for (CompanyModel companyModel1 : exreco) {
//                 if(!exre.contains(companyModel1.getOrgCode())){
//                     pexre.add(companyModel1.getOrgCode());
//                 }
//            }
//            stdUserEmpowerhygf.setEliminateAmosOrgCode(pexre);
//        }
		stdUserEmpowerhygf.setEliminateAmosOrgCode(exre);
		stdUserEmpowerhygf.setPermissionType("HYGF");
		stdUserEmpowerhygf.setRecDate(new Date());
		stdUserEmpowerhygf.setAmosUserId(personAccount.getPuserId());
		userEmpowerMapper.insert(stdUserEmpowerhygf);

		// ----------------------------权限表中新增数据-----------------------------
		PersonAccountFed personAccountFed = new PersonAccountFed();
		BeanUtils.copyProperties(personAccount, personAccountFed);
		personAccountFed.setSyncState(0);
		personAccountFed.setSyncDate(new Date());
		personAccountFedMapper.insert(personAccountFed);

		Map<String, Object> data = new HashMap<>();
		data.put("SEQUENCE_NBR", agencyUserModel.getSequenceNbr());
		ProduceMsg produceMsg = new ProduceMsg(data, INSERT, agencyUserModel.getUserId());
		querueProduce.produceMsg(JSON.toJSONString(produceMsg));

	}

	@Transactional
	public PersonDto updatePerson(PersonDto model, HttpServletRequest httpServletRequest, Long sequenceNbr)
			throws ParseException {

		if (!redisUtils.hasKey(Constants.JXIOP_DICT_POST) || !redisUtils.hasKey(Constants.JXIOP_DICT_CERTIFICATES)) {
			addRedisPostAndCerInfo();
		}
		// 岗位所需证书信息
		Map<String, String> postNameMap = (Map<String, String>) redisUtils.get(Constants.JXIOP_DICT_POST);
		// 证书临期信息
		Map<String, String> certificatesMap = (Map<String, String>) redisUtils.get(Constants.JXIOP_DICT_CERTIFICATES);

		// 获取人员基本信息数据
		PersonUser personUser = model.getPersonUser();
		// 获取人员账号信息
		PersonAccount personAccount = model.getPersonAccount();
		PersonAccount oldpersonAccount = new PersonAccount();
		personUser.setPhone(personAccount.getPhoneNum());

		// 人员基础信息
		PersonBasic personBasic = personBasicMapper.selectById(sequenceNbr);
		personBasic.setSequenceNbr(sequenceNbr);
		personAccount.setPassword(DesUtil.encode(personAccount.getPassword(), secretKey));
		personAccount.setSecondaryPassword(DesUtil.encode(personAccount.getSecondaryPassword(), secretKey));

		// 人员归属信息
		PersonSkillEducation personSkillEducation = new PersonSkillEducation();
		BeanUtils.copyProperties(personUser, personSkillEducation);
		personSkillEducation.setPersonId(personBasic.getSequenceNbr());
		PersonSkillEducation personSkillEducationd = personSkillEducationService
				.getOne(new QueryWrapper<PersonSkillEducation>().eq("person_id", personBasic.getSequenceNbr()));
		personSkillEducation.setSequenceNbr(personSkillEducationd.getSequenceNbr());
		personSkillEducationService.updateById(personSkillEducation);

		// 获取人员资质信息
		CertificationInfo personCertificate = model.getPersonCertificate();

		LambdaUpdateWrapper<PersonCertificate> wrapper = new LambdaUpdateWrapper<>();
		wrapper.eq(PersonCertificate::getPersonId, personBasic.getSequenceNbr());
		personCertificateService.remove(wrapper);

		// 默认红码
//        personBasic.setQrcodeColor(QrcodeColorEnum.RED.getCode());
		// 该岗位应获得的证书
		List<String> list2 = new ArrayList<>();
		if (StringUtils.isNotEmpty(personUser.getPostName())) {
			String certificates = String.valueOf(postNameMap.get(personUser.getPostName()));
			if (!StringUtils.isEmpty(certificates)) {
				list2 = Arrays.asList(certificates.split(","));
			}
		}
		List<String> list = new ArrayList(list2);
		// 人员资质信息
		Integer isInMonth = 0;
		Integer isOver = 0;
		// 过期的证书
		List<String> overCertificateList = new ArrayList<>();
		// 临期证书
		List<String> inMonthCertificateList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(personCertificate.getCertificationInfo())) {
			for (PersonCertificate item : personCertificate.getCertificationInfo()) {
				if (StringUtils.isNotEmpty(item.getValidPeriod()) && !Objects.isNull(item.getCertificateTime())) {
					int validPeriod = StringUtils.isEmpty(item.getValidPeriod()) ? 3
							: Integer.parseInt(item.getValidPeriod());
					Date date = DateUtils.dateAddYears(item.getCertificateTime(), validPeriod);
					if (list.contains(item.getCertificateName()) && DateUtils.dateCompare(date, new Date()) == -1) {
						isOver = 1;
						overCertificateList.add(item.getCertificateName());
					}
					if (list.contains(item.getCertificateName())
							&& DateUtils.dateBetweenIncludeToday(new Date(), date) < Integer
									.valueOf(certificatesMap.get(item.getCertificateName()))
							&& DateUtils.dateCompare(date, new Date()) == 1) {
						isInMonth = 1;
						inMonthCertificateList.add(item.getCertificateName());
					}
					item.setPersonId(personBasic.getSequenceNbr());
					personCertificateService.save(item);
				}
				list.remove(item.getCertificateName());
			}
		}
		// 缺证
		List<String> noCertificateList = new ArrayList<>(list);

		List<String> strings = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(overCertificateList)) {
			strings.add("过期证书：" + String.join("，", overCertificateList));
		}
		if (CollectionUtils.isNotEmpty(inMonthCertificateList)) {
			strings.add("临期证书：" + String.join("，", inMonthCertificateList));
		}
		if (CollectionUtils.isNotEmpty(noCertificateList)) {
			strings.add("缺少证书：" + String.join("，", noCertificateList));
		}

		String join = "";
		if (CollectionUtils.isNotEmpty(strings)) {
			join = String.join("；", strings);
		}
		String missingCertificateOld = personBasic.getMissingCertificate();
		personBasic.setMissingCertificate(join);
		CompanyModel companyModel = new CompanyModel();
		// 单位
		companyModel = this.getCompanyModel(personAccount.getProjectId());

		String qrcodeColorOld = personBasic.getQrcodeColor();
		if (CollectionUtils.isEmpty(list) && isInMonth == 0 && isOver == 0) {
			personBasic.setQrcodeColor(QrcodeColorEnum.GREEN.getCode());
			personBasic.setQrcodeDesc("证书齐全");
			personBasic.setQrcodeDate(new Date());
		} else if ((CollectionUtils.isEmpty(list) && isOver == 1) || (CollectionUtils.isNotEmpty(list))) {
			personBasic.setQrcodeColor(QrcodeColorEnum.RED.getCode());
			personBasic.setQrcodeDesc("证书不全");
			personBasic.setQrcodeDate(new Date());
		} else if (CollectionUtils.isEmpty(list) && isOver == 0 && isInMonth == 1) {
			personBasic.setQrcodeColor(QrcodeColorEnum.YELLOW.getCode());
			personBasic.setQrcodeDesc("证书临期");
			personBasic.setQrcodeDate(new Date());
		}
		personBasic.setProjectOrgCode(companyModel.getOrgCode());
		personAccount.setProjectName(companyModel.getCompanyName());

		// 人员账号信息
		personAccount.setPersonId(sequenceNbr);
		oldpersonAccount = personAccountService.getById(personAccount.getSequenceNbr());
		personAccountService.updateById(personAccount);
		// 新增平台账号
		// 组装数据
		AgencyUserModel usd = new AgencyUserModel();
		// 应用
		usd.setAppCodes(personAccount.getApplication());
		// 手机号
		usd.setMobile(personUser.getPhone());
		// 角色
		Map<Long, List<Long>> map = new HashMap<>();
		List<Long> cdids = personAccount.getRoles().stream().map(s -> Long.parseLong(s.trim()))
				.collect(Collectors.toList()); // 测点数组
		if (personAccount.getDepartmentId() != null) {

			map.put(personAccount.getDepartmentId(), cdids);
		} else {
			map.put(personAccount.getProjectId(), cdids);
		}
		usd.setOrgRoleSeqs(map);
		// 密码
		usd.setPassword(personAccount.getPassword());
		// 二次密码
		usd.setRePassword(personAccount.getSecondaryPassword());
		// 用户名
		usd.setRealName(personAccount.getName());
		// 账号
		usd.setUserName(personAccount.getAccountName());
		usd.setLockStatus("UNLOCK");
		usd.setUserId(personAccount.getPuserId());
		usd.setOriginalPassword(oldpersonAccount.getPassword());
		// 新增平台用户
		AgencyUserModel agencyUserModel = this.updateuser(personAccount.getPuserId(), usd);
		log.info("更新平台账户信息：：" + JSONObject.toJSONString(usd));
		// 设置userID
		usd.setUserId(agencyUserModel.getUserId());
		// 设置工号
		usd.setUserName(personAccount.getJobNumber());
		// 创建支持工号登录
		this.updateLoginInfo(oldpersonAccount.getJobNumber(), usd);
		// 查询部门
		DepartmentModel departmentModel = null;
		if (personAccount.getDepartmentId() != null) {
			departmentModel = this.getdepartmentModel(personAccount.getDepartmentId());
		}
		BeanUtils.copyProperties(personUser, personBasic, "qrcodeDesc", "qrcodeColor");
		if (departmentModel != null) {
			// personBasic.setProjectOrgCode(departmentModel.getOrgCode());
			personAccount.setProjectDepartmentName(departmentModel.getDepartmentName());
		}
		personBasic.setProjectOrgCode(companyModel.getOrgCode());

		if (personUser.getNativePlace() != null) {
			personBasic.setNativePlace(JSON.toJSONString(personUser.getNativePlace()));
		}
		personAccount.setProjectName(companyModel.getCompanyName());

		if (!join.equals(missingCertificateOld)) {
			personBasic.setRecDate(new Date());
			this.personBasicMapper.updateById(personBasic);
			if (("证书不全".equals(personBasic.getQrcodeDesc()) || "证书临期".equals(personBasic.getQrcodeDesc()))) {
				BizMessage bizMessage = new BizMessage();
				bizMessage.setIndexKey("RYFM");
				bizMessage.setIndexValue(personBasic.getPostName() + personBasic.getQrcodeDesc());
				RiskBizInfoVo riskBizInfoVo = fetchData(personBasic, personAccount, join);
				bizMessage.setBizInfo(riskBizInfoVo);
				bizMessage.setDataSource("人员赋码");
				try {
					emqKeeper.getMqttClient().publish(PersonBasicServiceImpl.RYFM_DATA_MQTT_TOPIC,
							JSON.toJSONString(bizMessage).getBytes(StandardCharsets.UTF_8), 2, false);
				} catch (MqttException e) {
					e.printStackTrace();
				}
			} else if ("证书齐全".equals(personBasic.getQrcodeDesc())) {
				HashMap<String, String> personMap = new HashMap<>();
				personMap.put("objectId", String.valueOf(personBasic.getSequenceNbr()));
				personMap.put("qrCodeColor", qrcodeColorOld);
				personMap.put("warningObjectType", "RYFM");
				personMap.put("sourceAttribution", personBasic.getProjectOrgCode());
				personMap.put("sourceAttributionDesc", personAccount.getProjectName());
				personMap.put("warningSourceType", "人员赋码");
				try {
					emqKeeper.getMqttClient().publish(PersonBasicServiceImpl.RYFM_GREEN,
							JSON.toJSONString(personMap).getBytes(StandardCharsets.UTF_8), 2, false);
				} catch (MqttException e) {
					e.printStackTrace();
				}
			}
		} else {
			this.personBasicMapper.updateById(personBasic);
		}
		StdUserEmpower stdUserEmpower = userEmpowerMapper.selectOne(new QueryWrapper<StdUserEmpower>()
				.eq("amos_user_id", personAccount.getPuserId()).eq("permission_type", "YTH"));
		if (ObjectUtils.isEmpty(stdUserEmpower)) {
			stdUserEmpower = new StdUserEmpower();
			stdUserEmpower.setRecDate(new Date());
			stdUserEmpower.setPermissionType("YTH");
			stdUserEmpower.setAmosOrgCode(Arrays.asList(personAccount.getYthPermission()));
			stdUserEmpower.setAmosUserId(personAccount.getPuserId());
			userEmpowerMapper.insert(stdUserEmpower);
		} else {
			stdUserEmpower.setAmosOrgCode(Arrays.asList(personAccount.getYthPermission()));
			stdUserEmpower.setRecDate(new Date());
			userEmpowerMapper.updateById(stdUserEmpower);
		}
		// 户用角色权限

		StdUserEmpower stdUserEmpowerhygf = userEmpowerMapper.selectOne(new QueryWrapper<StdUserEmpower>()
				.eq("amos_user_id", personAccount.getPuserId()).eq("permission_type", "HYGF"));
		if (ObjectUtils.isEmpty(stdUserEmpowerhygf)) {
			stdUserEmpowerhygf = new StdUserEmpower();
			List<CompanyModel> co = userEmpowerMapper.getCompanyBoList("region", null, null);
			List<String> re = personAccount.getRegionalCompaniesSeq();
			String flag = personAccount.getRegionalCompaniesSeqFlag();
			if (flag != null && !flag.isEmpty()) {
				if (flag.equals("all")) {
					List<String> all = new ArrayList<>();
					all.add("all");
					stdUserEmpowerhygf.setAmosOrgCode(all);
				} else {
					stdUserEmpowerhygf.setAmosOrgCode(re);
				}
			}
			List<String> exre = personAccount.getExternalRegionalCompaniesSeq();
//            if(exre!=null&&!exre.isEmpty()){
//                List<String> pexre=new ArrayList<>();
//                List<CompanyModel> exreco = co.stream().filter(product -> !"area".equals(product.getLevel())).collect(Collectors.toList());
//                for (CompanyModel companyModel1 : exreco) {
//                    if(!exre.contains(companyModel1.getOrgCode())){
//                        pexre.add(companyModel1.getOrgCode());
//                    }
//                }
//                stdUserEmpowerhygf.setEliminateAmosOrgCode(pexre);
//            }
			stdUserEmpowerhygf.setEliminateAmosOrgCode(exre);
			stdUserEmpowerhygf.setPermissionType("HYGF");
			stdUserEmpowerhygf.setRecDate(new Date());
			stdUserEmpowerhygf.setAmosUserId(personAccount.getPuserId());
			userEmpowerMapper.insert(stdUserEmpowerhygf);
		} else {
//            List<CompanyModel>  co=   userEmpowerMapper.getCompanyBoList("region",null,null);
			List<String> re = personAccount.getRegionalCompaniesSeq();
			String flag = personAccount.getRegionalCompaniesSeqFlag();
			if (flag != null && !flag.isEmpty()) {
				if (flag.equals("all")) {
					List<String> all = new ArrayList<>();
					all.add("all");
					stdUserEmpowerhygf.setAmosOrgCode(all);
				} else {
					stdUserEmpowerhygf.setAmosOrgCode(re);
				}
			} else {
				stdUserEmpowerhygf.setAmosOrgCode(re);
			}
			List<String> exre = personAccount.getExternalRegionalCompaniesSeq();
//            if(exre!=null&&!exre.isEmpty()){
//                List<String> pexre=new ArrayList<>();
//                List<CompanyModel> exreco = co.stream().filter(product -> !"area".equals(product.getLevel())).collect(Collectors.toList());
//                for (CompanyModel companyModel1 : exreco) {
//                    if(!exre.contains(companyModel1.getOrgCode())){
//                        pexre.add(companyModel1.getOrgCode());
//                    }
//                }
//                stdUserEmpowerhygf.setEliminateAmosOrgCode(pexre);
//            }
			stdUserEmpowerhygf.setEliminateAmosOrgCode(exre);
			stdUserEmpowerhygf.setPermissionType("HYGF");
			stdUserEmpowerhygf.setRecDate(new Date());
			stdUserEmpowerhygf.setAmosUserId(personAccount.getPuserId());
			userEmpowerMapper.updateById(stdUserEmpowerhygf);
		}
		personAccountService.updateById(personAccount);

		PersonAccountFed personAccountFed = new PersonAccountFed();
		BeanUtils.copyProperties(personAccount, personAccountFed);
		personAccountFed.setSyncState(1);
		personAccountFed.setSyncDate(new Date());
		personAccountFedMapper.updateById(personAccountFed);

		Map<String, Object> data = new HashMap<>();
		data.put("SEQUENCE_NBR", agencyUserModel.getSequenceNbr());
		ProduceMsg produceMsg = new ProduceMsg(data, UPDATE, agencyUserModel.getUserId());
		querueProduce.produceMsg(JSON.toJSONString(produceMsg));
		return model;
	}

	@Transactional
	public PersonDto getPerson(Long sequenceNbr, String type) {
		PersonDto personDto = new PersonDto();
		PersonUser personUser = new PersonUser();
		QueryWrapper<PersonBasic> wrapper1 = new QueryWrapper();
		wrapper1.eq("sequence_nbr", sequenceNbr);
		wrapper1.eq("is_delete", 0);

		// 人员基础信息
		PersonBasic personBasic = this.getOne(wrapper1);
		BeanUtils.copyProperties(personBasic, personUser);
		// 人员技能学历信息
		QueryWrapper<PersonSkillEducation> wrapper2 = new QueryWrapper();
		wrapper2.eq("person_id", sequenceNbr);
		PersonSkillEducation personSkillEducation = personSkillEducationService.getOne(wrapper2);
		BeanUtils.copyProperties(personSkillEducation, personUser);

		// 人员资质信息
		LambdaQueryWrapper<PersonCertificate> personCertificateLambdaQueryWrapper = new LambdaQueryWrapper<>();
		personCertificateLambdaQueryWrapper.eq(PersonCertificate::getPersonId, sequenceNbr);
		List<PersonCertificate> list = personCertificateService.list(personCertificateLambdaQueryWrapper);
		CertificationInfo certificationInfo = new CertificationInfo();
		certificationInfo.setCertificationInfo(list);

		QueryWrapper<PersonAccount> wrapper4 = new QueryWrapper();
		wrapper4.eq("person_id", sequenceNbr);
		// 人员账号信息
		PersonAccount personAccount = personAccountService.getOne(wrapper4);
		personAccount.setPhoneNum(personBasic.getPhone());
		// 对于密码进行解密
		if ("look".equals(type)) {
			personAccount.setIdNumber(DesensitizedUtil.idCardNum(personAccount.getIdNumber(), 0, 4));
		} else {
			personAccount.setPassword(DesUtil.decode(personAccount.getPassword(), secretKey));
			personAccount.setSecondaryPassword(DesUtil.decode(personAccount.getSecondaryPassword(), secretKey));
		}
		if (personBasic.getNativePlace() != null) {
			personUser.setNativePlace(JSON.parseArray(personBasic.getNativePlace(), Integer.class));
		}
		StdUserEmpower stdUserEmpower = userEmpowerMapper.selectOne(new QueryWrapper<StdUserEmpower>()
				.eq("amos_user_id", personAccount.getPuserId()).eq("permission_type", "YTH"));
		if (!ObjectUtils.isEmpty(stdUserEmpower)) {
			personAccount.setYthPermission(stdUserEmpower.getAmosOrgCode().get(0));
		}

		StdUserEmpower stdUserEmpowerhygf = userEmpowerMapper.selectOne(new QueryWrapper<StdUserEmpower>()
				.eq("amos_user_id", personAccount.getPuserId()).eq("permission_type", "HYGF"));
		if (!ObjectUtils.isEmpty(stdUserEmpowerhygf)) {

			if (stdUserEmpowerhygf.getAmosOrgCode() == null || stdUserEmpowerhygf.getAmosOrgCode().size() == 0) {
//                List<String> list2 = new ArrayList<>();
//                list2.add("all");
				personAccount.setRegionalCompaniesSeq(null);

			} else if (stdUserEmpowerhygf.getAmosOrgCode().size() == 1
					&& stdUserEmpowerhygf.getAmosOrgCode().get(0).equals("all")) {

				personAccount.setRegionalCompaniesSeqFlag("all");
				personAccount.setRegionalCompaniesSeq(null);

			} else {

				personAccount.setRegionalCompaniesSeqFlag("no");
				personAccount.setRegionalCompaniesSeq(stdUserEmpowerhygf.getAmosOrgCode());

			}
			personAccount.setExternalRegionalCompaniesSeq(stdUserEmpowerhygf.getEliminateAmosOrgCode());

		}
		personDto.setPersonUser(personUser);
		personDto.setPersonCertificate(certificationInfo);
		personDto.setPersonAccount(personAccount);
		return personDto;
	}

	@Transactional
	public int deletePerson(String[] ids) {

		// 查询所有平台用户
		QueryWrapper<PersonAccount> wrapper = new QueryWrapper();
		wrapper.in("person_id", ids);
		List<PersonAccount> list = personAccountService.list(wrapper);
		List<String> userid = new ArrayList<>();
//        List<String> loginId = new ArrayList<>();
		for (PersonAccount personAccount : list) {
			userid.add(personAccount.getPuserId());
//            loginId.add(personAccount.getJobNumber());
		}
		// 删除平台
		int deleteResult = personBasicMapper.deleteList(ids);
		this.deleuser(String.join(",", userid));
////        this.deleteLoginInfo(String.join(",", loginId));
//        this.deleteLoginInfo(loginId.get(1));
		QueryWrapper<PersonAccountFed> wrapper1 = new QueryWrapper();
		wrapper1.in("person_id", ids);
		personAccountFedMapper.delete(wrapper1);
		userEmpowerMapper
				.delete(new QueryWrapper<StdUserEmpower>().in("amos_user_id", userid).eq("permission_type", "YTH"));
		return deleteResult;
	}

	// 新增平台用户
	private AgencyUserModel setcreateUser(AgencyUserModel userDto) {
		FeignClientResult<AgencyUserModel> amosUser = Privilege.agencyUserClient.create(userDto);

		AgencyUserModel user = new AgencyUserModel();

		if (!ObjectUtils.isEmpty(amosUser)) {
			if (amosUser.getStatus() == 200) {
				user = amosUser.getResult();
			} else {
				throw new RuntimeException(amosUser.getMessage());
			}
		}
		return user;
	}

	private LoginInfoModel createLoginInfo(AgencyUserModel userDto) {
		FeignClientResult<LoginInfoModel> amosLoginfo = null;
		try {
			amosLoginfo = Privilege.agencyUserClient.createLoginInfo(userDto);
		} catch (Exception e) {
			FeignClientResult<List<String>> cResult = Privilege.agencyUserClient.multDeleteUser(userDto.getUserId(),
					true);
			throw new RuntimeException(e);
		}
		return amosLoginfo.getResult();
	}

	// 修改平台用户
	private AgencyUserModel updateuser(String userId, AgencyUserModel userDto) {
		FeignClientResult<AgencyUserModel> amosUser = null;
		FeignClientResult<AgencyUserModel> amosUser1 = null;
		try {
			amosUser = Privilege.agencyUserClient.update(userDto, userId);
			amosUser1 = Privilege.agencyUserClient.modifyPassword(userId, userDto);
		} catch (Exception e) {
			e.printStackTrace();
		}

		AgencyUserModel user = new AgencyUserModel();
		if (!ObjectUtils.isEmpty(amosUser)) {
			if (amosUser.getStatus() == 200) {
				user = amosUser.getResult();
			} else {
				throw new RuntimeException(amosUser.getMessage());
			}
		}
		if (!ObjectUtils.isEmpty(amosUser1)) {
			if (amosUser1.getStatus() == 200) {
				user = amosUser1.getResult();
			} else {
				throw new RuntimeException(amosUser1.getMessage());
			}
		}
		return user;
	}

	private LoginInfoModel updateLoginInfo(String loginId, AgencyUserModel userDto) {
		FeignClientResult<LoginInfoModel> amosLoginfo = null;
		try {
			amosLoginfo = Privilege.agencyUserClient.updateLoginInfo(userDto, loginId);
			// amosLoginfo = agencyuserFeign.updateLoginInfo(userDto, loginId);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return amosLoginfo.getResult();
	}

	private DepartmentModel getdepartmentModel(Long departmentId) {
		FeignClientResult<DepartmentModel> de = Privilege.departmentClient.seleteOne(departmentId);

		DepartmentModel departmentModel = new DepartmentModel();

		if (!ObjectUtils.isEmpty(de)) {
			if (de.getStatus() == 200) {
				departmentModel = de.getResult();
			} else {
				throw new RuntimeException(de.getMessage());
			}
		}
		return departmentModel;
	}

	public CompanyModel getCompanyModel(Long projectId) {
		FeignClientResult<CompanyModel> cResult = Privilege.companyClient.seleteOne(projectId);
		CompanyModel companyModel = new CompanyModel();

		if (!ObjectUtils.isEmpty(cResult)) {
			if (cResult.getStatus() == 200) {
				companyModel = cResult.getResult();
			} else {
				throw new RuntimeException(cResult.getMessage());
			}
		}
		return companyModel;
	}

	private void deleuser(String userid) {
		FeignClientResult<List<String>> cResult = Privilege.agencyUserClient.multDeleteUser(userid, true);

		if (!ObjectUtils.isEmpty(cResult)) {
			if (cResult.getStatus() != 200) {
				throw new RuntimeException(cResult.getMessage());
			}
		}
	}

	private String deleteLoginInfo(String loginId) {
		FeignClientResult<String> amosLoginfo = null;
		try {
			amosLoginfo = Privilege.agencyUserClient.deleteLoginInfo(loginId);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return amosLoginfo.getResult();
	}

	/**
	 * 分页查询
	 */
	public Page<UserMapperDto> queryPage(Page<UserMapperDto> page, String name, String accountName, String projectName,
			String orgCode) {

		List<UserMapperDto> list = personBasicMapper.queryPage((page.getCurrent() - 1) * page.getSize(), page.getSize(),
				name, accountName, projectName, orgCode);
		List<UserMapperDto> listcount = personBasicMapper.queryPagecount(name, accountName, projectName, orgCode);
		page.setTotal(listcount.size());
		page.setRecords(list);
		return page;
	}

	public List<Map<String, Object>> getPersonYardStatistics(String parentCode) {
		List<Map<String, Object>> resultList = personBasicMapper.getPersonYardStatistics(parentCode);
		resultList.forEach(item -> {
			String name = QrcodeColorEnum.getName(String.valueOf(item.get("qrCodeColor")));
			item.put("name", name);
			item.put("value", Integer.parseInt(item.get("value").toString()));
		});
		return resultList;
	}

//    public Page<Map<String, Object>> getPersonYardByPage(String parentCode,
//                                                         Integer current,
//                                                         Integer size,
//                                                         String date,
//                                                         String qrCodeColor) {
//        List<Map<String, Object>> resultList = personBasicMapper.getPersonYardByPage((current - 1) * size, size , parentCode, date, qrCodeColor);
//        Integer count = personBasicMapper.getPersonYardByPageCount(parentCode, date, qrCodeColor);
//
//        resultList.forEach(item -> {
//            String name = QrcodeColorEnum.getName(String.valueOf(item.get("qrCodeColor")));
//            item.put("name", name);
//        });
//        Page<Map<String, Object>> mapPage = new Page<>();
//        mapPage.setRecords(resultList);
//        mapPage.setCurrent(current);
//        mapPage.setSize(size);
//        mapPage.setTotal(count);
//        return mapPage;
//    }
}