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


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yeejoin.amos.boot.biz.common.bo.CompanyBo;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.module.common.api.constant.TZSCommonConstant;
import com.yeejoin.amos.boot.module.common.api.dao.ESEquipmentCategory;
import com.yeejoin.amos.boot.module.common.api.dao.EsBaseEnterpriseInfoDao;
import com.yeejoin.amos.boot.module.common.api.dao.EsEquipmentDao;
import com.yeejoin.amos.boot.module.common.api.dto.ESEquipmentCategoryDto;
import com.yeejoin.amos.boot.module.common.api.dto.UserPermissionDto;
import com.yeejoin.amos.boot.module.common.api.entity.ESEquipmentInfo;
import com.yeejoin.amos.boot.module.common.api.entity.EsBaseEnterpriseInfo;
import com.yeejoin.amos.boot.module.common.api.enums.UnitDataSourceEnum;
import com.yeejoin.amos.boot.module.common.biz.event.CommonPublisher;
import com.yeejoin.amos.boot.module.common.biz.refresh.DataRefreshEvent;
import com.yeejoin.amos.boot.module.tcm.api.dto.*;
import com.yeejoin.amos.boot.module.tcm.api.entity.*;
import com.yeejoin.amos.boot.module.tcm.api.enums.*;
import com.yeejoin.amos.boot.module.tcm.api.mapper.TzBaseEnterpriseInfoMapper;
import com.yeejoin.amos.boot.module.tcm.api.mapper.TzsUserInfoMapper;
import com.yeejoin.amos.boot.module.tcm.api.service.ITzBaseEnterpriseInfoService;
import com.yeejoin.amos.boot.module.tcm.api.vo.SortVo;
import com.yeejoin.amos.boot.module.tcm.biz.utils.RedisUtil;
import com.yeejoin.amos.boot.module.tcm.flc.api.dto.RegUnitIcDto;
import com.yeejoin.amos.boot.module.tcm.flc.api.dto.RegUnitInfoDto;
import com.yeejoin.amos.boot.module.tcm.flc.api.entity.RegUnitIc;
import com.yeejoin.amos.boot.module.tcm.flc.api.entity.RegUnitInfo;
import com.yeejoin.amos.boot.module.tcm.flc.api.feign.AccessFeignService;
import com.yeejoin.amos.boot.module.tcm.flc.api.mapper.RegUnitInfoMapper;
import com.yeejoin.amos.boot.module.tcm.flc.biz.service.impl.RegUnitIcServiceImpl;
import com.yeejoin.amos.boot.module.tcm.flc.biz.service.impl.RegUnitInfoServiceImpl;
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.RoleModel;
import com.yeejoin.amos.feign.privilege.util.DesUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.exception.instance.TooManyRequests;

import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 企业数据信息 服务实现类
 *
 * @author duanwei
 * @date 2022-08-10
 */
@Slf4j
@Service
public class TzBaseEnterpriseInfoServiceImpl
		extends BaseService<TzBaseEnterpriseInfoDto, TzBaseEnterpriseInfo, TzBaseEnterpriseInfoMapper>
		implements ITzBaseEnterpriseInfoService {

    public static final String HZXM = "HZXM";
	public static final String INSPECTION_AND_TESTING_INSTITUTIONS = "检验检测机构";
	public static final String INSPECTION_AGENCY = "检验机构";
	public static final String TESTING_INSTITUTIONS = "检测机构";
	/**
     * 企业管理员变更缓存key前缀
     */
    private final static String adminChange = "ADMIN_CHANGE_";

	@Value("${enterprise.regulatoryLabels.default.value:三级管控}")
	private String defaultRegulatoryLabels;

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    BaseUnitLicenceServiceImpl baseUnitLicenceService;

    @Autowired
    RegUnitIcServiceImpl regUnitIcService;

    @Autowired
	@Lazy
    RegUnitInfoServiceImpl regUnitInfoService;
    @Autowired
    DataDictionaryServiceImpl iDataDictionaryService;
    @Autowired
    RegUnitInfoMapper regUnitInfoMapper;
    @Autowired
    TzsBaseInstitutionServiceImpl tzsBaseInstitutionService;
    @Autowired
    private TzBaseEnterpriseInfoMapper tzBaseEnterpriseInfoMapper;
    @Autowired
    private StartPlatformTokenService platformTokenService;
    @Autowired
    private SpeUseUnitServiceImpl speUseUnitService;
    @Autowired
    private AccessFeignService accessFeignService;
    @Autowired
    private TzsUserInfoMapper tzsUserInfoMapper;
    @Autowired
    private EquipmentCategoryServiceImpl equipmentCategoryService;
	@Autowired
	private TzsUserInfoServiceImpl userInfoService;
	@Autowired
	private RedissonClient redissonClient;

	@Autowired
	private EmqKeeper emqKeeper;

	@Autowired
	private ESEquipmentCategory esEquipmentCategory;

	@Autowired
	private EsEquipmentDao esEquipmentDao;

	@Autowired
	private EsBaseEnterpriseInfoDao esBaseEnterpriseInfoDao;

    private static final Map<String ,String> JYJC_CERT_MAP = new HashMap<>();

	@Autowired
	@Qualifier("tcmTaskExecutor")
	private ThreadPoolTaskExecutor threadPoolTaskExecutor;

	@Autowired
	private CommonPublisher publisher;

	/**
	 * 公司类型下的资质类型map:key为登录人的公司类型、value为包含的资质枚举
	 */
	private static final Map<String ,String> COMPANY_TYPE_CERT_TYPE_MAP = new HashMap<>();
	/*
	  数据来源cb_data_dictionary type='UNIT_TYPE_NEW'，目前登录身份分为3个如下
	 */
	static {
		// 使用单位资质
		COMPANY_TYPE_CERT_TYPE_MAP.put("使用单位", "1232");
		// 检验检测机构资质：细分为1233-1、1233-2
		COMPANY_TYPE_CERT_TYPE_MAP.put("检验机构", "1233-1,1233-2");
		COMPANY_TYPE_CERT_TYPE_MAP.put("检测机构", "1233-2");
		// 安装改造维修单位身份资质：充装单位-1231 制造单位-1236 设计单位-1235 安装改造维修单位-1234
		COMPANY_TYPE_CERT_TYPE_MAP.put("安装改造维修单位", "1234");
		// 充装单位
		COMPANY_TYPE_CERT_TYPE_MAP.put("充装单位", "1231");
		// 制造单位
		COMPANY_TYPE_CERT_TYPE_MAP.put("制造单位", "1236");
		// 设计单位
		COMPANY_TYPE_CERT_TYPE_MAP.put("设计单位", "1235");
	}

	/**
	 * 机构类别字典类型
	 */
	private static final String JYJC_TYPE_DICT_CODE = "JYJC_TYPE";

	static {
		JYJC_CERT_MAP.put("1233-1","检验机构");
		JYJC_CERT_MAP.put("1233-2","检测机构");
	}
	/**
	 * 用户选择信心redis获取
	 **/
	protected ReginParams getSelectedOrgInfo() {
		return JSONObject.parseObject(redisUtil.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
	}

	@Override
	public List<EquEnterDto> getInfo(String sequenceNbr) {
		return tzBaseEnterpriseInfoMapper.getInfo(sequenceNbr);
	}

	@Override
	public IPage<TzBaseEnterpriseInfoDto> page(PageParam pageParam, TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto, String sort) {
		try {
//			List<String> orgCodeList = new ArrayList<>();
			if (tzBaseEnterpriseInfoDto.getSuperviseKey() != null) {
				FeignClientResult<CompanyModel> result = Privilege.companyClient
						.seleteOne(Long.valueOf(tzBaseEnterpriseInfoDto.getSuperviseKey()));
				if (result.getResult() != null) {
					tzBaseEnterpriseInfoDto.setSuperviseOrgCode(result.getResult().getOrgCode());
					tzBaseEnterpriseInfoDto.setOfficeRegionStr(result.getResult().getCompanyCode());
				}
			}
			Page<TzBaseEnterpriseInfoDto> page = new Page<>(pageParam.getCurrent(), pageParam.getSize());
			List<JSONObject> companyType1 = equipmentCategoryService.getCompanyType();
			String orgCode = null;
			String officeRegion = null;
			if (!ValidationUtil.isEmpty(companyType1)) {
				JSONObject companyTypeJson = companyType1.get(0);
				orgCode = companyTypeJson.getString("orgCode");
				officeRegion = companyTypeJson.getString("companyCode");
			}
//			if (!ValidationUtil.isEmpty(companyType1)) {
//				for (JSONObject jsonObject : companyType1) {
//					String orgCode = jsonObject.getString("orgCode");
//					if (!ValidationUtil.isEmpty(orgCode)) {
//						orgCodeList.add(orgCode);
//					}
//				}
//			}
			SortVo sortMap = userInfoService.sortFieldConversion(sort);
			// 密评专用（查tz_flc_reg_unit_info表中的admin_login_pwd字段，以用于验证密评数据完整性）

			List<RegUnitInfo> regUnitInfoList = regUnitInfoService.lambdaQuery().select(RegUnitInfo::getUnitCode, RegUnitInfo::getAdminLoginPwd)
					.eq(RegUnitInfo::getName, tzBaseEnterpriseInfoDto.getUseUnit()).list();
			regUnitInfoList.forEach(info -> System.out.println("unitCode=" + info.getUnitCode() + ", adminLoginPwd=" + info.getAdminLoginPwd()));
			IPage<TzBaseEnterpriseInfoDto> page2 = this.baseMapper.pageList(page, tzBaseEnterpriseInfoDto, orgCode, sortMap, officeRegion);
			page2.getRecords().forEach(info -> {
				info.setEnableStatus(info.getIsDelete() ? "停用" : "启用");
				if (ValidationUtil.isEmpty(info.getRegulatoryLabels()) && (info.getUnitType().contains(UnitTypeEnum.sydw.getName()) || info.getUnitType().equals(UnitTypeEnum.grzt.getName()))) {
					info.setRegulatoryLabels(defaultRegulatoryLabels);
				}
			});
			return page2;
		} catch (Exception ex) {
			String msg = ex.getMessage() == null ? "" : ex.getMessage();
			if (msg.contains("eyibc decrypt error")
					|| msg.contains("EYIBCException")
					|| msg.contains("olym jdbc error")
					|| msg.contains("100022:")
					|| msg.contains("数据非法")
					|| msg.contains("decrypt error, code: -65")) {
				throw new BadRequest("数据完整性被破坏（解密失败），请联系管理员。");
			}
			ex.printStackTrace();
			throw new BadRequest("系统内部错误，请联系管理员。");
		}
	}

	@Override
	public TzBaseEnterpriseInfoDto detail(Long id) {
		TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto = new TzBaseEnterpriseInfoDto();
		TzBaseEnterpriseInfo tzBaseEnterpriseInfo = this.getById(id);
		if (tzBaseEnterpriseInfo != null) {
			BeanUtils.copyProperties(tzBaseEnterpriseInfo, tzBaseEnterpriseInfoDto);
			tzBaseEnterpriseInfoDto.setSafetyTwoPhoto(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getSafetyTwoPhoto()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getSafetyTwoPhoto()));
			tzBaseEnterpriseInfoDto.setSafetyOnePhoto(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getSafetyOnePhoto()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getSafetyOnePhoto()));
			tzBaseEnterpriseInfoDto.setUnitBusinessLicense(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getUnitBusinessLicense()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getUnitBusinessLicense()));
			tzBaseEnterpriseInfoDto.setOtherAccessories(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getOtherAccessories()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getOtherAccessories()));
			tzBaseEnterpriseInfoDto.setUnitExequatur(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getUnitExequatur()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getUnitExequatur()));
			tzBaseEnterpriseInfoDto.setEquipCategory(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getEquipCategory()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getEquipCategory()));
		}

		ReginParams selectedOrgInfo = getSelectedOrgInfo();
		String companyType = selectedOrgInfo.getCompany().getCompanyType();
		String companyLevel = selectedOrgInfo.getCompany().getLevel();

		// 修改当前登录人选择的单位类型
		tzBaseEnterpriseInfoDto.setUnitType(companyType);

		// 当前用户选择角色的许可信息（使用。。安改维。。检验检测。。）
        assert tzBaseEnterpriseInfo != null;
		List<BaseUnitLicence> unitLicences = baseUnitLicenceService.list(new LambdaQueryWrapper<BaseUnitLicence>()
				.eq(BaseUnitLicence::getUnitCode, tzBaseEnterpriseInfo.getUseCode())
				.eq(BaseUnitLicence::getIsDelete, false));
		List<BaseUnitLicenceDto> unitLicenceDtos = new ArrayList<>();
		List<BaseUnitLicence> unitLicencesCollect = Optional.ofNullable(unitLicences).orElse(Collections.emptyList());
		if (BaseController.COMPANY_TYPE_COMPANY.equals(companyLevel)) {
			List<String> certTypeList = Arrays.asList(Optional.ofNullable(COMPANY_TYPE_CERT_TYPE_MAP.get(companyType))
					.orElse("")
					.split(","));
			// 充装、检验检测、制造、设计、安改维
			unitLicencesCollect = unitLicencesCollect.stream()
					.filter(unit -> unit.getCertTypeCode() != null && (certTypeList.contains(unit.getCertTypeCode())))
					.collect(Collectors.toList());
		}
		if (!ValidationUtil.isEmpty(unitLicencesCollect)) {
			for (BaseUnitLicence baseUnitLicence : unitLicencesCollect) {
				BaseUnitLicenceDto baseUnitLicenceDto = new BaseUnitLicenceDto();
				BeanUtils.copyProperties(baseUnitLicence, baseUnitLicenceDto);
				if (!ObjectUtils.isEmpty(baseUnitLicence.getQualificationCertificateAttachment())) {
					baseUnitLicenceDto.setQualificationCertificateAttachment(JSONObject.parseArray(baseUnitLicence.getQualificationCertificateAttachment()));
				}
				unitLicenceDtos.add(baseUnitLicenceDto);
			}
		}
		tzBaseEnterpriseInfoDto.setUnitLicences(unitLicenceDtos);
		// 管理员信息
		RegUnitInfo regUnitInfo = regUnitInfoService.getOne(
				new LambdaQueryWrapper<RegUnitInfo>().eq(RegUnitInfo::getUnitCode, tzBaseEnterpriseInfo.getUseCode()));
		RegUnitInfoDto regUnitInfoDto = new RegUnitInfoDto();
		if (regUnitInfo != null) {
			BeanUtils.copyProperties(regUnitInfo, regUnitInfoDto);
		}
		regUnitInfoDto.setAdminIdCardPhoto((ValidationUtil.isEmpty(regUnitInfo)||ValidationUtil.isEmpty(regUnitInfo.getAdminIdCardPhoto())) ? new ArrayList() : JSON.parseArray(regUnitInfo.getAdminIdCardPhoto()));
		tzBaseEnterpriseInfoDto.setRegUnitInfoDto(regUnitInfoDto);

		// 工商信息
		RegUnitIc regUnitIc = regUnitIcService.getOne(
				new LambdaQueryWrapper<RegUnitIc>().eq(RegUnitIc::getUnitCode, tzBaseEnterpriseInfo.getUseCode()));
		RegUnitIcDto regUnitIcDto = new RegUnitIcDto();
		if (regUnitIc != null) {
			BeanUtils.copyProperties(regUnitIc, regUnitIcDto);
		}
		tzBaseEnterpriseInfoDto.setRegUnitIcDto(regUnitIcDto);
		return tzBaseEnterpriseInfoDto;
	}

	@Override
	public Map<String, Object> getInfoByUseCodeMap(String useCode) {
		TzBaseEnterpriseInfoDto infoByUseCode = getInfoByUseCode(useCode);
		// 通过sourceId获取问题信息
		Map<String,Object> problemInfo = baseMapper.getProblemInfoBySourceId(infoByUseCode.getSequenceNbr().toString());
		ObjectMapper objectMapper = new ObjectMapper();
		Map<String,Object> resultMap = new HashMap<>();

		RegUnitIcDto regUnitIcDto = infoByUseCode.getRegUnitIcDto();
		RegUnitInfoDto regUnitInfoDto = infoByUseCode.getRegUnitInfoDto();
		TzsBaseInstitution tzsBaseInstitution = infoByUseCode.getRegUnitMessage();
		Map<String,Object> regUnitIcDtoMap = new HashMap<>();
		Map<String,Object> regUnitInfoDtoMap = new HashMap<>();
		Map<String,Object> tzsBaseInstitutionMap = new HashMap<>();
		try {
			resultMap = objectMapper.convertValue(infoByUseCode, Map.class);
			regUnitIcDtoMap = objectMapper.convertValue(regUnitIcDto, Map.class);
			regUnitInfoDtoMap = objectMapper.convertValue(regUnitInfoDto, Map.class);
			tzsBaseInstitutionMap = objectMapper.convertValue(tzsBaseInstitution, Map.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(!ObjectUtils.isEmpty(regUnitIcDtoMap)){
			resultMap.putAll(regUnitIcDtoMap);
		}
		if(!ObjectUtils.isEmpty(regUnitInfoDtoMap)){
			regUnitInfoDtoMap.remove("unitLicences");
			resultMap.putAll(regUnitInfoDtoMap);
		}
		if(!ObjectUtils.isEmpty(tzsBaseInstitutionMap)){
			resultMap.putAll(tzsBaseInstitutionMap);
		}
		resultMap.remove("regUnitIcDto");
		resultMap.remove("regUnitInfoDto");
		resultMap.remove("tzsBaseInstitution");

		resultMap.put("unitAddress", resultMap.get("province") + "/" + resultMap.get("city") + "/" + resultMap.get("district"));

		Map<String,Object> longitudeLatitudeMap = new HashMap<>();
		longitudeLatitudeMap.put("address", resultMap.get("address"));
		longitudeLatitudeMap.put("latitude", resultMap.get("latitude"));
		longitudeLatitudeMap.put("longitude", resultMap.get("longitude"));
		resultMap.put("longitudeLatitude", longitudeLatitudeMap);

		resultMap.put("problemTime", ObjectUtils.isEmpty(problemInfo) ? null : problemInfo.get("problem_time"));
		resultMap.put("problemStatus", (ObjectUtils.isEmpty(resultMap.get("status")) || "null".equals(resultMap.get("status"))) ? ProblemStatusEnum.NORMAL.getName() : ProblemStatusEnum.getName.get(resultMap.get("status")));
		return resultMap;
	}


	@Override
	public TzBaseEnterpriseInfoDto getInfoByUseCode(String useCode) {
		TzBaseEnterpriseInfo tzBaseEnterpriseInfo = tzBaseEnterpriseInfoMapper.selectOne(new QueryWrapper<TzBaseEnterpriseInfo>().eq("use_code", useCode));
		TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto = getDetail(tzBaseEnterpriseInfo);
		if (!ObjectUtils.isEmpty(tzBaseEnterpriseInfo)){
			LambdaQueryWrapper<TzsBaseInstitution> lambda = new QueryWrapper<TzsBaseInstitution>().lambda();
			lambda.eq(TzsBaseInstitution::getEnterpriseId, tzBaseEnterpriseInfo.getSequenceNbr());
			TzsBaseInstitution tzsBaseInstitution = tzsBaseInstitutionService.getBaseMapper().selectOne(lambda);
			tzBaseEnterpriseInfoDto.setRegUnitMessage(tzsBaseInstitution);
		}
		return ObjectUtils.isEmpty(tzBaseEnterpriseInfo) ? null : tzBaseEnterpriseInfoDto;
	}

	private TzBaseEnterpriseInfoDto getDetail(TzBaseEnterpriseInfo tzBaseEnterpriseInfo){
		TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto = detail(tzBaseEnterpriseInfo.getSequenceNbr());
		return convertDto(tzBaseEnterpriseInfo, tzBaseEnterpriseInfoDto);
	}

	private TzBaseEnterpriseInfoDto convertDto(TzBaseEnterpriseInfo tzBaseEnterpriseInfo, TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto) {
		if(!ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getOfficeRegion())){
			List<Integer> officeRegion = new ArrayList<>();
			for (String s : tzBaseEnterpriseInfo.getOfficeRegion().split("#")) {
				if (StringUtils.isEmpty(s) || "undefined".equals(s)) {
					continue;
				}
				officeRegion.add(Integer.valueOf(s));
			}
			tzBaseEnterpriseInfoDto.setOfficeRegion(officeRegion);
		}
		RegUnitIcDto regUnitIcDto = tzBaseEnterpriseInfoDto.getRegUnitIcDto();
		String creditCode = tzBaseEnterpriseInfoDto.getUseCode();
		if (!ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getRegisterType()) && tzBaseEnterpriseInfo.getRegisterType().contains(UnitTypeEnum.grzt.getName())) {
			// 个人主体时截取证件号码（eg. 6600_210423195703287959 证件类型_证件号码）
			if (creditCode.split("_").length > 1) {
				creditCode = creditCode.split("_")[1];
			}
		}
		// 陕西省内企业从工商平台查询工商信息
		if (UnitDataSourceEnum.SHAANXI.getName().equals(tzBaseEnterpriseInfo.getDataSources())
				&& EnterpriseEnums.QY_DW.getTypeName().equals(tzBaseEnterpriseInfo.getRegisterType())) {
			// 判断是否可以让用户编辑工商及许可信息 事业单位、个人主体或省外企业都可编辑
			tzBaseEnterpriseInfoDto.setCanEdit("0");
			tzBaseEnterpriseInfoDto.setLicenseCanEdit("1");
			Map<String, Object> resultMap = getAccessFeignResult(creditCode);
			if (!ValidationUtil.isEmpty(resultMap)) {
				String area = String.valueOf(resultMap.get("area"));
				String city = area.substring(0, area.indexOf("市") + 1);
				String district = area.substring(city.length());
				if (district.equals("高新区")) {
					district = "雁塔区";
				}
				String industryName = "";
				DataDictionary dataDictionary = iDataDictionaryService.getByCode(String.valueOf(resultMap.get("industryCode")), "HYXLDM");
				if (!ValidationUtil.isEmpty(dataDictionary)) {
					industryName = dataDictionary.getName();
				}
				String approveDate = String.valueOf(resultMap.get("approval_time"));
				approveDate = approveDate.contains("年") ? approveDate.replace("年", "-") : approveDate;
				approveDate = approveDate.contains("月") ? approveDate.replace("月", "-") : approveDate;
				approveDate = approveDate.contains("日") ? approveDate.replace("日", "") : approveDate;
				regUnitIcDto.setUnitCode(String.valueOf(resultMap.get("creditCode")));
				log.info("工商信息approveDate：{}", approveDate);
				String approve = approveDate + "核准";
				tzBaseEnterpriseInfoDto.setApproval(approve);
				try {
					regUnitIcDto.setApprovedDate(DateUtils.dateParse(approveDate, "yyyy-MM-dd"));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				regUnitIcDto.setUnitName(String.valueOf(resultMap.get("unitName")));
				regUnitIcDto.setRegisteredOrgan(String.valueOf(resultMap.get("registration_authority")));
				for (DataDictionary djjg : iDataDictionaryService.getByType("DJJG")) {
					if(djjg.getName().equals(resultMap.get("registration_authority"))){
						regUnitIcDto.setRegisteredOrganCode(djjg.getSequenceNbr().toString());
					}
				}
				regUnitIcDto.setBusinessState(String.valueOf(resultMap.get("operating_status")));
				regUnitIcDto.setProvince("陕西省");
				regUnitIcDto.setCity(city);
				regUnitIcDto.setDistrict(district);
				regUnitIcDto.setStree(String.valueOf(resultMap.get("street")));
				regUnitIcDto.setCommunity(String.valueOf(resultMap.get("community")));
				regUnitIcDto.setAddress(String.valueOf(resultMap.get("address")));
				regUnitIcDto.setLegalPerson(String.valueOf(resultMap.get("legalPeople")));
				regUnitIcDto.setIndustryName(industryName);
				regUnitIcDto.setRegisterAddress("陕西省/" + city + "/" + district);
				ArrayList<Object> objects = new ArrayList<>();
				objects.add("陕西省");
				objects.add(city);
				objects.add(district);
				regUnitIcDto.setRegisterAddressList(objects);
				regUnitIcDto.setIsNotAccess("1");
			}
		} else {
			regUnitIcDto = tzBaseEnterpriseInfoDto.getRegUnitIcDto();
			regUnitIcDto.setIsNotAccess("0");
			List<String> addressList = Lists.newArrayList();
			addressList.add(tzBaseEnterpriseInfo.getProvince());
			addressList.add(tzBaseEnterpriseInfo.getCity());
			addressList.add(tzBaseEnterpriseInfo.getDistrict());
			regUnitIcDto.setRegisterAddressList(addressList);
			// 判断是否可以让用户编辑工商及许可信息 事业单位、个人主体或省外企业都可编辑
			tzBaseEnterpriseInfoDto.setCanEdit("1");
			tzBaseEnterpriseInfoDto.setLicenseCanEdit("1");
		}
		tzBaseEnterpriseInfoDto.setRegUnitIcDto(regUnitIcDto);
		tzBaseEnterpriseInfoDto.setApprovalTime(regUnitIcDto.getApprovedDate());
		return tzBaseEnterpriseInfoDto;
	}

	private Map<String, Object> getAccessFeignResult(String creditCode) {
		try {
			return accessFeignService.getData(creditCode).getResult();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("获取工商信息失败：accessFeignService.getData(creditCode) error:{}", e.getMessage());
			return null;
		}
	}

	@Override
	public IPage<TzBaseEnterpriseInfoDto> page(PageParam pageParam, String companyCode) {
		TzBaseEnterpriseInfo tzBaseEnterpriseInfo = tzBaseEnterpriseInfoMapper.selectOne(new LambdaQueryWrapper<TzBaseEnterpriseInfo>().eq(TzBaseEnterpriseInfo::getUseCode, companyCode));
		Page<TzBaseEnterpriseInfoDto> page = new Page<>(pageParam.getCurrent(), pageParam.getSize());
		ArrayList<TzBaseEnterpriseInfoDto> result = new ArrayList<>();
		if (ValidationUtil.isEmpty(tzBaseEnterpriseInfo)) {
			return page.setRecords(result);
		}
		TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto = getDetail(tzBaseEnterpriseInfo);
		LambdaQueryWrapper<TzsBaseInstitution> lambda = new QueryWrapper<TzsBaseInstitution>().lambda();
		lambda.eq(TzsBaseInstitution::getEnterpriseId, tzBaseEnterpriseInfo.getSequenceNbr());
		TzsBaseInstitution tzsBaseInstitution = tzsBaseInstitutionService.getBaseMapper().selectOne(lambda);
		tzBaseEnterpriseInfoDto.setRegUnitMessage(tzsBaseInstitution);
		tzBaseEnterpriseInfoDto.setUserPermissionList(userInfoService.getUserPermissionOfCurrentLogin(UserPermissionDto.builder().cityCode(companyCode).build()));
		result.add(tzBaseEnterpriseInfoDto);
		return page.setRecords(result);
	}

	@Override
	public List<EquEnterDto> getInfoByUseUnit(String userUnit) {
		return tzBaseEnterpriseInfoMapper.getInfoByUseUnit(userUnit);
	}

	@Override
	public TzBaseEnterpriseInfoDto selectByUseUnit(String useUnit) {
		if(ValidationUtil.isEmpty(useUnit)){
			return new TzBaseEnterpriseInfoDto();
		}
		TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto = new TzBaseEnterpriseInfoDto();
		TzBaseEnterpriseInfo tzBaseEnterpriseInfo = tzBaseEnterpriseInfoMapper.selectByUseUnit(useUnit);
		if (tzBaseEnterpriseInfo != null) {
			BeanUtils.copyProperties(tzBaseEnterpriseInfo, tzBaseEnterpriseInfoDto);
		}
		// 许可信息
		List<BaseUnitLicence> unitLicences = baseUnitLicenceService.list(new LambdaQueryWrapper<BaseUnitLicence>()
				.eq(BaseUnitLicence::getUnitCode, tzBaseEnterpriseInfo.getUseCode()));
		List<BaseUnitLicenceDto> unitLicenceDtos = new ArrayList<BaseUnitLicenceDto>();
		if (!ValidationUtil.isEmpty(unitLicences)) {
			for (BaseUnitLicence baseUnitLicence : unitLicences) {
				BaseUnitLicenceDto baseUnitLicenceDto = new BaseUnitLicenceDto();
				BeanUtils.copyProperties(baseUnitLicence, baseUnitLicenceDto);
				unitLicenceDtos.add(baseUnitLicenceDto);
			}
		}

		tzBaseEnterpriseInfoDto.setUnitLicences(unitLicenceDtos);
		// 工商信息
		RegUnitIc regUnitIc = regUnitIcService.getOne(
				new LambdaQueryWrapper<RegUnitIc>().eq(RegUnitIc::getUnitCode, tzBaseEnterpriseInfo.getUseCode()));
		RegUnitIcDto regUnitIcDto = new RegUnitIcDto();
		if (regUnitIc != null) {
			BeanUtils.copyProperties(regUnitIc, regUnitIcDto);
		}
		tzBaseEnterpriseInfoDto.setRegUnitIcDto(regUnitIcDto);
		return tzBaseEnterpriseInfoDto;

	}

	@Override
	public String syncEnterpriseInfo() {
		platformTokenService.setRequestContext();
		List<TzBaseEnterpriseInfo> baseEnterpriseInfoList = new ArrayList<>();

		//获取平台企业表企业名称及sequence_code，并装入map中
		Collection<CompanyModel> companyModels = Privilege.companyClient.queryAgencyTree(null).getResult();
		Map<String,CompanyModel> companyMap = new HashMap<>();

		getCompanyInfoMap(companyModels,companyMap);

		int size = 500;
		int total = speUseUnitService.count();
		int current = total/size;
		current = current + 1;
		for(int i = 1; i<=current; i++){


			IPage<SpeUseUnit> page = new Page<>();
			page.setCurrent(i);
			page.setSize(size);
			List<SpeUseUnit> speUseUnitList = speUseUnitService.page(page).getRecords();
			for (SpeUseUnit speUseUnit : speUseUnitList) {

				if(speUseUnit.getSyncState() != 3){
					CompanyModel companyPrivilegeModel = Privilege.companyClient.queryByCompanyCode(speUseUnit.getCerCode()).getResult();
					QueryWrapper<TzBaseEnterpriseInfo> queryWrapper = new QueryWrapper<TzBaseEnterpriseInfo>();
					queryWrapper.eq("use_code",speUseUnit.getCerCode());
					TzBaseEnterpriseInfo tzBaseEnterprisePrivilegeInfo = this.getOne(queryWrapper);

					Map<String, Object> resultMap = getAccessFeignResult(speUseUnit.getCerCode());

					if (ValidationUtil.isEmpty(resultMap)){
						if(!ValidationUtil.isEmpty(companyPrivilegeModel)){
							List<AgencyUserModel> agencyUserModelList = Privilege.agencyUserClient.queryByCompanyId(companyPrivilegeModel.getSequenceNbr(),null,null,null).getResult();
							if(ValidationUtil.isEmpty(agencyUserModelList)){
								//spe表中的数据在工商查不到，且平台无用户，将删除企业数据
								Privilege.companyClient.deleteCompany(String.valueOf(companyPrivilegeModel.getSequenceNbr()));
								if (!ValidationUtil.isEmpty(tzBaseEnterprisePrivilegeInfo)) {
									this.deleteBySeq(tzBaseEnterprisePrivilegeInfo.getSequenceNbr());
								}
							}
						}
						//spe表中的数据在工商查不到,设置spe表状态为1
						speUseUnit.setSyncState(1);
						speUseUnitService.updateById(speUseUnit);
					}else {
						CompanyModel privilegeCompanyModel = Privilege.companyClient.queryByCompanyName(String.valueOf(resultMap.get("registration_authority"))).getResult();
						CompanyModel companyModel = new CompanyModel();
						companyModel.setCompanyName(speUseUnit.getName());
						companyModel.setCompanyCode(speUseUnit.getCerCode());
						companyModel.setLevel("company");
						companyModel.setAgencyCode("tzs");
						companyModel.setCompanyType("使用单位");
						companyModel.setAddress(String.valueOf(resultMap.get("address")));
						companyModel.setParentId(privilegeCompanyModel.getSequenceNbr());


						String area = String.valueOf(resultMap.get("area"));
						String province = "";
						if (area.contains("省")) {
							province = area.substring(0, area.indexOf("省") + 1);
						}
						String city = "";
						if (area.contains("市")) {
							city = area.substring(province.length(), area.indexOf("市") + 1);
						}
						String district = area.substring(city.length() + province.length());
						TzBaseEnterpriseInfo baseEnterpriseInfo = new TzBaseEnterpriseInfo();
						baseEnterpriseInfo.setUseUnit(speUseUnit.getName());
						baseEnterpriseInfo.setUseCode(speUseUnit.getCerCode());
						baseEnterpriseInfo.setUnitType("使用单位");
						baseEnterpriseInfo.setRegistrationAuthority(String.valueOf(resultMap.get("registration_authority")));
						baseEnterpriseInfo.setProvince(province);
						baseEnterpriseInfo.setCity(city);
						baseEnterpriseInfo.setDistrict(district);
						baseEnterpriseInfo.setStreet(String.valueOf(resultMap.get("street")));
						baseEnterpriseInfo.setCommunity(String.valueOf(resultMap.get("community")));
						baseEnterpriseInfo.setAddress(String.valueOf(resultMap.get("address")));
						baseEnterpriseInfo.setLegalPerson(String.valueOf(resultMap.get("legalPeople")));
						baseEnterpriseInfo.setIndustry(String.valueOf(resultMap.get("industry")));
						baseEnterpriseInfo.setSuperviseOrgName(String.valueOf(resultMap.get("registration_authority")));
						baseEnterpriseInfo.setSuperviseOrgCode(privilegeCompanyModel.getOrgCode());
						baseEnterpriseInfo.setOperatingStatus(String.valueOf(resultMap.get("operating_status")));
						baseEnterpriseInfo.setUnitType("使用单位");
						baseEnterpriseInfoList.add(baseEnterpriseInfo);


						//保存平台和业务的企业信息
						try {
							if (tzBaseEnterprisePrivilegeInfo == null && companyPrivilegeModel == null) {
								//当企业表、平台表 中没有时
								this.save(baseEnterpriseInfo);
								Privilege.companyClient.create(companyModel);
							} else if (tzBaseEnterprisePrivilegeInfo == null) {
								//企业表没有，平台表有
								this.save(baseEnterpriseInfo);
								if (!companyPrivilegeModel.getCompanyType().contains(companyModel.getCompanyType())) {
									companyPrivilegeModel.setCompanyType(companyPrivilegeModel.getCompanyType() + "," + companyModel.getCompanyType());
									Privilege.companyClient.update(companyPrivilegeModel, companyPrivilegeModel.getSequenceNbr());
								}
							} else if (companyPrivilegeModel == null) {
								//平台表没有，企业表有
								if (!tzBaseEnterprisePrivilegeInfo.getUnitType().contains(baseEnterpriseInfo.getUnitType())) {
									tzBaseEnterprisePrivilegeInfo.setUnitType(tzBaseEnterprisePrivilegeInfo.getUnitType() + "," + baseEnterpriseInfo.getUnitType());
									this.updateById(tzBaseEnterprisePrivilegeInfo);
								}
								Privilege.companyClient.create(companyModel);
							} else {
								//企业表有 平台表有
								if (!companyPrivilegeModel.getCompanyType().contains(companyModel.getCompanyType())) {
									companyPrivilegeModel.setCompanyType(companyPrivilegeModel.getCompanyType() + "," + companyModel.getCompanyType());
									Privilege.companyClient.update(companyPrivilegeModel, companyPrivilegeModel.getSequenceNbr());
								}
								if (!tzBaseEnterprisePrivilegeInfo.getUnitType().contains(baseEnterpriseInfo.getUnitType())) {
									tzBaseEnterprisePrivilegeInfo.setUnitType(tzBaseEnterprisePrivilegeInfo.getUnitType() + "," + baseEnterpriseInfo.getUnitType());
									this.updateById(tzBaseEnterprisePrivilegeInfo);
								}
							}
							setSpeUseUnitState(3,speUseUnit);
						} catch (Exception e) {
							System.out.println(e.getMessage());
							//当报错时 设置状态为 2
							speUseUnit.setSyncState(2);
							speUseUnitService.updateById(speUseUnit);
						}
					}
				}
			}
		}
		return "ok";
	}

	@Transactional
	@Override
	public TzBaseEnterpriseInfoDto companyInfoUpdate(Map<String, Object> map, ReginParams reginParams) {
		TzBaseEnterpriseInfo tzBaseEnterpriseInfo = new TzBaseEnterpriseInfo();
		tzBaseEnterpriseInfo.setSequenceNbr(Long.valueOf(map.get("sequenceNbr").toString()));
		tzBaseEnterpriseInfo = this.getById(tzBaseEnterpriseInfo.getSequenceNbr());
		//修改基本信息
		tzBaseEnterpriseInfo.setEquipCategory(JSON.toJSONString(map.get("equipCategory")));
		Map<String, String> map1 = (Map<String, String>) map.get("longitudeLatitude");
		tzBaseEnterpriseInfo.setAddress(ObjectUtils.isEmpty(map1.get("address")) ? null : map1.get("address"));
		tzBaseEnterpriseInfo.setLongitude(ObjectUtils.isEmpty(map1.get("longitude")) ? null : String.valueOf(map1.get("longitude")));
		tzBaseEnterpriseInfo.setLatitude(ObjectUtils.isEmpty(map1.get("latitude")) ? null : String.valueOf(map1.get("latitude")));
		tzBaseEnterpriseInfo.setUseContact(ObjectUtils.isEmpty(map.get("useContact")) ? null : String.valueOf(map.get("useContact")));
		tzBaseEnterpriseInfo.setContactPhone(ObjectUtils.isEmpty(map.get("contactPhone")) ? null : String.valueOf(map.get("contactPhone")));
		tzBaseEnterpriseInfo.setUnitBusinessLicense(ObjectUtils.isEmpty(map.get("unitBusinessLicense")) ? null : JSON.toJSONString(map.get("unitBusinessLicense")));
		tzBaseEnterpriseInfo.setIndustrySupervisor(ObjectUtils.isEmpty(map.get("industrySupervisor")) ? null : String.valueOf(map.get("industrySupervisor")));
		tzBaseEnterpriseInfo.setSuperviseOrgCode(ObjectUtils.isEmpty(map.get("superviseOrgCode")) ? null : String.valueOf(map.get("superviseOrgCode")));
		tzBaseEnterpriseInfo.setSuperviseOrgName(ObjectUtils.isEmpty(map.get("superviseOrgName")) ? null : String.valueOf(map.get("superviseOrgName")));
		tzBaseEnterpriseInfo.setOtherAccessories(ObjectUtils.isEmpty(map.get("otherAccessories")) ? null : JSON.toJSONString(map.get("otherAccessories")));
		tzBaseEnterpriseInfo.setLegalPerson(ObjectUtils.isEmpty(map.get("legalPerson")) ? null : (String)map.get("legalPerson"));
		String officeRegion = null;
		if(!ObjectUtils.isEmpty(map.get("officeRegion"))){
			List list = (List<Object>) map.get("officeRegion");
			officeRegion = list.stream().map(String::valueOf).collect(Collectors.joining("#")).toString();
		}
		tzBaseEnterpriseInfo.setOfficeRegion(officeRegion);
		tzBaseEnterpriseInfo.setOfficeAddress(ObjectUtils.isEmpty(map.get("officeAddress")) ? null : (String)map.get("officeAddress"));
		// 修改事业单位信息
		TzsBaseInstitutionDto baseInstitutionDto =  JSON.toJavaObject(JSON.parseObject(JSON.toJSONString(map.get("regUnitMessage"))), TzsBaseInstitutionDto.class);
		if (!ValidationUtil.isEmpty(baseInstitutionDto)) {
			TzsBaseInstitution baseInstitution = new TzsBaseInstitution();
			BeanUtils.copyProperties(baseInstitutionDto, baseInstitution);
			// 用"单位信息"更新以下字段
			tzBaseEnterpriseInfo.setAddress(ObjectUtils.isEmpty(map.get("address")) ? null : (String)map.get("address"));
			tzBaseEnterpriseInfo.setProvince(baseInstitutionDto.getUnitAddress().get(0));
			tzBaseEnterpriseInfo.setCity(baseInstitutionDto.getUnitAddress().get(1));
			tzBaseEnterpriseInfo.setDistrict(baseInstitutionDto.getUnitAddress().get(2));

			tzsBaseInstitutionService.saveOrUpdate(baseInstitution);
		}

		// 修改tz_flc_reg_unit_info表信息
		RegUnitInfo regUnitInfo;
		LambdaQueryWrapper<RegUnitInfo> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(RegUnitInfo::getUnitCode, tzBaseEnterpriseInfo.getUseCode());
		regUnitInfo = regUnitInfoService.getOne(queryWrapper);
		if (ValidationUtil.isEmpty(regUnitInfo)) {
			regUnitInfo = new RegUnitInfo();
		}
		regUnitInfo.setName(tzBaseEnterpriseInfo.getUseUnit());
		regUnitInfo.setUnitCode(tzBaseEnterpriseInfo.getUseCode());
		regUnitInfo.setManagementUnit(tzBaseEnterpriseInfo.getGoverningBody());
//		regUnitInfo.setManagementUnitId(tzBaseEnterpriseInfo.getGoverningBody());
		regUnitInfo.setProvince(tzBaseEnterpriseInfo.getProvince());
		regUnitInfo.setCity(tzBaseEnterpriseInfo.getCity());
		regUnitInfo.setDistrict(tzBaseEnterpriseInfo.getDistrict());
		regUnitInfo.setAddress(tzBaseEnterpriseInfo.getAddress());
		regUnitInfo.setLegalPerson(tzBaseEnterpriseInfo.getLegalPerson());
		regUnitInfo.setContactPerson(tzBaseEnterpriseInfo.getUseContact());
		regUnitInfoService.saveOrUpdate(regUnitInfo);

		//修改工商信息
		RegUnitIc regUnitIc = new RegUnitIc();
		RegUnitIcDto regUnitIcDto = JSON.parseObject(JSON.toJSONString(map.get("regUnitIcDto")), new TypeReference<RegUnitIcDto>() {
		});
		if (!ValidationUtil.isEmpty(regUnitIcDto.getSequenceNbr())) {
			List<String> addressList = (List<String>) map.get("registerAddressList");
			if (!ValidationUtil.isEmpty(addressList) && addressList.size() > 2) {
				tzBaseEnterpriseInfo.setProvince(addressList.get(0));
				tzBaseEnterpriseInfo.setCity(addressList.get(1));
				tzBaseEnterpriseInfo.setDistrict(addressList.get(2));
			}
			tzBaseEnterpriseInfo.setCommunity(ObjectUtils.isEmpty(map.get("community")) ? null : String.valueOf(map.get("community")));
			tzBaseEnterpriseInfo.setStreet(ObjectUtils.isEmpty(map.get("street")) ? null : String.valueOf(map.get("street")));
			tzBaseEnterpriseInfo.setLegalPerson(ObjectUtils.isEmpty(map.get("legalPerson")) ? null : String.valueOf(map.get("legalPerson")));
			regUnitIc.setIndustryName(ObjectUtils.isEmpty(map.get("industryName")) ? null : String.valueOf(map.get("industryName")));
			DataDictionary regOrganCodeDict = iDataDictionaryService.getByCode(String.valueOf(map.get("registeredOrganCode")),"DJJG");
			regUnitIc.setRegisteredOrgan(ObjectUtils.isEmpty(regOrganCodeDict) ? null : String.valueOf(regOrganCodeDict.getName()));
			regUnitIc.setRegisteredOrganCode(ObjectUtils.isEmpty(map.get("registeredOrganCode")) ? null : String.valueOf(map.get("registeredOrganCode")));
			Date approvedDate;
			try {
				if (!ValidationUtil.isEmpty(map.get("approvedDate"))) {
					approvedDate = DateUtils.dateParse(String.valueOf(map.get("approvedDate")), "yyyy-MM-dd");
					regUnitIc.setApprovedDate(ObjectUtils.isEmpty(map.get("approvedDate")) ? null : approvedDate);
				}
			} catch (ParseException e) {
				throw new BadRequest("请核对核准时间");
			}
			regUnitIc.setBusinessStateCode(ObjectUtils.isEmpty(map.get("businessState")) ? null : String.valueOf(map.get("businessState")));
			if (!ValidationUtil.isEmpty(map.get("businessState"))) {
				DataDictionary businessStateDict = iDataDictionaryService.getByCode(String.valueOf(map.get("businessState")),"jyzt");
				regUnitIc.setBusinessState(ObjectUtils.isEmpty(businessStateDict) ? null : businessStateDict.getName());
			}

			regUnitIcService.update(regUnitIc, new QueryWrapper<RegUnitIc>().eq("unit_code", regUnitIcDto.getUnitCode()));
		}
		//许可信息先登录人选择的身份删除相应的许可信息,原因前端列表对数据可增减
		removeLicenceDataBeforeSave(reginParams, tzBaseEnterpriseInfo);
		//保存许可信息
		saveLicenceData(map);
		// 企业信息变更-同步修改企业下人员绑定设备类型
		ArrayList<String> newData = new ArrayList<>();
		JSONArray objects = JSON.parseArray(tzBaseEnterpriseInfo.getEquipCategory());
		objects.forEach(item -> newData.add(item.toString()));
        boolean b = this.updateById(tzBaseEnterpriseInfo);
        if (b) {
			try {
				CompanyModel updateModel = Privilege.companyClient.queryByCompanyCode(String.valueOf(map.get("useCode"))).getResult();
				HashMap<String, Object> parentMessage = (HashMap<String, Object>) Privilege.companyClient.queryByOrgcode(String.valueOf(map.get("superviseOrgCode"))).getResult();
				// 目前平台返回key为compnay(存在拼写错误)
				CompanyModel parentModel = JSON.parseObject(JSON.toJSONString(parentMessage.get("compnay")), CompanyModel.class);
				updateModel.setParentId(parentModel.getSequenceNbr());
				Privilege.companyClient.update(updateModel, updateModel.getSequenceNbr());
			} catch (Exception e) {
				throw new BadRequest("操作失败！");
			}
			updateUserInfo(newData, String.valueOf(map.get("useCode")));
			TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto = new TzBaseEnterpriseInfoDto();
			BeanUtils.copyProperties(tzBaseEnterpriseInfo, tzBaseEnterpriseInfoDto);
			publisher.publish(new DataRefreshEvent(this,  Collections.singletonList(tzBaseEnterpriseInfo.getSequenceNbr() + ""), DataRefreshEvent.DataType.enterprise.name(), DataRefreshEvent.Operation.UPDATE));
			return tzBaseEnterpriseInfoDto;
        } else {
            return null;
        }

    }

	private void saveLicenceData(Map<String, Object> map) {
		List<BaseUnitLicence> licences = Lists.newArrayList();
		List<DataDictionary> dictionaries = regUnitInfoService.initAllDataDictionaryList();
		Object unitLicences = map.get("unitLicences");
		if (unitLicences instanceof Collection && !((Collection<?>) unitLicences).isEmpty()) {
			JSON.parseArray(JSON.toJSONString(unitLicences)).forEach(obj -> {
				BaseUnitLicence baseUnitLicence = JSON.toJavaObject((JSONObject) obj, BaseUnitLicence.class);
				if (ObjectUtils.isEmpty(baseUnitLicence.getCertTypeCode())) {
					throw new BadRequest("请完善资质/许可信息后保存！");
				}
				baseUnitLicence.setUnitCode(ObjectUtils.isEmpty(map.get("useCode")) ? null : (String) map.get("useCode"));
				baseUnitLicence.setUnitName(ObjectUtils.isEmpty(map.get("useUnit")) ? null : (String) map.get("useUnit"));
				// 处理许可字典值对应名称
				handleDictName(baseUnitLicence, dictionaries);
				// 添加到结果集合
				licences.add(baseUnitLicence);
			});
		}
		if (!ValidationUtil.isEmpty(licences)){
			baseUnitLicenceService.saveOrUpdateBatch(licences);
		}
	}

	private void removeLicenceDataBeforeSave(ReginParams reginParams, TzBaseEnterpriseInfo tzBaseEnterpriseInfo) {
		if (tzBaseEnterpriseInfo == null) return;
		String companyType = reginParams.getCompany().getCompanyType();
		String useCode = tzBaseEnterpriseInfo.getUseCode();
		String certTypeCodes = COMPANY_TYPE_CERT_TYPE_MAP.getOrDefault(companyType, "");
		if (useCode == null || certTypeCodes.isEmpty()) return;
		LambdaQueryWrapper<BaseUnitLicence> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(BaseUnitLicence::getUnitCode, useCode);
		wrapper.and(w -> Arrays.stream(certTypeCodes.split(","))
				.forEach(certTypeCode -> w.or().likeRight(BaseUnitLicence::getCertTypeCode, certTypeCode)));

		baseUnitLicenceService.remove(wrapper);
	}

	/**
	 * 处理单位许可证书名称。
	 * 该方法通过查询数据字典，根据给定的许可证书代码，设置许可证书的类型、项目代码名称、子项目名称、参数名称、
	 * 审批机构名称、申请类型名称和评估方式名称。
	 *
	 * @param baseUnitLicence 包含许可证书信息的基类单位许可证书对象。
	 */
	private void handleDictName(BaseUnitLicence baseUnitLicence, List<DataDictionary> dictionaries) {
		// 当前登录账户信息
		ReginParams selectedOrgInfo = getSelectedOrgInfo();
		String companyType = selectedOrgInfo.getCompany().getCompanyType();

	    // 根据新的单位类型代码查询许可证书类型名称
		fillCertTypeName(baseUnitLicence, dictionaries, companyType);

		// 查询项目代码对应的名称
        Optional<String> itemCodeOptional = dictionaries.stream()
                .filter(d -> ((!ValidationUtil.isEmpty(d.getExtend()) && d.getExtend().startsWith("XK-")) || HZXM.equals(d.getType())) && d.getCode().equals(baseUnitLicence.getItemCode()))
                .map(DataDictionary::getName)
                .findFirst();
        // 设置项目代码名称
        itemCodeOptional.ifPresent(baseUnitLicence::setItemCodeName);

	    // 查询子项目代码对应的名称
	    Optional<String> subItemOptional = dictionaries.stream()
	            .filter(d -> !ValidationUtil.isEmpty(d.getExtend()) && d.getExtend().startsWith("XK-") && d.getCode().equals(baseUnitLicence.getSubItemCode()))
	            .map(DataDictionary::getName)
	            .findFirst();
	    // 设置子项目名称
	    subItemOptional.ifPresent(baseUnitLicence::setSubItemName);

	    // 查询参数代码对应的名称
	    Optional<String> parameterOptional = dictionaries.stream()
	            .filter(d -> !ValidationUtil.isEmpty(d.getExtend()) && d.getExtend().startsWith("XK-") && d.getCode().equals(baseUnitLicence.getParameterCode()))
	            .map(DataDictionary::getName)
	            .findFirst();
	    // 设置参数名称
	    parameterOptional.ifPresent(baseUnitLicence::setParameter);

	    // 查询审批机构代码对应的名称
	    Optional<String> approvedOrgenOptional = dictionaries.stream()
	            .filter(d -> d.getType().equals("DJJG") && d.getCode().equals(baseUnitLicence.getApprovedOrganCode()))
	            .map(DataDictionary::getName)
	            .findFirst();
	    // 设置审批机构名称
	    approvedOrgenOptional.ifPresent(baseUnitLicence::setApprovedOrgan);

	    // 查询申请类型代码对应的名称
	    Optional<String> applyTypeOptional = dictionaries.stream()
	            .filter(d -> d.getType().equals("xkfszt") && d.getCode().equals(baseUnitLicence.getApplyTypeCode()))
	            .map(DataDictionary::getName)
	            .findFirst();
	    // 设置申请类型名称
	    applyTypeOptional.ifPresent(baseUnitLicence::setApplyType);

	    // 查询评估方式代码对应的名称
	    Optional<String> appraisalTypeOptional = dictionaries.stream()
	            .filter(d -> d.getType().equals("xkpsfs") && d.getCode().equals(baseUnitLicence.getAppraisalTypeCode()))
	            .map(DataDictionary::getName)
	            .findFirst();
	    // 设置评估方式名称
	    appraisalTypeOptional.ifPresent(baseUnitLicence::setAppraisalType);
        // 检验、检测时冗余证书类型名称
	    this.setAgencyTypeName(baseUnitLicence, dictionaries);
	}

	private void setAgencyTypeName(BaseUnitLicence baseUnitLicence, List<DataDictionary> dictionaries) {
		if(StringUtils.isNotEmpty(baseUnitLicence.getAgencyType())){
			Optional<DataDictionary>  op = dictionaries.stream().filter(d->d.getType().equals(JYJC_TYPE_DICT_CODE) && d.getCode().equals(baseUnitLicence.getAgencyType())).findAny();
			op.ifPresent(dataDictionary -> baseUnitLicence.setAgencyTypeName(dataDictionary.getName()));
		}
	}

	private void fillCertTypeName(BaseUnitLicence baseUnitLicence, List<DataDictionary> dictionaries, String companyType) {
		if (Arrays.asList(INSPECTION_AGENCY, TESTING_INSTITUTIONS).contains(companyType)) {
			if(StringUtils.isEmpty(baseUnitLicence.getCertType())){
				String certTypeName = JYJC_CERT_MAP.get(baseUnitLicence.getCertTypeCode());
				baseUnitLicence.setCertType(certTypeName);
			}
			baseUnitLicence.setLicenceType(LicenceTypeEnum.JYJC.getCode());
		} else {
			Optional<String> certTypeOptional = dictionaries.stream()
					.filter(d -> "UNIT_TYPE_NEW".equals(d.getType()) && baseUnitLicence.getCertTypeCode().startsWith(d.getCode()))
					.map(DataDictionary::getName)
					.findFirst();
			// 设置许可证书类型
			certTypeOptional.ifPresent(baseUnitLicence::setCertType);
		}
	}

	private void updateUserInfo(ArrayList<String> newDate, String creditCode) {
		LambdaQueryWrapper<TzsUserInfo> lambda = new QueryWrapper<TzsUserInfo>().lambda();
		lambda.eq(TzsUserInfo::getUnitCode, creditCode);
		List<TzsUserInfo> tzsUserInfos = tzsUserInfoMapper.selectList(lambda);
		List<TzsUserInfo> newTzsUserInfos = new ArrayList<>();
		tzsUserInfos.forEach(item -> {
			boolean update = false;
			if (!ObjectUtils.isEmpty(item.getEquipType())) {
				JSONArray objects = JSON.parseArray(item.getEquipType());
				ArrayList<String> oldDate = new ArrayList<>();
				objects.forEach(itemTpe -> {
					oldDate.add(itemTpe.toString());
				});
				for (Object object : objects) {
					if (!newDate.contains(object)) {
						update = true;
						oldDate.remove(object.toString());
					}
				}
				if (update) {
					if (!ObjectUtils.isEmpty(oldDate)) {
						item.setEquipType(JSON.toJSONString(oldDate));
					} else {
						item.setEquipType(null);
					}
					newTzsUserInfos.add(item);
				}
			}
		});
		if (!ValidationUtil.isEmpty(newTzsUserInfos)) {
			userInfoService.saveOrUpdateBatch(newTzsUserInfos, 1000);
		}
	}

	@Override
	public String setLabel(List<Long> enterpriseIds, List<String> enterpriseLabels) {
		List<TzBaseEnterpriseInfo> tzBaseEnterpriseInfos = tzBaseEnterpriseInfoMapper.selectBatchIds(enterpriseIds);
		if (!ObjectUtils.isEmpty(enterpriseLabels)) {
			for (TzBaseEnterpriseInfo tzBaseEnterpriseInfo : tzBaseEnterpriseInfos) {
				// 标签递增逻辑
//			if (!ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getRegulatoryLabels())) {
//				String result = checkLabel(enterpriseLabels, tzBaseEnterpriseInfo.getRegulatoryLabels());
//				tzBaseEnterpriseInfo.setRegulatoryLabels(result);
//			} else {
//				String labels = String.join(",", enterpriseLabels);
//				tzBaseEnterpriseInfo.setRegulatoryLabels(labels);
//			}
				String labels = String.join(",", enterpriseLabels);
				tzBaseEnterpriseInfo.setRegulatoryLabels(labels);
			}
		} else {
			tzBaseEnterpriseInfos.forEach(item -> {
				item.setRegulatoryLabels(null);
			});
		}
		this.updateBatchById(tzBaseEnterpriseInfos);
		return "success";
	}

	private String checkLabel(List<String> enterpriseLabels, String result) {
		List<String> strings = Arrays.asList(result.split(","));
		ArrayList<String> res = new ArrayList<>(strings);
		List<String> collect = enterpriseLabels.stream().filter(item -> !strings.contains(item)).collect(Collectors.toList());
		res.addAll(collect);
		return String.join(",", res);
	}

	@Override
	public Map<String, Object> adminInfoUpdate(Map<String, Object> map) {
		// 按照用户进行加锁，解决用户重复提交导致的身份信息重复问题
		String userId = RequestContext.getExeUserId();
		RLock lock = redissonClient.getLock(this.buildUserUpdateLockKey(userId));
		Map<String, Object> resultMap = new HashMap<>();
		try {
			boolean isLocked = lock.tryLock(0, 180, TimeUnit.SECONDS);
			if (!isLocked) {
				throw new TooManyRequests("信息正在保存中，请稍后重试！");
			}
			//每一个企业只有一个管理员，所以当前登录用户即管理员用户
			AgencyUserModel me = Privilege.agencyUserClient.getme().getResult();
			//自己不能修改自己 所以需要设置为机器人
			platformTokenService.setRequestContext();
			RegUnitInfo regUnitInfo = new RegUnitInfo();
			String unitCode = String.valueOf(map.get("unitCode"));
			regUnitInfo.setAdminName(String.valueOf(map.get("adminName")));
			regUnitInfo.setAdminIdNumber(String.valueOf(map.get("adminIdNumber")));
			regUnitInfo.setAdminIdCardPhoto(JSON.toJSONString(map.get("adminIdCardPhoto")));
			regUnitInfo.setAdminTel(String.valueOf(map.get("adminTel")));
			me.setMobile(regUnitInfo.getAdminTel());
			me.setRealName(String.valueOf(map.get("adminName")));
			Privilege.agencyUserClient.update(me, me.getUserId());
			regUnitInfoService.update(regUnitInfo, new LambdaQueryWrapper<RegUnitInfo>().eq(RegUnitInfo::getUnitCode, unitCode));
			resultMap.put("success", regUnitInfo);
			redisUtil.del(adminChange + map.get("adminTel"));
		} catch (InterruptedException e) {
			log.error("tryLock获取锁失败：",e);
			throw new BadRequest("系统繁忙，请稍后重试！");
		} catch (TooManyRequests e) {
			log.error(e.getMessage(),e);
			throw e;
		} finally {
			if (lock.isHeldByCurrentThread()) {
				lock.unlock();
			}
		}
		return resultMap;
	}

	private String buildUserUpdateLockKey(String userId) {
		return String.format("TCM_USER_UPDATE_LOCK_KEY:%s", userId);
	}

	public void setSpeUseUnitState(int state,SpeUseUnit speUseUnit){
		speUseUnit.setSyncState(state);
		speUseUnitService.updateById(speUseUnit);
	}

	public Map<String, CompanyModel> getCompanyInfoMap(Collection companyModels,Map<String, CompanyModel> map){
		if(companyModels == null){
			return map;
		}
		Iterator iter = companyModels.iterator();
		while(iter.hasNext()){
			String json = JSON.toJSONString(iter.next());
			CompanyModel companyModel =  JSON.parseObject(json,CompanyModel.class);
			map.put(companyModel.getCompanyName(),companyModel);
			getCompanyInfoMap(companyModel.getChildren(),map);
		}
		return map;
	}

	@Override
	public BaseUnitLicence getUnitLicenceMessage(String unitCode) {
		// 许可信息
		LambdaQueryWrapper<BaseUnitLicence> lambda = new QueryWrapper<BaseUnitLicence>().lambda();
		lambda.eq(BaseUnitLicence::getUnitCode, unitCode);
		lambda.orderByDesc(BaseUnitLicence::getExpiryDate);
		lambda.last("limit 1");
		return baseUnitLicenceService.getBaseMapper().selectOne(lambda);

	}

	@Override
	public IPage<TzBaseEnterpriseInfoDto> getInfoById(Long sequenceNbr, String companyCode) {
		try {
			TzBaseEnterpriseInfo tzBaseEnterpriseInfo = this.getById(sequenceNbr);

			TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto = detailById(tzBaseEnterpriseInfo);
			convertDto(tzBaseEnterpriseInfo, tzBaseEnterpriseInfoDto);

			LambdaQueryWrapper<TzsBaseInstitution> lambda = new QueryWrapper<TzsBaseInstitution>().lambda();
			lambda.eq(TzsBaseInstitution::getEnterpriseId, tzBaseEnterpriseInfo.getSequenceNbr());
			TzsBaseInstitution tzsBaseInstitution = tzsBaseInstitutionService.getBaseMapper().selectOne(lambda);
			tzBaseEnterpriseInfoDto.setRegUnitMessage(tzsBaseInstitution);
			tzBaseEnterpriseInfoDto.setUserPermissionList(userInfoService.getUserPermissionOfCurrentLogin(UserPermissionDto.builder().cityCode(companyCode).build()));

			Page<TzBaseEnterpriseInfoDto> page = new Page<>(1, 10);
			page.setRecords(Arrays.asList(tzBaseEnterpriseInfoDto));
			return page;
		} catch (Exception ex) {
			String msg = ex.getMessage() == null ? "" : ex.getMessage();
			if (msg.contains("eyibc decrypt error")
					|| msg.contains("EYIBCException")
					|| msg.contains("olym jdbc error")
					|| msg.contains("数据非法")
					|| msg.contains("decrypt error, code: -65")) {
				throw new BadRequest("数据完整性被破坏（解密失败），请联系管理员。");
			}
			ex.printStackTrace();
			throw new BadRequest("系统内部错误，请联系管理员。");
		}
	}

	private TzBaseEnterpriseInfoDto detailById(TzBaseEnterpriseInfo tzBaseEnterpriseInfo) {
		// region 根据ID获取详情
		if (tzBaseEnterpriseInfo == null) {
			return null;
		}
		TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto = new TzBaseEnterpriseInfoDto();
		BeanUtils.copyProperties(tzBaseEnterpriseInfo, tzBaseEnterpriseInfoDto);
		tzBaseEnterpriseInfoDto.setSafetyTwoPhoto(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getSafetyTwoPhoto()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getSafetyTwoPhoto()));
		tzBaseEnterpriseInfoDto.setSafetyOnePhoto(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getSafetyOnePhoto()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getSafetyOnePhoto()));
		tzBaseEnterpriseInfoDto.setUnitBusinessLicense(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getUnitBusinessLicense()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getUnitBusinessLicense()));
		tzBaseEnterpriseInfoDto.setOtherAccessories(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getOtherAccessories()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getOtherAccessories()));
		tzBaseEnterpriseInfoDto.setUnitExequatur(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getUnitExequatur()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getUnitExequatur()));
		tzBaseEnterpriseInfoDto.setEquipCategory(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getEquipCategory()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getEquipCategory()));
		tzBaseEnterpriseInfoDto.setUnitType(tzBaseEnterpriseInfo.getUnitType());
		List<String> unitTypes = Arrays.stream(tzBaseEnterpriseInfo.getUnitType().split("#")).collect(Collectors.toList());
		List<DataDictionary> dataDictionaries = iDataDictionaryService.getByType("UNIT_TYPE_NEW");
		tzBaseEnterpriseInfoDto.setUnitTypeCodes(dataDictionaries.stream()
									   .filter(e -> unitTypes.contains(e.getName())).map(DataDictionary::getCode).collect(Collectors.toList()));
		// 当前用户选择角色的许可信息（使用。。安改维。。检验检测。。）
		List<BaseUnitLicence> unitLicences = baseUnitLicenceService.list(new LambdaQueryWrapper<BaseUnitLicence>()
				.eq(BaseUnitLicence::getUnitCode, tzBaseEnterpriseInfo.getUseCode()));
		List<BaseUnitLicenceDto> unitLicenceDtos = new ArrayList<>();
		List<BaseUnitLicence> unitLicencesCollect = Optional.ofNullable(unitLicences).orElse(Collections.emptyList());
		if (!ValidationUtil.isEmpty(unitLicencesCollect)) {
			for (BaseUnitLicence baseUnitLicence : unitLicencesCollect) {
				BaseUnitLicenceDto baseUnitLicenceDto = new BaseUnitLicenceDto();
				BeanUtils.copyProperties(baseUnitLicence, baseUnitLicenceDto);
				unitLicenceDtos.add(baseUnitLicenceDto);
			}
		}
		tzBaseEnterpriseInfoDto.setUnitLicences(unitLicenceDtos);
		// 管理员信息
		RegUnitInfo regUnitInfo = regUnitInfoService.getOne(
				new LambdaQueryWrapper<RegUnitInfo>().eq(RegUnitInfo::getUnitCode, tzBaseEnterpriseInfo.getUseCode()));
		RegUnitInfoDto regUnitInfoDto = new RegUnitInfoDto();
		if (regUnitInfo != null) {
			BeanUtils.copyProperties(regUnitInfo, regUnitInfoDto);
		}
		regUnitInfoDto.setAdminIdCardPhoto((ValidationUtil.isEmpty(regUnitInfo)||ValidationUtil.isEmpty(regUnitInfo.getAdminIdCardPhoto())) ? new ArrayList() : JSON.parseArray(regUnitInfo.getAdminIdCardPhoto()));
		tzBaseEnterpriseInfoDto.setRegUnitInfoDto(regUnitInfoDto);

		// 工商信息
		RegUnitIc regUnitIc = regUnitIcService.getOne(
				new LambdaQueryWrapper<RegUnitIc>().eq(RegUnitIc::getUnitCode, tzBaseEnterpriseInfo.getUseCode()));
		RegUnitIcDto regUnitIcDto = new RegUnitIcDto();
		if (regUnitIc != null) {
			BeanUtils.copyProperties(regUnitIc, regUnitIcDto);
		}
		tzBaseEnterpriseInfoDto.setRegUnitIcDto(regUnitIcDto);
		return tzBaseEnterpriseInfoDto;
		// endregion
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public TzBaseEnterpriseInfoDto updateCompanyInfoById(Map<String, Object> map, ReginParams reginParams) {
		log.info("根据ID修改企业信息 => {}, 更新人 => {}", map, RequestContext.getExeUserId());
		RegUnitInfo olrRegUnitInfo = new RegUnitInfo();
		try {
			TzBaseEnterpriseInfo tzBaseEnterpriseInfo = new TzBaseEnterpriseInfo();
			tzBaseEnterpriseInfo.setSequenceNbr(Long.valueOf(map.get("sequenceNbr").toString()));
			tzBaseEnterpriseInfo = this.getById(tzBaseEnterpriseInfo.getSequenceNbr());

			String newSuperviseOrgCode = ObjectUtils.isEmpty(map.get("superviseOrgCode")) ? null : String.valueOf(map.get("superviseOrgCode"));

			if (!tzBaseEnterpriseInfo.getSuperviseOrgCode().equals(newSuperviseOrgCode)) {
				System.out.println("监管单位变更");
			}

			//修改基本信息
			tzBaseEnterpriseInfo.setEquipCategory(JSON.toJSONString(map.get("equipCategory")));
			Map<String, String> locationMap = (Map<String, String>) map.get("longitudeLatitude");
			if (locationMap != null) {
				tzBaseEnterpriseInfo.setAddress(locationMap.get("address"));
				tzBaseEnterpriseInfo.setLongitude(locationMap.get("longitude"));
				tzBaseEnterpriseInfo.setLatitude(locationMap.get("latitude"));
			}

			tzBaseEnterpriseInfo.setUseContact(ObjectUtils.isEmpty(map.get("useContact")) ? null : String.valueOf(map.get("useContact")));
			tzBaseEnterpriseInfo.setContactPhone(ObjectUtils.isEmpty(map.get("contactPhone")) ? null : String.valueOf(map.get("contactPhone")));
			tzBaseEnterpriseInfo.setUnitBusinessLicense(ObjectUtils.isEmpty(map.get("unitBusinessLicense")) ? null : JSON.toJSONString(map.get("unitBusinessLicense")));
			tzBaseEnterpriseInfo.setIndustrySupervisor(ObjectUtils.isEmpty(map.get("industrySupervisor")) ? null : String.valueOf(map.get("industrySupervisor")));
			tzBaseEnterpriseInfo.setSuperviseOrgCode(newSuperviseOrgCode);
			tzBaseEnterpriseInfo.setSuperviseOrgName(ObjectUtils.isEmpty(map.get("superviseOrgName")) ? null : String.valueOf(map.get("superviseOrgName")));
			tzBaseEnterpriseInfo.setOtherAccessories(ObjectUtils.isEmpty(map.get("otherAccessories")) ? null : JSON.toJSONString(map.get("otherAccessories")));
			tzBaseEnterpriseInfo.setLegalPerson(ObjectUtils.isEmpty(map.get("legalPerson")) ? null : (String)map.get("legalPerson"));
			String officeRegion = null;
			if(!ObjectUtils.isEmpty(map.get("officeRegion"))){
				List<?> list = (List<?>) map.get("officeRegion");
				officeRegion = list.stream().map(String::valueOf).collect(Collectors.joining("#")).toString();
			}
			tzBaseEnterpriseInfo.setOfficeRegion(officeRegion);
			tzBaseEnterpriseInfo.setOfficeAddress(ObjectUtils.isEmpty(map.get("officeAddress")) ? null : (String)map.get("officeAddress"));
			// 修改事业单位信息
			if (map.containsKey("regUnitMessage")) {
				TzsBaseInstitutionDto baseInstitutionDto =  JSON.toJavaObject(JSON.parseObject(JSON.toJSONString(map.get("regUnitMessage"))), TzsBaseInstitutionDto.class);
				if (!ValidationUtil.isEmpty(baseInstitutionDto)) {
					TzsBaseInstitution baseInstitution = new TzsBaseInstitution();
					BeanUtils.copyProperties(baseInstitutionDto, baseInstitution);
					// 用"单位信息"更新以下字段
					tzBaseEnterpriseInfo.setAddress(ObjectUtils.isEmpty(map.get("address")) ? null : (String)map.get("address"));
					tzBaseEnterpriseInfo.setProvince(baseInstitutionDto.getUnitAddress().get(0));
					tzBaseEnterpriseInfo.setCity(baseInstitutionDto.getUnitAddress().get(1));
					tzBaseEnterpriseInfo.setDistrict(baseInstitutionDto.getUnitAddress().get(2));

					tzsBaseInstitutionService.saveOrUpdate(baseInstitution);
				}
			}

			// 修改tz_flc_reg_unit_info表信息
			LambdaQueryWrapper<RegUnitInfo> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(RegUnitInfo::getUnitCode, tzBaseEnterpriseInfo.getUseCode());
			RegUnitInfo regUnitInfo = regUnitInfoService.getOne(queryWrapper);
			if (ValidationUtil.isEmpty(regUnitInfo)) {
				throw new BadRequest("未找到单位注册信息");
			}
			BeanUtils.copyProperties(regUnitInfo, olrRegUnitInfo);
			FeignClientResult<AgencyUserModel> userResult = Privilege.agencyUserClient.queryByUserId(regUnitInfo.getAdminUserId());
			AgencyUserModel agencyUserModel = Optional.ofNullable(userResult).map(FeignClientResult::getResult).orElse(null);
			if (ValidationUtil.isEmpty(agencyUserModel)) {
				throw new BadRequest("未找到单位管理员信息");
			}
			regUnitInfo.setName(tzBaseEnterpriseInfo.getUseUnit());
			regUnitInfo.setUnitCode(tzBaseEnterpriseInfo.getUseCode());
			regUnitInfo.setManagementUnit(tzBaseEnterpriseInfo.getGoverningBody());
			regUnitInfo.setProvince(tzBaseEnterpriseInfo.getProvince());
			regUnitInfo.setCity(tzBaseEnterpriseInfo.getCity());
			regUnitInfo.setDistrict(tzBaseEnterpriseInfo.getDistrict());
			regUnitInfo.setAddress(tzBaseEnterpriseInfo.getAddress());
			regUnitInfo.setLegalPerson(tzBaseEnterpriseInfo.getLegalPerson());
			regUnitInfo.setContactPerson(tzBaseEnterpriseInfo.getUseContact());
			// 处理单位信息
			handleUnitType(map, regUnitInfo, agencyUserModel);
			String[] unitTypes = regUnitInfo.getUnitType().split(",");


			// -- 20250627 调整为监管单位不能修改工商信息和资质
			regUnitInfoService.updateBySeq(regUnitInfo);
			// 企业信息变更-同步修改企业下人员绑定设备类型
			ArrayList<String> newData = new ArrayList<>();
			JSONArray objects = JSON.parseArray(tzBaseEnterpriseInfo.getEquipCategory());
			objects.forEach(item -> newData.add(item.toString()));

			tzBaseEnterpriseInfo.setAppId(regUnitInfo.getAppId());
			tzBaseEnterpriseInfo.setUnitType(String.join("#", unitTypes));

			// 添加使用单位类型的，并且原企业标签为空则默认给三级管控
			if (ValidationUtil.isEmpty(tzBaseEnterpriseInfo.getRegulatoryLabels()) && Arrays.asList(unitTypes).contains(UnitTypeEnum.sydw.getName())) {
				tzBaseEnterpriseInfo.setRegulatoryLabels(defaultRegulatoryLabels);
			}

			boolean updateResult = this.updateById(tzBaseEnterpriseInfo);
			if (updateResult) {
				log.info("更新企业信息, 单位类型 => {}", tzBaseEnterpriseInfo.getUseUnitCode());
				String useCode = String.valueOf(map.get("useCode"));
				CompanyModel updateModel = Privilege.companyClient.queryByCompanyCode(useCode).getResult();
				HashMap<String, Object> parentMessage = (HashMap<String, Object>) Privilege.companyClient.queryByOrgcode(String.valueOf(map.get("superviseOrgCode"))).getResult();
				// 目前平台返回key为compnay(存在拼写错误)
				CompanyModel parentModel = JSON.parseObject(JSON.toJSONString(parentMessage.get("compnay")), CompanyModel.class);
				updateModel.setParentId(parentModel.getSequenceNbr());// 更新单位的上下级
				updateModel.setCompanyType(regUnitInfo.getUnitType());// 更新单位类型
				updateCompanyInfo(tzBaseEnterpriseInfo, updateModel);
				log.info("更新企业信息, 单位 => {}", tzBaseEnterpriseInfo.getUseUnitCode());
				updateUnit(map, regUnitInfo, agencyUserModel, updateModel);
				log.info("更新企业信息, 注册用户 => {}", tzBaseEnterpriseInfo.getUseUnitCode());
				updateUserInfo(newData, useCode);
				// 同步平台并且刷新历史数据
				TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto = new TzBaseEnterpriseInfoDto();
				BeanUtils.copyProperties(tzBaseEnterpriseInfo, tzBaseEnterpriseInfoDto);
				// 更新完成后清理缓存
				redisUtil.del(RedisKey.buildReginRoleKey(agencyUserModel.getUserId()));
				publisher.publish(new DataRefreshEvent(this,  Collections.singletonList(tzBaseEnterpriseInfo.getSequenceNbr() + ""), DataRefreshEvent.DataType.enterprise.name(), DataRefreshEvent.Operation.UPDATE));
				return tzBaseEnterpriseInfoDto;
			} else {
				return null;
			}
		} catch (Exception e) {
			if (!ValidationUtil.isEmpty(olrRegUnitInfo)) {
				regUnitInfoService.updateBySeq(olrRegUnitInfo);
			}
			log.error("更新企业信息失败: ", e);
			throw new BadRequest("更新企业信息失败！");
		}
	}

	@Transactional (rollbackFor = Exception.class)
	@Override
	public TzIndividualityDto personalInfoUpdateById(Map<String, Object> map) {
		return userInfoService.personalInfoUpdateById((Map<String, Object>) map.get("raw"));
	}

    public void updateCompanyInfo(TzBaseEnterpriseInfo tzBaseEnterpriseInfo, CompanyModel updateModel) {
		FeignClientResult<CompanyModel> companyResult = Privilege.companyClient.update(updateModel, updateModel.getSequenceNbr());
		if (companyResult == null || companyResult.getStatus() != 200) {
			log.error("更新单位错误: {}", companyResult);
			throw new BadRequest("更新单位失败！");
		}
		String newOrgCode = Optional.ofNullable(companyResult.getResult()).map(CompanyModel::getOrgCode).orElse(null);
		updateModel.setOrgCode(newOrgCode);
		// 更新企业的org_code
		UpdateWrapper<TzBaseEnterpriseInfo> updateWrapper = new UpdateWrapper<>();
		updateWrapper.set("org_code", newOrgCode);
		updateWrapper.eq("sequence_nbr", tzBaseEnterpriseInfo.getSequenceNbr());
		this.update(updateWrapper);
	}

	private void handleUnitType(Map<String, Object> map, RegUnitInfo regUnitInfo, AgencyUserModel agencyUserModel) {
		Object unitTypeCodesObj = map.get("unitTypeCodes");
		if (!(unitTypeCodesObj instanceof List<?>)) {
			return;
		}
		@SuppressWarnings("unchecked")
		List<String> unitTypeCodes = (List<String>) unitTypeCodesObj;
		if (ValidationUtil.isEmpty(unitTypeCodes)) {
			return;
		}

		List<DataDictionary> unitTypeList = regUnitInfoService.setAndGetUnitTypeList();
		if (unitTypeList == null || unitTypeList.isEmpty()) {
			return;
		}

		Map<String, DataDictionary> dataDictionaryMap = unitTypeList.stream()
																	.collect(Collectors.toMap(DataDictionary::getCode, Function.identity(), (k1, k2) -> k1));

		List<String> unitTypeNameList = unitTypeCodes.stream()
													 .map(dataDictionaryMap::get)
													 .filter(Objects::nonNull)
													 .map(DataDictionary::getName)
													 .collect(Collectors.toList());

		String unitTypeNames = String.join(",", unitTypeNameList);
		String unitTypeCodesStr = String.join(",", unitTypeCodes);

		regUnitInfo.setUnitType(unitTypeNames);
		regUnitInfo.setUnitTypeCode(unitTypeCodesStr);

		// 省内充装单位1231：生成对接数据账号
		// final String FILLING_UNIT_TYPE = RegUnitInfoServiceImpl.FILLING_UNIT_TYPE;
		// if (unitTypeCodes.contains(FILLING_UNIT_TYPE)
		// 		&& (ValidationUtil.isEmpty(regUnitInfo.getIsNationwide()) || "0".equals(regUnitInfo.getIsNationwide()))) {
		if (ValidationUtil.isEmpty(regUnitInfo.getIsNationwide()) || "0".equals(regUnitInfo.getIsNationwide())) {
			if (ValidationUtil.isEmpty(regUnitInfo.getAppId())) {
				String appId = DesUtil.encode(regUnitInfo.getAdminUserId(), RegUnitInfoServiceImpl.SECRETKEY);

				if (agencyUserModel == null) {
					AgencyUserModel shadowUser = new AgencyUserModel();
					shadowUser.setUserId(regUnitInfo.getAdminUserId());
					shadowUser.setUserName(appId);
					shadowUser.setPassword(RegUnitInfoServiceImpl.DEFAULT_PASSWORD);
					try {
						Privilege.agencyUserClient.createLoginInfoAppId(shadowUser);
					} catch (Exception e) {
						// 记录日志并保留原始异常
						log.error("创建登录信息失败", e);
						throw new RuntimeException("创建登录信息失败", e);
					}
				}

				regUnitInfo.setAppId(appId);
			}
		}
	}

	private void updateUnit(Map<String, Object> map, RegUnitInfo regUnitInfo, AgencyUserModel agencyUserModel, CompanyModel companyInfo) {
		List<String> unitTypeCodes = (List<String>) map.get("unitTypeCodes");
		if (ValidationUtil.isEmpty(unitTypeCodes)) {
			return;
		}
		// 2.更新管理员的角色
		Set<String> appCodesSet = new HashSet<>();
		Map<Long, List<Long>> roleSeqMap = new HashMap<>();
		Map<Long, List<RoleModel>> orgRoles = new HashMap<>();
		List<RoleModel> userRoleList = new ArrayList<>();
		List<Long> roleIds = new ArrayList<>();
		Set<String> roleNameSet = new HashSet<>();

		FeignClientResult<List<RoleModel>> roleListResult = Privilege.roleClient.queryRoleList(null, null);
		List<RoleModel> roleModels = roleListResult.getResult();

		List<DataDictionary> unitTypeList = regUnitInfoService.setAndGetUnitTypeList();
		Map<String, DataDictionary> dataDictionaryMap = unitTypeList.stream().collect(Collectors.toMap(DataDictionary::getCode, Function.identity(), (k1, k2) -> k1));
		for (String typeCode : unitTypeCodes) {
			DataDictionary unitType = dataDictionaryMap.get(typeCode);
			String appCode = unitType.getTypeDesc() != null ? unitType.getTypeDesc() : "";
			String[] appCodes = appCode.split(",");
			Collections.addAll(appCodesSet, appCodes);
			roleNameSet.add(unitType.getName());
			userRoleList.addAll(roleModels.stream()
										   .filter(r -> unitType.getExtend().contains(r.getSequenceNbr().toString())).collect(Collectors.toList()));
			userRoleList.forEach(r -> {
				if (!roleIds.contains(r.getSequenceNbr())) {
					roleIds.add(r.getSequenceNbr());
				}
			});
			roleSeqMap.put(companyInfo.getSequenceNbr(), roleIds);
			orgRoles.put(companyInfo.getSequenceNbr(), userRoleList);
		}

		agencyUserModel.setAppCodes(new ArrayList<>(appCodesSet));
		agencyUserModel.setOrgRoles(orgRoles);
		agencyUserModel.setOrgRoleSeqs(roleSeqMap);
		FeignClientResult<AgencyUserModel> userResult = Privilege.agencyUserClient.update(agencyUserModel, regUnitInfo.getAdminUserId());
		System.out.println(userResult);
		if (userResult == null || userResult.getResult() == null) {
			throw new BadRequest("单位更新失败");
		}
	}

	/**
	 * 同步平台并且刷新历史数据
	 *
	 *
	 * @param useCode useCode
	 * @author yangyang
	 * @date 2025/7/1 14:50
	 */
	@Deprecated
	public void asyncPlatformAndRefreshHistoricalData(String useCode) {
		// 同步平台ORG_CODE
		LambdaQueryWrapper<TzsUserInfo> lambda = new QueryWrapper<TzsUserInfo>().lambda();
		lambda.eq(TzsUserInfo::getUnitCode, useCode);
		lambda.isNotNull(TzsUserInfo::getAmosUserId);
		List<TzsUserInfo> tzsUserInfos = tzsUserInfoMapper.selectList(lambda);
		// 异步刷新历史数据
		String token = RequestContext.getToken();
		String appKey = RequestContext.getAppKey();
		String product = RequestContext.getProduct();

		threadPoolTaskExecutor.execute(() -> {
			RequestContext.setToken(token);
			RequestContext.setAppKey(appKey);
			RequestContext.setProduct(product);

			try {
				// 刷新平台的企业下面用户的super_org_code
				if (!ValidationUtil.isEmpty(tzsUserInfos)) {
					String userIds = tzsUserInfos.stream().map(TzsUserInfo::getAmosUserId).collect(Collectors.joining(","));
					FeignClientResult<List<AgencyUserModel>> agencyUserClientResult = Privilege.agencyUserClient.queryByIds(userIds, false);
					if (agencyUserClientResult != null && agencyUserClientResult.getResult() != null) {
						List<AgencyUserModel> agencyUserModels = agencyUserClientResult.getResult();
						for (AgencyUserModel userModel : agencyUserModels) {
							// 更新, 刷新企业下用户的super_org_code
							try {
								Privilege.agencyUserClient.update(userModel, userModel.getUserId());
							} catch (Exception e) {
								log.error("更新用户 {} 的 super_org_code 失败", userModel.getUserId(), e);
							}
						}
					}
				}
			} catch (Exception e) {
				log.error("异步刷新企业用户信息发生异常", e);
			} finally {
				RequestContext.clean();
			}
		});

	}

	/**
	 * 平台编辑单位层级信息后, 异步通知, 刷新tz_base_enterprise_info表org_code
	 * 同时更新其他表缓存的企业org_code
	 *
	 * @param dataResult dataResult
	 * @author yangyang
	 * @date 2025/7/3 14:03
	 */
	@Override
	@Async
	@Transactional(rollbackFor = Exception.class)
	public void refreshCompanyInfo(JSONObject dataResult, String method) {
		try {
			CompanyBo companyBo = JSON.parseObject(dataResult.toJSONString(), CompanyBo.class);
			// 调用平台获取子单位
			platformTokenService.setRequestContext(); // 异步调用需要设置请求上下文
			FeignClientResult<List<CompanyModel>> result = Privilege.companyClient.queryListByOrgCode(companyBo.getOrgCode());
			if (result == null || result.getResult() == null) {
				log.error("平台获取子单位失败");
				return;
			}
			List<CompanyModel> companyModels = result.getResult().stream().filter(i -> !i.getCompanyType().equals("监管机构") && !i.getCompanyType().equals("行政审批局")).collect(Collectors.toList());

			// 如果消息中的单位是企业
			if (!companyBo.getCompanyType().equals("监管机构") && !companyBo.getCompanyType().equals("行政审批局")) {
				switch (Objects.requireNonNull(PlatformOpMethodTypeEnum.getEnumByCode(method))) {
					case CREATE:
					case INSERT:
					case DELETE:
						// 暂无操作
						break;
					case UPDATE:
						// 更新企业单位对应业务表冗余信息
						updateCompanyInfo(companyModels);
						break;
				}
			}
		} catch (Exception e) {
			willInfo("refreshCompanyInfo", dataResult, method, e);
			e.printStackTrace();
			log.error("刷新企业信息发生异常", e);
		}
	}

	private void willInfo(String willKey, JSONObject dataResult, String method, Exception e) {
		Map<String, Object> willInfo = new HashMap<>();
		willInfo.put("dataResult", dataResult);
		willInfo.put("method", method);
		willInfo.put("errorMessage", e.getMessage());
		redisUtil.set(willKey + "_" + System.currentTimeMillis(), JSONObject.toJSONString(willInfo));
	}

	/**
	 * 平台编辑监管单位层级信息后, 异步通知, 刷新tz_base_enterprise_info表orgCode
	 * 同时更新其他表缓存的监管单位orgCode
	 *
	 * @param newOrgCode 新orgCode
	 * @param oldOrgCode 旧orgCode
	 *
	 */
	@Override
	@Transactional
	@Async
	public void refreshSupervisionOrgCode(JSONObject dataResult, String newOrgCode, String oldOrgCode) {
		log.info("开始刷新监管单位orgCode：{}", dataResult);
		try {
			if (!ValidationUtil.isEmpty(newOrgCode) && !ValidationUtil.isEmpty(oldOrgCode) && !newOrgCode.equals(oldOrgCode)) {
				JSONObject newModel = (JSONObject) dataResult.get("newModel");
				String companyLevel = newModel.getString("level");
				log.info("监管单位信息：{}", newModel);
				if (!CompanyLevelEnum.COMPANY.getCode().equals(companyLevel)) {// 只处理监管单位，企业的orgCode变更在refreshCompanyInfo中处理
					// 1. 查询旧属地监管部门orgCode对应所有的公司
					List<String> companySeqList = tzBaseEnterpriseInfoMapper.selectCompanyBySupervisionOrgCode(oldOrgCode);
					// 2. 查询旧属地监管部门orgCode对应的所有设备
					List<String> equipmentRecordList = tzBaseEnterpriseInfoMapper.selectEquipmentBySupervisionOrgCode(oldOrgCode);
					log.info("start-查询旧属地监管部门orgCode对应的所有设备equipmentRecordList：{}，companySeqList：{}", equipmentRecordList.size(), companySeqList.size());
					// 3. 3.1 更新单位及业务表的监管单位orgCode
					tzBaseEnterpriseInfoMapper.updateRedundantSupervisionOrgCodeUnit(newModel.getString("companyName"), newOrgCode, oldOrgCode);
					// 3.2 更新业务表统计表冗余的监管单位orgCode
					tzBaseEnterpriseInfoMapper.updateRedundantSupervisionOrgCodeStatistics(newOrgCode, oldOrgCode);
					log.info("end-查询旧属地监管部门orgCode对应的所有设备equipmentRecordList：{}，companySeqList：{}", equipmentRecordList.size(), companySeqList.size());
					// 4. 更新idx_biz_view_jg_all es设备信息
					updateEquipmentJgAllEs(newOrgCode, oldOrgCode, equipmentRecordList, newModel.getString("companyName"));
					// 5. 更新idx_biz_enterprise_info es企业信息
					updateEnterpriseInfoEs(newOrgCode, oldOrgCode, companySeqList);
					// 6. 更新idx_biz_equipment_info es设备信息
					updateEquipmentInfoEs(newOrgCode, oldOrgCode, equipmentRecordList);
				}
			}
		} catch (Exception e) {
			willInfo("refreshSupervisionOrgCode", dataResult, "orgCodeUpdate", e);
			log.error("刷新监管单位orgCode发生异常", e);
		}
		log.info("刷新监管单位orgCode结束");
	}

	private void updateEquipmentInfoEs(String newOrgCode, String oldOrgCode, List<String> equipmentRecordList) {
		log.info("开始更新idx_biz_equipment_info es设备属地监管部门信息，新orgCode{}, 旧orgCode:{}", newOrgCode, oldOrgCode);
		if (!ValidationUtil.isEmpty(equipmentRecordList)) {
			updateEsInfo(newOrgCode, oldOrgCode, equipmentRecordList, esEquipmentDao::findAllById, ESEquipmentInfo::setORG_BRANCH_CODE, ESEquipmentInfo::getORG_BRANCH_CODE, esEquipmentDao::saveAll);
		}
		log.info("更新idx_biz_equipment_info es设备属地监管部门信息结束");
	}

	private void updateEnterpriseInfoEs(String newOrgCode, String oldOrgCode, List<String> companySeqList) {
		log.info("开始更新idx_biz_enterprise_info es企业属地监管部门信息，新orgCode{}, 旧orgCode:{}", newOrgCode, oldOrgCode);
		if (!ValidationUtil.isEmpty(companySeqList)) {
			updateEsInfo(newOrgCode, oldOrgCode, companySeqList, esBaseEnterpriseInfoDao::findAllById, EsBaseEnterpriseInfo::setSuperviseOrgCode, EsBaseEnterpriseInfo::getSuperviseOrgCode, esBaseEnterpriseInfoDao::saveAll);
		}
		log.info("更新idx_biz_enterprise_info es设备属地监管部门信息结束");
	}

	private <T> void updateEsInfo(String newOrgCode, String oldOrgCode, List<String> recordList,
								  Function<List<String>, Iterable<T>> findAllByIdFunc,
								  BiConsumer<T, String> updateOrgCodeFunc,
								  Function<T, String> getOrgCodeFunc,
								  Consumer<List<T>> saveAllFunc) {
		log.info("待更新es recordList数量：{}", recordList.size());
		int batchSize = 1000;
		for (int i = 0; i < recordList.size(); i += batchSize) {
			int endIndex = Math.min(i + batchSize, recordList.size());
			List<String> subList = recordList.subList(i, endIndex);

			Iterable<T> recordIterator = findAllByIdFunc.apply(subList);
			List<T> updatedRecord = new ArrayList<>();

			recordIterator.forEach(record -> {
				String equipOrgBranchCode = getOrgCodeFunc.apply(record);
				if (ValidationUtil.isEmpty(equipOrgBranchCode)) {
					updateOrgCodeFunc.accept(record, newOrgCode); // 补偿旧数据es属地监管部门为空，则用数据库中设备属地监管部门更新
				} else {
					String updatedOrgCode = equipOrgBranchCode.replace(oldOrgCode, newOrgCode);
					updateOrgCodeFunc.accept(record, updatedOrgCode);
				}
				updatedRecord.add(record);
			});

			if (!updatedRecord.isEmpty()) {
				log.info("待更新updatedRecord数量：{}", updatedRecord.size());
				saveAllFunc.accept(updatedRecord);
			}
		}
	}

	private void updateEquipmentJgAllEs(String newOrgCode, String oldOrgCode, List<String> equipmentRecordList, String supervisionName) {
		log.info("开始更新idx_biz_view_jg_all es设备属地监管部门信息，新orgCode{}, 旧orgCode:{}", newOrgCode, oldOrgCode);
		if (!ValidationUtil.isEmpty(equipmentRecordList)) {
			updateEsInfo(newOrgCode, oldOrgCode, equipmentRecordList, esEquipmentCategory::findAllById, ESEquipmentCategoryDto::setOrgBranchCode, ESEquipmentCategoryDto::getOrgBranchCode, esEquipmentCategory::saveAll);
		}
		// 根据旧属地监管部门orgCode查找es对应设备，更新数据库中设备属地字段
		List<ESEquipmentCategoryDto> esEquipmentCategoryList = esEquipmentCategory.findByOrgBranchCodeKeywordStartingWith(oldOrgCode);
		if (!ValidationUtil.isEmpty(esEquipmentCategoryList)) {
			List<String> esRecordList = Lists.newArrayList();
			List<ESEquipmentCategoryDto> updatedEsDtoList = ValidationUtil.isEmpty(equipmentRecordList) ? esEquipmentCategoryList : esEquipmentCategoryList.stream().filter(esDto -> !equipmentRecordList.contains(esDto.getSEQUENCE_NBR())).collect(Collectors.toList());
			log.info("开始更新es设备有属地监管部门，数据库无属地监管部门的设备信息。需更新数据{}条", updatedEsDtoList.size());
			if (!ValidationUtil.isEmpty(updatedEsDtoList)) {
				updatedEsDtoList.forEach(esDto -> {
					esDto.setOrgBranchCode(esDto.getOrgBranchCode().replace(oldOrgCode, newOrgCode));
					esDto.setORG_BRANCH_NAME(supervisionName);
					esRecordList.add(esDto.getSEQUENCE_NBR());
				});
				int batchSize = 1000;
				for (int i = 0; i < updatedEsDtoList.size(); i += batchSize) {
					int endIndex = Math.min(i + batchSize, updatedEsDtoList.size());
					List<ESEquipmentCategoryDto> subList = updatedEsDtoList.subList(i, endIndex);
					esEquipmentCategory.saveAll(subList);
					log.info("es jgAll表本批次更新数据{}条", subList.size());
				}
				for (int i = 0; i < esRecordList.size(); i += batchSize) {
					int endIndex = Math.min(i + batchSize, esRecordList.size());
					List<String> subList = esRecordList.subList(i, endIndex);
					tzBaseEnterpriseInfoMapper.updateEquipmentSupervisionOrgCode(newOrgCode, supervisionName, subList);
					log.info("数据库supervision表本批次更新数据{}条", subList.size());
				}
			}
			log.info("更新数据库设备有属地监管部门，数据库无属地监管部门的设备结束");
		}
		log.info("更新idx_biz_view_jg_all es设备属地监管部门信息结束");
	}

	/**
	 * 分批发布数据刷新事件
	 * @param dataIds 数据ID列表
	 * @param dataType 数据类型
	 * @param batchSize 批次大小
	 */
	private void publishDataRefreshEvents(List<String> dataIds, DataRefreshEvent.DataType dataType, int batchSize) {
		if (ValidationUtil.isEmpty(dataIds)) {
			return;
		}
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
			@Override
			public void afterCommit() {
				log.info("开始发布数据刷新事件");
				int total = dataIds.size();
				int pages = (total + batchSize - 1) / batchSize; // 计算总页数

				for (int page = 0; page < pages; page++) {
					int fromIndex = page * batchSize;
					int toIndex = Math.min((page + 1) * batchSize, total);
					List<String> subList = dataIds.subList(fromIndex, toIndex);

					if (!ValidationUtil.isEmpty(subList)) {
						try {
							log.info("开始发布数据刷新事件列表size:{}", subList.size());
							emqKeeper.getMqttClient().publish(String.format(TZSCommonConstant.DATA_REFRESH_TOPIC, dataType.name(), DataRefreshEvent.Operation.UPDATE), JSONObject.toJSONString(subList).getBytes(StandardCharsets.UTF_8), 2, false);
							log.info("发布数据刷新事件列表结束");
						} catch (MqttException e) {
							throw new RuntimeException(e);
						}
					}
					// 休眠50毫秒再发送
					try {
						Thread.sleep(50);
					} catch (InterruptedException e) {
						throw new RuntimeException(e);
					}
				}
				log.info("发布数据刷新事件结束");
			}
		});
	}

	/**
	 * 更新企业单位对应业务表冗余信息
	 * @param companyModels 企业列表
	 */
	private void updateCompanyInfo(List<CompanyModel> companyModels) {
		if (!ValidationUtil.isEmpty(companyModels)) {
			// 只处理非监管机构
			List<String> useCodes = companyModels.stream().map(CompanyModel::getCompanyCode).filter(Objects::nonNull).collect(Collectors.toList());
			Map<String, List<CompanyModel>> companyModelMap = companyModels.stream().collect(Collectors.groupingBy(CompanyModel::getCompanyCode));
			List<TzBaseEnterpriseInfo> tzBaseEnterpriseInfos = tzBaseEnterpriseInfoMapper.selectList(new QueryWrapper<TzBaseEnterpriseInfo>().in("use_code", useCodes));
			// privilege_company 有触发器更新，只需要更新 tz_base_enterprise_info
			int updateCount = 0;
			if (!ValidationUtil.isEmpty(tzBaseEnterpriseInfos)) {
				for (TzBaseEnterpriseInfo tzBaseEnterpriseInfo : tzBaseEnterpriseInfos) {
					String oldOrgCode = tzBaseEnterpriseInfo.getOrgCode();// 旧的org_code
					CompanyModel companyModel = companyModelMap.get(tzBaseEnterpriseInfo.getUseCode()).get(0);
					String newOrgCode = companyModel.getOrgCode();// 新的org_code
					String oldSuperviseOrgCode = tzBaseEnterpriseInfo.getSuperviseOrgCode();
					String newSuperviseOrgCode = companyModel.getOrgCode().replace("*" + companyModel.getCompanyOrgCode(), "");
					// 更新 tz_base_enterprise_info。只有管辖机构有改动才更新
					if (!newOrgCode.equals(oldOrgCode)) {
						HashMap<String, Object> parentMessage = (HashMap<String, Object>) Privilege.companyClient.queryByOrgcode(newSuperviseOrgCode).getResult();
						// 目前平台返回key为compnay(存在拼写错误)
						CompanyModel parentModel = JSON.parseObject(JSON.toJSONString(parentMessage.get("compnay")), CompanyModel.class);

						updateUnitOrgCode(tzBaseEnterpriseInfo, parentModel, oldSuperviseOrgCode, newSuperviseOrgCode, oldOrgCode, newOrgCode);
						updateCount++;
					}
				}
				log.info("刷新企业信息成功，共更新{}条数据", updateCount);
			}
		}
	}

	public void updateUnitOrgCode(TzBaseEnterpriseInfo tzBaseEnterpriseInfo, CompanyModel parentModel, String oldSuperviseOrgCode, String newSuperviseOrgCode, String oldOrgCode, String newOrgCode) {
		tzBaseEnterpriseInfoMapper.updateSubCompanyOrgCode(parentModel.getCompanyName(), oldSuperviseOrgCode, newSuperviseOrgCode, oldOrgCode, newOrgCode, tzBaseEnterpriseInfo.getSequenceNbr());
		tzBaseEnterpriseInfoMapper.updateUnitOrgCode(oldOrgCode, newOrgCode, tzBaseEnterpriseInfo.getUseCode());
		publisher.publish(new DataRefreshEvent(this,  Collections.singletonList(tzBaseEnterpriseInfo.getSequenceNbr() + ""), DataRefreshEvent.DataType.enterprise.name(), DataRefreshEvent.Operation.UPDATE));
	}
}
