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


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.ISpeUseUnitService;
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.entity.RegUnitIc;
import com.yeejoin.amos.boot.module.tzs.flc.biz.service.impl.RegUnitIcServiceImpl;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;

import java.util.*;


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.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;

/**
 * 企业数据信息 服务实现类
 *
 * @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.appkey}")
	String appkey;

	@Autowired
	private TzBaseEnterpriseInfoMapper tzBaseEnterpriseInfoMapper;

	@Autowired
	BaseUnitLicenceServiceImpl baseUnitLicenceService;

	@Autowired
	RegUnitIcServiceImpl regUnitIcService;

	@Autowired
	private IBaseUnitLicenceService iBaseUnitLicenceService;

	@Autowired
	private ISpeUseUnitService speUseUnitService;

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

	@Override
	public IPage<TzBaseEnterpriseInfoDto> page(PageParam pageParam, TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto) {
		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());
		return this.baseMapper.page(page, tzBaseEnterpriseInfoDto);
	}

	@Override
	public TzBaseEnterpriseInfoDto detail(Long id) {
		TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto = new TzBaseEnterpriseInfoDto();
		TzBaseEnterpriseInfo tzBaseEnterpriseInfo = this.getById(id);
		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>();
		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 List<EquEnterDto> getInfoByUseUnit(String userUnit) {
		return tzBaseEnterpriseInfoMapper.getInfoByUseUnit(userUnit);
	}

	@Override
	public TzBaseEnterpriseInfoDto selectByUseUnit(String useUnit) {
		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>();
		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+1;
		for(int i = 0; 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.getAuditOrgName().equals("西安市工商局经开分局") && !speUseUnit.getAuditOrgName().equals("碑林区市场监督管理局")){
					continue;
				}
				if(ValidationUtil.isEmpty(companyMap.get(speUseUnit.getAuditOrgName()))){
					continue;
				}

				TzBaseEnterpriseInfo baseEnterpriseInfo = new TzBaseEnterpriseInfo();
				baseEnterpriseInfo.setUseUnit(speUseUnit.getName());
				baseEnterpriseInfo.setUseCode(speUseUnit.getCerCode());
				baseEnterpriseInfo.setUnitType(speUseUnit.getUnitNature());
				baseEnterpriseInfo.setRegistrationAuthority(speUseUnit.getCerRegiOrg());
				baseEnterpriseInfo.setProvince(speUseUnit.getOffiAddrProvince());
				baseEnterpriseInfo.setCity(speUseUnit.getOffiAddrCity());
				baseEnterpriseInfo.setDistrict(speUseUnit.getOffiAddrArea());
				baseEnterpriseInfo.setStreet(speUseUnit.getOffiAddrStreet());
				baseEnterpriseInfo.setCommunity(speUseUnit.getOffiAddrVillage());
				baseEnterpriseInfo.setAddress(speUseUnit.getOffiAddrDetail());
				baseEnterpriseInfo.setLegalPerson(speUseUnit.getLegalPerson());
				baseEnterpriseInfo.setLegalPhone(speUseUnit.getLegalPersonPhone());
				baseEnterpriseInfo.setUseContact(speUseUnit.getResponPerson());
				baseEnterpriseInfo.setContactPhone(speUseUnit.getResponPersonPhone());
				baseEnterpriseInfo.setIndustry(speUseUnit.getIndustry());
				baseEnterpriseInfo.setSuperviseOrgName(speUseUnit.getAuditOrgName());
				baseEnterpriseInfo.setSuperviseOrgCode(speUseUnit.getAuditOrgCode());
				baseEnterpriseInfo.setOperatingStatus(String.valueOf(speUseUnit.getStatus()));
				baseEnterpriseInfo.setUnitType("使用单位");
				baseEnterpriseInfo.setSuperviseOrgCode(companyMap.get(speUseUnit.getAuditOrgName()).getOrgCode());
				baseEnterpriseInfoList.add(baseEnterpriseInfo);

				CompanyModel companyModel = new CompanyModel();
				String address = speUseUnit.getOffiAddrProvince()+speUseUnit.getOffiAddrCity()+speUseUnit.getOffiAddrArea()+speUseUnit.getOffiAddrStreet()+speUseUnit.getOffiAddrVillage()+speUseUnit.getOffiAddrDetail();
				companyModel.setCompanyName(speUseUnit.getName());
				companyModel.setCompanyCode(speUseUnit.getCerCode());
				companyModel.setLevel("company");
				companyModel.setAgencyCode("tzs");
				companyModel.setCompanyType("使用单位");
				companyModel.setAddress(address);
				companyModel.setParentId(companyMap.get(speUseUnit.getAuditOrgName()).getParentId());

				//保存平台和业务的企业信息
				try {
					Privilege.companyClient.create(companyModel);
					this.save(baseEnterpriseInfo);
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
			}
		}
		return "ok";
	}

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

}
