package com.hz.pm.api.common.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hz.pm.api.common.helper.RegionCacheHelper;
import com.hz.pm.api.expert.controller.ExpertController;
import com.hz.pm.api.expert.model.*;
import com.hz.pm.api.expert.model.req.ExpertRegistrationRequest;
import com.hz.pm.api.meta.constant.DictTypeEnum;
import com.hz.pm.api.meta.constant.ExpertTagEnum;
import com.hz.pm.api.meta.helper.DictionaryCache;
import com.hz.pm.api.meta.helper.TagCache;
import com.hz.pm.api.meta.model.ExpertRegionInfo;
import com.hz.pm.api.meta.model.dto.DictionaryDTO;
import com.hz.pm.api.meta.model.dto.TagDTO;
import com.hz.pm.api.organization.model.entity.DingOrganization;
import com.hz.pm.api.organization.service.IDingOrganizationService;
import com.hz.pm.api.sys.model.dto.RegionDTO;

import java.io.File;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * ExpertRegisterUtil
 * </p>
 *
 * @author WendyYang
 * @since 10:03 2023/11/21
 */
public class ExpertRegisterUtil {

    private ExpertRegisterUtil() {
    }

    private static final String SEPARATOR = "，|,|\\n";

    public static RegionCacheHelper regionCacheHelper;
    public static DictionaryCache dictionaryCache;
    public static IDingOrganizationService organizationService;
    public static TagCache tagCache;
    public static ExpertController expertController;

    public static void registerExpertBatch(String path) {
        ExcelReader reader = ExcelUtil.getReader(new File(path));
        List<Map<String, Object>> experts = reader.readAll();
        experts.forEach(w -> {
            ExpertRegistrationRequest request = new ExpertRegistrationRequest();
            ExpertBasicInfo basic = new ExpertBasicInfo();
            basic.setBank(MapUtil.getStr(w, "开户行"));
            basic.setBankNo(MapUtil.getStr(w, "银行卡号"));
            basic.setName(MapUtil.getStr(w, "*姓名"));
            basic.setPhoneNo(MapUtil.getStr(w, "*手机"));
            basic.setGender("男".equals(MapUtil.getStr(w, "性别")) ? "1" : "0");
            // 政治面貌
            basic.setPolitical(new ArrayList<>());
            String political = MapUtil.getStr(w, "政治面貌");
            List<DictionaryDTO> politicalDicts = dictionaryCache.listDictByDictType(DictTypeEnum.POLITICAL.getKey());
            if (!politicalDicts.isEmpty()) {
                politicalDicts.stream()
                        .filter(dict -> dict.getName().equals(political))
                        .findFirst().ifPresent(dictionary -> {
                            DictFieldInfoDTO dict = new DictFieldInfoDTO();
                            dict.setDictionaryName(dictionary.getName());
                            dict.setDictionaryCode(dictionary.getDictionaryCode());
                            dict.setDictionaryFieldName(dictionary.getDictionaryType());
                            basic.getPolitical().add(dict);
                        });
            }
            ExpertEduInfo eduInfo = new ExpertEduInfo();
            eduInfo.setSchool("暂无");
            eduInfo.setAcademicTitle("暂无");
            eduInfo.setGraduatedAt(LocalDate.now());
            eduInfo.setEdu(new ArrayList<>());
            eduInfo.setDegree(new ArrayList<>());
            // 学历
            String eduStr = MapUtil.getStr(w, "学历");
            List<DictionaryDTO> eduDicts = dictionaryCache.listDictByDictType(DictTypeEnum.EDU.getKey());
            if (!eduDicts.isEmpty()) {
                eduDicts.stream()
                        .filter(dict -> dict.getName().equals(eduStr))
                        .findFirst().ifPresent(dictionary -> {
                            DictFieldInfoDTO dict = new DictFieldInfoDTO();
                            dict.setDictionaryName(dictionary.getName());
                            dict.setDictionaryCode(dictionary.getDictionaryCode());
                            dict.setDictionaryFieldName(dictionary.getDictionaryType());
                            eduInfo.getEdu().add(dict);
                        });
            }
            // 学位
            String degreeStr = MapUtil.getStr(w, "学位");
            List<DictionaryDTO> degreeDicts = dictionaryCache.listDictByDictType(DictTypeEnum.DEGREE.getKey());
            if (!degreeDicts.isEmpty()) {
                degreeDicts.stream()
                        .filter(dict -> dict.getName().equals(degreeStr))
                        .findFirst().ifPresent(dictionary -> {
                            DictFieldInfoDTO dict = new DictFieldInfoDTO();
                            dict.setDictionaryName(dictionary.getName());
                            dict.setDictionaryCode(dictionary.getDictionaryCode());
                            dict.setDictionaryFieldName(dictionary.getDictionaryType());
                            eduInfo.getDegree().add(dict);
                        });
            }
            request.setEduInfo(eduInfo);
            // 专家层级
            String expertRegionStr = MapUtil.getStr(w, "*专家层级").replace("景宁县", "景宁畲族自治县");
            RegionDTO expertRegion = regionCacheHelper.getByRegionName(expertRegionStr);
            if (expertRegion != null) {
                basic.setExpertRegionInfo(BeanUtil.copyProperties(expertRegion, ExpertRegionInfo.class));
            }
            // 履职意向
            String intentionRegions = MapUtil.getStr(w, "*履职意向").replace("景宁县", "景宁畲族自治县");
            basic.setExpertIntentionWorkRegions(new ArrayList<>());
            for (String intentionRegionStr : intentionRegions.split("")) {
                RegionDTO currRegion = regionCacheHelper.getByRegionName(intentionRegionStr);
                if (currRegion != null) {
                    basic.getExpertIntentionWorkRegions().add(BeanUtil.copyProperties(currRegion, ExpertRegionInfo.class));
                }
            }
            request.setBasicInfo(basic);
            // 职业信息
            ExpertJobInfo jobInfo = new ExpertJobInfo();
            jobInfo.setAddress("暂无");
            jobInfo.setExperience("暂无");
            jobInfo.setJobStatus(new ArrayList<>());
            jobInfo.setCompany(MapUtil.getStr(w, "*工作单位"));
            List<DingOrganization> organizations = organizationService.list(Wrappers.lambdaQuery(DingOrganization.class)
                    .eq(DingOrganization::getOrganizationName, jobInfo.getCompany()));
            if (organizations.size() == 1) {
                jobInfo.setCompanyUniqCode(organizations.get(0).getOrganizationCode());
            }
            jobInfo.setAdministrativeDuties(MapUtil.getStr(w, "行政职务"));
            jobInfo.setAdministrativeRank(new ArrayList<>());
            String administrativeRankStr = MapUtil.getStr(w, "行政职级");
            List<DictionaryDTO> administrativeRankDicts = dictionaryCache.listDictByDictType(DictTypeEnum.ADMINISTRATIVE_RANK.getKey());
            if (!administrativeRankDicts.isEmpty()) {
                administrativeRankDicts.stream()
                        .filter(dict -> dict.getName().equals(administrativeRankStr))
                        .findFirst().ifPresent(dictionary -> {
                            DictFieldInfoDTO dict = new DictFieldInfoDTO();
                            dict.setDictionaryName(dictionary.getName());
                            dict.setDictionaryCode(dictionary.getDictionaryCode());
                            dict.setDictionaryFieldName(dictionary.getDictionaryType());
                            jobInfo.getAdministrativeRank().add(dict);
                        });
            }
            jobInfo.setCompanyAttribute(new ArrayList<>());
            String companyTypeStr = MapUtil.getStr(w, "*单位类型");
            List<DictionaryDTO> companyTypeDicts = dictionaryCache.listDictByDictType(DictTypeEnum.COMPANY_ATTRIBUTE.getKey());
            if (!companyTypeDicts.isEmpty()) {
                companyTypeDicts.stream()
                        .filter(dict -> dict.getName().equals(companyTypeStr))
                        .findFirst().ifPresent(dictionary -> {
                            DictFieldInfoDTO dict = new DictFieldInfoDTO();
                            dict.setDictionaryName(dictionary.getName());
                            dict.setDictionaryCode(dictionary.getDictionaryCode());
                            dict.setDictionaryFieldName(dictionary.getDictionaryType());
                            jobInfo.getCompanyAttribute().add(dict);
                        });
            }
            request.setJobInfo(jobInfo);
            ExpertProfessionalInfo professionalInfo = new ExpertProfessionalInfo();
            professionalInfo.setAwards("暂无");
            professionalInfo.setIndustrySector(new ArrayList<>());
            professionalInfo.setOther(new ArrayList<>());
            Map<String, TagDTO> tagMap = tagCache.getNameTagMap();
            String otherTagStr = MapUtil.getStr(w, "其他标签");
            if (StrUtils.isNotBlank(otherTagStr)) {
                for (String othTag : otherTagStr.split(SEPARATOR)) {
                    tagMap.entrySet().stream()
                            .filter(tag -> tag.getValue().getParentCode().equals(ExpertTagEnum.OTHER.getKey())
                                    && tag.getValue().getTagName().equals(othTag))
                            .forEach(tag -> {
                                TagFieldInfo expertTag = new TagFieldInfo();
                                expertTag.setTagCode(tag.getValue().getTagCode());
                                expertTag.setTagFieldName(tag.getValue().getParentCode());
                                expertTag.setTagName(tag.getValue().getTagName());
                                professionalInfo.getOther().add(expertTag);
                            });
                }
            }

            String avoidCompanyStr = MapUtil.getStr(w, "*回避单位");
            professionalInfo.setAvoidCompanyList(new ArrayList<>());
            List<DingOrganization> avoidOrges = organizationService.list(Wrappers.lambdaQuery(DingOrganization.class)
                    .in(DingOrganization::getOrganizationName, avoidCompanyStr.split(SEPARATOR)));
            if (!avoidOrges.isEmpty()) {
                avoidOrges.forEach(org -> {
                    ExpertAvoidCompanyInfo companyInfo = new ExpertAvoidCompanyInfo();
                    companyInfo.setCompanyName(org.getOrganizationName());
                    companyInfo.setCompanyUniqCode(org.getOrganizationCode());
                    professionalInfo.getAvoidCompanyList().add(companyInfo);
                });
            }

            professionalInfo.setGoodAt(new ArrayList<>());
            String goodAtStr = MapUtil.getStr(w, "*擅长方向");
            for (String othTag : goodAtStr.split(SEPARATOR)) {
                tagMap.entrySet().stream()
                        .filter(tag -> tag.getValue().getTagName().equals(othTag))
                        .forEach(tag -> {
                            TagFieldInfo expertTag = new TagFieldInfo();
                            expertTag.setTagCode(tag.getValue().getTagCode());
                            expertTag.setTagFieldName(ExpertTagEnum.GOOD_AT.getKey());
                            expertTag.setTagName(tag.getValue().getTagName());
                            professionalInfo.getGoodAt().add(expertTag);
                        });
            }
            String industrySectorStr = MapUtil.getStr(w, "行业领域");
            for (String othTag : industrySectorStr.split(SEPARATOR)) {
                tagMap.entrySet().stream()
                        .filter(tag -> tag.getValue().getTagName().equals(othTag))
                        .forEach(tag -> {
                            TagFieldInfo expertTag = new TagFieldInfo();
                            expertTag.setTagCode(tag.getValue().getTagCode());
                            expertTag.setTagFieldName(ExpertTagEnum.INDUSTRY_SECTOR.getKey());
                            expertTag.setTagName(tag.getValue().getTagName());
                            professionalInfo.getIndustrySector().add(expertTag);
                        });
            }
            professionalInfo.setTechnicalExpertise(new ArrayList<>());
            String techStr = MapUtil.getStr(w, "技术专长");
            for (String othTag : techStr.split(SEPARATOR)) {
                tagMap.entrySet().stream()
                        .filter(tag -> tag.getValue().getTagName().equals(othTag))
                        .forEach(tag -> {
                            TagFieldInfo expertTag = new TagFieldInfo();
                            expertTag.setTagCode(tag.getValue().getTagCode());
                            expertTag.setTagFieldName(ExpertTagEnum.TECHNICAL_EXPERTISE.getKey());
                            expertTag.setTagName(tag.getValue().getTagName());
                            professionalInfo.getTechnicalExpertise().add(expertTag);
                        });
            }
            professionalInfo.setTitleLevel(new ArrayList<>());
            String titleLevel = MapUtil.getStr(w, "*职称级别");
            List<DictionaryDTO> titleLevelDicts = dictionaryCache.listDictByDictType(DictTypeEnum.TITLE_LEVEL.getKey());
            if (!titleLevelDicts.isEmpty()) {
                titleLevelDicts.stream()
                        .filter(dict -> dict.getName().equals(titleLevel))
                        .findFirst().ifPresent(dictionary -> {
                            DictFieldInfoDTO dict = new DictFieldInfoDTO();
                            dict.setDictionaryName(dictionary.getName());
                            dict.setDictionaryCode(dictionary.getDictionaryCode());
                            dict.setDictionaryFieldName(dictionary.getDictionaryType());
                            professionalInfo.getTitleLevel().add(dict);
                        });
            }
            professionalInfo.setTechnicalTitles(MapUtil.getStr(w, "技术职称"));
            request.setProfessionalInfo(professionalInfo);
            ExpertRecommendInfo recommendInfo = new ExpertRecommendInfo();
            recommendInfo.setRecommendedWay(new ArrayList<>());
            request.setRecommendInfo(recommendInfo);
            try {
                expertController.expertBasicInfoSubmit(request);
            } catch (Exception e) {
                System.out.println(JSONUtil.toJsonStr(request));
            }
        });
    }

}
