package com.jwipc.supplier.logic.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.jwipc.constant.DelFlag;
import com.jwipc.constant.DictCode;
import com.jwipc.security.LoginUtil;
import com.jwipc.supplier.constant.AuthenticationState;
import com.jwipc.supplier.constant.InformationStatus;
import com.jwipc.supplier.constant.SignUpThrough;
import com.jwipc.supplier.convert.SupplierBankConvert;
import com.jwipc.supplier.dto.SupplierImportDTO;
import com.jwipc.supplier.entity.*;
import com.jwipc.supplier.logic.SupplierImportLogic;
import com.jwipc.supplier.logic.SupplierPurchaseCategoryLogic;
import com.jwipc.supplier.model.po.SupplierTemplateFieldPO;
import com.jwipc.supplier.service.*;
import com.jwipc.sys.client.*;
import com.jwipc.sys.client.dto.*;
import com.jwipc.util.DateUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p> </p>
 *
 * @author BOGON
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SupplierImportLogicImpl implements SupplierImportLogic {
    private final DictClient dictClient;
    private final PurchaseGroupClient purchaseGroupClient;
    private final PurchaseOrgClient purchaseOrgClient;
    private final CompanyClient companyClient;
    private final TaxClient taxClient;
        private final ISupplierPurchaseCategoryService supplierPurchaseCategoryService;
    private final AreaClient areaClient;
    private final ISupplierService supplierService;
    private final ISupplierInvitaionService supplierInvitaionService;
    private final UserClient userClient;
    private final ISupplierTemplateService supplierTemplateService;
    private final ISupplierTemplateFieldRelationService supplierTemplateFieldRelationService;
    private final ISupplierFieldService supplierFieldService;
    private final ISupplierExtensionService supplierExtensionService;
    private final UserRoleClient userRoleClient;
    private final ISupplierContactsService supplierContactsService;
    private final ISupplierBankService supplierBankService;
    private final PurchaseCategoryClient purchaseCategoryClient;
    private final SupplierPurchaseCategoryLogic supplierPurchaseCategoryLogic;
    private final SequenceClient sequenceClient;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String,List<SupplierImportDTO>> processor(MultipartFile file,String supplierAttribution) {
        Map<String,List<SupplierImportDTO>> map=  new HashMap<String,List<SupplierImportDTO>>();
        List<SupplierImportDTO> exportData = Lists.newArrayList();
        try {
            List<SupplierImportDTO> importDTOS = Lists.newArrayList();
            //需要缓存全部的字典
            //企业性质
            final List<DictDTO> supplierTypeDict = dictClient.getDicByType(DictCode.SUPPLIER_TYPE.getCode());
            final Map<String, String> supplierTypeDictCache = convertDict(supplierTypeDict);
            //供应商供货类型(语言)
            final List<DictDTO> supplyType = dictClient.getDicByType(DictCode.SUPPLY_TYPE.getCode());
            final Map<String, String> supplyTypeCache = convertDict(supplyType);
            //供应商类型
            final List<DictDTO> supplierClassify = dictClient.getDicByType(DictCode.SUPPLIER_CLASSIFY.getCode());
            final Map<String, String> supplierClassifyCache = convertDict(supplierClassify);
            //环保要求
            final List<DictDTO> rohsFlag = dictClient.getDicByType(DictCode.ROHS_FLAG.getCode());
            final Map<String, String> rohsFlagCache = convertDict(rohsFlag);
            //供应商属性
            final List<DictDTO> supplierAttr = dictClient.getDicByType(DictCode.SUPPLIER_ATTR.getCode());
            final Map<String, String> supplierAttrCache = convertDict(supplierAttr);
            //供应商分组
            final List<DictDTO> supplierGroup = dictClient.getDicByType(DictCode.SUPPLIER_GROUP.getCode());
            final Set<String> supplierGroupCache = supplierGroup.stream().map(DictDTO::getCode)
                    .collect(Collectors.toSet());
            //评审方式
            final List<DictDTO> assessType = dictClient.getDicByType(DictCode.ASSESS_TYPE.getCode());
            final Map<String, String> assessTypeCache = convertDict(assessType);
            //采购策略
            final List<DictDTO> procurementStrategy = dictClient.getDicByType(DictCode.PROCUREMENT_STRATEGY.getCode());
            final Map<String, String> procurementStrategyCache = convertDict(procurementStrategy);
            //统驭科目
            final List<DictDTO> controllingAccounts = dictClient.getDicByType(DictCode.CONTROLLING_ACCOUNTS.getCode());
            final Map<String, String> controllingAccountsCache = convertDict(controllingAccounts);
            //付款方式
            final List<DictDTO> paymentWay = dictClient.getDicByType(DictCode.PAYMENT_WAY.getCode());
            final Set<String> paymentWayCache = paymentWay.stream().map(DictDTO::getCode).collect(Collectors.toSet());
            //付款条件
            final List<DictDTO> paymentTerms = dictClient.getDicByType(DictCode.PAYMENT_TERMS.getCode());
            final Set<String> paymentTermsCache = paymentTerms.stream().map(DictDTO::getCode)
                    .collect(Collectors.toSet());
            //币种
            final List<DictDTO> currency = dictClient.getDicByType(DictCode.CURRENCY.getCode());
            final Set<String> currencyCache = currency.stream().map(DictDTO::getCode).collect(Collectors.toSet());

            //采购组缓存
            final List<PurchaseGroupDTO> all = purchaseGroupClient.getAll();
            Set<String> purchaseGroupCache = all.stream().map(PurchaseGroupDTO::getPurchaseGroupCode)
                    .collect(Collectors.toSet());
            //采购组织缓存
            Set<String> purchaseOrgCache =
                    purchaseOrgClient.getAll().stream().map(PurchaseOrgDTO::getPurchaseOrgCode)
                            .collect(Collectors.toSet());
            //公司缓存
            final List<CompanyDTO> companyDTOS = companyClient.getAll();
            //需要去公司的编码
            final Set<String> companyCodeCache = companyDTOS.stream().map(CompanyDTO::getCompanyCode)
                    .collect(Collectors.toSet());
            //税码缓存
            final List<TaxDTO> taxDTOS = taxClient.getAll();
            final Set<String> taxCache = taxDTOS.stream().map(TaxDTO::getTaxCode).collect(Collectors.toSet());
            //采购品类缓存
            final List<PurchaseCategoryClientDTO> purchaseCategories = purchaseCategoryClient.getAll();
            final Map<String, PurchaseCategoryClientDTO> purchaseCategoryCache = purchaseCategories.stream()
                    .collect(Collectors.toMap(PurchaseCategoryClientDTO::getFirstLevelPurchaseName, a -> a));
            //系统用户缓存
            Map<String, UserDTO> userCache = Maps.newHashMap();

            EasyExcel.read(file.getInputStream(), SupplierImportDTO.class, new ReadListener<SupplierImportDTO>() {
                @Override
                public void invoke(SupplierImportDTO data, AnalysisContext context) {
                    //校验国家
                    final String areaName = areaClient.getAreaName(data.getCountry());
                    Set<String> msg = Sets.newHashSet();
                    if (StrUtil.isEmpty(areaName)) {
                        msg.add(StrUtil.format("国家编码:{}不存在！", data.getCountry()));
                    } else {
                        //校验地区
                        final String areaCode = areaClient.getAreaCode(data.getCountry(), data.getRegion());
                        if (StrUtil.isEmpty(areaCode)) {
                            msg.add(StrUtil.format("地区(省份):{}不存在！", data.getRegion()));
                        } else {
                            final String cityCode = areaClient.getAreaCode(areaCode, data.getCity());
                            if (StrUtil.isEmpty(cityCode)) {
                                msg.add(StrUtil.format("城市:{}不存在！", data.getCity()));
                            }
                        }
                    }
                    //校验币种
                    if (!currencyCache.contains(data.getCurrency())) {
                        msg.add(StrUtil.format("币种:{}不存在！", data.getCurrency()));
                    }
                    //校验语言
                    final String language = data.getLanguage();
                    if (StrUtil.isEmpty(supplyTypeCache.get(language))) {
                        msg.add(StrUtil.format("语言:{}不存在！", data.getLanguage()));
                    }
                    //校验环保要求
                    final String environmentalRequirements = data.getEnvironmentalRequirements();
                    if (StrUtil.isEmpty(rohsFlagCache.get(environmentalRequirements))) {
                        msg.add(StrUtil.format("环保要求:{}不存在！", data.getEnvironmentalRequirements()));
                    }
                    //校验企业类型
                    final String enterpriseType = data.getEnterpriseType();
                    if (StrUtil.isEmpty(supplierTypeDictCache.get(enterpriseType))) {
                        msg.add(StrUtil.format("企业类型:{}不存在！", data.getEnterpriseType()));
                    }
                    //校验供应商类型
                    final String companyNature = data.getCompanyNature();
                    if (StrUtil.isEmpty(supplierClassifyCache.get(companyNature))) {
                        msg.add(StrUtil.format("企业性质:{}不存在！", data.getCompanyNature()));
                    }
                    //校验采购组
                    final String purchaseGroup = data.getPurchaseGroup();
                    if (!purchaseGroupCache.contains(purchaseGroup)) {
                        msg.add(StrUtil.format("采购组编码:{}不存在！", data.getPurchaseGroup()));
                    }
                    //校验属性
                    final String attribute = data.getAttribute();
                    if (StrUtil.isEmpty(supplierAttrCache.get(attribute))) {
                        msg.add(StrUtil.format("属性:{}不存在！", data.getAttribute()));
                    }
                    //校验供应商分组
                    final String supplierGroup1 = data.getSupplierGroup();
                    if (!supplierGroupCache.contains(supplierGroup1)) {
                        msg.add(StrUtil.format("供应商分组:{}不存在！", data.getSupplierGroup()));
                    }
                    //校验评审方式
                    final String reviewMethod = data.getReviewMethod();
                    if (StrUtil.isEmpty(assessTypeCache.get(reviewMethod))) {
                        msg.add(StrUtil.format("评审方式:{}不存在！", data.getReviewMethod()));
                    }
                    //校验采购策略
                    final String purchaseStrategy = data.getPurchaseStrategy();
                    if (StrUtil.isEmpty(procurementStrategyCache.get(purchaseStrategy))) {
                        msg.add(StrUtil.format("采购策略:{}不存在！", data.getPurchaseStrategy()));
                    }
                    //校验采购类别，采购类别是根据中文、分割
                    final String productCategory = data.getProductCategory();
                    final Set<String> split = new HashSet<>(StrUtil.split(productCategory, "、"));
                    for (String s : split) {
                        if (Objects.isNull(purchaseCategoryCache.get(s))) {
                            msg.add(StrUtil.format("采购类别:{}不存在！", s));
                        }
                    }
                    //校验采购组织
                    final String purchaseOrganization = data.getPurchaseOrganization();
                    if (!purchaseOrgCache.contains(purchaseOrganization)) {
                        msg.add(StrUtil.format("采购组织:{}不存在！", data.getPurchaseOrganization()));
                    }
                    //校验付款方式
                    final String paymentMethod = data.getPaymentMethod();
                    if (!paymentWayCache.contains(paymentMethod)) {
                        msg.add(StrUtil.format("付款方式:{}不存在！", data.getPaymentMethod()));
                    }
                    //校验付款条件
                    final String paymentTerms1 = data.getPaymentTerms();
                    if (!paymentTermsCache.contains(paymentTerms1)) {
                        msg.add(StrUtil.format("付款条件:{}不存在！", data.getPaymentTerms()));
                    }
                    //校验公司
                    final String companyCode = data.getCompanyCode();
                    if (!companyCodeCache.contains(companyCode)) {
                        msg.add(StrUtil.format("公司:{}不存在！", data.getCompanyCode()));
                    }
                    //校验税码
                    final String taxCode = data.getTaxCode();
                    if (!taxCache.contains(taxCode)) {
                        msg.add(StrUtil.format("税码:{}不存在！", data.getTaxCode()));
                    }
                    //校验统驭科目
                    final String controlSubject = data.getControlSubject();
                    if (StrUtil.isEmpty(controllingAccountsCache.get(controlSubject))) {
                        msg.add(StrUtil.format("统驭科目:{}不存在！", data.getControlSubject()));
                    }
                    //校验邀请人
                    final String applicant = data.getApplicant();
                    if (Objects.isNull(userCache.get(applicant))) {
                        //需要去查询
                        final UserDTO userDTO = userClient.getByName(applicant);
                        if (Objects.nonNull(userDTO)) {
                            userCache.put(applicant, userDTO);
                        } else {
                            msg.add(StrUtil.format("邀请人:{}不存在！", data.getApplicant()));
                        }
                    }
                    //校验供应商状态
                    final String supplierStatus = data.getSupplierStatus();
                    final Set<String> allTitle = AuthenticationState.getAllTitle();
                    if (!allTitle.contains(supplierStatus)) {
                        msg.add(StrUtil.format("供应商状态:{}不存在！", data.getSupplierStatus()));
                    }

                    if(StringUtils.isNotEmpty(supplierAttribution)){//资源整合部导入
                        final String sr = data.getSupplierRegister();
                        if (StringUtils.isEmpty(sr)) {
                            msg.add(StrUtil.format("工商注册地址不能为空！"));
                        }
                    }
                    //如果校验全部没问题
                    if (msg.isEmpty()) {
                        importDTOS.add(data);
                    } else {
                        data.setErrorMsg(String.join(StrUtil.LF, msg));
                        exportData.add(data);
                    }
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                }
            }).headRowNumber(3).sheet(0).doRead();
            //检验通过的数据开始更新数据库
            //需要区分模板字段
            Map<String, String> templateData = Maps.newHashMap();
            //需要区分是不是同一个供应商不同公司，如果是同一个供应商不同公司，就不需要更新供应商数据，只需要处理品类数据
            Set<String> supplierCache = Sets.newHashSet();
            Set<Long> supplierIds = Sets.newHashSet();
            for (SupplierImportDTO importDTO : importDTOS) {
                String supplierCode = "";
                if(StringUtils.isNotEmpty(supplierAttribution)){//资源整合部导入
                    supplierCode = sequenceClient.getCodeSequenceNo("zy_supplier_code",5);
                }else{
                    supplierCode = importDTO.getSupplierCode();
                }


                Long supplierId;
                Long invitaionId;
                if (supplierCache.contains(supplierCode)) {
                    //判断是已经存在，如果存在就更新
                    Supplier supplier = supplierService.getOne(new LambdaQueryWrapper<Supplier>()
                            .eq(Supplier::getSupplierCode, supplierCode), false);
                    supplierId = supplier.getId();
                    final SupplierInvitaion invitaion = supplierInvitaionService.getOne(
                            new LambdaQueryWrapper<SupplierInvitaion>()
                                    .eq(SupplierInvitaion::getSupplierId, supplierId), false);
                    invitaionId = invitaion.getId();
                } else {
                    supplierCache.add(supplierCode);
                    boolean isNew = false;
                    //判断是已经存在，如果存在就更新
                    Supplier supplier = supplierService.getOne(new LambdaQueryWrapper<Supplier>()
                            .eq(Supplier::getSupplierCode, supplierCode), false);
                    SupplierInvitaion supplierInvitaion;
                    if (Objects.isNull(supplier)) {
                        isNew = true;
                        supplier = new Supplier();
                        supplier.setSupplierCode(supplierCode);
                        if(StringUtils.isEmpty(supplierAttribution)){//正常导入
                            supplier.setSupplierErpCode(supplierCode);
                        }else{
                            supplier.setSupplierAttribution(10);//资源整合导入需要打标识
                        }
                        supplier.setSupplierTempCode(supplierCode);

                        supplierInvitaion = new SupplierInvitaion();
                    } else {
                        supplier.setSupplierCode(supplierCode);
                        if(StringUtils.isEmpty(supplierAttribution)){//正常导入导入
                            supplier.setSupplierErpCode(supplierCode);
                        }
                        supplier.setSupplierTempCode(supplierCode);
                        supplierInvitaion = supplierInvitaionService.getOne(new LambdaQueryWrapper<SupplierInvitaion>()
                                .eq(SupplierInvitaion::getSupplierId, supplier.getId()), false);
                        supplierFieldService.remove(
                                new LambdaQueryWrapper<SupplierField>().eq(SupplierField::getSupplierId,
                                        supplier.getId()));
                        supplierExtensionService.remove(
                                new LambdaQueryWrapper<SupplierExtension>().eq(SupplierExtension::getSupplierId,
                                        supplier.getId()));
                    }
                    supplier.setCountry(importDTO.getCountry());
                    supplierInvitaion.setRecommender(userCache.get(importDTO.getApplicant()).getAccountName());
                    supplierInvitaion.setCreateId(userCache.get(importDTO.getApplicant()).getId());
                    supplier.setSupplierName(importDTO.getSupplierName().trim());
                    supplier.setShortName(importDTO.getSupplierShortName());
                    supplier.setSupplierNameEn(importDTO.getEnglishName());
                    final String areaCode = areaClient.getAreaCode(importDTO.getCountry(), importDTO.getRegion());
                    supplier.setProvince(areaCode);
                    final String cityCode = areaClient.getAreaCode(areaCode, importDTO.getCity());
                    supplier.setCity(cityCode);
                    supplier.setEstablishmentDate(DateUtils.formatYYYYMMDDHms(importDTO.getEstablishmentDate()));
                    supplier.setTel(importDTO.getPhone());
                    supplier.setEmail(importDTO.getEmail());
                    supplier.setLegal(importDTO.getLegalRepresentative());
                    supplier.setZipCode(importDTO.getPostcode());
                    supplier.setSupplyType(importDTO.getLanguage());
                    supplier.setSupplierGenre(supplierClassifyCache.get(importDTO.getCompanyNature()));//企业性质
                    supplier.setSupplierTypeId(supplierTypeDictCache.get(importDTO.getEnterpriseType()));//企业类型
                    templateData.put("q1", importDTO.getAreaSize());//占地面积
                    templateData.put("street", importDTO.getStreetAddress());//占地面积
                    templateData.put("currency_code", importDTO.getCurrency());//占地面积
                    templateData.put("register_money", importDTO.getRegisteredCapital());//注册资金
                    supplier.setMobile(importDTO.getMobilePhone());
                    supplier.setBusinessRegisterNo(importDTO.getTaxNumber());
                    templateData.put("rohs_flag", rohsFlagCache.get(importDTO.getEnvironmentalRequirements()));//环保要求
                    supplier.setAddress(importDTO.getStreetAddress());
                    supplier.setSupplierTypeId(supplierTypeDictCache.get(importDTO.getEnterpriseType()));
                    templateData.put("product_brand", importDTO.getProductBrand());//产品品牌
                    templateData.put("t_supplier_main_customer_product", importDTO.getMainCustomers());//主要客户
                    templateData.put("transportation", importDTO.getControllingParty());//控制方(集团母公司)
                    //取模板 使用制造商的模板 manufacturer
                    final SupplierTemplate manufacturer = supplierTemplateService.getOne(
                            new LambdaQueryWrapper<SupplierTemplate>()
                                    .eq(SupplierTemplate::getTemplateCode, "manufacturer"), false);
                    supplierInvitaion.setTemplateId(manufacturer.getId());
                    supplierInvitaion.setSupplierType(supplier.getSupplierGenre());
                    supplier.setTemplateId(manufacturer.getId());
                    supplier.setPurchaseOrgCode(importDTO.getPurchaseOrganization());
                    supplier.setPurchaseGroupCode(importDTO.getPurchaseGroup());
                    supplier.setSignUpUser(LoginUtil.getUserId());
                    supplier.setSignUpThrough(SignUpThrough.REGISTERED.getStatus());
                    if(StringUtils.isEmpty(supplierAttribution)){
                        supplier.setSignUpRemark("初始导入");
                    }
                    supplier.setInfoState(InformationStatus.REGISTRATION_COMPLETED.getValue());
                    supplier.setSpecialRemark(importDTO.getSpecialApplyReason());
                    supplier.setProcurementStrategy(procurementStrategyCache.get(importDTO.getPurchaseStrategy()));
                    supplier.setAttr(supplierAttrCache.get(importDTO.getAttribute()));
                    supplier.setSupplierGroup(importDTO.getSupplierGroup());
                    supplier.setAssessType(assessTypeCache.get(importDTO.getReviewMethod()));
                    supplier.setCustomer1Code(importDTO.getCustomerCode());
                    supplier.setCustomer1Name(importDTO.getCustomerFull());
                    supplier.setColBeiyOne(importDTO.getSupplierRegister());
                    //供应商数据保存
                    supplierService.saveOrUpdate(supplier);
                    supplierId = supplier.getId();
                    supplierIds.add(supplierId);
                    //需要创建用户，需要创建用户角色关联表
                    if (isNew) {
                        CreateUserCDTO createUserDTO = new CreateUserCDTO();
                        createUserDTO.setAccountName(supplierCode);
                        createUserDTO.setUsername(supplier.getSupplierName());
                        createUserDTO.setSupplierId(supplier.getId());
                        createUserDTO.setEmail(supplier.getEmail());
                        final Long userId = userClient.createSupplierUser(createUserDTO);
                        //需要创建供应商默认角色
                        userRoleClient.createSupplierDefaultRole(userId);
                    }
                    supplierInvitaion.setEmail(supplier.getEmail());
                    supplierInvitaion.setShortName(supplier.getShortName());
                    supplierInvitaion.setSupplierId(supplier.getId());
                    supplierInvitaion.setInviteDesc(importDTO.getApplyReason());
                    supplierInvitaion.setPurchaseGroupCode(importDTO.getPurchaseGroup());
                    //供应商邀请信息保存
                    supplierInvitaionService.saveOrUpdate(supplierInvitaion);
                    invitaionId = supplierInvitaion.getId();
                    //保存供应商模板字段
                    final List<SupplierTemplateFieldPO> supplierTemplateFieldPOS =
                            supplierTemplateFieldRelationService.selectByTemplate(
                                    String.valueOf(manufacturer.getId()), DelFlag.NORMAL.getStatus());
                    //需要组装成code-标题
                    final Map<String, String> fieldNamTitleMap = supplierTemplateFieldPOS.stream()
                            .collect(Collectors.toMap(a -> StrUtil.toCamelCase(a.getFieldName()), a -> {
                                if (StrUtil.isNotEmpty(a.getFieldAlias())) {
                                    return a.getFieldAlias();
                                } else {
                                    return a.getLabelName();
                                }
                            }));
                    //需要把模板的字段信息保存一份，要不然后面模板修改了这个地方就出现问题
                    List<SupplierField> supplierFields = Lists.newArrayList();
                    for (SupplierTemplateFieldPO fieldPO : supplierTemplateFieldPOS) {
                        SupplierField supplierField = new SupplierField();
                        supplierField.setFieldCode(fieldPO.getFieldName());
                        supplierField.setFieldAlias(
                                StrUtil.isNotEmpty(
                                        fieldPO.getFieldAlias()) ? fieldPO.getFieldAlias() : fieldPO.getLabelName());
                        supplierField.setFieldSort(fieldPO.getFieldSort());
                        supplierField.setFieldType(fieldPO.getFieldType());
                        supplierField.setSqlSentence(fieldPO.getSqlSentence());
                        supplierField.setValidateStr(fieldPO.getValidateStr());
                        supplierField.setRequired(fieldPO.getRequired());
                        supplierField.setFormControl(fieldPO.getFormControl());
                        supplierField.setSupplierId(supplier.getId());
                        supplierFields.add(supplierField);
                    }
                    if (CollUtil.isNotEmpty(supplierFields)) {
                        supplierFieldService.saveBatch(supplierFields);
                    }
                    List<String> tableColumns = supplierService.getTableStruct();
                    List<SupplierExtension> supplierExtensions = new ArrayList<>();
                    for (String key : templateData.keySet()) {
                        if (!tableColumns.contains(StrUtil.toUnderlineCase(key))) {
                            //这个地方的字段是供应商主表中
                            SupplierExtension supplierExtension = new SupplierExtension();
                            supplierExtension.setExtensionKey(StrUtil.toCamelCase(key));
                            final String label = fieldNamTitleMap.get(key);
                            supplierExtension.setExtensionLabel(label);
                            supplierExtension.setExtensionValue(templateData.get(key));
                            supplierExtension.setSupplierId(supplier.getId());
                            supplierExtensions.add(supplierExtension);
                        }
                    }
                    if (CollUtil.isNotEmpty(supplierExtensions)) {
                        supplierExtensionService.saveBatch(supplierExtensions, 300);
                    }
                    //需要保存业务员信息
                    final String salespersonName = importDTO.getSalespersonName();
                    final String salespersonEmail = importDTO.getSalespersonEmail();
                    final String salespersonPhone = importDTO.getSalespersonPhone();
                    saveContact(salespersonName, salespersonPhone, salespersonEmail, supplier,
                            DictCode.ContactType.BUSINESS.getType());
                    //需要保存业务经理
                    final String managerName = importDTO.getManagerName();
                    final String managerPhone = importDTO.getManagerPhone();
                    final String managerEmail = importDTO.getManagerEmail();
                    saveContact(managerName, managerPhone, managerEmail, supplier,
                            DictCode.ContactType.BUSINESS_MANAGER.getType());

                    //需要保存财务人员
                    final String financeName = importDTO.getFinanceName();
                    final String financePhone = importDTO.getFinancePhone();
                    final String financeEmail = importDTO.getFinanceEmail();
                    saveContact(financeName, financePhone, financeEmail, supplier,
                            DictCode.ContactType.FINANCE.getType());

                    //需要保存品保人员
                    final String qualityName = importDTO.getQualityName();
                    final String qualityPhone = importDTO.getQualityPhone();
                    final String qualityEmail = importDTO.getQualityEmail();
                    saveContact(qualityName, qualityPhone, qualityEmail, supplier,
                            DictCode.ContactType.QUALITY.getType());

                    //需要保存品保经理
                    final String qualityManagerName = importDTO.getQualityManagerName();
                    final String qualityManagerPhone = importDTO.getQualityManagerPhone();
                    final String qualityManagerEmail = importDTO.getQualityManagerEmail();
                    saveContact(qualityManagerName, qualityManagerPhone, qualityManagerEmail, supplier,
                            DictCode.ContactType.QUALITY_MANAGER.getType());

                    //保存供应商银行信息
                    final SupplierBank db = supplierBankService.getOne(new LambdaQueryWrapper<SupplierBank>()
                            .eq(SupplierBank::getSupplierId, supplier.getId())
                            .eq(SupplierBank::getCompanyCode, importDTO.getCompanyCode()), false);
                    SupplierBank supplierBank = new SupplierBank();
                    if (Objects.nonNull(db)) {
                        supplierBank.setId(db.getId());
                    }
                    supplierBank.setSupplierId(supplier.getId());
                    supplierBank.setCompanyName(importDTO.getPayee());
                    supplierBank.setBankAddress(importDTO.getBankAddress());
                    supplierBank.setSupplierCode(supplierCode);
                    supplierBank.setSupplierName(supplier.getSupplierName().trim());
                    supplierBank.setBankAccount(importDTO.getBankAccount());
                    supplierBank.setBankInterCode(importDTO.getSwiftCode());
                    supplierBank.setBankCode(importDTO.getBankCode());
                    supplierBank.setOpeningBankName(importDTO.getReceivingBank());
                    supplierBank.setCompanyCode(importDTO.getCompanyCode());
                    supplierBankService.saveOrUpdate(supplierBank);
                }

                //保存采购品类数据
                final String productCategory = importDTO.getProductCategory();
                final Set<String> split = new HashSet<>(StrUtil.split(productCategory, "、"));
                for (String s : split) {
                    final PurchaseCategoryClientDTO purchaseCategory = purchaseCategoryCache.get(s);
                    final SupplierPurchaseCategory dbData = supplierPurchaseCategoryService.getOne(
                            new LambdaQueryWrapper<SupplierPurchaseCategory>()
                                    .eq(SupplierPurchaseCategory::getSupplierId, supplierId)
                                    .eq(SupplierPurchaseCategory::getPurchaseCategoryCode,
                                            purchaseCategory.getFirstLevelPurchaseCode())
                                    .eq(SupplierPurchaseCategory::getCompanyCode,
                                            importDTO.getCompanyCode()),
                            false);
                    SupplierPurchaseCategory category = new SupplierPurchaseCategory();
                    if (Objects.nonNull(dbData)) {
                        category.setId(dbData.getId());
                    }
                    category.setInvitationId(invitaionId);
                    category.setSupplierId(supplierId);
                    //处理下模板上如果是资源整合导入的默认为潜在，如果是正常导入的默认为表格中的数据
                    if(StringUtils.isEmpty(supplierAttribution)){//资源整合导入
                        category.setState(AuthenticationState.getByTitle(importDTO.getSupplierStatus()).getState());
                        //判断品类是否为Z006客供品类  2025-07-08 邓京术 给客供供应商打上客供供应商标识，因为后面下订单审批流程不一样。
                        if (purchaseCategory.getFirstLevelPurchaseCode().equals("Z006")) {
                            //1 客供品类
                            LambdaUpdateWrapper<Supplier> supplierLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                            supplierLambdaUpdateWrapper.eq(Supplier::getId, supplierId).set(Supplier::getSupplierAttribution, 30).set(Supplier::getSupplierCategoryType,"1");
                            supplierService.update(supplierLambdaUpdateWrapper);

                        }
                    }else{
                        category.setState(2);
                    }
                    category.setPaymentMethod(importDTO.getPaymentMethod());
                    category.setPaymentTerms(importDTO.getPaymentTerms());
                    category.setPurchaseCategoryCode(purchaseCategory.getFirstLevelPurchaseCode());
                    category.setPurchaseCategoryName(purchaseCategory.getFirstLevelPurchaseName());
                    category.setPurchaseOrgCode(importDTO.getPurchaseOrganization());
                    category.setCompanyCode(importDTO.getCompanyCode());
                    category.setTaxCode(importDTO.getTaxCode());
                    category.setControlSubject(controllingAccountsCache.get(importDTO.getControlSubject()));
                    category.setCurrencyCode(importDTO.getCurrency());
                    supplierPurchaseCategoryService.saveOrUpdate(category);
                }

            }
            for (Long supplierId : supplierIds) {
                supplierPurchaseCategoryLogic.updateFirstForAll(supplierId);
            }
            map.put("true",importDTOS);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        map.put("false",exportData);
        return map;
    }

    private void saveContact(String managerName,
                             String managerPhone,
                             String managerEmail, Supplier supplier, int type)
    {
        if (StrUtil.isNotEmpty(managerName) && StrUtil.isNotEmpty(managerPhone) &&
                StrUtil.isNotEmpty(managerEmail)) {
            //需要查询是否存在如果存在更新
            final SupplierContacts db = supplierContactsService.getOne(
                    new LambdaQueryWrapper<SupplierContacts>()
                            .eq(SupplierContacts::getSupplierId, supplier.getId())
                            .eq(SupplierContacts::getContactsType, type)
                            .eq(SupplierContacts::getContactsName, managerName));
            SupplierContacts supplierContacts = new SupplierContacts();
            if (Objects.nonNull(db)) {
                supplierContacts.setId(db.getId());
            }
            supplierContacts.setSupplierId(supplier.getId());
            supplierContacts.setContactsName(managerName);
            supplierContacts.setContactsType(String.valueOf(type));
            supplierContacts.setEmail(managerEmail);
            supplierContacts.setContactsTel(managerPhone);
            supplierContactsService.saveOrUpdate(supplierContacts);
        }
    }

    private Map<String, String> convertDict(List<DictDTO> dictDTOS) {
        return dictDTOS.stream().collect(Collectors.toMap(DictDTO::getName, DictDTO::getCode));
    }
}