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.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
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.tcm.api.dto.BaseUnitLicenceDto;
import com.yeejoin.amos.boot.module.tcm.api.dto.EquEnterDto;
import com.yeejoin.amos.boot.module.tcm.api.dto.TzBaseEnterpriseInfoDto;
import com.yeejoin.amos.boot.module.tcm.api.dto.TzsBaseInstitutionDto;
import com.yeejoin.amos.boot.module.tcm.api.entity.*;
import com.yeejoin.amos.boot.module.tcm.api.enums.EnterpriseEnums;
import com.yeejoin.amos.boot.module.tcm.api.enums.UnitTypeEnum;
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.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.enums.UnitDataSourceEnum;
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 org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
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 java.sql.Array;
import java.text.ParseException;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 企业数据信息 服务实现类
 *
 * @author duanwei
 * @date 2022-08-10
 */
@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 String adminChange = "ADMIN_CHANGE_";
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    BaseUnitLicenceServiceImpl baseUnitLicenceService;

    @Autowired
    RegUnitIcServiceImpl regUnitIcService;

    @Autowired
    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 ITzBaseEnterpriseInfoService tzBaseEnterpriseInfoService;
    @Autowired
    private TzsUserInfoMapper tzsUserInfoMapper;
    @Autowired
    private EquipmentCategoryServiceImpl equipmentCategoryService;

	/**
	 * 用户选择信心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) {
		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());
			}
		}
		Page<TzBaseEnterpriseInfoDto> page = new Page<>(pageParam.getCurrent(), pageParam.getSize());
		List<JSONObject> companyType1 = equipmentCategoryService.getCompanyType();
		if (!ValidationUtil.isEmpty(companyType1)) {
			for (JSONObject jsonObject : companyType1) {
				String orgCode = jsonObject.getString("orgCode");
				if (!ValidationUtil.isEmpty(orgCode)) {
					orgCodeList.add(orgCode);
				}
			}
		}

		return this.baseMapper.pageList(page, tzBaseEnterpriseInfoDto,orgCodeList);
	}

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

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

		// 当前用户选择角色的许可信息（使用。。安改维。。检验检测。。）
		List<BaseUnitLicence> unitLicences = baseUnitLicenceService.list(new LambdaQueryWrapper<BaseUnitLicence>()
				.eq(BaseUnitLicence::getUnitCode, tzBaseEnterpriseInfo.getUseCode()));
		List<BaseUnitLicenceDto> unitLicenceDtos = new ArrayList<>();
		Predicate<BaseUnitLicence> certTypePredicate;
		if (INSPECTION_AND_TESTING_INSTITUTIONS.equals(companyType)) {
			certTypePredicate = baseUnitLicence -> INSPECTION_AGENCY.equals(baseUnitLicence.getCertType()) ||
					TESTING_INSTITUTIONS.equals(baseUnitLicence.getCertType());
		} else {
			certTypePredicate = baseUnitLicence -> companyType.contains(baseUnitLicence.getCertType());
		}
		List<BaseUnitLicence> unitLicencesCollect = unitLicences.stream()
				.filter(certTypePredicate)
				.collect(Collectors.toList());
		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;

	}

	@Override
	public TzBaseEnterpriseInfoDto getInfoByUseCode(String useCode) {
		TzBaseEnterpriseInfo tzBaseEnterpriseInfo = tzBaseEnterpriseInfoMapper.selectOne(new QueryWrapper<TzBaseEnterpriseInfo>().eq("use_code", useCode));
		return ObjectUtils.isEmpty(tzBaseEnterpriseInfo) ? null : getDetail(tzBaseEnterpriseInfo);
	}

	private TzBaseEnterpriseInfoDto getDetail(TzBaseEnterpriseInfo tzBaseEnterpriseInfo){
		TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto = detail(tzBaseEnterpriseInfo.getSequenceNbr());
		RegUnitIcDto regUnitIcDto = tzBaseEnterpriseInfoDto.getRegUnitIcDto();
		String creditCode = tzBaseEnterpriseInfoDto.getUseCode();
		if (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())) {
			Map<String, Object> resultMap = accessFeignService.getData(creditCode).getResult();
			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")));
			String approve = approveDate.substring(0, 10) + "核准";
			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");
			// 判断是否可以让用户编辑工商及许可信息 事业单位、个人主体或省外企业都可编辑
			tzBaseEnterpriseInfoDto.setCanEdit("0");
			tzBaseEnterpriseInfoDto.setLicenseCanEdit("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;
	}

	@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);
		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 = accessFeignService.getData(speUseUnit.getCerCode()).getResult();

					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) {
		TzBaseEnterpriseInfo tzBaseEnterpriseInfo = new TzBaseEnterpriseInfo();
		tzBaseEnterpriseInfo.setSequenceNbr(Long.valueOf(map.get("sequenceNbr").toString()));
		tzBaseEnterpriseInfo = tzBaseEnterpriseInfoService.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"));

		// 修改事业单位信息
		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");
			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.setAddress(ObjectUtils.isEmpty(map.get("regAddress")) ? null : String.valueOf(map.get("regAddress")));
			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 {
				approvedDate = DateUtils.dateParse(String.valueOf(map.get("approvedDate")), "yyyy-MM-dd");
			} catch (ParseException e) {
				throw new RuntimeException(e);
			}
			regUnitIc.setBusinessStateCode(ObjectUtils.isEmpty(map.get("businessState")) ? null : String.valueOf(map.get("businessState")));
			DataDictionary businessStateDict = iDataDictionaryService.getByCode(String.valueOf(map.get("businessState")),"jyzt");
			regUnitIc.setBusinessState(ObjectUtils.isEmpty(businessStateDict) ? null : businessStateDict.getName());
			regUnitIc.setApprovedDate(ObjectUtils.isEmpty(map.get("approvedDate")) ? null : approvedDate);

			regUnitIcService.update(regUnitIc, new QueryWrapper<RegUnitIc>().eq("unit_code", regUnitIcDto.getUnitCode()));
		}

		//修改许可信息
		List<BaseUnitLicence> licences = Lists.newArrayList();
		JSON.parseArray(JSON.toJSONString(map.get("unitLicences"))).forEach(obj -> {
			BaseUnitLicence baseUnitLicence = JSON.toJavaObject((JSONObject )obj, BaseUnitLicence.class);
			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);
			licences.add(baseUnitLicence);
		});
		baseUnitLicenceService.saveOrUpdateBatch(licences);
		// 企业信息变更-同步修改企业下人员绑定设备类型
		ArrayList<String> newData = new ArrayList<>();
		JSONArray objects = JSON.parseArray(tzBaseEnterpriseInfo.getEquipCategory());
		objects.forEach(item ->{
			newData.add(item.toString());
		});
        boolean b = tzBaseEnterpriseInfoService.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);
			return tzBaseEnterpriseInfoDto;
        } else {
            return null;
        }

    }

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


	    // 根据新的单位类型代码查询许可证书类型名称
		Optional<String> certTypeOptional;
		if (INSPECTION_AND_TESTING_INSTITUTIONS.equals(companyType)) {
			certTypeOptional = Optional.of(baseUnitLicence.getCertType());
		} else {
			certTypeOptional = dictionaries.stream()
					.filter(d -> "UNIT_TYPE_NEW".equals(d.getType()) && baseUnitLicence.getCertTypeCode().startsWith(d.getCode()))
					.map(DataDictionary::getName)
					.findFirst();
		}
		// 设置许可证书类型
		certTypeOptional.ifPresent(baseUnitLicence::setCertType);

        // 查询项目代码对应的名称
        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);
	}

	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);
		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);
					}
					tzsUserInfoMapper.updateById(item);
				}
			}
		});
	}

	@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) {
		//每一个企业只有一个管理员，所以当前登录用户即管理员用户
		AgencyUserModel me = Privilege.agencyUserClient.getme().getResult();
		//自己不能修改自己 所以需要设置为机器人
		platformTokenService.setRequestContext();
		Map<String, Object> resultMap = new HashMap<>();
		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")));
		try {
			Privilege.agencyUserClient.update(me, me.getUserId());
			regUnitInfoService.update(regUnitInfo, new LambdaQueryWrapper<RegUnitInfo>().eq(RegUnitInfo::getUnitCode, unitCode));
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			throw new BadRequest(e.getMessage());
		}
		resultMap.put("success", regUnitInfo);
		redisUtil.del(adminChange + map.get("adminTel"));
		return resultMap;
	}

	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);

	}
}
