package com.yeejoin.amos.boot.module.statistcs.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.fasterxml.jackson.databind.ObjectMapper;
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.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.statistics.api.enums.ProblemStatusEnum;
import com.yeejoin.amos.boot.module.statistics.api.dto.TzBaseEnterpriseInfoDto;
import com.yeejoin.amos.boot.module.statistics.api.entity.TzsBaseInstitution;
import com.yeejoin.amos.boot.module.statistics.api.enums.EnterpriseEnums;
import com.yeejoin.amos.boot.module.statistics.api.enums.UnitDataSourceEnum;
import com.yeejoin.amos.boot.module.statistics.api.enums.UnitTypeEnum;
import com.yeejoin.amos.boot.module.statistics.api.feign.AccessFeignService;
import com.yeejoin.amos.boot.module.statistics.api.mapper.EnterpriseBizMapper;
import com.yeejoin.amos.boot.module.statistics.api.mapper.TzsBaseInstitutionMapper;
import com.yeejoin.amos.boot.module.ymt.api.dto.BaseUnitLicenceDto;
import com.yeejoin.amos.boot.module.ymt.api.entity.BaseUnitLicence;
import com.yeejoin.amos.boot.module.statistics.api.entity.TzBaseEnterpriseInfo;
import com.yeejoin.amos.boot.module.ymt.api.mapper.BaseUnitLicenceMapper;
import com.yeejoin.amos.boot.module.ymt.api.mapper.TzBaseEnterpriseInfoMapper;
import com.yeejoin.amos.boot.module.ymt.flc.api.dto.RegUnitIcDto;
import com.yeejoin.amos.boot.module.ymt.flc.api.dto.RegUnitInfoDto;
import com.yeejoin.amos.boot.module.ymt.flc.api.entity.RegUnitIc;
import com.yeejoin.amos.boot.module.ymt.flc.api.entity.RegUnitInfo;
import com.yeejoin.amos.boot.module.ymt.flc.api.mapper.RegUnitIcMapper;
import com.yeejoin.amos.boot.module.ymt.flc.api.mapper.RegUnitInfoMapper;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
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 java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;


/**
 * @author Administrator
 */
@Service
public class EnterpriseBizByTCMServiceImpl {

    public static final String INSPECTION_AND_TESTING_INSTITUTIONS = "检验检测机构";
    public static final String INSPECTION_AGENCY = "检验机构";
    public static final String TESTING_INSTITUTIONS = "检测机构";

    private RedisUtils redisUtils;

    private StCommonServiceImpl stCommonService;

    private TzBaseEnterpriseInfoMapper tzBaseEnterpriseInfoMapper;

    private EnterpriseBizMapper enterpriseBizMapper;

    private TzsBaseInstitutionMapper tzsBaseInstitutionMapper;

    private AccessFeignService accessFeignService;

    private DataDictionaryServiceImpl iDataDictionaryService;

    private BaseUnitLicenceMapper baseUnitLicenceMapper;

    private RegUnitInfoMapper regUnitInfoMapper;

    private RegUnitIcMapper regUnitIcMapper;

    public EnterpriseBizByTCMServiceImpl(RedisUtils redisUtils, StCommonServiceImpl stCommonService,
                                         TzBaseEnterpriseInfoMapper tzBaseEnterpriseInfoMapper,
                                         EnterpriseBizMapper enterpriseBizMapper,
                                         TzsBaseInstitutionMapper tzsBaseInstitutionMapper,
                                         AccessFeignService accessFeignService,
                                         DataDictionaryServiceImpl iDataDictionaryService,
                                         BaseUnitLicenceMapper baseUnitLicenceMapper,
                                         RegUnitInfoMapper regUnitInfoMapper,
                                         RegUnitIcMapper regUnitIcMapper) {
        this.redisUtils = redisUtils;
        this.stCommonService = stCommonService;
        this.tzBaseEnterpriseInfoMapper = tzBaseEnterpriseInfoMapper;
        this.enterpriseBizMapper = enterpriseBizMapper;
        this.tzsBaseInstitutionMapper = tzsBaseInstitutionMapper;
        this.accessFeignService = accessFeignService;
        this.iDataDictionaryService = iDataDictionaryService;
        this.baseUnitLicenceMapper = baseUnitLicenceMapper;
        this.regUnitInfoMapper = regUnitInfoMapper;
        this.regUnitIcMapper = regUnitIcMapper;
    }

    public Map<String, Object> getInfoByUseCodeMap(String useCode) {
        TzBaseEnterpriseInfoDto infoByUseCode = getInfoByUseCode(useCode);
        // 通过sourceId获取问题信息
        Map<String,Object> problemInfo = enterpriseBizMapper.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;
    }

    public TzBaseEnterpriseInfoDto getInfoByUseCode(String useCode) {
        TzBaseEnterpriseInfo tzBaseEnterpriseInfo = enterpriseBizMapper.queryByUseCode(useCode);
        if (ObjectUtils.isEmpty(tzBaseEnterpriseInfo)) {
            return null;
        }
        TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto = getDetail(tzBaseEnterpriseInfo);
        if (!ObjectUtils.isEmpty(tzBaseEnterpriseInfo)){
            LambdaQueryWrapper<TzsBaseInstitution> lambda = new QueryWrapper<TzsBaseInstitution>().lambda();
            lambda.eq(TzsBaseInstitution::getEnterpriseId, tzBaseEnterpriseInfo.getSequenceNbr());
            TzsBaseInstitution tzsBaseInstitution = tzsBaseInstitutionMapper.selectOne(lambda);
            tzBaseEnterpriseInfoDto.setRegUnitMessage(tzsBaseInstitution);
        }
        return ObjectUtils.isEmpty(tzBaseEnterpriseInfo) ? null : tzBaseEnterpriseInfoDto;
    }

    private TzBaseEnterpriseInfoDto getDetail(TzBaseEnterpriseInfo tzBaseEnterpriseInfo){
        TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto = detail(tzBaseEnterpriseInfo.getSequenceNbr());
        if(!ObjectUtils.isEmpty(tzBaseEnterpriseInfo.getOfficeRegion())){
            List<Integer> officeRegion = new ArrayList<>();
            for (String s : tzBaseEnterpriseInfo.getOfficeRegion().split("#")) {
                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())) {
            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;
    }


    public TzBaseEnterpriseInfoDto detail(Long id) {
        TzBaseEnterpriseInfoDto tzBaseEnterpriseInfoDto = new TzBaseEnterpriseInfoDto();
        TzBaseEnterpriseInfo tzBaseEnterpriseInfo = enterpriseBizMapper.queryBySeq(String.valueOf(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 = baseUnitLicenceMapper.selectList(new LambdaQueryWrapper<BaseUnitLicence>()
                .eq(BaseUnitLicence::getUnitCode, tzBaseEnterpriseInfo.getUseCode()));
        List<BaseUnitLicenceDto> unitLicenceDtos = new ArrayList<>();
        List<BaseUnitLicence> unitLicencesCollect;
        if ("监管机构".equals(companyType)) {
            unitLicencesCollect = unitLicences;
        } else {
            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());
            }
            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 = regUnitInfoMapper.selectOne(
                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 = regUnitIcMapper.selectOne(
                new LambdaQueryWrapper<RegUnitIc>().eq(RegUnitIc::getUnitCode, tzBaseEnterpriseInfo.getUseCode()));
        RegUnitIcDto regUnitIcDto = new RegUnitIcDto();
        if (regUnitIc != null) {
            BeanUtils.copyProperties(regUnitIc, regUnitIcDto);
        }
        tzBaseEnterpriseInfoDto.setRegUnitIcDto(regUnitIcDto);
        return tzBaseEnterpriseInfoDto;

    }

    /**
     * 用户选择信心redis获取
     **/
    protected ReginParams getSelectedOrgInfo() {
        return JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
    }


}
