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


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.module.tzs.api.dto.BaseUnitLicenceDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.EquEnterDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.TzBaseEnterpriseInfoDto;
import com.yeejoin.amos.boot.module.tzs.api.entity.BaseUnitLicence;
import com.yeejoin.amos.boot.module.tzs.api.entity.PageParam;
import com.yeejoin.amos.boot.module.tzs.api.entity.SpeUseUnit;
import com.yeejoin.amos.boot.module.tzs.api.entity.TzBaseEnterpriseInfo;
import com.yeejoin.amos.boot.module.tzs.api.mapper.TzBaseEnterpriseInfoMapper;
import com.yeejoin.amos.boot.module.tzs.api.service.IBaseUnitLicenceService;
import com.yeejoin.amos.boot.module.tzs.api.service.ITzBaseEnterpriseInfoService;
import com.yeejoin.amos.boot.module.tzs.biz.utils.RedisUtil;
import com.yeejoin.amos.boot.module.tzs.flc.api.dto.RegUnitIcDto;
import com.yeejoin.amos.boot.module.tzs.flc.api.dto.RegUnitInfoDto;
import com.yeejoin.amos.boot.module.tzs.flc.api.entity.RegUnitIc;
import com.yeejoin.amos.boot.module.tzs.flc.api.entity.RegUnitInfo;
import com.yeejoin.amos.boot.module.tzs.flc.api.feign.AccessFeignService;
import com.yeejoin.amos.boot.module.tzs.flc.api.mapper.RegUnitInfoMapper;
import com.yeejoin.amos.boot.module.tzs.flc.biz.service.impl.RegUnitIcServiceImpl;
import com.yeejoin.amos.boot.module.tzs.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.IdPasswordAuthModel;
import com.yeejoin.amos.feign.privilege.util.DesUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.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 java.text.ParseException;
import java.util.*;

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

	@Autowired
	RedisUtil redisUtil;

	@Value("${admin.product}")
	String product;

	@Value("${admin.product.web}")
	String webProduct;

	@Value("${admin.appkey}")
	String appkey;

	@Autowired
	private TzBaseEnterpriseInfoMapper tzBaseEnterpriseInfoMapper;

	@Autowired
	BaseUnitLicenceServiceImpl baseUnitLicenceService;

	@Autowired
	RegUnitIcServiceImpl regUnitIcService;

	@Autowired
	RegUnitInfoServiceImpl regUnitInfoService;

	@Autowired
	private IBaseUnitLicenceService iBaseUnitLicenceService;

	@Autowired
	private SpeUseUnitServiceImpl speUseUnitService;

	@Autowired
	private AccessFeignService accessFeignService;

    @Autowired
    private ITzBaseEnterpriseInfoService tzBaseEnterpriseInfoService;
	@Autowired
	DataDictionaryServiceImpl iDataDictionaryService;

	@Autowired
	RegUnitInfoMapper regUnitInfoMapper;

	@Value("${tzs.admin.name:tzs_admin}")
	private String tzsAdminName;

	@Value("${tzs.admin.pwd:a1234567}")
	private String tzsAdminPwd;

	@Value("${redis.cache.failure.time}")
	private Long redisRegionTimeSecond;

	/**机器人用户token缓存key */
	public static final String TZS_USER_TOKEN = "TZS_USER_TOKEN";

	/**
	 * 企业管理员变更缓存key前缀
	 */
	private final  String adminChange = "ADMIN_CHANGE_";
	@Autowired
	private EquipmentCategoryServiceImpl equipmentCategoryService;

	@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.setUnitExequatur(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getUnitExequatur()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getUnitExequatur()));
			tzBaseEnterpriseInfoDto.setEquipCategory(ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getEquipCategory()) ? new ArrayList() : JSON.parseArray(tzBaseEnterpriseInfo.getEquipCategory()));
		}
		// 许可信息
		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);
		// 管理员信息
		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 = new RegUnitIcDto();
		Map<String, Object> resultMap = accessFeignService.getData(tzBaseEnterpriseInfoDto.getUseCode()).getResult();
		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")));
			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")));
			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);
		}
		tzBaseEnterpriseInfoDto.setRegUnitIcDto(regUnitIcDto);
		tzBaseEnterpriseInfoDto.setApprovalTime(regUnitIcDto.getApprovedDate());
		return tzBaseEnterpriseInfoDto;
	}

	@Override
	public IPage<TzBaseEnterpriseInfoDto> page(PageParam pageParam, String companyName) {
		TzBaseEnterpriseInfo tzBaseEnterpriseInfo = tzBaseEnterpriseInfoMapper.selectOne(new QueryWrapper<TzBaseEnterpriseInfo>().eq("use_unit", companyName));
		TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto = getDetail(tzBaseEnterpriseInfo);
		ArrayList<TzBaseEnterpriseInfoDto> result = new ArrayList<>();
		result.add(tzBaseEnterpriseInfoDto);
		Page<TzBaseEnterpriseInfoDto> page = new Page<>(pageParam.getCurrent(), pageParam.getSize());
		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() {
		RequestContext.setAppKey(appkey);
		RequestContext.setProduct(product);
		RequestContext.setToken(String.valueOf(redisUtil.get("platform_token")));

		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";
	}

    @Override
    public TzBaseEnterpriseInfoDto companyInfoUpdate(Map<String, Object> map) {
        TzBaseEnterpriseInfo tzBaseEnterpriseInfo = new TzBaseEnterpriseInfo();
        tzBaseEnterpriseInfo.setSequenceNbr(Long.valueOf(map.get("sequenceNbr").toString()));

        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.setUnitExequatur(ObjectUtils.isEmpty(map.get("unitExequatur")) ? null : JSON.toJSONString(map.get("unitExequatur")));
        tzBaseEnterpriseInfo.setIndustrySupervisor(ObjectUtils.isEmpty(map.get("industrySupervisor")) ? null : String.valueOf(map.get("industrySupervisor")));

        tzBaseEnterpriseInfo.setSafetyOne(ObjectUtils.isEmpty(map.get("safetyOne")) ? null : String.valueOf(map.get("safetyOne")));
        tzBaseEnterpriseInfo.setSafetyOneId(ObjectUtils.isEmpty(map.get("safetyOneId")) ? null : String.valueOf(map.get("safetyOneId")));
        tzBaseEnterpriseInfo.setSafetyOnePhone(ObjectUtils.isEmpty(map.get("safetyOnePhone")) ? null : String.valueOf(map.get("safetyOnePhone")));
        tzBaseEnterpriseInfo.setSafetyOnePhoto(ObjectUtils.isEmpty(map.get("safetyOnePhoto")) ? null : JSON.toJSONString(map.get("safetyOnePhoto")));
        tzBaseEnterpriseInfo.setSafetyTwo(ObjectUtils.isEmpty(map.get("safetyTwo")) ? null : String.valueOf(map.get("safetyTwo")));
        tzBaseEnterpriseInfo.setSafetyTwoId(ObjectUtils.isEmpty(map.get("safetyTwoId")) ? null : String.valueOf(map.get("safetyTwoId")));
        tzBaseEnterpriseInfo.setSafetyTwoPhone(ObjectUtils.isEmpty(map.get("safetyTwoPhone")) ? null : String.valueOf(map.get("safetyTwoPhone")));
        tzBaseEnterpriseInfo.setSafetyTwoPhoto(ObjectUtils.isEmpty(map.get("safetyTwoPhoto")) ? null : JSON.toJSONString(map.get("safetyTwoPhoto")));

        tzBaseEnterpriseInfo.setMaintenPerson(ObjectUtils.isEmpty(map.get("maintenPerson")) ? null : String.valueOf(map.get("maintenPerson")));
        tzBaseEnterpriseInfo.setMaintenTelephone(ObjectUtils.isEmpty(map.get("maintenTelephone")) ? null : String.valueOf(map.get("maintenTelephone")));
        tzBaseEnterpriseInfo.setQualityPerson(ObjectUtils.isEmpty(map.get("qualityPerson")) ? null : String.valueOf(map.get("qualityPerson")));
        tzBaseEnterpriseInfo.setQualityTelephone(ObjectUtils.isEmpty(map.get("qualityTelephone")) ? null : String.valueOf(map.get("qualityTelephone")));
        tzBaseEnterpriseInfo.setSqa(ObjectUtils.isEmpty(map.get("sqa")) ? null : String.valueOf(map.get("sqa")));
        tzBaseEnterpriseInfo.setSqaPhone(ObjectUtils.isEmpty(map.get("sqaPhone")) ? null : String.valueOf(map.get("sqaPhone")));
        tzBaseEnterpriseInfo.setTechnicalPerson(ObjectUtils.isEmpty(map.get("technicalPerson")) ? null : String.valueOf(map.get("technicalPerson")));

        boolean b = tzBaseEnterpriseInfoService.updateById(tzBaseEnterpriseInfo);
        if (b) {
            TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto = new TzBaseEnterpriseInfoDto();
            BeanUtils.copyProperties(tzBaseEnterpriseInfo, tzBaseEnterpriseInfoDto);
            return tzBaseEnterpriseInfoDto;
        } else {
            return null;
        }

    }


	public Map<String, Object> adminInfoUpdate(Map<String, Object> map) {
		//每一个企业只有一个管理员，所以当前登录用户即管理员用户
		AgencyUserModel me = Privilege.agencyUserClient.getme().getResult();
		RequestContext.setAppKey(appkey);
		RequestContext.setProduct(webProduct);
		//获取机器人的token，获取不到则去登录
		if (ObjectUtils.isEmpty(redisUtil.get(TZS_USER_TOKEN))) {
			loginCtiUser();
		}
		RequestContext.setToken(String.valueOf(redisUtil.get(TZS_USER_TOKEN)));
		Map<String, Object> resultMap = new HashMap<>();
		if (!ObjectUtils.isEmpty(me)) {
			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(String.valueOf(map.get("adminTel")));
			me.setRealName(String.valueOf(map.get("adminName")));
			FeignClientResult<AgencyUserModel> updateResult = Privilege.agencyUserClient.update(me, String.valueOf(map.get("adminUserId")));
			if (200 == updateResult.getStatus()) {
				regUnitInfoService.update(regUnitInfo, new QueryWrapper<RegUnitInfo>().eq("unit_code", unitCode));
				resultMap.put("success", regUnitInfo);
				redisUtil.del(adminChange + map.get("adminTel"));
			} else {
				resultMap.put("fail", "平台用户修改失败，请联系管理员");
			}
		} else {
			resultMap.put("fail", "平台用户不存在");
		}
		return resultMap;
	}

	//机器人用户登录
	private void loginCtiUser() {
		String passwd = DesUtil.encode(tzsAdminPwd, "qaz");
		IdPasswordAuthModel loninData = new IdPasswordAuthModel();
		loninData.setLoginId(tzsAdminName);
		loninData.setPassword(passwd);
		FeignClientResult loginResult = Privilege.authClient.idpassword(loninData);
		if(loginResult.getStatus() == 200) {
			HashMap resultMap = (HashMap) loginResult.getResult();
			redisUtil.set(TZS_USER_TOKEN,  resultMap.get("token").toString(), redisRegionTimeSecond);
		}
	}


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

}
