package com.jwipc.supplier.logic.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.common.collect.Lists;
import com.jwipc.api.constant.RestCode;
import com.jwipc.api.dto.ApiResult;
import com.jwipc.api.dto.OaFileParamDTO;
import com.jwipc.constant.DictCode;
import com.jwipc.constant.FlagConst;
import com.jwipc.constant.FreezeConst;
import com.jwipc.constant.OaProcessType;
import com.jwipc.exception.DaoException;
import com.jwipc.prop.SysProp;
import com.jwipc.security.LoginUtil;
import com.jwipc.security.dto.CurrentUserDTO;
import com.jwipc.supplier.constant.*;
import com.jwipc.supplier.convert.SupplierBankVersionConvert;
import com.jwipc.supplier.convert.SupplierContactsVersionConvert;
import com.jwipc.supplier.convert.SupplierPurchaseCategoryVersionConvert;
import com.jwipc.supplier.dto.CreateOrUpdateOaDTO;
import com.jwipc.supplier.entity.*;
import com.jwipc.supplier.logic.SupplierToOaLogic;
import com.jwipc.supplier.service.*;
import com.jwipc.sys.client.*;
import com.jwipc.sys.client.dto.*;
import com.jwipc.util.DateUtils;
import com.jwipc.util.EncryptUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.jwipc.util.DateUtils.yyyyMMddDash;


/**
 * <p> </p>
 *
 * @author BOGON
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@RequiredArgsConstructor
public class SupplierToOaLogicImpl implements SupplierToOaLogic {
    private static final Logger log = LoggerFactory.getLogger(SupplierToOaLogicImpl.class);
    private final ISupplierPurchaseCategoryService supplierPurchaseCategoryService;
    private final ISupplierInvitaionService supplierInvitaionService;
    private final ISupplierBankService supplierBankService;
    private final ISupplierContactsService supplierContactsService;
    private final ISupplierExtensionService supplierExtensionService;
    private final DictClient dictClient;
    private final ISupplierSqeScoreService supplierSqeScoreService;
    private final ISupplierQualificationService supplierQualificationService;
    private final FileClient fileClient;
    private final TaxClient taxClient;
    private final CompanyClient companyClient;
    private final PurchaseOrgClient purchaseOrgClient;
    private final PurchaseGroupClient purchaseGroupClient;
    private final SupplierOaClient supplierOaClient;
    private final ISupplierChangeVersionService supplierChangeVersionService;
    private final ISupplierService supplierService;
    private final ISupplierVersionService supplierVersionService;
    private final ISupplierPurchaseCategoryVersionService supplierPurchaseCategoryVersionService;
    private final SupplierPurchaseCategoryVersionConvert supplierPurchaseCategoryVersionConvert;
    private final ISupplierContactsVersionService supplierContactsVersionService;
    private final SupplierContactsVersionConvert supplierContactsVersionConvert;
    private final ISupplierBankVersionService supplierBankVersionService;
    private final SupplierBankVersionConvert supplierBankVersionConvert;
    private final AreaClient areaClient;
    private final ISupplierQualificationChangeItemService supplierQualificationChangeItemService;
    private final SysProp sysProp;

    @Override
    public void supplierAccessToOa(Supplier supplier, List<SupplierPurchaseCategory> purchaseCategories,Integer sa) {
        CreateOrUpdateOaDTO orUpdateOaDTO = new CreateOrUpdateOaDTO();
        final CreateOrUpdateOaDTO.Head head = new CreateOrUpdateOaDTO.Head();

        final List<CompanyDTO> companyDTOS = companyClient.getAll();
        final Map<String, String> companyCache = companyDTOS.stream()
                .collect(Collectors.toMap(CompanyDTO::getCompanyCode, CompanyDTO::getCompanyName));

        final List<DictDTO> controllingAccounts = dictClient.getDicByType(DictCode.CONTROLLING_ACCOUNTS.getCode());
        final Map<String, String> controllingAccountsCache = controllingAccounts.stream()
                .collect(Collectors.toMap(DictDTO::getCode, DictDTO::getName));

        final List<DictDTO> supplierAccetpDeadline = dictClient.getDicByType(DictCode.SUPPLIER_ACCETP_DEADLINE.getCode());
        final Map<String, String> accetpDeadlineCache = supplierAccetpDeadline.stream()
                .collect(Collectors.toMap(DictDTO::getCode, DictDTO::getName));

        final List<DictDTO> paymentTerms = dictClient.getDicByType(DictCode.PAYMENT_TERMS.getCode());
        final Map<String, String> paymentTermsCache = paymentTerms.stream()
                .collect(Collectors.toMap(DictDTO::getCode, DictDTO::getName));

        final List<DictDTO> paymentWay = dictClient.getDicByType(DictCode.PAYMENT_WAY.getCode());
        final Map<String, String> paymentWayCache = paymentWay.stream()
                .collect(Collectors.toMap(DictDTO::getCode, DictDTO::getName));

        final List<PurchaseOrgDTO> purchaseOrgDTOS = purchaseOrgClient.getAll();
        final Map<String, String> purchaseOrgCache = purchaseOrgDTOS.stream()
                .collect(Collectors.toMap(PurchaseOrgDTO::getPurchaseOrgCode, PurchaseOrgDTO::getPurchaseOrgDesc));

        final List<PurchaseGroupDTO> purchaseGroupDTOS = purchaseGroupClient.getAll();
        final Map<String, String> purchaseGroupCache = purchaseGroupDTOS.stream()
                .collect(Collectors.toMap(PurchaseGroupDTO::getPurchaseGroupCode,
                        PurchaseGroupDTO::getPurchaseGroupName));

        final SupplierInvitaion invitaionServiceOne = supplierInvitaionService.getOne(
                new LambdaQueryWrapper<SupplierInvitaion>()
                        .eq(SupplierInvitaion::getSupplierId, supplier.getId()), false);
        final CurrentUserDTO currentUser = LoginUtil.getCurrentUser();
        final String loginName = currentUser.getLoginName();
        final List<SupplierExtension> supplierExtensions = supplierExtensionService.list(
                new LambdaQueryWrapper<SupplierExtension>().eq(SupplierExtension::getSupplierId, supplier.getId()));
//        final Map<String, String> extVal = supplierExtensions.stream().filter(ext -> ext.getExtensionKey() != null)
//                .collect(Collectors.toMap(SupplierExtension::getExtensionKey, SupplierExtension::getExtensionValue));
        final Map<String, String> extVal = supplierExtensions.stream()
                .filter(ext -> ext.getExtensionKey() != null)
                .collect(Collectors.toMap(
                        SupplierExtension::getExtensionKey,
                        ext -> ext.getExtensionValue() != null ? ext.getExtensionValue() : "", // 使用默认值替换 null 值
                        (existing, replacement) -> existing, // 合并函数，这里不需要，因为键是唯一的
                        HashMap::new // 指定 Map 类型，虽然 HashMap 是默认类型，但显式指定可以增加代码清晰度
                ));


        final String categoryNames = purchaseCategories.stream().map(SupplierPurchaseCategory::getPurchaseCategoryName)
                .collect(Collectors.joining(StrUtil.COMMA));
        final String categoryCodes = purchaseCategories.stream().map(SupplierPurchaseCategory::getPurchaseCategoryCode)
                .collect(Collectors.joining(StrUtil.COMMA));
        head.setFd_shenQingDanHao(String.valueOf(supplier.getId()));
        head.setFd_tePiYuanYin(supplier.getSpecialRemark());
        head.setFd_sqePingShen(StringUtils.isNotEmpty(supplier.getApprovalOpinion()) ? supplier.getApprovalOpinion() : "" );
        String supplierAttribution = "";
        if(!Objects.isNull(sa) && (sa == 10)){//如果是资源整合部供应商，则需要传递值
            if(supplier.getSupplierAttribution()!=null){
                supplierAttribution = String.valueOf(supplier.getSupplierAttribution());
            }
            head.setFd_srmType(OaProcessType.SUPPLIER_IMPORT_ACCESS.getType());
        } else if(!Objects.isNull(sa) && ( sa == 50 || sa == 60)){//如果是代收款或者手板供应商供应商，则需要传递值
            supplierAttribution = sa.toString();
            head.setFd_srmType(OaProcessType.SUPPLIER_ACCESS.getType());

        }else{
            head.setFd_srmType(OaProcessType.SUPPLIER_ACCESS.getType());
        }
        head.setSupplierAttribution(supplierAttribution);
        basicInfo(supplier, categoryNames, categoryCodes, purchaseCategories.get(0).getTaxCode(), head, loginName,
                extVal,
                invitaionServiceOne, purchaseGroupCache, purchaseCategories.get(0).getOaId());
        //获取供应商联系人
        final List<SupplierContacts> supplierContacts = supplierContactsService.list(
                new LambdaQueryWrapper<SupplierContacts>().eq(SupplierContacts::getSupplierId, supplier.getId()));
        final Map<Integer, List<SupplierContacts>> supplierContactsCache = supplierContacts.stream()
                .filter(a -> Objects.nonNull(a.getContactsType()))
                .collect(Collectors.groupingBy(a -> Integer.valueOf(a.getContactsType())));
        supplierCantacts(supplierContactsCache, head);
        final SupplierSqeScore sqeScore = supplierSqeScoreService.getOne(new LambdaQueryWrapper<SupplierSqeScore>()
                .eq(SupplierSqeScore::getSupplierId, supplier.getId()), false);
        sqe(sqeScore, head);
        //供应商资质数据
        final List<SupplierQualification> supplierQualifications = supplierQualificationService.list(
                new LambdaQueryWrapper<SupplierQualification>()
                        .eq(SupplierQualification::getSupplierId, supplier.getId()));
        final Map<String, List<SupplierQualification>> qualificationCache = supplierQualifications.stream()
                .collect(Collectors.groupingBy(a -> a.getQualificationCode()));
        final Set<Long> filIds = supplierQualifications.stream().map(SupplierQualification::getFileId)
                .collect(Collectors.toSet());
        final Set<Long> collect = supplierQualifications.stream().filter(a -> Objects.nonNull(a.getSqeFileId()))
                .map(SupplierQualification::getSqeFileId)
                .collect(Collectors.toSet());
        filIds.addAll(collect);
        final List<FileResposePreviewCDTO> previewUrl = fileClient.getPreviewUrl(filIds);
        final Map<Long, FileResposePreviewCDTO> fileCache = previewUrl.stream()
                .collect(Collectors.toMap(a -> a.getId(), a -> a));
        zizhi(qualificationCache, head, fileCache, orUpdateOaDTO);
        //银行信息
        final List<SupplierBank> list = supplierBankService.list(new LambdaQueryWrapper<SupplierBank>()
                .eq(SupplierBank::getSupplierId, supplier.getId())
                .groupBy(SupplierBank::getCompanyCode));
        bank(list, orUpdateOaDTO, companyCache);
        gongsi(purchaseCategories, companyCache,accetpDeadlineCache, controllingAccountsCache, paymentWayCache, paymentTermsCache,
                orUpdateOaDTO);
        zuzhi(purchaseCategories, purchaseOrgCache, orUpdateOaDTO, StrUtil.EMPTY);
        final ApiResult<String> orUpdate = supplierOaClient.createOrUpdate(orUpdateOaDTO);
        final String code = orUpdate.getCode();
        if (code.equals(RestCode.SAP_SUCCESS.getCode())) {
            final String oaId = orUpdate.getData();
            final LambdaUpdateWrapper<SupplierPurchaseCategory> updateWrapper =
                    new LambdaUpdateWrapper<SupplierPurchaseCategory>()
                            .set(SupplierPurchaseCategory::getEffectiveTime,
                                    LocalDateTime.now().plusMonths(3))//当前日期向后3个月
                            .set(SupplierPurchaseCategory::getApprState,
                                    PurchaseCategoryApprStatus.APPROVALING.getStatus());
            final Set<Long> ids = purchaseCategories.stream().map(SupplierPurchaseCategory::getId)
                    .collect(Collectors.toSet());
            if (StrUtil.isNotEmpty(oaId)) {
                updateWrapper.set(SupplierPurchaseCategory::getOaId, oaId);
            }
            updateWrapper.in(SupplierPurchaseCategory::getId, ids);
            supplierPurchaseCategoryService.update(updateWrapper);
        } else {
            throw new DaoException(orUpdate.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void supplierChangeToOa(SupplierChangeVersion paramDTO) {
        final Long changeId = paramDTO.getId();
        final List<CompanyDTO> companyDTOS = companyClient.getAll();
        final Map<String, String> companyCache = companyDTOS.stream()
                .collect(Collectors.toMap(CompanyDTO::getCompanyCode, CompanyDTO::getCompanyName));
        final List<DictDTO> supplierAccetpDeadline = dictClient.getDicByType(DictCode.SUPPLIER_ACCETP_DEADLINE.getCode());
        final Map<String, String> accetpDeadlineCache = supplierAccetpDeadline.stream()
                .collect(Collectors.toMap(DictDTO::getCode, DictDTO::getName));

        final List<DictDTO> controllingAccounts = dictClient.getDicByType(DictCode.CONTROLLING_ACCOUNTS.getCode());
        final Map<String, String> controllingAccountsCache = controllingAccounts.stream()
                .collect(Collectors.toMap(DictDTO::getCode, DictDTO::getName));

        final List<DictDTO> paymentTerms = dictClient.getDicByType(DictCode.PAYMENT_TERMS.getCode());
        final Map<String, String> paymentTermsCache = paymentTerms.stream()
                .collect(Collectors.toMap(DictDTO::getCode, DictDTO::getName));

        final List<DictDTO> paymentWay = dictClient.getDicByType(DictCode.PAYMENT_WAY.getCode());
        final Map<String, String> paymentWayCache = paymentWay.stream()
                .collect(Collectors.toMap(DictDTO::getCode, DictDTO::getName));

        final List<PurchaseOrgDTO> purchaseOrgDTOS = purchaseOrgClient.getAll();
        final Map<String, String> purchaseOrgCache = purchaseOrgDTOS.stream()
                .collect(Collectors.toMap(PurchaseOrgDTO::getPurchaseOrgCode, PurchaseOrgDTO::getPurchaseOrgDesc));
        CreateOrUpdateOaDTO orUpdateOaDTO = new CreateOrUpdateOaDTO();
        final CreateOrUpdateOaDTO.Head head = new CreateOrUpdateOaDTO.Head();
        //需要把变更信息找到
        final SupplierChangeVersion changeVersion = supplierChangeVersionService.getById(changeId);
        final Long supplierId = changeVersion.getSupplierId();
        final Supplier supplier = supplierService.getById(supplierId);
        head.setFd_daiTaoTai(String.valueOf(paramDTO.getEliminateFlag()));
        if(StringUtils.isNotEmpty(paramDTO.getExecutionTime())){
            head.setExecutionTime(paramDTO.getExecutionTime());
            head.setPaymentTerms(paramDTO.getPaymentTerms());
        }

        head.setFd_sqePingShen(StringUtils.isNotEmpty(supplier.getApprovalOpinion()) ? supplier.getApprovalOpinion() : "" );
        //需要查询到扩展数据然后把修改数据填充进去
        final List<SupplierExtension> supplierExtensions = supplierExtensionService.list(
                new LambdaQueryWrapper<SupplierExtension>().eq(SupplierExtension::getSupplierId, supplier.getId()));
        final Map<String, String> extVal = supplierExtensions.stream()
                .collect(Collectors.toMap(SupplierExtension::getExtensionKey,
                        a -> Objects.nonNull(a.getExtensionValue()) ? a.getExtensionValue() : ""));
        //需要把变更基础信息查询放进来
        final List<SupplierVersion> list = supplierVersionService.list(new LambdaQueryWrapper<SupplierVersion>()
                .eq(SupplierVersion::getChangeVersionId, changeId));
        if (CollUtil.isNotEmpty(list)) {
            final Map<String, String> collect = list.stream()
                    .collect(Collectors.toMap(SupplierVersion::getField, SupplierVersion::getValue));
            BeanUtil.fillBeanWithMap(collect, supplier, true);
            extVal.putAll(collect);
        }
        final SupplierInvitaion invitaionServiceOne = supplierInvitaionService.getOne(
                new LambdaQueryWrapper<SupplierInvitaion>()
                        .eq(SupplierInvitaion::getSupplierId, supplier.getId()), false);

        final List<PurchaseGroupDTO> purchaseGroupDTOS = purchaseGroupClient.getAll();
        final Map<String, String> purchaseGroupCache = purchaseGroupDTOS.stream()
                .collect(Collectors.toMap(PurchaseGroupDTO::getPurchaseGroupCode,
                        PurchaseGroupDTO::getPurchaseGroupName));
        //获取变更后的品类数据
        final List<SupplierPurchaseCategory> supplierPurchaseCategories = getSupplierPurchaseCategories(
                changeId, supplier);
        //这个地方需要获取品类中日期最长的
        final Optional<LocalDateTime> max = supplierPurchaseCategories.stream()
                .filter(a -> Objects.nonNull(a.getEffectiveTime()))
                .map(SupplierPurchaseCategory::getEffectiveTime)
                .max(Comparator.naturalOrder());
        max.ifPresent(localDateTime -> head.setFd_linShiQiXian(DateUtils.formatYYYYMMDDDash(localDateTime)));
        final String categoryNames = supplierPurchaseCategories.stream()
                .map(SupplierPurchaseCategory::getPurchaseCategoryName)
                .collect(Collectors.joining(StrUtil.COMMA));
        final String categoryCodes = supplierPurchaseCategories.stream().map(a -> a.getPurchaseCategoryCode())
                .collect(Collectors.joining(StrUtil.COMMA));
        final CurrentUserDTO currentUser = LoginUtil.getCurrentUser();
        final String loginName = currentUser.getLoginName();
        head.setFd_shenQingDanHao(String.valueOf(changeId));
        head.setFd_srmType(OaProcessType.SUPPLIER_CHANGE.getType());
        if (CollUtil.isEmpty(supplierPurchaseCategories)) {
            throw new DaoException("无法取消所有品类");
        }
        basicInfo(supplier, categoryNames, categoryCodes, supplierPurchaseCategories.get(0).getTaxCode(), head,
                loginName, extVal,
                invitaionServiceOne, purchaseGroupCache, paramDTO.getBpmCode());
        final ChangeVersionOaType oaType = ChangeVersionOaType.forValue(paramDTO.getOaType());
        switch (oaType) {
            case NONE:
                head.setFd_isCaiWu(FlagConst.N.getMsg());
                head.setFd_isZhiLiang(FlagConst.N.getMsg());
                break;
            case FINANCE:
                head.setFd_isCaiWu(FlagConst.Y.getMsg());
                head.setFd_isZhiLiang(FlagConst.N.getMsg());
                break;
            case QUALITY:
                head.setFd_isCaiWu(FlagConst.N.getMsg());
                head.setFd_isZhiLiang(FlagConst.Y.getMsg());
                break;
            case FINANCE_AND_QUALITY:
                head.setFd_isCaiWu(FlagConst.Y.getMsg());
                head.setFd_isZhiLiang(FlagConst.Y.getMsg());
                break;
        }


        String encryptHex = EncryptUtils.encrypt(String.valueOf(changeId));
        head.setFd_bianGneg(
                StrUtil.format("{}/pc/supplier/supplierChange/page/lookup?id={}&type=1", sysProp.getWebsiteUrl(),
                        encryptHex));
        head.setFd_gongYingShangDaiMa(supplier.getSupplierErpCode());
        //供应变更后的联系人数据
        final Map<Integer, List<SupplierContacts>> supplierContactsCache = getSupplierContactsCache(
                changeId, supplier);
        supplierCantacts(supplierContactsCache, head);
        final SupplierSqeScore sqeScore = supplierSqeScoreService.getOne(new LambdaQueryWrapper<SupplierSqeScore>()
                .eq(SupplierSqeScore::getSupplierId, supplier.getId()), false);
        sqe(sqeScore, head);
        //供应商资质数据
        final List<SupplierQualification> supplierQualifications = supplierQualificationService.list(
                new LambdaQueryWrapper<SupplierQualification>()
                        .eq(SupplierQualification::getSupplierId, supplier.getId()));
        //需要查询到变更的数据
        final List<SupplierQualificationChangeItem> changeItems = supplierQualificationChangeItemService.list(
                new LambdaQueryWrapper<SupplierQualificationChangeItem>()
                        .eq(SupplierQualificationChangeItem::getVersionChangeId, changeId));
        final List<SupplierQualificationChangeItem> editItem = changeItems.stream()
                .filter(a -> Objects.nonNull(a.getQualificationId())).toList();
        final Map<Long, SupplierQualificationChangeItem> editItemCache = editItem.stream()
                .collect(Collectors.toMap(SupplierQualificationChangeItem::getQualificationId, a -> a));
        for (SupplierQualification supplierQualification : supplierQualifications) {
            final Long id = supplierQualification.getId();
            if (CollUtil.isNotEmpty(editItemCache) && Objects.nonNull(editItemCache.get(id))) {
                final SupplierQualificationChangeItem tmp = editItemCache.get(id);
                supplierQualification.setFileId(tmp.getNewFileId());
                supplierQualification.setQualificationNumber(tmp.getNewQualificationNumber());
                supplierQualification.setAvailableEndDate(tmp.getNewAvailableEndDate());
            }
        }
        final List<SupplierQualificationChangeItem> addItem = changeItems.stream()
                .filter(a -> Objects.isNull(a.getQualificationId())).toList();
        for (SupplierQualificationChangeItem changeItem : addItem) {
            SupplierQualification supplierQualification = new SupplierQualification();
            supplierQualification.setQualificationCode(changeItem.getQualificationCode());
            supplierQualification.setFileId(changeItem.getNewFileId());
            supplierQualification.setAvailableEndDate(changeItem.getNewAvailableEndDate());
            supplierQualifications.add(supplierQualification);
        }

        final Map<String, List<SupplierQualification>> qualificationCache = supplierQualifications.stream()
                .collect(Collectors.groupingBy(SupplierQualification::getQualificationCode));
        final Set<Long> filIds = supplierQualifications.stream().map(SupplierQualification::getFileId)
                .collect(Collectors.toSet());
        final Set<Long> collect = supplierQualifications.stream().filter(a -> Objects.nonNull(a.getSqeFileId()))
                .map(SupplierQualification::getSqeFileId)
                .collect(Collectors.toSet());
        filIds.addAll(collect);
        final List<FileResposePreviewCDTO> previewUrl = fileClient.getPreviewUrl(filIds);
        final Map<Long, FileResposePreviewCDTO> fileCache = previewUrl.stream()
                .collect(Collectors.toMap(FileResposeCDTO::getId, a -> a));
        zizhi(qualificationCache, head, fileCache, orUpdateOaDTO);
        //获取银行数据
        final List<SupplierBank> collect1 = getSupplierBanks(changeId, supplier);
        bank(collect1, orUpdateOaDTO, companyCache);
        gongsi(supplierPurchaseCategories, companyCache,accetpDeadlineCache,controllingAccountsCache, paymentWayCache, paymentTermsCache,
                orUpdateOaDTO);
        String freeze = StrUtil.EMPTY;
        if (Objects.nonNull(paramDTO.getIsFreeze())
                && paramDTO.getIsFreeze().equals(FreezeConst.FREEZE.getCode())) {
            freeze = "X";
        }
        zuzhi(supplierPurchaseCategories, purchaseOrgCache, orUpdateOaDTO, freeze);
        final ApiResult<String> orUpdate = supplierOaClient.createOrUpdate(orUpdateOaDTO);
        final String code = orUpdate.getCode();
        if (code.equals(RestCode.SAP_SUCCESS.getCode())) {
            final String oaId = orUpdate.getData();
            paramDTO.setBpmState(SupplierChangeBpmState.APPROVALING.getVal());
            if (StrUtil.isNotEmpty(oaId)) {
                paramDTO.setBpmCode(oaId);
            }
            supplierChangeVersionService.updateById(paramDTO);
        } else {
            throw new DaoException(orUpdate.getMessage());
        }

    }

    @NotNull
    private List<SupplierBank> getSupplierBanks(Long changeId, Supplier supplier) {
        final List<SupplierBankVersion> supplierBankVersions = supplierBankVersionService.list(
                new LambdaQueryWrapper<SupplierBankVersion>()
                        .eq(SupplierBankVersion::getChangeVersionId, changeId));
        final List<SupplierBankVersion> addOrUpdate = supplierBankVersions.stream()
                .filter(a -> a.getType() == VersionChangeType.CREATE.getType() ||
                        a.getType() == VersionChangeType.EDIT.getType()).toList();
        final Set<Long> delIds = supplierBankVersions.stream()
                .filter(a -> a.getType() == VersionChangeType.DEL.getType() ||
                        a.getType() == VersionChangeType.EDIT.getType())
                .map(SupplierBankVersion::getMasterId).collect(Collectors.toSet());
        final List<SupplierBank> supplierBanks = supplierBankService.list(new LambdaQueryWrapper<SupplierBank>()
                .eq(SupplierBank::getSupplierId, supplier.getId()));
        final List<SupplierBank> supplierBanks1 = supplierBanks.stream().filter(a -> !delIds.contains(a.getId()))
                .toList();
        log.info("supplierBanks: {}", supplierBanks1);
        List<SupplierBank> masterEntity = supplierBankVersionConvert.toMasterEntity(addOrUpdate);
        log.info("masterEntity: {}", masterEntity);
        masterEntity.addAll(supplierBanks1);
        return masterEntity;
    }

    @NotNull
    private Map<Integer, List<SupplierContacts>> getSupplierContactsCache(Long changeId, Supplier supplier) {
        final List<SupplierContactsVersion> contactsVersions = supplierContactsVersionService.list(
                new LambdaQueryWrapper<SupplierContactsVersion>()
                        .eq(SupplierContactsVersion::getChangeVersionId, changeId));
        final List<SupplierContactsVersion> addOrUpdate = contactsVersions.stream()
                .filter(a -> a.getType() == VersionChangeType.CREATE.getType() ||
                        a.getType() == VersionChangeType.EDIT.getType()).toList();
        final Set<Long> delIds = contactsVersions.stream()
                .filter(a -> a.getType() == VersionChangeType.DEL.getType() ||
                        a.getType() == VersionChangeType.EDIT.getType())
                .map(SupplierContactsVersion::getMasterId).collect(Collectors.toSet());
        final List<SupplierContacts> supplierContacts = supplierContactsService.list(
                new LambdaQueryWrapper<SupplierContacts>().eq(SupplierContacts::getSupplierId, supplier.getId()));
        final List<SupplierContacts> list1 = supplierContacts.stream().filter(a -> !delIds.contains(a.getId()))
                .toList();
        List<SupplierContacts> cc = supplierContactsVersionConvert.toMasterEntity(addOrUpdate);
        cc.addAll(list1);
        final Map<Integer, List<SupplierContacts>> supplierContactsCache = cc.stream()
                .collect(Collectors.groupingBy(a -> Integer.valueOf(a.getContactsType())));
        return supplierContactsCache;
    }

    @NotNull
    private List<SupplierPurchaseCategory> getSupplierPurchaseCategories(Long changeId, Supplier supplier) {
        final List<SupplierPurchaseCategoryVersion> listed = supplierPurchaseCategoryVersionService.list(
                new LambdaQueryWrapper<SupplierPurchaseCategoryVersion>()
                        .eq(SupplierPurchaseCategoryVersion::getChangeVersionId, changeId));
        /**
         * 需要把本次删除和编辑和冻结状态的数据的采购品类id拿出来
         * 需要把数据库中存在的采购品类拿出来，然后把本次变更的数据剔除掉
         * 然后把本次新增和编辑的数据添加进去
         */
        final Set<Long> delIds = listed.stream()
                .filter(a -> a.getType() == VersionChangeType.DEL.getType() ||
                        a.getType() == VersionChangeType.EDIT.getType() ||
                        Objects.equals(a.getIsFreeze(), FreezeConst.FREEZE.getCode()))
                .map(SupplierPurchaseCategoryVersion::getMasterId).collect(Collectors.toSet());
        final List<SupplierPurchaseCategoryVersion> tmp = listed.stream()
                .filter(a -> a.getType() == VersionChangeType.CREATE.getType() ||
                        a.getType() == VersionChangeType.EDIT.getType()).toList();
        final List<SupplierPurchaseCategoryVersion> addOrUpdate = tmp.stream()
                .filter(a -> Objects.equals(a.getIsFreeze(), FreezeConst.NORMAL.getCode()))
                .collect(Collectors.toList());
        //只查询 小批量，合格
        List<Integer> state = Lists.newArrayList();
        state.add(AuthenticationState.QUALIFIED.getState());
        state.add(AuthenticationState.SMALL_BATCH.getState());
        state.add(AuthenticationState.FORMAL.getState());
        final List<SupplierPurchaseCategory> list1 = supplierPurchaseCategoryService.list(
                new LambdaQueryWrapper<SupplierPurchaseCategory>()
                        .in(SupplierPurchaseCategory::getState, state)
                        .eq(SupplierPurchaseCategory::getIsFreeze, FreezeConst.NORMAL.getCode())
                        .eq(SupplierPurchaseCategory::getSupplierId, supplier.getId()));
        final List<SupplierPurchaseCategory> collect = new java.util.ArrayList<>(
                list1.stream().filter(a -> !delIds.contains(a.getId()))
                        .toList());
        List<SupplierPurchaseCategory> newCategory = supplierPurchaseCategoryVersionConvert.toMastEntity(addOrUpdate);
        newCategory.addAll(collect);
        return newCategory;
    }

    private void basicInfo(Supplier supplier, String categoruNames, String categoryCodes, String taxCode,
                           CreateOrUpdateOaDTO.Head head, String loginName, Map<String, String> extVal,
                           SupplierInvitaion invitaionServiceOne, Map<String, String> purchaseGroupCache, String oaId)
    {
        final List<DictDTO> supplierType = dictClient.getDicByType(DictCode.SUPPLIER_TYPE.getCode());
        final Map<String, String> supplierTypeCache = supplierType.stream()
                .collect(Collectors.toMap(DictDTO::getCode, DictDTO::getName));

        final List<DictDTO> supplyType = dictClient.getDicByType(DictCode.SUPPLY_TYPE.getCode());
        final Map<String, String> supplyTypeCache = supplyType.stream()
                .collect(Collectors.toMap(DictDTO::getCode, DictDTO::getName));

        final List<DictDTO> supplierClassify = dictClient.getDicByType(DictCode.SUPPLIER_CLASSIFY.getCode());
        final Map<String, String> supplierClassifyCache = supplierClassify.stream()
                .collect(Collectors.toMap(DictDTO::getCode, DictDTO::getName));

        final List<DictDTO> supplierAttr = dictClient.getDicByType(DictCode.SUPPLIER_ATTR.getCode());
        final Map<String, String> supplierAttrCache = supplierAttr.stream()
                .collect(Collectors.toMap(DictDTO::getCode, DictDTO::getName));

        final List<DictDTO> procurementStrategy = dictClient.getDicByType(DictCode.PROCUREMENT_STRATEGY.getCode());
        final Map<String, String> procurementStrategyCache = procurementStrategy.stream()
                .collect(Collectors.toMap(DictDTO::getCode, DictDTO::getName));

        final List<DictDTO> assessType = dictClient.getDicByType(DictCode.ASSESS_TYPE.getCode());
        final Map<String, String> assessTypeCache = assessType.stream()
                .collect(Collectors.toMap(DictDTO::getCode, DictDTO::getName));

        final List<DictDTO> rohsFlag = dictClient.getDicByType(DictCode.ROHS_FLAG.getCode());
        final Map<String, String> rohsFlagCache = rohsFlag.stream()
                .collect(Collectors.toMap(DictDTO::getCode, DictDTO::getName));

        final List<DictDTO> supplierGroup = dictClient.getDicByType(DictCode.SUPPLIER_GROUP.getCode());
        final Map<String, String> supplierGroupCache = supplierGroup.stream()
                .collect(Collectors.toMap(DictDTO::getCode, DictDTO::getName));

        final List<TaxDTO> tax = taxClient.getAll();
        final Map<String, BigDecimal> taxCache = tax.stream()
                .collect(Collectors.toMap(TaxDTO::getTaxCode, TaxDTO::getTaxValue));
        if (StrUtil.isNotEmpty(oaId)) {
            head.setProcessId(oaId);//如果是驳回需要重新传入
        }
        head.setFd_shenQingRenXingMing(loginName);//申请人工号
        head.setFd_caiGouZu(purchaseGroupCache.get(supplier.getPurchaseGroupCode()));//采购组
        head.setFd_caiGouZuDaiMa(supplier.getPurchaseGroupCode());//采购组
        head.setFd_zhangHuZu(supplierGroupCache.get(supplier.getSupplierGroup()));//供应商分组
        head.setFd_zhangHuZuDaiMa(supplier.getSupplierGroup());//供应商分组
        head.setFd_gongYingShangMingCheng1(supplier.getSupplierName());//供应商名称1
        head.setFd_gongYingShangMingCheng2(supplier.getShortName());//供应商简称
        head.setFd_gongYingShangMingCheng3(supplier.getSupplierNameEn());//英文名称
        head.setFd_gongYingShangDaiMa(supplier.getSupplierErpCode());//供应商编码
        final String country = areaClient.getAreaName(supplier.getCountry());
        head.setFd_guoJia(country);//国家
        head.setFd_guoJiaDaiMa(supplier.getCountry());//国家

        final String areaName = areaClient.getAreaName(supplier.getProvince(), supplier.getCountry());
        head.setFd_diQu(areaName);//地区(省份)
        head.setFd_diQuDaiMa(supplier.getProvince());//地区(省份)
        if (StrUtil.isEmpty(supplier.getCity())) {
            //如果城市为空就需要把省份的名称设置到城市中
            head.setFd_chengShi(areaName);//城市
        } else {
            final String cityName = areaClient.getAreaName(supplier.getCity(), supplier.getProvince());
            head.setFd_chengShi(cityName);//城市
        }
        head.setFd_youBian(supplier.getZipCode());//邮编
        head.setFd_jieDaoDiZhi(supplier.getAddress());//街道/门牌
        head.setFd_yuYan(supplyTypeCache.get(supplier.getSupplyType()));//语言
        head.setFd_yuYanDaiMa(supplier.getSupplyType());//语言代码
        head.setFd_dianHua(supplier.getTel());//电话
        head.setFd_yiDongDianHua(supplier.getMobile());//移动电话
        head.setFd_dianZiYouJian(supplier.getEmail());//电子邮件
        head.setFd_sqyy(invitaionServiceOne.getInviteDesc());//申请原因
        head.setFd_faRen(supplier.getLegal());//法人代表
        head.setFd_chengLiRiQi(supplier.getEstablishmentDate());//成立日期
        head.setFd_zhuCeZiBen(StringUtils.isNotEmpty(extVal.get("registerMoney")) ? extVal.get("registerMoney") : "");//注册资金
        head.setFd_zhanDiMianJi(StringUtils.isNotEmpty(extVal.get("q1")) ? extVal.get("q1") : "");//占地面积
        head.setFd_huanBaoYaoQiu(StringUtils.isNotEmpty(rohsFlagCache.get(extVal.get("rohsFlag")))? rohsFlagCache.get(extVal.get("rohsFlag")) : "");//环保要求
        head.setFd_qiYeLeiXing(supplierTypeCache.get(supplier.getSupplierTypeId()));//企业类型
        head.setFd_xingZhi(supplierClassifyCache.get(supplier.getSupplierGenre()));//企业性质
        head.setFd_kongZhiFang(StringUtils.isNotEmpty(extVal.get("transportation")) ? extVal.get("transportation") : "");//控制方(集团母公司)
        head.setFd_shuXing(supplierAttrCache.get(supplier.getAttr()));//属性
        head.setFd_chanpinLeiBie(categoruNames);//产品类别
        head.setFd_chanPinLeiBieBianMa(categoryCodes);//产品类别编码
        head.setFd_chanPinPinPai(StringUtils.isNotEmpty(extVal.get("productBrand")) ? extVal.get("productBrand") :"");//产品品牌/制造商简称
        head.setFd_keHu(supplier.getCustomer2Name());//客户
        head.setFd_keHuDaiMa(supplier.getCustomer2Code());//客户
        head.setFd_zhuYaoKeHu(StringUtils.isNotEmpty(extVal.get("tSupplierMainCustomerProduct")) ? extVal.get("tSupplierMainCustomerProduct") : "");//主要客户
        head.setFd_shuiMa(taxCache.get(taxCode).multiply(new BigDecimal("100")).toString());//税码名称
        head.setFd_shuiMaDaiMa(taxCode);////税码代码
        head.setFd_shuiHao(supplier.getBusinessRegisterNo());//税号
        head.setFd_shuiHaoLeiBie("CN5");//税号类别
        head.setFd_caiGouCeLv(procurementStrategyCache.get(supplier.getProcurementStrategy()));//采购策略
        head.setFd_shiXiaoRiQi(DateUtil.format(LocalDateTime.now().plusMonths(3L), yyyyMMddDash));//失效日期
        head.setFd_pinShenFangShi(assessTypeCache.get(supplier.getAssessType()));//评审方式
        head.setSupplierRegister(supplier.getColBeiyOne());//工商注册地址
        //  head.setFd_sqePingShen(supplier.getApprovalOpinion());
    }

    private void supplierCantacts(Map<Integer, List<SupplierContacts>> supplierContactsCache,
                                  CreateOrUpdateOaDTO.Head head)
    {
        //业务员
        final List<SupplierContacts> supplierContacts1 = supplierContactsCache.get(
                DictCode.ContactType.BUSINESS.getType());
        if (CollUtil.isNotEmpty(supplierContacts1)) {
            //默认取第一个
            final SupplierContacts tmp = supplierContacts1.get(0);
            head.setFd_yeWuYuan(tmp.getContactsName());//业务员姓名
            head.setFd_yeWuYuanDianHua(tmp.getContactsTel());//业务员电话
            head.setFd_yeWuYuanYouXiang(tmp.getEmail());//业务员邮箱
        }
        //业务经理
        final List<SupplierContacts> contacts = supplierContactsCache.get(
                DictCode.ContactType.BUSINESS_MANAGER.getType());
        if (CollUtil.isNotEmpty(contacts)) {
            final SupplierContacts tmp = contacts.get(0);
            head.setFd_yeWuJingLi(tmp.getContactsName());//业务经理姓名
            head.setFd_yeWuJingLiDianHua(tmp.getContactsTel());//业务经理电话
            head.setFd_yeWuJingLiYouXiang(tmp.getEmail());//业务经理邮箱
        }

        //品保人员
        final List<SupplierContacts> supplierContacts2 = supplierContactsCache.get(
                DictCode.ContactType.QUALITY.getType());
        if (CollUtil.isNotEmpty(supplierContacts2)) {
            final SupplierContacts tmp = supplierContacts2.get(0);
            head.setFd_pinBao(tmp.getContactsName());//品保人员姓名
            head.setFd_pinBaoDianHua(tmp.getContactsTel());//品保人员电话
            head.setFd_pinBaoYouXiang(tmp.getEmail());//品保人员邮箱
        }

        //品质经理
        final List<SupplierContacts> supplierContacts3 = supplierContactsCache.get(
                DictCode.ContactType.QUALITY_MANAGER.getType());
        if (CollUtil.isNotEmpty(supplierContacts3)) {
            final SupplierContacts tmp = supplierContacts3.get(0);
            head.setFd_pinZhi(tmp.getContactsName());//品质经理姓名
            head.setFd_pinZhiDianHua(tmp.getContactsTel());//品质经理电话
            head.setFd_pinZhiYouXiang(tmp.getEmail());//品质经理邮箱
        }

        //财务人员
        final List<SupplierContacts> supplierContacts4 = supplierContactsCache.get(
                DictCode.ContactType.FINANCE.getType());
        if (CollUtil.isNotEmpty(supplierContacts4)) {
            final SupplierContacts tmp = supplierContacts4.get(0);
            head.setFd_caiWu(tmp.getContactsName());//财务人员姓名
            head.setFd_caiWuDianHua(tmp.getContactsTel());//财务人员电话
            head.setFd_caiWuYouXiang(tmp.getEmail());//财务人员邮箱
        }
    }

    private void sqe(SupplierSqeScore sqeScore, CreateOrUpdateOaDTO.Head head) {
        if (Objects.nonNull(sqeScore)) {
            head.setFd_gyyDengji(sqeScore.getSupplierLevel());//供应商等级
            head.setFd_pingShenDate(DateUtils.formatYYYYMMDDDash(LocalDate.from(sqeScore.getCreateTime())));//评审日期
            if (Objects.nonNull(sqeScore.getQsaScore())) {
                head.setFd_qsaScore(sqeScore.getQsaScore().toString());//QSA评分
            } else {
                head.setFd_qsaScore(StrUtil.EMPTY);//QSA评分
            }

            if (Objects.nonNull(sqeScore.getQpaScore())) {
                head.setFd_qpaScore(sqeScore.getQpaScore().toString());//QPA评分
            } else {
                head.setFd_qpaScore(StrUtil.EMPTY);//QPA评分
            }

            if (Objects.nonNull(sqeScore.getPurchasePriceScore())) {
                head.setFd_cgjgScore(sqeScore.getPurchasePriceScore().toString());//采购价格评分
            } else {
                head.setFd_cgjgScore(StrUtil.EMPTY);//采购价格评分
            }

            if (Objects.nonNull(sqeScore.getPurchaseScore())) {
                head.setFd_cgjqScore(sqeScore.getPurchaseScore().toString());//采购交期评分
            } else {
                head.setFd_cgjqScore(StrUtil.EMPTY);//采购交期评分
            }


            if (Objects.nonNull(sqeScore.getRdScore())) {
                head.setFd_yanFaScore(sqeScore.getRdScore().toString());//研发评分
            } else {
                head.setFd_yanFaScore(StrUtil.EMPTY);//研发评分
            }


            head.setFd_zongScore(sqeScore.getTotalScore().toString());//总分
            if (Objects.nonNull(sqeScore.getNonManufacturerPurchaseScore())) {
                head.setFd_feiZhiZaoScore(sqeScore.getNonManufacturerPurchaseScore().toString());//非制造商采购评分
            }
            head.setFd_youShi(sqeScore.getSupplierStrength());//供应商优势
            head.setFd_lieShi(sqeScore.getSupplierWeakness());//供应商劣势
        }
    }

    private void zizhi(Map<String, List<SupplierQualification>> qualificationCache, CreateOrUpdateOaDTO.Head head,
                       Map<Long, FileResposePreviewCDTO> fileCache, CreateOrUpdateOaDTO orUpdateOaDTO)
    {
        //营业执照
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_019.name()))) {

            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_019.name()).get(0);
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_yyzzUrl(JSON.toJSONString(Lists.newArrayList(build)));//营业执照附件
            }
            head.setFd_yyzzDate(tmp.getAvailableEndDate());//营业执照有效期
        }

        //ISO 9001证书
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_002.name()))) {

            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_002.name()).get(0);
            //需要处理成
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_9001Url(JSON.toJSONString(Lists.newArrayList(build)));//ISO 9001附件
            }
            head.setFd_9001Date(tmp.getAvailableEndDate());//ISO 9001证书有效期
        }

        //出口许可证
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_017.name()))) {

            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_017.name()).get(0);
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_ckUrl(JSON.toJSONString(Lists.newArrayList(build)));//出口许可证附件
            }
            head.setFd_ckDate(tmp.getAvailableEndDate());//出口许可证（适用于海外供应商）有效期
        }

        //海关评级文件
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_016.name()))) {
            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_016.name()).get(0);
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_hgUrl(JSON.toJSONString(Lists.newArrayList(build)));//海关评级文件附件
            }
            head.setFd_hgDate(tmp.getAvailableEndDate());//海关评级文件有效期
        }

        //ISO 14001证书有效期
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_001.name()))) {

            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_001.name()).get(0);
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_14001Url(JSON.toJSONString(Lists.newArrayList(build)));//ISO 14001证书附件
            }
            head.setFd_14001Date(tmp.getAvailableEndDate());//ISO 14001证书有效期
        }

        //ISO 45001证书有效期
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_006.name()))) {

            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_006.name()).get(0);
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_45001Url(JSON.toJSONString(Lists.newArrayList(build)));//ISO 45001证书附件
            }
            head.setFd_45001Date(tmp.getAvailableEndDate());//ISO 45001证书有效期
        }

        //其它有效期
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_039.name()))) {

            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_039.name()).get(0);
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_qiTaXieYiUrl(JSON.toJSONString(Lists.newArrayList(build)));//其它有效期附件
            }
            head.setFd_qiTaXieYi(tmp.getVersion());
            head.setFd_qiTaXieYiDate(tmp.getAvailableEndDate());//其它有效期
        }

        //采购框架协议
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_007.name()))) {

            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_007.name()).get(0);
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_cgkjXieYiUrl(JSON.toJSONString(Lists.newArrayList(build)));
            }
            head.setFd_cgkjXieYi(tmp.getVersion());
            head.setFd_cgkjXieYiDate(tmp.getAvailableStartDate());
        }

        //供应商产品质量保证协议
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_009.name()))) {

            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_009.name()).get(0);
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_zlbzXieYiUrl(JSON.toJSONString(Lists.newArrayList(build)));
            }
            head.setFd_zlbzXieYi(tmp.getVersion());
            head.setFd_zlbzXieYiDate(tmp.getAvailableStartDate());
        }

        //供应商物料PCN变更协议
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_011.name()))) {

            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_011.name()).get(0);
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_pcnXieYiUrl(JSON.toJSONString(Lists.newArrayList(build)));
            }
            head.setFd_pcnXieYi(tmp.getVersion());
            head.setFd_pcnXieYiDate(tmp.getAvailableStartDate());
        }

        //环保保证函
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_014.name()))) {

            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_014.name()).get(0);
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_huanBaoXieYiUrl(JSON.toJSONString(Lists.newArrayList(build)));
            }
            head.setFd_huanBaoXieYi(tmp.getVersion());
            head.setFd_huanBaoXieYiDate(tmp.getAvailableStartDate());
        }


        //C-TPAT安全调查问卷
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_005.name()))) {

            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_005.name()).get(0);
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_anQuanXieYiUrl(JSON.toJSONString(Lists.newArrayList(build)));
            }
            head.setFd_anQuanXieYi(tmp.getVersion());
            head.setFd_anQuanXieYiDate(tmp.getAvailableStartDate());
        }

        //供应商行为守则自查表
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_013.name()))) {

            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_013.name()).get(0);
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_xingWeiXieYiUrl(JSON.toJSONString(Lists.newArrayList(build)));
            }
            head.setFd_xingWeiXieYi(tmp.getVersion());
            head.setFd_xingWeiXieYiDate(tmp.getAvailableStartDate());
        }

        //供应商保密协议
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_008.name()))) {

            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_008.name()).get(0);
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_baoMiXieYiUrl(JSON.toJSONString(Lists.newArrayList(build)));
            }
            head.setFd_baoMiXieYi(tmp.getVersion());
            head.setFd_baoMiXieYiDate(tmp.getAvailableStartDate());
        }

        //廉洁协议书
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_015.name()))) {

            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_015.name()).get(0);
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_lianJieXieYiUrl(JSON.toJSONString(Lists.newArrayList(build)));
            }
            head.setFd_lianJieXieYi(tmp.getVersion());
            head.setFd_lianJieXieYiDate(tmp.getAvailableStartDate());
        }

        //供应商信息安全协议书
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_012.name()))) {

            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_012.name()).get(0);
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_xinXiXieYiuUrl(JSON.toJSONString(Lists.newArrayList(build)));
            }
            head.setFd_xinXiXieYi(tmp.getVersion());
            head.setFd_xinXiXieYiDate(tmp.getAvailableStartDate());
        }

        //供应商社会责任承诺书
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_010.name()))) {

            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_010.name()).get(0);
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_zeRenXieYiUrl(JSON.toJSONString(Lists.newArrayList(build)));
            }
            head.setFd_zeRenXieYi(tmp.getVersion());
            head.setFd_zeRenXieYiDate(tmp.getAvailableStartDate());
        }

        //收款委托书
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_068.name()))) {

            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_068.name()).get(0);
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_shouKuanShuUrl(JSON.toJSONString(Lists.newArrayList(build)));
            }
            head.setFd_shouKuanShu(tmp.getVersion());
            head.setFd_shouKuanShuDate(tmp.getAvailableStartDate());
        }
        //银行信息
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_069.name()))) {

            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_069.name()).get(0);
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_yinHangUrl(JSON.toJSONString(Lists.newArrayList(build)));
            }
            head.setFd_yinHang(tmp.getVersion());
            head.setFd_yinHangDate(tmp.getAvailableStartDate());
        }
        //其他补充协议
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_025.name()))) {

            final SupplierQualification tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_025.name()).get(0);
            final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
            if (Objects.nonNull(fileResposeDTO)) {
                final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                        .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl()).build();
                head.setFd_qiTaXieYiUrl(JSON.toJSONString(Lists.newArrayList(build)));
            }
            head.setFd_qiTaXieYi(tmp.getVersion());
            head.setFd_qiTaXieYiDate(tmp.getAvailableStartDate());
        }

        //供应商基本资料调查表
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_021.name()))) {
            List<OaFileParamDTO> fileParamDTOS = Lists.newArrayList();
            final List<SupplierQualification> tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_021.name());
            for (SupplierQualification ttmp : tmp) {
                final FileResposePreviewCDTO fileResposeDTO = fileCache.get(ttmp.getSqeFileId());
                if (Objects.nonNull(fileResposeDTO)) {
                    final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                            .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl())
                            .build();
                    fileParamDTOS.add(build);
                }

            }
            head.setFd_jbdcUrl(JSON.toJSONString(fileParamDTOS));
        }


        //供应商准入门槛
        List<OaFileParamDTO> fileParamDTOS = Lists.newArrayList();
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_026.name()))) {

            final List<SupplierQualification> tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_026.name());
            for (SupplierQualification ttmp : tmp) {
                final FileResposePreviewCDTO fileResposeDTO = fileCache.get(ttmp.getSqeFileId());
                if (Objects.nonNull(fileResposeDTO)) {
                    final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                            .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl())
                            .build();
                    fileParamDTOS.add(build);
                }

            }
        }
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_020.name()))) {
            final List<SupplierQualification> tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_020.name());
            for (SupplierQualification ttmp : tmp) {
                final FileResposePreviewCDTO fileResposeDTO = fileCache.get(ttmp.getSqeFileId());
                if (Objects.nonNull(fileResposeDTO)) {
                    final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                            .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl())
                            .build();
                    fileParamDTOS.add(build);
                }

            }
        }
        head.setFd_jbyqUrl(JSON.toJSONString(fileParamDTOS));

        //QSA Checklist
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_022.name()))) {
            List<OaFileParamDTO> fileParamDTOS1 = Lists.newArrayList();
            final List<SupplierQualification> tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_022.name());
            for (SupplierQualification ttmp : tmp) {
                final FileResposePreviewCDTO fileResposeDTO = fileCache.get(ttmp.getSqeFileId());
                if (Objects.nonNull(fileResposeDTO)) {
                    final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                            .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl())
                            .build();
                    fileParamDTOS1.add(build);
                }

            }
            head.setFd_qsaUrl(JSON.toJSONString(fileParamDTOS1));
        }


        //QPA Checklist
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_023.name()))) {
            List<OaFileParamDTO> fileParamDTOS1 = Lists.newArrayList();
            final List<SupplierQualification> tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_023.name());
            for (SupplierQualification ttmp : tmp) {
                final FileResposePreviewCDTO fileResposeDTO = fileCache.get(ttmp.getSqeFileId());
                if (Objects.nonNull(fileResposeDTO)) {
                    final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                            .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl())
                            .build();
                    fileParamDTOS1.add(build);
                }

            }
            head.setFd_qpaUrl(JSON.toJSONString(fileParamDTOS1));
        }

        //新供应商评鉴总表
        List<OaFileParamDTO> pinjianFiles = Lists.newArrayList();
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_024.name()))) {

            final List<SupplierQualification> tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_024.name());
            for (SupplierQualification ttmp : tmp) {
                final FileResposePreviewCDTO fileResposeDTO = fileCache.get(ttmp.getSqeFileId());
                if (Objects.nonNull(fileResposeDTO)) {
                    final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                            .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl())
                            .build();
                    pinjianFiles.add(build);
                }

            }
        }
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_064.name()))) {
            final List<SupplierQualification> tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_064.name());
            for (SupplierQualification ttmp : tmp) {
                final FileResposePreviewCDTO fileResposeDTO = fileCache.get(ttmp.getSqeFileId());
                if (Objects.nonNull(fileResposeDTO)) {
                    final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                            .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl())
                            .build();
                    pinjianFiles.add(build);
                }

            }
        }
        head.setFd_pjUrl(JSON.toJSONString(pinjianFiles));

        //评审其他附件
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_065.name()))) {
            List<OaFileParamDTO> fileParamDTOS1 = Lists.newArrayList();
            final List<SupplierQualification> tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_065.name());
            for (SupplierQualification ttmp : tmp) {
                final FileResposePreviewCDTO fileResposeDTO = fileCache.get(ttmp.getSqeFileId());
                if (Objects.nonNull(fileResposeDTO)) {
                    final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                            .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl())
                            .build();
                    fileParamDTOS1.add(build);
                }
            }
            head.setFd_psqtUrl(JSON.toJSONString(fileParamDTOS1));
        }

        //供应商审核报告
        if (Objects.nonNull(qualificationCache.get(DictCode.SupplierQualification.SRM_ZZ_066.name()))) {
            List<OaFileParamDTO> fileParamDTOS1 = Lists.newArrayList();
            final List<SupplierQualification> tmp = qualificationCache.get(
                    DictCode.SupplierQualification.SRM_ZZ_066.name());
            for (SupplierQualification ttmp : tmp) {
                final FileResposePreviewCDTO fileResposeDTO = fileCache.get(ttmp.getSqeFileId());
                if (Objects.nonNull(fileResposeDTO)) {
                    final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                            .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl())
                            .build();
                    fileParamDTOS1.add(build);
                }
            }
            head.setFd_shbgUrl(JSON.toJSONString(fileParamDTOS1));
        }

        //代理证附件
        final ArrayList<OaFileParamDTO> objects = Lists.newArrayList();
        for (String code : DictCode.SupplierQualification.getDailiZheng()) {
            if (Objects.nonNull(qualificationCache.get(code))) {
                final SupplierQualification tmp = qualificationCache.get(code).get(0);
                head.setFd_daiLIZhengDate(tmp.getAvailableEndDate());
                final FileResposePreviewCDTO fileResposeDTO = fileCache.get(tmp.getFileId());
                if (Objects.nonNull(fileResposeDTO)) {
                    final OaFileParamDTO build = OaFileParamDTO.builder().url(fileResposeDTO.getPreviewUrl())
                            .date(tmp.getAvailableEndDate())
                            .fileName(fileResposeDTO.getFileName()).downloadUrl(fileResposeDTO.getDownloadUrl())
                            .build();
                    objects.add(build);
                }
            }
        }
        head.setFd_daiLIZhengUrl(JSON.toJSONString(objects));
        orUpdateOaDTO.setHead(head);
    }

    private void bank(List<SupplierBank> list, CreateOrUpdateOaDTO orUpdateOaDTO, Map<String, String> companyCache) {
        if (CollUtil.isNotEmpty(list)) {
            final CreateOrUpdateOaDTO.YinhangItem yinhangItem = new CreateOrUpdateOaDTO.YinhangItem();
            yinhangItem.setItem(Lists.newArrayList());
            for (SupplierBank supplierBank : list) {
                final CreateOrUpdateOaDTO.YinhangItem.Item item = new CreateOrUpdateOaDTO.YinhangItem.Item();
                item.setFd_yingHangDaiMa(supplierBank.getBankCode());//银行行号 Bank Code
                item.setFd_zhangHuChiYouRen(supplierBank.getCompanyName());//收款单位
                item.setFd_yingHangZhanghao(supplierBank.getBankAccount());//银行账号
                item.setFd_yingHangMingCheng(supplierBank.getOpeningBankName());//收款银行（外币填写英文）
                item.setFd_yingHangDiZhi(supplierBank.getBankAddress());//银行地址（外币填写英文详细地址）
                item.setFd_yingHangGuoJiDaiMa(supplierBank.getBankInterCode());//银行国际代码 Swift Code
                item.setFd_gongSiDaiMa(supplierBank.getCompanyCode());
                final String companyName = companyCache.get(supplierBank.getCompanyCode());
                item.setFd_gongSi(companyName);
                yinhangItem.getItem().add(item);
            }
            orUpdateOaDTO.setYinhangItem(yinhangItem);
        }
    }

    private void gongsi(List<SupplierPurchaseCategory> purchaseCategories, Map<String, String> companyCache,
                        Map<String, String> accetpDeadlineCache,
                        Map<String, String> controllingAccountsCache, Map<String, String> paymentWayCache,
                        Map<String, String> paymentTermsCache, CreateOrUpdateOaDTO orUpdateOaDTO)
    {
        //公司数据
        // 按照 paymentTerms, paymentMethod, companyCode, 和 controlSubject 进行分组，并只保留相同属性的唯一条目
        Map<List<String>, SupplierPurchaseCategory> uniqueCategories = purchaseCategories.stream()
                .collect(Collectors.toMap(
                        category -> List.of(category.getPaymentTerms(), category.getPaymentMethod(),
                                category.getCompanyCode(), category.getControlSubject()),
                        category -> category,
                        (existing, replacement) -> existing // 如果有重复的键，保留第一个条目
                ));
        final CreateOrUpdateOaDTO.FuKuanItem fuKuanItem = new CreateOrUpdateOaDTO.FuKuanItem();
        fuKuanItem.setItem(Lists.newArrayList());
        for (SupplierPurchaseCategory value : uniqueCategories.values()) {
            final CreateOrUpdateOaDTO.FuKuanItem.Item item = new CreateOrUpdateOaDTO.FuKuanItem.Item();
            item.setFd_gongSi(companyCache.get(value.getCompanyCode()));
            item.setFd_gongSiDaiMa(value.getCompanyCode());
            item.setFd_tongYuKeMu(controllingAccountsCache.get(value.getControlSubject()));
            item.setFd_tongYuKeMuDaiMa(value.getControlSubject());
            item.setFd_fuKuanFangshi(paymentWayCache.get(value.getPaymentMethod()));
            item.setFd_fuKuanFangshiDaiMa(value.getPaymentMethod());
            item.setFd_fuKuanTiaoJian(paymentTermsCache.get(value.getPaymentTerms()));
            item.setFd_fuKuanTiaoJianDaiMa(value.getPaymentTerms());
            item.setFd_zhangQi(accetpDeadlineCache.get(value.getAcceptanceMethod()));
            fuKuanItem.getItem().add(item);
        }
        orUpdateOaDTO.setFuKuanItem(fuKuanItem);
    }

    private void zuzhi(List<SupplierPurchaseCategory> purchaseCategories, Map<String, String> purchaseOrgCache,
                       CreateOrUpdateOaDTO orUpdateOaDTO, String freeze)
    {
        //zuZhiItem
        // 按照  进行分组，并只保留相同属性的唯一条目
        Map<List<String>, SupplierPurchaseCategory> uniqueCategories1 = purchaseCategories.stream()
                .collect(Collectors.toMap(
                        category -> List.of(category.getPurchaseOrgCode(), category.getCurrencyCode()),
                        category -> category,
                        (existing, replacement) -> existing // 如果有重复的键，保留第一个条目
                ));
        final CreateOrUpdateOaDTO.ZuZhiItem zuZhiItem = new CreateOrUpdateOaDTO.ZuZhiItem();
        zuZhiItem.setItem(Lists.newArrayList());
        for (SupplierPurchaseCategory value : uniqueCategories1.values()) {
            final CreateOrUpdateOaDTO.ZuZhiItem.Item item = new CreateOrUpdateOaDTO.ZuZhiItem.Item();
            item.setFd_caiGouZuZhi(purchaseOrgCache.get(value.getPurchaseOrgCode()));
            item.setFd_caiGouZuZhiDaiMa(value.getPurchaseOrgCode());
            item.setFd_huoBi(value.getCurrencyCode());
            if (freeze.equals("X")) {
                item.setFd_dongJieDate(DateUtils.formatYYYYMMDDDash(LocalDate.now()));
            }
            item.setFd_zhuangTai(freeze);
            zuZhiItem.getItem().add(item);
        }
        orUpdateOaDTO.setZuZhiItem(zuZhiItem);
    }
}