package com.jwipc.inquiry.logic.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jwipc.aggregation.ModelAggregationService;
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.OaProcessType;
import com.jwipc.dto.ExportDataDTO;
import com.jwipc.dto.ExportEnumDataDTO;
import com.jwipc.exception.DaoException;
import com.jwipc.inquiry.constant.FixOaClient;
import com.jwipc.inquiry.constant.InquiryStatus;
import com.jwipc.inquiry.constant.InquirySupplierStatus;
import com.jwipc.inquiry.constant.SysConfigKey;
import com.jwipc.inquiry.convert.*;
import com.jwipc.inquiry.dto.*;
import com.jwipc.inquiry.entity.*;
import com.jwipc.inquiry.logic.InquiryLogic;
import com.jwipc.inquiry.logic.InquiryMaterialSupplierLogic;
import com.jwipc.inquiry.logic.InquiryTemplateLogic;
import com.jwipc.inquiry.logic.PriceInfoLogic;
import com.jwipc.inquiry.model.po.AssistantMaterialSupplierPO;
import com.jwipc.inquiry.model.po.AssistantSupplierPO;
import com.jwipc.inquiry.model.po.InquiryMaterialSupplierPO;
import com.jwipc.inquiry.model.query.InquiryQuoteQuery;
import com.jwipc.inquiry.service.*;
import com.jwipc.order.clent.dto.PurchaseDetailDTO;
import com.jwipc.order.client.PurchaseOrderClient;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.prop.PriceHandle;
import com.jwipc.prop.SysProp;
import com.jwipc.security.LoginUtil;
import com.jwipc.supplier.clent.dto.SupplierAvlBaseDTO;
import com.jwipc.supplier.clent.dto.SupplierDTO;
import com.jwipc.supplier.clent.dto.SupplierPurchaseCategoryDTO;
import com.jwipc.supplier.client.SupplierClient;
import com.jwipc.supplier.entity.Supplier;
import com.jwipc.sys.client.*;
import com.jwipc.sys.client.dto.*;
import com.jwipc.sys.entity.User;
import com.jwipc.util.EasyExcelImportUtils;
import com.jwipc.util.EasyExcelUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import static com.jwipc.constant.SysConfigKey.INQUIRY_FIX_NO_OA_PURCHASE_CATEGORY_CODE;
import static java.util.stream.Collectors.groupingBy;

/**
 * @author shenyang.ou
 * @date 2024/2/22 11:36
 * @desc 询价物料供应商
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class InquiryMaterialSupplierLogicImpl implements InquiryMaterialSupplierLogic {
    private final IInquiryMaterialService inquiryMaterialService;
    private final ProductClient productClient;
    private final IInquiryMaterialSupplierService inquiryMaterialSupplierService;
    private final SysConfigClient sysConfigClient;
    private final IInquirySupplierQuoteLogService inquirySupplierQuoteLogService;
    private final IInquiryMaterialSupplierExtendService inquiryMaterialSupplierExtendService;
    private final IInquiryService inquiryService;
    private final IInquiryApproveService inquiryApproveService;
    private final IInquirySupplierService inquirySupplierService;
    private final UserClient userClient;
    private final IInquirySupplierCostQuoteDetailService inquirySupplierCostQuoteDetailService;
    private final InquirySupplierConvert inquirySupplierConvert;
    private final InquiryMaterialConvert inquiryMaterialConvert;
    private final InquiryMaterialSupplierConvert inquiryMaterialSupplierConvert;
    private final PriceHandle priceHandle;
    private final InquirySupplierCostQuoteDetailConvert inquirySupplierCostQuoteDetailConvert;
    private final InquiryMaterialSupplierExtendConvert inquiryMaterialSupplierExtendConvert;
    private final IPriceInfoService priceInfoService;
    private final PriceInfoLogic priceInfoLogic;
    private final PriceInfoConvert priceInfoConvert;
    private final InquiryTemplateLogic inquiryTemplateLogic;
    private final InquiryLogic inquiryLogic;
    private final DictClient dictClient;
    private final FixOaClient fixOaClient;
    private final ExchangeRateClient exchangeRateClient;
    private final SupplierClient supplierClient;
    private final EmailSendClient emailSendClient;
    private final ProductGroupClient productGroupClient;
    private final ModelAggregationService modelAggregationService;
    private final TaxClient taxClient;
    private final PurchaseCategoryClient purchaseCategoryClient;
    private final FileClient fileClient;
    private final SysProp sysProp;
    private final PurchaseOrderClient purchaseOrderClient;

    /**
     * 根据询价id查询询价物料供应商（分组）
     */
    @Override
    public List<InquiryMaterialSupplierDTO> getGroupListByInquiryId(Long inquiryId,Integer bidFlag) {
        List<InquiryMaterialSupplierPO> inquiryPOS = inquiryMaterialSupplierService.getGroupListByInquiryId(inquiryId,bidFlag);
        List<InquiryMaterialSupplierDTO> inquiryMaterialSupplierDTOS = inquiryMaterialSupplierConvert.po2DTOList(inquiryPOS);
        inquiryMaterialSupplierDTOS.forEach(s -> {
            if (null!=s.getNoTaxPrice()){
                s.setConversionPrice(s.getNoTaxPrice().multiply(s.getExchangeRate()));
            }
            if (null!=s.getHistoryPrice()&&null!=s.getConversionPrice()){
                BigDecimal chajia = s.getHistoryPrice().subtract(s.getConversionPrice());
                s.setIncreasePrice(chajia.divide(s.getHistoryPrice(), 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString());
            }
            //初始化原始配额 2024-12-02 邓京术
            if (Objects.isNull(s.getConfirmQuotaView()) || s.getConfirmQuotaView().equals(BigDecimal.ZERO)) {
                s.setConfirmQuotaView(s.getConfirmQuota());
            }

        });
        return inquiryMaterialSupplierDTOS;
    }

    /**
     * 根据询价id和询价物料id查询询价物料供应商
     *
     * @param inquiryId         询价id
     * @param inquiryMaterialId 询价物料id
     * @return 询价物料供应商
     */
    @Override
    public List<InquiryMaterialSupplierDTO> getListByInquiryIdAndInquiryMaterialId(Long inquiryId, Long inquiryMaterialId) {
        List<InquiryMaterialSupplierPO> inquiryPOS = inquiryMaterialSupplierService.getListByInquiryIdAndInquiryMaterialId(inquiryId,inquiryMaterialId);
        inquiryPOS.forEach(s -> {
            //初始化原始配额 2024-12-02 邓京术
            if (Objects.isNull(s.getConfirmQuotaView()) || s.getConfirmQuotaView().equals(BigDecimal.ZERO)) {
                s.setConfirmQuotaView(s.getConfirmQuota());
            }
        });
        return inquiryMaterialSupplierConvert.po2DTOList(inquiryPOS);
    }

    /**
     * 获取供应商报价列表
     *
     * @param query  参数
     * @return 供应商报价列表
     */
    @Override
    public List<InquiryMaterialSupplierDTO> quoteList(InquiryQuoteQuery query) {
        List<InquiryMaterialSupplierPO> inquiryPOS = inquiryMaterialSupplierService.quoteList(query);
        List<InquiryMaterialSupplierDTO> inquiryMaterialSupplierDTOS = inquiryMaterialSupplierConvert.po2DTOList(inquiryPOS);
        inquiryMaterialSupplierDTOS.forEach(s -> {
            if (null!=s.getNoTaxPrice()){
                s.setConversionPrice(s.getNoTaxPrice().multiply(s.getExchangeRate()));
            }
            if (null!=s.getHistoryPrice()&&null!=s.getConversionPrice()){
                BigDecimal chajia = s.getConversionPrice().subtract(s.getHistoryPrice());
                if (s.getHistoryPrice().compareTo(BigDecimal.ZERO)!=0){
                    s.setIncreasePrice(chajia.divide(s.getHistoryPrice(), 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString());
                }
            }
            //初始化原始配额 2024-12-02 邓京术
            if (Objects.isNull(s.getConfirmQuotaView()) || s.getConfirmQuotaView().equals(BigDecimal.ZERO)) {
                s.setConfirmQuotaView(s.getConfirmQuota());
            }
        });
        if (query.getProductGroupWithCategoryFlag()!=null){
            //无需oa审批的采购品类 移出来，不要放在循环中查询 2024-12-25 邓京术
            final String noOaPurchaseCategoryCode = sysConfigClient.getTextConfig(INQUIRY_FIX_NO_OA_PURCHASE_CATEGORY_CODE.getCode());
            //产品组缓存 减少重复查询
            Map productGroupMap = Maps.newHashMap();
            inquiryMaterialSupplierDTOS.forEach(inquiryMaterialSupplierDTO -> {
                //物料组和品类关系是否存在
                AtomicBoolean materialGroupWithCategoryFlag = new AtomicBoolean(false);
                    //校验物料组和品类关系是否存在
                    List<SupplierPurchaseCategoryDTO> supplierPurchaseCategoryDTOS = supplierClient.getList(String.valueOf(inquiryMaterialSupplierDTO.getSupplierId()));
                    if (CollectionUtil.isNotEmpty(supplierPurchaseCategoryDTOS)){
                        supplierPurchaseCategoryDTOS.forEach(supplierPurchaseCategoryDTO -> {
                            ProductGroupDTO productGroupDTO = productGroupClient.getByCodeAndCategory(inquiryMaterialSupplierDTO.getMaterialGroupCode(),supplierPurchaseCategoryDTO.getPurchaseCategoryCode());
                            if (ObjectUtil.isNotNull(productGroupDTO)){
                                materialGroupWithCategoryFlag.set(true);
                            }
                        });
                    }
                    //校验物料组的品类是不是MRO,如果是所有供应商都可以报
                    ProductGroupDTO productGroupDTO1 = null;
                    if (productGroupMap.keySet().contains(inquiryMaterialSupplierDTO.getMaterialGroupCode())) {
                        productGroupDTO1 = (ProductGroupDTO) productGroupMap.get(inquiryMaterialSupplierDTO.getMaterialGroupCode());
                    } else {
                        productGroupDTO1 = productGroupClient.getByCode(inquiryMaterialSupplierDTO.getMaterialGroupCode());
                        if (ObjectUtil.isNotNull(productGroupDTO1)) {
                            productGroupMap.put(inquiryMaterialSupplierDTO.getMaterialGroupCode(), productGroupDTO1);
                        }
                    }
                    if (ObjectUtil.isNotNull(productGroupDTO1) && StringUtils.isEmpty(productGroupDTO1.getCategoryCode())){
                        materialGroupWithCategoryFlag.set(true);
                    }else {
                        if (ObjectUtil.isNotNull(productGroupDTO1)&&noOaPurchaseCategoryCode.contains(productGroupDTO1.getCategoryCode())){
                            materialGroupWithCategoryFlag.set(true);
                        }
                    }
                inquiryMaterialSupplierDTO.setProductGroupWithCategoryFlag(materialGroupWithCategoryFlag.get()?1:0);
            });
        }
        markLowPrice(query,inquiryMaterialSupplierDTOS);
        return inquiryMaterialSupplierDTOS;
    }

    /**
     * 标记最低价
     * @param query
     * @param inquiryMaterialSupplierDTOS
     */
    public void markLowPrice(InquiryQuoteQuery query,List<InquiryMaterialSupplierDTO> inquiryMaterialSupplierDTOS){
        //标记最低价
        Map<Long, List<InquiryMaterialSupplierDTO>> maps = inquiryMaterialSupplierDTOS.stream().collect(groupingBy(InquiryMaterialSupplierDTO::getInquiryMaterialId));
        if (ObjectUtil.isNotNull(query.getSupplierId())){
            maps = inquiryMaterialSupplierDTOS.stream().collect(groupingBy(InquiryMaterialSupplierDTO::getSupplierId));
        }
        for (Long inquiryMaterialId : maps.keySet()) {
            List<InquiryMaterialSupplierDTO> inquiryMaterialSupplierDTOList = maps.get(inquiryMaterialId);
            if (inquiryMaterialSupplierDTOList.size() > 0) {
                //过滤掉价格为0的数据
                inquiryMaterialSupplierDTOList.removeIf(s -> Objects.isNull(s.getConversionPrice())||s.getConversionPrice().compareTo(BigDecimal.ZERO)==0);
                Optional<BigDecimal> min = inquiryMaterialSupplierDTOList.stream()
                        .map(InquiryMaterialSupplierDTO::getConversionPrice)
                        .filter(Objects::nonNull)
                        .min(BigDecimal::compareTo);
                if (min.isPresent()){
                    List<InquiryMaterialSupplierDTO> list = inquiryMaterialSupplierDTOList.stream()
                            .filter(s -> Objects.nonNull(s.getConversionPrice())&&s.getConversionPrice().compareTo(min.get()) == 0)
                            .toList();
                    list.forEach(s -> s.setMinPriceFlag(1));
                }
            }
        }
    }

    @Override
    public PageView quoteListPage(InquiryQuoteQuery query) {
        final Page<InquiryMaterialSupplier> dbPage = PageUtil.toPage(query);
        List<InquiryMaterialSupplierPO> inquiryPOS = inquiryMaterialSupplierService.quoteListPage(dbPage,query);
        List<InquiryMaterialSupplierDTO> inquiryMaterialSupplierDTOS = inquiryMaterialSupplierConvert.po2DTOList(inquiryPOS);
        inquiryMaterialSupplierDTOS.forEach(s -> {
            if (null!=s.getNoTaxPrice()){
                s.setConversionPrice(s.getNoTaxPrice().multiply(s.getExchangeRate()));
            }
            if (null!=s.getHistoryPrice()&&null!=s.getConversionPrice()){
                BigDecimal chajia = s.getConversionPrice().subtract(s.getHistoryPrice());
                s.setIncreasePrice(chajia.divide(s.getHistoryPrice(), 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString());
            }
            //初始化原始配额 2024-12-02 邓京术
            if (Objects.isNull(s.getConfirmQuotaView()) || s.getConfirmQuotaView().equals(BigDecimal.ZERO)) {
                s.setConfirmQuotaView(s.getConfirmQuota());
            }

        });
        return PageUtil.getPV(inquiryMaterialSupplierDTOS, dbPage.getTotal());
    }

    /**
     * 获取已经报价的供应商列表
     *
     * @param inquiryId 询价id
     * @return 已经报价的供应商列表
     */
    @Override
    public List<AssistantSupplierDTO> getAssistantSupplierByInquiryId(Long inquiryId) {
        List<AssistantSupplierPO> assistantSupplierPOS = inquiryMaterialSupplierService.getAssistantSupplierByInquiryId(inquiryId);
        List<AssistantSupplierDTO> assistantSupplierDTOS = inquiryMaterialSupplierConvert.assistantSupplierPO2DTOList(assistantSupplierPOS);
        modelAggregationService.processRelationAggregation(assistantSupplierDTOS);
        //字典赋值
        assistantSupplierDTOS.forEach(assistantSupplierDTO -> {
            DictDTO dictDTO = dictClient.getDictByTypeAndCode(DictCode.PAYMENT_TERMS.getCode(), assistantSupplierDTO.getPaymentMethod());
            if (ObjectUtil.isNotNull(dictDTO)){
                assistantSupplierDTO.setPaymentMethodName(dictDTO.getName());
            }
        });
        return assistantSupplierDTOS;
    }

    /**
     * 报价保存
     *
     * @param param 参数
     */
    @Override
    @Transactional
    public void saveQuote(InquirySupplierQuoteParamDTO param) {
        final LocalDateTime now = LocalDateTime.now();
        final InquirySupplier oldInquirySupplier = inquirySupplierService.getById(param.getId());
        //更新询价供应商数据
        InquirySupplier inquirySupplier = inquirySupplierConvert.paramDTO2Entity(param);
        //是否为供应商报价判断 2024--11-15 邓京术
        boolean isQuote = false;
        Inquiry inquiry = inquiryService.getById(oldInquirySupplier.getInquiryId());
        SupplierDTO supplierDTO = supplierClient.getSupplierByCode(oldInquirySupplier.getSupplierCode());

        //如果状态为议价中或者已议价
        if (oldInquirySupplier.getInquirySupplierStatus()==InquirySupplierStatus.OPINION_ING.getStatus()||oldInquirySupplier.getInquirySupplierStatus()==InquirySupplierStatus.OPINION_FINISH.getStatus()){
            //状态改为已议价
            inquirySupplier.setInquirySupplierStatus(InquirySupplierStatus.OPINION_FINISH.getStatus());
        }else {
            //状态改为已报价
            inquirySupplier.setInquirySupplierStatus(InquirySupplierStatus.QUOTE_FINISH.getStatus());
            if (oldInquirySupplier.getQuoteFlag() == 0) {
                isQuote = true;
            }
        }
        inquirySupplier.setQuoteFlag(1);
        inquirySupplier.setUpdateTime(now);
        inquirySupplier.setUpdateUser(LoginUtil.getUserId());
        inquirySupplierService.updateById(inquirySupplier);
        //更新询价物料供应商信息
        List<InquiryMaterialSupplier> inquiryMaterialSuppliers = new ArrayList<>();
        List<InquiryMaterialSupplierExtend> inquiryMaterialSupplierExtends = new ArrayList<>();
        List<InquirySupplierQuoteLog> inquirySupplierQuoteLogs = new ArrayList<>();
        for (InquiryMaterialSupplierDTO inquiryMaterialSupplierDTO : param.getInquiryMaterialSupplierList()){
            InquiryMaterialSupplier inquiryMaterialSupplier = inquiryMaterialSupplierConvert.DTO2Entity(inquiryMaterialSupplierDTO);
            inquiryMaterialSupplier.setUpdateTime(now);
            inquiryMaterialSupplier.setUpdateUser(LoginUtil.getUserId());
            if (inquiryMaterialSupplier.getTaxPrice()!=null){
                inquiryMaterialSupplier.setTaxPriceFlag(1);
            }
            //议价标识置为已议价
            inquiryMaterialSupplier.setBargainFlag(inquirySupplier.getInquirySupplierStatus()==InquirySupplierStatus.OPINION_FINISH.getStatus()&&inquiryMaterialSupplier.getBargainFlag()!=0?2:0);
            //如果初始含税报价为空
            InquiryMaterialSupplier materialSupplier = inquiryMaterialSupplierService.getById(inquiryMaterialSupplier.getId());
            if (materialSupplier.getFirstTaxPrice()==null){
                inquiryMaterialSupplier.setFirstTaxPrice(inquiryMaterialSupplier.getTaxPrice());
                inquiryMaterialSupplier.setFirstNoTaxPrice(inquiryMaterialSupplier.getNoTaxPrice());
            }
            //记录报价日志
            if (inquiryMaterialSupplier.getTaxPrice()!=null){
                InquirySupplierQuoteLog inquirySupplierQuoteLog = new InquirySupplierQuoteLog();
                inquirySupplierQuoteLog.setInquiryId(inquiryMaterialSupplier.getInquiryId());
                inquirySupplierQuoteLog.setInquiryMaterialSupplierId(inquiryMaterialSupplier.getId());
                inquirySupplierQuoteLog.setTaxPrice(inquiryMaterialSupplier.getTaxPrice());
                inquirySupplierQuoteLog.setNoTaxPrice(inquiryMaterialSupplier.getNoTaxPrice());
                inquirySupplierQuoteLog.setType(oldInquirySupplier.getInquirySupplierStatus()==InquirySupplierStatus.OPINION_ING.getStatus()?2:1);
                inquirySupplierQuoteLog.setSupplierFormFiles(inquirySupplier.getSupplierFormFiles());
                inquirySupplierQuoteLog.setCreateTime(now);
                inquirySupplierQuoteLogs.add(inquirySupplierQuoteLog);
            }
            inquiryMaterialSuppliers.add(inquiryMaterialSupplier);
            //根据物料报价id号判断是否新增, 如果是新增报价，则根据供应商attr类型来设置物料报价的有效期开始截止日 2024-11-15号 邓京术  如果是2类型的自购原材料厂商，则有效期为半年， 其他暂时为一年
            if (isQuote) {
                List<DictDTO> dictDTOS = dictClient.getDicByType("supplier_material_quote_expiredate");
                dictDTOS.stream().forEach(item -> {
                    //如果字典的类型配置与供应商类型相等，则取出有效期月份
                    if (StringUtils.isNotEmpty(supplierDTO.getAttr()) && item.getName().equals(supplierDTO.getAttr())) {
                        LocalDateTime quoteEndDate = inquiry.getBeginTime();
                        LocalDateTime plusOneMonth = quoteEndDate.plusMonths(Integer.parseInt(item.getCode()));
                        inquiryMaterialSupplier.setQuoteEndDate(plusOneMonth);
                    }
                });
            }
            InquiryMaterialSupplierExtend inquiryMaterialSupplierExtend = inquiryMaterialSupplierExtendConvert.DTO2Entity(inquiryMaterialSupplierDTO);
            inquiryMaterialSupplierExtend.setInquiryId(inquiryMaterialSupplier.getInquiryId());
            inquiryMaterialSupplierExtend.setInquirySupplierId(inquiryMaterialSupplier.getId());
            inquiryMaterialSupplierExtends.add(inquiryMaterialSupplierExtend);
        }
        inquiryMaterialSupplierService.updateBatchById(inquiryMaterialSuppliers);
        inquiryMaterialSupplierExtendService.updateBatchById(inquiryMaterialSupplierExtends);
        inquirySupplierQuoteLogService.saveBatch(inquirySupplierQuoteLogs);
        //更新供应商成本报价信息
        List<InquirySupplierCostQuoteDetail> inquirySupplierCostQuoteDetails = inquirySupplierCostQuoteDetailConvert.dto2EntityList(param.getCostQuoteList());
        inquirySupplierCostQuoteDetailService.saveOrUpdateBatch(inquirySupplierCostQuoteDetails);

        //报价邮件提醒
        //发送报价邮件提醒
        final EmailTmpSingleSendDTO emailTxtSingleSendDTO = new EmailTmpSingleSendDTO();
        emailTxtSingleSendDTO.setTemplateCode("JW_POST_140");
        Map<String, Object> params = Maps.newHashMap();

        //获取采购
        UserDTO user = userClient.getByUserId(inquiry.getCreateUser());
        if (ObjectUtil.isNotNull(user)&&StrUtil.isNotEmpty(user.getEmail())){
            params.put("inquiryTitle", inquiry.getInquiryTitle());
            params.put("supplierName", supplierDTO.getSupplierName());
            params.put("url", sysProp.getWebsiteUrl());
            emailTxtSingleSendDTO.setParams(params);
            emailTxtSingleSendDTO.setReceiver(user.getEmail());
            emailTxtSingleSendDTO.setSender(LoginUtil.getUserId());
            emailSendClient.async(emailTxtSingleSendDTO);
        }

        //如果是新报价，则判断其他全部供应商有没有报价
        if (inquirySupplier.getInquirySupplierStatus()==InquirySupplierStatus.QUOTE_FINISH.getStatus()&&oldInquirySupplier.getQuoteFlag()==0){
            List<InquirySupplier> inquirySupplierList = inquirySupplierService.list(Wrappers.lambdaQuery(InquirySupplier.class)
                    .eq(InquirySupplier::getInquiryId,oldInquirySupplier.getInquiryId())
                    .ne(InquirySupplier::getSupplierId,oldInquirySupplier.getSupplierId()));
            //判断其他全部供应商有没有报价，如果都报价了，则发送全部报价邮件
            if (inquirySupplierList.stream().allMatch(inquirySupplier1 -> inquirySupplier1.getQuoteFlag()==1)){
                final EmailTmpSingleSendDTO emailTxtSingleSendDTO1 = new EmailTmpSingleSendDTO();
                emailTxtSingleSendDTO1.setTemplateCode("JW_POST_141");
                Map<String, Object> params1 = Maps.newHashMap();
                if (ObjectUtil.isNotNull(user)&&StrUtil.isNotEmpty(user.getEmail())){
                    params1.put("inquiryTitle", inquiry.getInquiryTitle());
                    params1.put("url", sysProp.getWebsiteUrl());
                    emailTxtSingleSendDTO1.setParams(params1);
                    emailTxtSingleSendDTO1.setReceiver(user.getEmail());
                    emailTxtSingleSendDTO1.setSender(LoginUtil.getUserId());
                    emailSendClient.async(emailTxtSingleSendDTO1);
                }
            }
        }
    }

    /**
     * 议价
     *
     * @param param 参数
     */
    @Override
    @Transactional
    public void bargain(InquirySupplierBargainParamDTO param) {
        Inquiry inquiry = inquiryService.getById(param.getInquiryId());
        inquiry.setBargainFiles(param.getBargainFiles());
        inquiry.setBargainRemark(param.getBargainRemark());
        inquiry.setUpdateTime(LocalDateTime.now());
        inquiry.setUpdateUser(LoginUtil.getUserId());
        inquiryService.updateById(inquiry);
        //设置物料供应商议价标识
        List<InquiryMaterialSupplier> inquiryMaterialSuppliers = inquiryMaterialSupplierConvert.dto2EntityList(param.getInquiryMaterialSupplierList());
        //只取参与报价的供应商
        inquiryMaterialSuppliers = inquiryMaterialSuppliers.stream().filter(inquiryMaterialSupplier -> inquiryMaterialSupplier.getJoinQuoteFlag()==1).collect(Collectors.toList());
        Map<String,String> map = new HashMap<>();
        for (InquiryMaterialSupplier inquiryMaterialSupplier : inquiryMaterialSuppliers){
            inquiryMaterialSupplier.setBargainFlag(1);
            inquiryMaterialSupplier.setUpdateTime(LocalDateTime.now());
            inquiryMaterialSupplier.setUpdateUser(LoginUtil.getUserId());
            if (StringUtils.isNotEmpty(inquiryMaterialSupplier.getSupplierEmail())){
                List<String> emailList = Arrays.asList(StringUtils.split(inquiryMaterialSupplier.getSupplierEmail(), ","));
                for (String email:emailList){
                    map.put(email,inquiryMaterialSupplier.getSupplierCode());
                }
            }
        }
        //发送议价邮件
        if (ObjectUtil.isNotEmpty(map)){
            for(Map.Entry entry : map.entrySet()){
                String mapKey = (String) entry.getKey();
                String mapValue = (String)entry.getValue();
                final EmailTmpSingleSendDTO emailTxtSingleSendDTO = new EmailTmpSingleSendDTO();
                emailTxtSingleSendDTO.setTemplateCode("JW_POST_060");
                Map<String, Object> params = Maps.newHashMap();
                SupplierDTO supplierDTO = supplierClient.getSupplierByCode(mapValue);
                params.put("supplierName", supplierDTO.getSupplierName());
                params.put("inquiryTitle", inquiry.getInquiryTitle());
                params.put("url", sysProp.getWebsiteUrl());
                params.put("supplierCode", mapValue);
                emailTxtSingleSendDTO.setParams(params);
                emailTxtSingleSendDTO.setReceiver(mapKey);
                emailTxtSingleSendDTO.setSender(LoginUtil.getUserId());
                emailSendClient.async(emailTxtSingleSendDTO);
            }
        }
        inquiryMaterialSupplierService.updateBatchById(inquiryMaterialSuppliers);
        //更新询价供应商状态为议价
        Map<Long, List<InquiryMaterialSupplier>> maps = inquiryMaterialSuppliers.stream().collect(groupingBy(InquiryMaterialSupplier::getSupplierId));
        List<InquirySupplier> inquirySuppliers = new ArrayList<>();
        for (Long supplierId : maps.keySet()) {
            InquirySupplier inquirySupplier = inquirySupplierService.getOne(Wrappers.lambdaQuery(InquirySupplier.class).eq(InquirySupplier::getInquiryId,param.getInquiryId()).eq(InquirySupplier::getSupplierId,supplierId).last(" limit 1"));
            if (ObjectUtil.isNotEmpty(inquirySupplier)){
                inquirySupplier.setInquirySupplierStatus(InquirySupplierStatus.OPINION_ING.getStatus());
                inquirySupplier.setUpdateTime(LocalDateTime.now());
                inquirySupplier.setUpdateUser(LoginUtil.getUserId());
                inquirySuppliers.add(inquirySupplier);
            }
        }
        inquirySupplierService.updateBatchById(inquirySuppliers);

    }

    /**
     * 议价截止
     *
     * @param param 参数
     */
    @Override
    public void bargainEnd(InquirySupplierBargainParamDTO param) {
        Inquiry inquiry = inquiryService.getById(param.getInquiryId());
        inquiry.setBargainFiles(param.getBargainFiles());
        inquiry.setBargainRemark(param.getBargainRemark());
        inquiry.setUpdateTime(LocalDateTime.now());
        inquiry.setUpdateUser(LoginUtil.getUserId());
        inquiryService.updateById(inquiry);
        //设置物料供应商议价标识
        List<InquiryMaterialSupplier> inquiryMaterialSuppliers = inquiryMaterialSupplierConvert.dto2EntityList(param.getInquiryMaterialSupplierList());
        //只取参与议价的供应商
        inquiryMaterialSuppliers = inquiryMaterialSuppliers.stream().filter(inquiryMaterialSupplier -> inquiryMaterialSupplier.getBargainFlag()==1||inquiryMaterialSupplier.getBargainFlag()==2).collect(Collectors.toList());
        inquiryMaterialSuppliers.forEach(inquiryMaterialSupplier -> {
            inquiryMaterialSupplier.setBargainFlag(0);
            inquiryMaterialSupplier.setUpdateTime(LocalDateTime.now());
            inquiryMaterialSupplier.setUpdateUser(LoginUtil.getUserId());
        });
        inquiryMaterialSupplierService.updateBatchById(inquiryMaterialSuppliers);
        //更新询价供应商状态为截止
        Map<Long, List<InquiryMaterialSupplier>> maps = inquiryMaterialSuppliers.stream().collect(groupingBy(InquiryMaterialSupplier::getSupplierId));
        List<InquirySupplier> inquirySuppliers = new ArrayList<>();
        for (Long supplierId : maps.keySet()) {
            InquirySupplier inquirySupplier = inquirySupplierService.getOne(Wrappers.lambdaQuery(InquirySupplier.class).eq(InquirySupplier::getInquiryId,param.getInquiryId()).eq(InquirySupplier::getSupplierId,supplierId).last(" limit 1"));
            if (ObjectUtil.isNotEmpty(inquirySupplier)){
                inquirySupplier.setInquirySupplierStatus(InquirySupplierStatus.END.getStatus());
                inquirySupplier.setUpdateTime(LocalDateTime.now());
                inquirySupplier.setUpdateUser(LoginUtil.getUserId());
                inquirySuppliers.add(inquirySupplier);
            }
        }
        inquirySupplierService.updateBatchById(inquirySuppliers);
    }

    /**
     * 定价
     *
     * @param param 参数
     */
    @Override
    @Transactional
    public void fixPrice(InquirySupplierBargainParamDTO param) {
        Inquiry inquiry = inquiryService.getById(param.getInquiryId());
        inquiry.setBargainFiles(param.getBargainFiles());
        inquiry.setBargainRemark(param.getBargainRemark());
        inquiry.setPurchaseCategoryCode(param.getPurchaseCategoryCode());
        inquiry.setSpotFlag(param.getSpotFlag());
        inquiry.setBusinessAgreeFlag(param.getBusinessAgreeFlag());
        inquiry.setCustomerBearFlag(param.getCustomerBearFlag());
        inquiry.setBearRatio(param.getBearRatio());
        inquiry.setStatus(param.getOptType()==0?InquiryStatus.END.getStatus():InquiryStatus.FIX_PENDING.getStatus());
        if (param.getOptType()==1){
            inquiry.setFinishTime(LocalDateTime.now());
        }
        inquiry.setUpdateTime(LocalDateTime.now());
        inquiry.setUpdateUser(LoginUtil.getUserId());
        inquiryService.updateById(inquiry);
        //先取消所有的定价
        List<InquiryMaterialSupplier> cancelInquiryMaterialSuppliers = inquiryMaterialSupplierService.list(Wrappers.lambdaQuery(InquiryMaterialSupplier.class).eq(InquiryMaterialSupplier::getInquiryId,param.getInquiryId()));
        cancelInquiryMaterialSuppliers.forEach(inquiryMaterialSupplier -> {
            inquiryMaterialSupplier.setBidFlag(0);
        });
        inquiryMaterialSupplierService.updateBatchById(cancelInquiryMaterialSuppliers);
        List<DictDTO> dictDTOS = dictClient.getDicByType("supplier_material_quote_expiredate");
        List<InquiryMaterialSupplier> inquiryMaterialSuppliers = inquiryMaterialSupplierConvert.dto2EntityList(param.getInquiryMaterialSupplierList());
        //优化查询供应商 2024-12-25 邓京术
        Map supplierMap = Maps.newHashMap();
        for (InquiryMaterialSupplier inquiryMaterialSupplier : inquiryMaterialSuppliers){
            //设置物料供应商中标标识
            inquiryMaterialSupplier.setBidFlag(1);
            //检查是否为潜在供应商
            SupplierDTO supplierDTO = null;
            if (supplierMap.keySet().contains(inquiryMaterialSupplier.getSupplierId())) {
                supplierDTO = (SupplierDTO) supplierMap.get(inquiryMaterialSupplier.getSupplierId());
            } else {
                supplierDTO = supplierClient.getSupplierById(inquiryMaterialSupplier.getSupplierId());
                supplierMap.put(inquiryMaterialSupplier.getSupplierId(), supplierDTO);
            }
            if (StrUtil.isEmpty(supplierDTO.getSupplierErpCode())){
                throw new DaoException(StrUtil.format("供应商{}为潜在状态，不能生成价格信息，不允许定价",supplierDTO.getSupplierCode()));
            }
            //根据物料报价id号判断是否新增, 如果是新增报价，则根据供应商attr类型来设置物料报价的有效期开始截止日 2024-12-19号 邓京术  如果是2类型的自购原材料厂商，则有效期为半年， 其他暂时为一年
            SupplierDTO finalSupplierDTO = supplierDTO;
            dictDTOS.stream().forEach(item -> {
                //如果字典的类型配置与供应商类型相等，则取出有效期月份
                if (StringUtils.isNotEmpty(finalSupplierDTO.getAttr()) && item.getName().equals(finalSupplierDTO.getAttr())) {
                    LocalDateTime quoteEndDate = inquiryMaterialSupplier.getQuoteFromDate();
                    LocalDateTime plusOneMonth = quoteEndDate.plusMonths(Integer.parseInt(item.getCode()));
                    inquiryMaterialSupplier.setQuoteEndDate(plusOneMonth);
                }
            });
            //推送OA的报价审批
            param.getInquiryMaterialSupplierList().stream().forEach(inquiryMaterialSupplierDTO -> {
                if (inquiryMaterialSupplierDTO.getId() == inquiryMaterialSupplier.getId()) {
                    inquiryMaterialSupplierDTO.setQuoteEndDate(inquiryMaterialSupplier.getQuoteEndDate());
                }
            });
            //设置物料供应商定价总金额
            inquiryMaterialSupplier.setBidTotalPrice(inquiryMaterialSupplier.getBidNumber().multiply(inquiryMaterialSupplier.getTaxPrice()));
            inquiryMaterialSupplier.setBidTime(LocalDateTime.now());
            inquiryMaterialSupplier.setUpdateTime(LocalDateTime.now());
            inquiryMaterialSupplier.setUpdateUser(LoginUtil.getUserId());
        }
        inquiryMaterialSupplierService.updateBatchById(inquiryMaterialSuppliers);
        //无需oa审批的采购品类
        final String noOaPurchaseCategoryCode = sysConfigClient.getTextConfig(INQUIRY_FIX_NO_OA_PURCHASE_CATEGORY_CODE.getCode());
        //如果为提交，调用定价审批接口
        if (param.getOptType()==1){
            //如果无需oa审批
            if (noOaPurchaseCategoryCode.contains(param.getPurchaseCategoryCode())){
                //更新所有询价供应商状态为询价结束
                inquiry.setStatus(InquiryStatus.SUPERVISOR_ING.getStatus());

                this.updateInquirySupplierStatus(param.getInquiryId());
            }else {
                //更新所有询价供应商状态为询价结束
//                inquiry.setStatus(InquiryStatus.FIX_PENDING.getStatus());
//                inquiry.setStatus(InquiryStatus.FIX_ING.getStatus());
                //提交oa审批
                //调用定价审批接口
                //定价导入审批流程
                List<InquiryMaterialSupplierDTO> inquiryMaterialSupplierList = param.getInquiryMaterialSupplierList();
                //过滤掉物料编码为空的
                List<InquiryMaterialSupplierDTO> filterInquiryMaterialSupplierList = inquiryMaterialSupplierList.stream().filter(inquiryMaterialSupplier -> StringUtils.isNotEmpty(inquiryMaterialSupplier.getMaterialCode())).toList();
                final ApiResult<String> orUpdate = fixOaClient.priceImport(this.priceImportData(inquiry,filterInquiryMaterialSupplierList));
                final String code = orUpdate.getCode();
                final String oaId = orUpdate.getData();
                final String message = orUpdate.getMessage();
                inquiry.setOaResult(message);
                inquiry.setOaTime(LocalDateTime.now());
                if (code.equals(RestCode.SAP_SUCCESS.getCode())) {
                    inquiry.setStatus(InquiryStatus.FIX_ING.getStatus());
                    inquiry.setOaWorkId(oaId);
                    inquiryService.updateById(inquiry);
                    //更新所有询价供应商状态为询价结束
                    this.updateInquirySupplierStatus(param.getInquiryId());
                    //更新所有询价供应商状态为询价结束
                    this.updateInquirySupplierStatus(param.getInquiryId());
                }else {
                    throw new DaoException("OA接口报错："+orUpdate.getMessage());
                }
            }
            inquiryService.updateById(inquiry);


            //结束所有的议价供应商
            List<InquiryMaterialSupplier> inquiryMaterialSuppliers1 = inquiryMaterialSupplierService.list(Wrappers.lambdaQuery(InquiryMaterialSupplier.class).eq(InquiryMaterialSupplier::getInquiryId,inquiry.getId()));
            //只取参与议价的供应商
            inquiryMaterialSuppliers1 = inquiryMaterialSuppliers1.stream().filter(inquiryMaterialSupplier -> inquiryMaterialSupplier.getBargainFlag()==1||inquiryMaterialSupplier.getBargainFlag()==2).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(inquiryMaterialSuppliers1)){
                inquiryMaterialSuppliers1.forEach(inquiryMaterialSupplier -> {
                    inquiryMaterialSupplier.setBargainFlag(0);
                    inquiryMaterialSupplier.setUpdateTime(LocalDateTime.now());
                    inquiryMaterialSupplier.setUpdateUser(LoginUtil.getUserId());
                });
                inquiryMaterialSupplierService.updateBatchById(inquiryMaterialSuppliers1);
                //更新询价供应商状态为截止
                Map<Long, List<InquiryMaterialSupplier>> maps = inquiryMaterialSuppliers1.stream().collect(groupingBy(InquiryMaterialSupplier::getSupplierId));
                List<InquirySupplier> inquirySuppliers = new ArrayList<>();
                for (Long supplierId : maps.keySet()) {
                    InquirySupplier inquirySupplier = inquirySupplierService.getOne(Wrappers.lambdaQuery(InquirySupplier.class).eq(InquirySupplier::getInquiryId,param.getInquiryId()).eq(InquirySupplier::getSupplierId,supplierId).last(" limit 1"));
                    if (ObjectUtil.isNotEmpty(inquirySupplier)){
                        inquirySupplier.setInquirySupplierStatus(InquirySupplierStatus.END.getStatus());
                        inquirySupplier.setUpdateTime(LocalDateTime.now());
                        inquirySupplier.setUpdateUser(LoginUtil.getUserId());
                        inquirySuppliers.add(inquirySupplier);
                    }
                }
                inquirySupplierService.updateBatchById(inquirySuppliers);
            }
        }


    }

    /**
     * 校验待淘汰供应商历史下单
     * @param param
     */
    @Override
    public void checkEliminateFlag(InquirySupplierBargainParamDTO param) {
        //2025-01-06
        List<InquiryMaterialSupplierDTO> inquiryMaterialSupplierListD = param.getInquiryMaterialSupplierList();
        //过滤掉物料编码为空的
        List<InquiryMaterialSupplierDTO> filterInquiryMaterialSupplierListD = inquiryMaterialSupplierListD.stream().filter(inquiryMaterialSupplier -> StringUtils.isNotEmpty(inquiryMaterialSupplier.getMaterialCode())).toList();
        //将供应商编码和供应商物料等信息存放到MAP里
        Map<String, List<String>> supplierMaterialMap = filterInquiryMaterialSupplierListD.stream()
                .collect(Collectors.groupingBy(
                        InquiryMaterialSupplierDTO::getSupplierCode, // 键映射器：获取供应商编码
                        Collectors.mapping( // 值映射器：将DTO映射到其物料
                                InquiryMaterialSupplierDTO::getMaterialCode,
                                Collectors.toList() // 收集器：将物料放入列表
                        )
                ));
        Iterator<Map.Entry<String, List<String>>> iterator = supplierMaterialMap.entrySet().iterator();
        //校验思路 1.根据供应商编码 和定价物料 到订单明细表中查询是否存在该供应商及物料所下的采购订单，存在允许定价，不存在则不允许定价
        while (iterator.hasNext()) {
            Map.Entry<String, List<String>> entry = iterator.next();
            String supplierCode = entry.getKey();//供应商编码
            List<String> materials = entry.getValue();
            //查询供应商信息
            SupplierDTO supplierByCode = supplierClient.getSupplierByCode(supplierCode);
            if (!Objects.isNull(supplierByCode.getEliminateFlag()) && supplierByCode.getEliminateFlag() == 1) {
                //待淘汰供应商本次定价的所有物料编号
                List<PurchaseDetailDTO> orderDetaiBySupplierCodeAndMaterial = purchaseOrderClient.getOrderDetaiBySupplierCodeAndMaterial(supplierCode, materials);
                if(CollectionUtils.isNotEmpty(orderDetaiBySupplierCodeAndMaterial)){
                    //将查询出来的物料和供应商进行处理 找出存在和不存在的物料进行提示
                    Set<String> uniqueMaterialCodes = orderDetaiBySupplierCodeAndMaterial.stream()
                            .map(PurchaseDetailDTO::getMaterialCode) // 提取每个DTO的materialCode
                            .collect(Collectors.toSet());
                    List<String> missingElements = materials.stream()
                            .filter(element -> !uniqueMaterialCodes.contains(element))
                            .collect(Collectors.toList());
                    if(CollectionUtils.isNotEmpty(missingElements)){//存在差异
                        throw new DaoException(StrUtil.format("供应商{}为待淘汰状态，这些定价物料没有下过采购订单{}不能生成价格信息，不允许定价",supplierCode,String.join(", ", missingElements)));
                    }

                }else{
                    //没有对应的订单
                    throw new DaoException(StrUtil.format("供应商{}为待淘汰状态且没有对应的历史采购订单，不能生成价格信息，不允许定价",supplierCode));            }
                }

        }
    }

    /**
     * 计算配额
     *
     * @param param 参数
     */
    @Override
    @Transactional
    public void calculateQuota(InquirySupplierCalculateQuotaParamDTO param) {
        //先取消所有的定价
        List<InquiryMaterialSupplier> cancelInquiryMaterialSuppliers = inquiryMaterialSupplierService.list(Wrappers.lambdaQuery(InquiryMaterialSupplier.class).eq(InquiryMaterialSupplier::getInquiryId,param.getInquiryId()));
        cancelInquiryMaterialSuppliers.forEach(inquiryMaterialSupplier -> {
            inquiryMaterialSupplier.setBidFlag(0);
        });
        inquiryMaterialSupplierService.updateBatchById(cancelInquiryMaterialSuppliers);

        param.getInquiryMaterialSupplierList().forEach(inquiryMaterialSupplier -> {
            //设置物料供应商中标标识
            if (inquiryMaterialSupplier.getConversionPrice()!=null&&inquiryMaterialSupplier.getConversionPrice().compareTo(BigDecimal.ZERO)!=0){
                inquiryMaterialSupplier.setBidFlag(1);
            }
            //设置物料供应商定价总金额
            inquiryMaterialSupplier.setBidTotalPrice(inquiryMaterialSupplier.getBidNumber().multiply(inquiryMaterialSupplier.getTaxPrice()));
            inquiryMaterialSupplier.setBidTime(LocalDateTime.now());
            inquiryMaterialSupplier.setUpdateTime(LocalDateTime.now());
            inquiryMaterialSupplier.setUpdateUser(LoginUtil.getUserId());
        });
        List<InquiryMaterialSupplier> inquiryMaterialSuppliers = inquiryMaterialSupplierConvert.dto2EntityList(param.getInquiryMaterialSupplierList());
        inquiryMaterialSupplierService.updateBatchById(inquiryMaterialSuppliers);

        List<CalculateQuotaDTO> calculateQuotaDTOS = new ArrayList<>();
        param.getInquiryMaterialSupplierList().forEach(inquiryMaterialSupplierDTO -> {
            calculateQuotaDTOS.add(CalculateQuotaDTO.builder()
                    .id(inquiryMaterialSupplierDTO.getId())
                    .materialAndSupplierCode(String.valueOf(inquiryMaterialSupplierDTO.getInquiryMaterialId()))
                    .joinQuoteFlag(inquiryMaterialSupplierDTO.getJoinQuoteFlag())
                    .paymentMethod(inquiryMaterialSupplierDTO.getPaymentMethod())
                    .currencyCode(inquiryMaterialSupplierDTO.getCurrencyCode())
                    .noTaxPrice(inquiryMaterialSupplierDTO.getNoTaxPrice())
                    .exchangeRate(inquiryMaterialSupplierDTO.getExchangeRate()).build());
        });

        List<CalculateQuotaDTO> calculateQuotaDTOS1 = this.calculateQuotaClient(calculateQuotaDTOS);
        List<InquiryMaterialSupplier> inquiryMaterialSupplierSaves = new ArrayList<>();
        calculateQuotaDTOS1.forEach(calculateQuotaDTO -> {
//            if (calculateQuotaDTO.getJoinQuoteFlag()==1){
                InquiryMaterialSupplier inquiryMaterialSupplier = new InquiryMaterialSupplier();
                inquiryMaterialSupplier.setId(calculateQuotaDTO.getId());
                inquiryMaterialSupplier.setConfirmQuota(calculateQuotaDTO.getConfirmQuota());
                //增加配额系统参考值 2024-12-02 邓京术
                inquiryMaterialSupplier.setConfirmQuotaView(calculateQuotaDTO.getConfirmQuota());
                inquiryMaterialSupplier.setQuotaPrice(calculateQuotaDTO.getQuotaPrice());
                inquiryMaterialSupplierSaves.add(inquiryMaterialSupplier);
//            }
        });
        if (CollectionUtils.isNotEmpty(inquiryMaterialSupplierSaves)){
            inquiryMaterialSupplierService.updateBatchById(inquiryMaterialSupplierSaves);
        }
    }

    /**
     * 更新所有询价供应商状态为询价结束
     * @param inquiryId 询价id
     */
    public void updateInquirySupplierStatus(Long inquiryId){
        //更新所有询价供应商状态为询价结束
        List<InquirySupplier> inquirySuppliers = inquirySupplierService.list(Wrappers.lambdaQuery(InquirySupplier.class).eq(InquirySupplier::getInquiryId,inquiryId));
        inquirySuppliers.forEach(inquirySupplier -> {
            inquirySupplier.setInquirySupplierStatus(InquirySupplierStatus.FINISH.getStatus());
            inquirySupplier.setUpdateTime(LocalDateTime.now());
            inquirySupplier.setUpdateUser(LoginUtil.getUserId());
        });
        inquirySupplierService.updateBatchById(inquirySuppliers);
    }

    public PriceImportDTO priceImportData(Inquiry inquiry,List<InquiryMaterialSupplierDTO> inquiryMaterialSupplierList){
        PriceImportDTO priceImportDTO = new PriceImportDTO();
        //组装头
        PriceImportDTO.Head head = new PriceImportDTO.Head();
        head.setFd_srmType(String.valueOf(OaProcessType.INQUIRY_PRICE.getType()));
        //OA流程ID
        head.setProcessId(StringUtils.isNotEmpty(inquiry.getOaWorkId())?inquiry.getOaWorkId():"");
        head.setFd_caigouLeiXing("询价");
        //申请人工号
        UserDTO userDTO = userClient.getByUserId(inquiry.getCreateUser());
        head.setFd_shenQingRenXingMing(ObjectUtil.isNotNull(userDTO)?userDTO.getAccountName():"");
        //SRM单号
        head.setFd_shenQingDanHao(inquiry.getInquiryCode());
        //器件分类
        PurchaseCategoryClientDTO purchaseCategoryClientDTO = purchaseCategoryClient.getByCode(inquiry.getPurchaseCategoryCode());
        head.setFd_qiJianFenLei(ObjectUtil.isNotNull(purchaseCategoryClientDTO)?purchaseCategoryClientDTO.getFirstLevelPurchaseName():"");
        //是否现货
        head.setFd_isXianHuo(inquiry.getSpotFlag()==1?"是":"否");
        //事业部是否同意
        head.setFd_shiYeBuShiFuTongYi(inquiry.getBusinessAgreeFlag()==null?"":inquiry.getBusinessAgreeFlag()==1?"是":"否");
        //客户是否承担
        head.setFd_keHuShiFuChengDan(inquiry.getCustomerBearFlag()==null?"":inquiry.getCustomerBearFlag()==1?"是":"否");
        //承担比例%
        head.setFd_chengDanBiLi(inquiry.getBearRatio()==null?"":inquiry.getBearRatio().toPlainString());
        List<OaFileParamDTO> list = new ArrayList<>();
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, "0CoJUm6Qyw8W8jud".getBytes(), "0102030405060708".getBytes());
        String encryptHex = aes.encryptHex(String.valueOf(inquiry.getId()));
        OaFileParamDTO build = OaFileParamDTO.builder().fileName("详情页面地址").url(sysProp.getHostUrl()+"/pc/inquiry/fix/fixPrice/look?id="+encryptHex).build();
        list.add(build);
        //详情页面地址
        head.setFd_pageUrl(JSON.toJSONString(list));
        //备注
        head.setFd_beiZhu(StringUtils.isNotEmpty(inquiry.getBargainRemark())?inquiry.getBargainRemark():"");
        //定价附件
        if (StringUtils.isNotEmpty(inquiry.getBargainFiles())){
            final List<String> split = StrUtil.split(inquiry.getBargainFiles(), StrUtil.COMMA);
            final List<FileResposePreviewCDTO> previewUrl = fileClient.getPreviewUrl(split);
            if (CollUtil.isNotEmpty(previewUrl)) {
                List<OaFileParamDTO> fileParamDTOS = Lists.newArrayList();
                for (FileResposePreviewCDTO fileResposePreviewDTO : previewUrl) {
                    fileParamDTOS.add(OaFileParamDTO.builder().fileName(fileResposePreviewDTO.getFileName())
                            .url(fileResposePreviewDTO.getPreviewUrl()).downloadUrl(
                                    fileResposePreviewDTO.getDownloadUrl()).build());
                }
                head.setFd_fuJian(JSON.toJSONString(fileParamDTOS));
            }
        }else {
            head.setFd_fuJian("");
        }

        priceImportDTO.setHead(head);

        //组装明细
        List<TaxDTO> taxDTOS = taxClient.getAll();
        final Map<String, TaxDTO> taxCache = taxDTOS.stream().collect(Collectors.toMap(TaxDTO::getTaxCode, a -> a));
        PriceImportDTO.ItemHead itemHead = new PriceImportDTO.ItemHead();
        List<PriceImportDTO.ItemHead.Item> itemList = new ArrayList<>();
        inquiryMaterialSupplierList.forEach(inquiryMaterialSupplierDTO -> {
            PriceImportDTO.ItemHead.Item item = new PriceImportDTO.ItemHead.Item();
            //供应商代码
            item.setFd_gongYingShangDaiMa(inquiryMaterialSupplierDTO.getSupplierCode());
            //供应商名称
            item.setFd_gongYingShangMingChen(inquiryMaterialSupplierDTO.getSupplierName());
            //物料编码
            item.setFd_wuLiaoBianMa(inquiryMaterialSupplierDTO.getMaterialCode());
            //描述
            item.setFd_miaoShu(inquiryMaterialSupplierDTO.getMaterialName());
            //物料单位
            item.setFd_jgdw(inquiryMaterialSupplierDTO.getPurchaseUnit());
            //税码（SAP代码）
            item.setFd_shuiMa(inquiryMaterialSupplierDTO.getTaxCode());
            TaxDTO taxDTO = taxCache.get(inquiryMaterialSupplierDTO.getTaxCode());
            //税码值
            item.setFd_shuiMaZhi(taxDTO.getTaxValue().multiply(BigDecimal.valueOf(100)).toPlainString());
            //币种
            item.setFd_biZhong(inquiryMaterialSupplierDTO.getCurrencyCode());
            //含税价格(PCS)
            item.setFd_hsj(inquiryMaterialSupplierDTO.getTaxPrice().stripTrailingZeros());
            //换算后价格 未税*汇率
            item.setFd_huanSuanHouJiaGe(inquiryMaterialSupplierDTO.getNoTaxPrice().multiply(inquiryMaterialSupplierDTO.getExchangeRate()));
            final BigDecimal bigDecimal = inquiryMaterialSupplierDTO.getTaxPrice().stripTrailingZeros();

            List<Integer> scaleList = new ArrayList<>();
            scaleList.add(bigDecimal.scale());
            if (inquiryMaterialSupplierDTO.getStagePrice1()!=null){
                scaleList.add(inquiryMaterialSupplierDTO.getStagePrice1().stripTrailingZeros().scale());
            }
            if (inquiryMaterialSupplierDTO.getStagePrice2()!=null){
                scaleList.add(inquiryMaterialSupplierDTO.getStagePrice2().stripTrailingZeros().scale());
            }
            if (inquiryMaterialSupplierDTO.getStagePrice3()!=null){
                scaleList.add(inquiryMaterialSupplierDTO.getStagePrice3().stripTrailingZeros().scale());
            }
            if (inquiryMaterialSupplierDTO.getStagePrice4()!=null){
                scaleList.add(inquiryMaterialSupplierDTO.getStagePrice4().stripTrailingZeros().scale());
            }
            if (inquiryMaterialSupplierDTO.getStagePrice5()!=null){
                scaleList.add(inquiryMaterialSupplierDTO.getStagePrice5().stripTrailingZeros().scale());
            }
            //取最大的小数点
            int scale = scaleList.stream().mapToInt(Integer::intValue).max().orElse(1);
            String scaleStr = (scale > 2&&scale<=5)?"1000":scale>5?"10000":"1";
            //价格单位(转换SAP)
            item.setFd_danWei(scaleStr);
            //含税价格(转换SAP)
            item.setFd_jiaGe(bigDecimal.multiply(new BigDecimal(scaleStr)));
            //汇率
            item.setFd_huiLv(inquiryMaterialSupplierDTO.getExchangeRate().toPlainString());
            //有效期起始日
            item.setFd_youXiaoQiQiShiRi(LocalDateTimeUtil.format(inquiryMaterialSupplierDTO.getQuoteFromDate(),"yyyy-MM-dd"));
            //有效期结束日
            item.setFd_zhongZhiRiQi(LocalDateTimeUtil.format(inquiryMaterialSupplierDTO.getQuoteEndDate(),"yyyy-MM-dd"));
            //配额
            item.setFd_peiE(inquiryMaterialSupplierDTO.getConfirmQuota());
            item.setFd_peiECK(inquiryMaterialSupplierDTO.getConfirmQuotaView());
            //备注
            item.setFd_beiZhu(StringUtils.isNotEmpty(inquiryMaterialSupplierDTO.getRemark())?inquiryMaterialSupplierDTO.getRemark():"");
            //信息类别0标准2寄售3外协
            item.setFd_xinXiLeiBie(inquiry.getPurchaseType());
            //关税(没有就填0)
            item.setFd_guanShui(inquiryMaterialSupplierDTO.getTariff()==null?BigDecimal.ZERO:inquiryMaterialSupplierDTO.getTariff());
           //采购组织代码
            item.setFd_suoShuZuZhi(inquiry.getPurchaseOrgCode());
            //工厂代码
            item.setFd_gongChangCode(inquiryMaterialSupplierDTO.getFactoryCode());
            //制造商型号
            item.setFd_zhiZaoXingHao(StringUtils.isNotEmpty(inquiryMaterialSupplierDTO.getMpn())?inquiryMaterialSupplierDTO.getMpn():"");
            //制造商中文
            item.setFd_zhiZaoShang(StringUtils.isNotEmpty(inquiryMaterialSupplierDTO.getManufacturer())?inquiryMaterialSupplierDTO.getManufacturer():"");
            //制造商英文
            item.setFd_zhiZaoYingWen(StringUtils.isNotEmpty(inquiryMaterialSupplierDTO.getManufacturerEn())?inquiryMaterialSupplierDTO.getManufacturerEn():"");
            //国系
            if (StringUtils.isNotEmpty(inquiryMaterialSupplierDTO.getCountryName())){
                DictDTO dictDTO = dictClient.getDictByTypeAndCode(DictCode.COUNTRY_SERIES.getCode(),inquiryMaterialSupplierDTO.getCountryName());
                if(dictDTO != null){
                    item.setFd_guoXi(dictDTO.getName());
                }
            }else {
                item.setFd_guoXi(StringUtils.isNotEmpty(inquiryMaterialSupplierDTO.getCountryName())?inquiryMaterialSupplierDTO.getCountryName():"");
            }
            //计划交货时间（L/T）
            item.setFd_jiaoHuoShiJian(inquiryMaterialSupplierDTO.getConfirmDeliveryDate()==null?"":String.valueOf(inquiryMaterialSupplierDTO.getConfirmDeliveryDate()));
            //最新订单数量（MOQ）
            item.setFd_shuLiang(String.valueOf(inquiryMaterialSupplierDTO.getMoq()));
            //最小包装量（MPQ）
            item.setFd_zuiXiaoBaoZhuangLiang(String.valueOf(inquiryMaterialSupplierDTO.getMpq()));
            //阶梯数量1
            item.setFd_jieTiShuLiang1(inquiryMaterialSupplierDTO.getStageNum1()==null?"":inquiryMaterialSupplierDTO.getStageNum1().toPlainString());
            //阶梯价格1
            item.setFd_jieTiJiaGe1(inquiryMaterialSupplierDTO.getStagePrice1()==null?"":inquiryMaterialSupplierDTO.getStagePrice1().multiply(new BigDecimal(scaleStr)).stripTrailingZeros().toPlainString());
            //阶梯数量2
            item.setFd_jieTiShuLiang2(inquiryMaterialSupplierDTO.getStageNum2()==null?"":inquiryMaterialSupplierDTO.getStageNum2().toPlainString());
            //阶梯价格2
            item.setFd_jieTiJiaGe2(inquiryMaterialSupplierDTO.getStagePrice2()==null?"":inquiryMaterialSupplierDTO.getStagePrice2().multiply(new BigDecimal(scaleStr)).stripTrailingZeros().toPlainString());
            //阶梯数量3
            item.setFd_jieTiShuLiang3(inquiryMaterialSupplierDTO.getStageNum3()==null?"":inquiryMaterialSupplierDTO.getStageNum3().toPlainString());
            //阶梯价格3
            item.setFd_jieTiJiaGe3(inquiryMaterialSupplierDTO.getStagePrice3()==null?"":inquiryMaterialSupplierDTO.getStagePrice3().multiply(new BigDecimal(scaleStr)).stripTrailingZeros().toPlainString());
            //阶梯数量4
            item.setFd_jieTiShuLiang4(inquiryMaterialSupplierDTO.getStageNum4()==null?"":inquiryMaterialSupplierDTO.getStageNum4().toPlainString());
            //阶梯价格4
            item.setFd_jieTiJiaGe4(inquiryMaterialSupplierDTO.getStagePrice4()==null?"":inquiryMaterialSupplierDTO.getStagePrice4().multiply(new BigDecimal(scaleStr)).stripTrailingZeros().toPlainString());
            //阶梯数量5
            item.setFd_jieTiShuLiang5(inquiryMaterialSupplierDTO.getStageNum5()==null?"":inquiryMaterialSupplierDTO.getStageNum5().toPlainString());
            //阶梯价格5
            item.setFd_jieTiJiaGe5(inquiryMaterialSupplierDTO.getStagePrice5()==null?"":inquiryMaterialSupplierDTO.getStagePrice5().multiply(new BigDecimal(scaleStr)).stripTrailingZeros().toPlainString());
            //状态
//            item.setFd_zhuangTai(inquiryMaterialSupplierDTO.getJoinQuoteFlag()==1?"导入":"参考");
            item.setFd_zhuangTai("导入");
            if (null!=inquiryMaterialSupplierDTO.getHistoryPrice()){
                PriceInfoDTO priceInfoDTO = priceInfoLogic.getById(inquiryMaterialSupplierDTO.getHistoryPriceId());
                //是否新料
                item.setFd_shiFuXinLiao("否");
                //上次价格币种
                item.setFd_shangCiJiaGeBiZhong(priceInfoDTO.getCurrencyCode());
                //上次汇率
                item.setFd_shangCiHuiLv(priceInfoDTO.getExchangeRate().toPlainString());
                //上次税码
                item.setFd_shangCiShuiMa(priceInfoDTO.getTaxCode());
                //上次价格原价
                item.setFd_shangCiJiaGeYuanJia(priceInfoDTO.getTaxPrice().toPlainString());
                //上次未税价格
                BigDecimal huansuanhou = priceInfoDTO.getNoTaxPrice().multiply(priceInfoDTO.getExchangeRate());
                item.setFd_shangCiWeiShuiJiaGe(huansuanhou.toPlainString());
                //差价（RMB） $明细表1.是否新料$ * ($明细表1.换算后价格$ - $明细表1.上次未税价格$ )
                final BigDecimal chajia = item.getFd_huanSuanHouJiaGe().subtract(huansuanhou);
                item.setFd_chaJia(chajia.toPlainString());
                //涨幅 $明细表1.是否新料$ * 100 * $明细表1.差价（RMB）$ / $明细表1.上次未税价格$
                item.setFd_zhangFu(chajia.divide(huansuanhou, 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString());
            }else {
                //是否新料
                item.setFd_shiFuXinLiao("是");
                //上次价格币种
                item.setFd_shangCiJiaGeBiZhong("");
                //上次汇率
                item.setFd_shangCiHuiLv("");
                //上次税码
                item.setFd_shangCiShuiMa("");
                //上次价格原价
                item.setFd_shangCiJiaGeYuanJia("");
                //上次未税价格
                item.setFd_shangCiWeiShuiJiaGe("");
                //差价（RMB）
                item.setFd_chaJia("");
                //涨幅
                item.setFd_zhangFu("");
            }
            //潮湿等级
            item.setFd_chaoShiDengJi(StringUtils.isNotEmpty(inquiryMaterialSupplierDTO.getMsl())?inquiryMaterialSupplierDTO.getMsl():"");
            //取消窗
            item.setFd_quXiaoChuang(StringUtils.isNotEmpty(inquiryMaterialSupplierDTO.getCancelWindow())?inquiryMaterialSupplierDTO.getCancelWindow():"");
            //推迟窗
            item.setFd_tuiChiChuang(StringUtils.isNotEmpty(inquiryMaterialSupplierDTO.getDelayWindow())?inquiryMaterialSupplierDTO.getDelayWindow():"");
            //ECCN码
            item.setFd_eCCNMa(StringUtils.isNotEmpty(inquiryMaterialSupplierDTO.getEccn())?inquiryMaterialSupplierDTO.getEccn():"");
            //风险等级
            item.setFd_fengXianDengJi(StringUtils.isNotEmpty(inquiryMaterialSupplierDTO.getRiskLevel())?inquiryMaterialSupplierDTO.getRiskLevel():"");
            //物流代理费
            item.setFd_daiLiFei("CNY".equals(inquiryMaterialSupplierDTO.getCurrencyCode())?BigDecimal.ZERO:inquiryMaterialSupplierDTO.getLogisticsAgencyFee()==null?BigDecimal.ZERO:inquiryMaterialSupplierDTO.getLogisticsAgencyFee());
            itemList.add(item);
        });
        itemHead.setItem(itemList);
        priceImportDTO.setItem(itemHead);
        return priceImportDTO;
    }

    /**
     * 定价确认
     *
     * @param param 参数
     */
    @Override
    @Transactional
    public void fixConfirm(InquirySupplierBargainConfirmParamDTO param) {
        Inquiry inquiry = inquiryService.getById(param.getInquiryId());
        inquiry.setBargainRemark(param.getBargainRemark());
        inquiry.setUpdateTime(LocalDateTime.now());
        inquiry.setUpdateUser(LoginUtil.getUserId());
        //如果驳回
        if (param.getOptType()==2){
            inquiry.setStatus(InquiryStatus.END.getStatus());
            inquiry.setFinishTime(null);
            //如果驳回，更新所有询价供应商状态为询价截止
            List<InquirySupplier> inquirySuppliers = inquirySupplierService.list(Wrappers.lambdaQuery(InquirySupplier.class).eq(InquirySupplier::getInquiryId,param.getInquiryId()));
            inquirySuppliers.forEach(inquirySupplier -> {
                inquirySupplier.setInquirySupplierStatus(InquirySupplierStatus.END.getStatus());
                inquirySupplier.setUpdateTime(LocalDateTime.now());
                inquirySupplier.setUpdateUser(LoginUtil.getUserId());
            });
            inquirySupplierService.updateBatchById(inquirySuppliers);
        }else {
//            //生成价格信息记录,如果成功，更新标识
//            //根据询价id组装价格信息记录数据
//            List<CreatePriceInfoPO> createPriceInfoPOS = priceInfoService.getByInquiryId(inquiry.getId());
//            List<CreatePriceInfoDTO> createPriceInfoDTOS = priceInfoConvert.po2DtoList(createPriceInfoPOS);
//            createPriceInfoDTOS.forEach(createPriceInfoDTO -> {
//                createPriceInfoDTO.setCreateUser(LoginUtil.getUserId());
//                //TODO 先给1
//                createPriceInfoDTO.setExchangeRate(BigDecimal.ONE);
//            });
//            //只取参与报价的供应商
//            List<CreatePriceInfoDTO> filterCreatePriceInfoDTOS = createPriceInfoDTOS.stream().filter(inquiryMaterialSupplier -> inquiryMaterialSupplier.getJoinQuoteFlag()==1).collect(Collectors.toList());
//            priceInfoLogic.createPriceInfo(filterCreatePriceInfoDTOS);
            //无需oa审批的采购品类
            final String noOaPurchaseCategoryCode = sysConfigClient.getTextConfig(INQUIRY_FIX_NO_OA_PURCHASE_CATEGORY_CODE.getCode());
            if (noOaPurchaseCategoryCode.contains(inquiry.getPurchaseCategoryCode())){
                inquiry.setGenPriceInfo(2);
            }else {
                inquiry.setGenPriceInfo(1);
            }
            inquiry.setStatus(InquiryStatus.FINISH.getStatus());

        }
        inquiryService.updateById(inquiry);
        InquiryApprove inquiryApprove = new InquiryApprove();
        inquiryApprove.setInquiryId(inquiry.getId());
        inquiryApprove.setApproveResult(param.getOptType()==2?0:1);
        inquiryApprove.setApproveOpinion(param.getOptRemark());
        inquiryApprove.setApproveUserId(LoginUtil.getUserId());
        inquiryApprove.setApproveUserCode(LoginUtil.getAccount());
        inquiryApprove.setApproveUserName(LoginUtil.getName());
        inquiryApprove.setApproveTime(LocalDateTime.now());
        inquiryApproveService.save(inquiryApprove);
    }

    /**
     * 主管确认
     *
     * @param param 参数
     */
    @Override
    @Transactional
    public void chargeConfirm(InquirySupplierBargainConfirmParamDTO param) {
        Inquiry inquiry = inquiryService.getById(param.getInquiryId());
        inquiry.setBargainRemark(param.getBargainRemark());
        inquiry.setUpdateTime(LocalDateTime.now());
        inquiry.setUpdateUser(LoginUtil.getUserId());
        //如果驳回
        if (param.getOptType()==2){
            inquiry.setStatus(InquiryStatus.END.getStatus());
            inquiry.setFinishTime(null);
            //如果驳回，更新所有询价供应商状态为询价截止
            List<InquirySupplier> inquirySuppliers = inquirySupplierService.list(Wrappers.lambdaQuery(InquirySupplier.class).eq(InquirySupplier::getInquiryId,param.getInquiryId()));
            inquirySuppliers.forEach(inquirySupplier -> {
                inquirySupplier.setInquirySupplierStatus(InquirySupplierStatus.END.getStatus());
                inquirySupplier.setUpdateTime(LocalDateTime.now());
                inquirySupplier.setUpdateUser(LoginUtil.getUserId());
            });
            inquirySupplierService.updateBatchById(inquirySuppliers);
        }else {
            //无需oa审批的采购品类
//            final String noOaPurchaseCategoryCode = sysConfigClient.getTextConfig(INQUIRY_FIX_NO_OA_PURCHASE_CATEGORY_CODE.getCode());
//            if (inquiry.getPurchaseCategoryCode().equals(noOaPurchaseCategoryCode)){
            List<InquiryMaterialSupplier> cancelInquiryMaterialSuppliers = inquiryMaterialSupplierService.list(Wrappers.lambdaQuery(InquiryMaterialSupplier.class).eq(InquiryMaterialSupplier::getInquiryId,param.getInquiryId()).eq(InquiryMaterialSupplier::getBidFlag,1));
            BigDecimal bidTotalPrice = cancelInquiryMaterialSuppliers.stream().map(InquiryMaterialSupplier::getBidTotalPrice).reduce(BigDecimal.ZERO, BigDecimal::add);

            //总价 <= 1w，主管审批  ；（2）总价 > 1w，主管、总监 审批；
            if (bidTotalPrice.compareTo(BigDecimal.valueOf(10000))>0){
                inquiry.setStatus(InquiryStatus.DIRECTOR_ING.getStatus());
            }else {
                inquiry.setStatus(InquiryStatus.FINISH.getStatus());
            }

                inquiry.setUpdateTime(LocalDateTime.now());
                inquiry.setUpdateUser(LoginUtil.getUserId());
//            }else {
//                //提交oa审批
//                //调用定价审批接口
//                //定价导入审批流程
//                List<InquiryMaterialSupplierDTO> inquiryMaterialSupplierList = param.getInquiryMaterialSupplierList();
//                //过滤掉物料编码为空的
//                List<InquiryMaterialSupplierDTO> filterInquiryMaterialSupplierList = inquiryMaterialSupplierList.stream().filter(inquiryMaterialSupplier -> StringUtils.isNotEmpty(inquiryMaterialSupplier.getMaterialCode())).toList();
//                final ApiResult<String> orUpdate = fixOaClient.priceImport(this.priceImportData(inquiry,filterInquiryMaterialSupplierList));
//                final String code = orUpdate.getCode();
//                final String oaId = orUpdate.getData();
//                final String message = orUpdate.getMessage();
//                inquiry.setOaResult(message);
//                inquiry.setOaTime(LocalDateTime.now());
//                if (code.equals(RestCode.SAP_SUCCESS.getCode())) {
//                    inquiry.setStatus(InquiryStatus.FIX_ING.getStatus());
//                    inquiry.setOaWorkId(oaId);
//                    inquiryService.updateById(inquiry);
//                    //更新所有询价供应商状态为询价结束
//                    this.updateInquirySupplierStatus(param.getInquiryId());
//                }else {
//                    throw new DaoException("OA接口报错："+orUpdate.getMessage());
//                }
//            }
        }
        inquiryService.updateById(inquiry);
        InquiryApprove inquiryApprove = new InquiryApprove();
        inquiryApprove.setInquiryId(inquiry.getId());
        inquiryApprove.setApproveResult(param.getOptType()==2?0:1);
        inquiryApprove.setApproveOpinion(param.getOptRemark());
        inquiryApprove.setApproveUserId(LoginUtil.getUserId());
        inquiryApprove.setApproveUserCode(LoginUtil.getAccount());
        inquiryApprove.setApproveUserName(LoginUtil.getName());
        inquiryApprove.setApproveTime(LocalDateTime.now());
        inquiryApproveService.save(inquiryApprove);


    }

    @Override
    public void quoteExport(HttpServletResponse response, Long inquiryId) throws IOException {
        InquiryDTO inquiryDTO = inquiryLogic.getById(inquiryId);
        // 查询数据列表，直接调用列表的查询，无需特殊改动
        InquiryQuoteQuery query = new InquiryQuoteQuery();
        query.setInquiryId(inquiryId);
        query.setSupplierId(Objects.requireNonNull(LoginUtil.getCurrentUser()).supplierId);
        List<InquiryMaterialSupplierPO> exportData =  inquiryMaterialSupplierService.quoteList(query);
        exportData.forEach(inquiryMaterialSupplierDTO -> {
            //赋值Avl信息
            if (StringUtils.isEmpty(inquiryMaterialSupplierDTO.getMpn())&&StringUtils.isNotEmpty(inquiryMaterialSupplierDTO.getMaterialCode())&&StringUtils.isEmpty(inquiryMaterialSupplierDTO.getCountryName())){
                SupplierAvlBaseDTO supplierAvlBaseDTO = supplierClient.findSupplierAvlItem(inquiryMaterialSupplierDTO.getSupplierCode(),inquiryMaterialSupplierDTO.getMaterialCode());
                if (ObjectUtil.isNotNull(supplierAvlBaseDTO)){
                    inquiryMaterialSupplierDTO.setMpn(supplierAvlBaseDTO.getMpn());
                    inquiryMaterialSupplierDTO.setMpn(supplierAvlBaseDTO.getMpn());
                    inquiryMaterialSupplierDTO.setManufacturer(supplierAvlBaseDTO.getProductName());
                    inquiryMaterialSupplierDTO.setManufacturerEn(supplierAvlBaseDTO.getProductNameEn());
                    inquiryMaterialSupplierDTO.setCountryName(supplierAvlBaseDTO.getCountryName());
                    inquiryMaterialSupplierDTO.setMsl(supplierAvlBaseDTO.getMsl());
                    inquiryMaterialSupplierDTO.setEccn(supplierAvlBaseDTO.getEccn());
                    inquiryMaterialSupplierDTO.setMpq(StrUtil.isEmpty(supplierAvlBaseDTO.getMpq())?null: Long.valueOf(supplierAvlBaseDTO.getMpq()));
                    inquiryMaterialSupplierDTO.setMoq(StrUtil.isEmpty(supplierAvlBaseDTO.getMoq())?null: Long.valueOf(supplierAvlBaseDTO.getMoq()));
                    inquiryMaterialSupplierDTO.setConfirmDeliveryDate(StrUtil.isEmpty(supplierAvlBaseDTO.getCif())?null: Integer.valueOf(supplierAvlBaseDTO.getCif()));
                }
            }
        });
        List<ExportDataDTO> exportDataDTOS = new ArrayList<>();
        //先加载固定字段
        exportDataDTOS.add(ExportDataDTO.builder().title("").field("id").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("物料编码").field("materialCode").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("物料名称").field(inquiryDTO.getSupplierMaterialFlag()==0?"materialName":"materialDesc").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("详细规格参数").field("materialSpec").build());
//        exportDataDTOS.add(ExportDataDTO.builder().title("品牌").field("brand").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("备注").field("remark").build());
        //供应商填写的需要加载头颜色
        exportDataDTOS.add(ExportDataDTO.builder().title("含税单价").field("taxPrice").color(IndexedColors.YELLOW.getIndex()).build());
        //是否有阶梯报价
        boolean stagePriceFlag = false;
        for (InquiryMaterialSupplierPO inquiryMaterialSupplierPO : exportData){
            if (inquiryMaterialSupplierPO.getStagePriceFlag()==1){
                stagePriceFlag = true;
                break;
            }
        }
        if (stagePriceFlag){
            //加载阶梯报价
            List<InquiryTemplateFieldDTO> stagePriceInquiryTemplateFieldDTOS = inquiryTemplateLogic.getFieldByTemplateCodeAndFieldGroup(inquiryDTO.getTemplateCode(),2,null);
            stagePriceInquiryTemplateFieldDTOS.forEach(s -> {
                exportDataDTOS.add(ExportDataDTO.builder().title(s.getLabelName()).field(s.getFieldName()).color(IndexedColors.YELLOW.getIndex()).build());
                if ("stagePrice1".equals(s.getFieldName())){
                    exportData.forEach(inquiryMaterialSupplierPO -> inquiryMaterialSupplierPO.setStageNum1(new BigDecimal(s.getFieldAlias())));
                    exportDataDTOS.add(ExportDataDTO.builder().title("阶梯数量1").field("stageNum1").color(IndexedColors.YELLOW.getIndex()).build());
                }
                if ("stagePrice2".equals(s.getFieldName())){
                    exportData.forEach(inquiryMaterialSupplierPO -> inquiryMaterialSupplierPO.setStageNum2(new BigDecimal(s.getFieldAlias())));
                    exportDataDTOS.add(ExportDataDTO.builder().title("阶梯数量2").field("stageNum2").color(IndexedColors.YELLOW.getIndex()).build());
                }
                if ("stagePrice3".equals(s.getFieldName())){
                    exportData.forEach(inquiryMaterialSupplierPO -> inquiryMaterialSupplierPO.setStageNum3(new BigDecimal(s.getFieldAlias())));
                    exportDataDTOS.add(ExportDataDTO.builder().title("阶梯数量3").field("stageNum3").color(IndexedColors.YELLOW.getIndex()).build());
                }
                if ("stagePrice4".equals(s.getFieldName())){
                    exportData.forEach(inquiryMaterialSupplierPO -> inquiryMaterialSupplierPO.setStageNum4(new BigDecimal(s.getFieldAlias())));
                    exportDataDTOS.add(ExportDataDTO.builder().title("阶梯数量4").field("stageNum4").color(IndexedColors.YELLOW.getIndex()).build());
                }
                if ("stagePrice5".equals(s.getFieldName())){
                    exportData.forEach(inquiryMaterialSupplierPO -> inquiryMaterialSupplierPO.setStageNum5(new BigDecimal(s.getFieldAlias())));
                    exportDataDTOS.add(ExportDataDTO.builder().title("阶梯数量5").field("stageNum5").color(IndexedColors.YELLOW.getIndex()).build());
                }
            });
        }
        //再从模板中取供应商需要的字段
        List<InquiryTemplateFieldDTO> inquiryTemplateFieldDTOS = inquiryTemplateLogic.getSupplierFieldByTemplateCode(inquiryDTO.getTemplateCode());
        //先加载供应商可见但不可编辑的列
        inquiryTemplateFieldDTOS.forEach(s -> {
            if (s.getSupplierLookFlag()==1){
                exportDataDTOS.add(ExportDataDTO.builder().title(StrUtil.isNotEmpty(s.getFieldAlias())?s.getFieldAlias():s.getLabelName()).field(s.getFieldName()).build());
            }
        });
        //再加载供应商可见且可编辑的列，排除下拉框和文件
        inquiryTemplateFieldDTOS.forEach(s -> {
            if (s.getSupplierLookFlag()==0&&!"files".equals(s.getFieldType())){
                if ("dict".equals(s.getFieldType())){
                    List<DictDTO> dictDTOS = dictClient.getDicByType(s.getDictTypeCode());
                    List<ExportEnumDataDTO> exportEnum = new ArrayList<>();
                    dictDTOS.forEach(dictDTO -> {
                        ExportEnumDataDTO exportEnumDataDTO = new ExportEnumDataDTO();
                        exportEnumDataDTO.setCode(dictDTO.getCode());
                        exportEnumDataDTO.setCodeWithDesc(dictDTO.getName());
                        exportEnum.add(exportEnumDataDTO);
                    });
                    exportDataDTOS.add(ExportDataDTO.builder().title(StrUtil.isNotEmpty(s.getFieldAlias())?s.getFieldAlias():s.getLabelName()).field(s.getFieldName()).color(s.getAllowEditFlag()==1?IndexedColors.YELLOW.getIndex():null).selectList(dictDTOS.stream().map(DictDTO::getName).distinct().toList()).exportEnum(exportEnum).build());
                }else if ("data".equals(s.getFieldType())&&"taxCode".equals(s.getFieldName())){
                    List<TaxDTO> taxDTOS = taxClient.getAll();
                    List<ExportEnumDataDTO> exportEnum = new ArrayList<>();
                    taxDTOS.forEach(taxDTO -> {
                        ExportEnumDataDTO exportEnumDataDTO = new ExportEnumDataDTO();
                        exportEnumDataDTO.setCode(taxDTO.getTaxCode());
                        exportEnumDataDTO.setCodeWithDesc(taxDTO.getTaxName());
                        exportEnum.add(exportEnumDataDTO);
                    });
                    exportDataDTOS.add(ExportDataDTO.builder().title(StrUtil.isNotEmpty(s.getFieldAlias())?s.getFieldAlias():s.getLabelName()).field(s.getFieldName()).color(s.getAllowEditFlag()==1?IndexedColors.YELLOW.getIndex():null).selectList(taxDTOS.stream().map(TaxDTO::getTaxName).distinct().toList()).exportEnum(exportEnum).build());
                }else {
                    exportDataDTOS.add(ExportDataDTO.builder().title(StrUtil.isNotEmpty(s.getFieldAlias())?s.getFieldAlias():s.getLabelName()).field(s.getFieldName()).color(s.getAllowEditFlag()==1?IndexedColors.YELLOW.getIndex():null).build());
                }
            }
        });

        //动态导出工具类，只需要修改导出excel名称
        EasyExcelUtils.trendsModelWrite(response,"报价列表-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN),"sheet", exportData, JSON.toJSONString(exportDataDTOS));
    }

    @Override
    public List<Map<String,String>> quoteImport(MultipartFile file, Long inquiryId){
        try {
            List<Map<String,String>> dataList = EasyExcelImportUtils.parseExcelToData(file.getInputStream(), 2);
            InquiryDTO inquiryDTO = inquiryLogic.getById(inquiryId);
            //从模板中取供应商需要的字段
            List<InquiryTemplateFieldDTO> inquiryTemplateFieldDTOS = inquiryTemplateLogic.getSupplierFieldByTemplateCode(inquiryDTO.getTemplateCode());

            //税率
            final List<TaxDTO> taxDTOS = taxClient.getAll();
            final Map<String, TaxDTO> taxCache = taxDTOS.stream().collect(Collectors.toMap(TaxDTO::getTaxName, a -> a));
            for (Map<String,String> map : dataList){
                //再加载供应商可见且可编辑的列，排除下拉框和文件
                inquiryTemplateFieldDTOS.forEach(s -> {
                    if (s.getSupplierLookFlag()==0&&!"files".equals(s.getFieldType())){
                        if ("dict".equals(s.getFieldType())){
                            String name = map.get(s.getFieldName());
                            if (StringUtils.isNotEmpty(name)){
                                DictDTO dictDTO = dictClient.getDictByTypeAndName(s.getDictTypeCode(),name);
                                if (ObjectUtil.isNull(dictDTO)){
                                    throw new DaoException(StrUtil.format("{}:{}，填写有误，请下拉选择，不可自定义填写",StrUtil.isNotEmpty(s.getFieldAlias())?s.getFieldAlias():s.getLabelName(),name));
                                }else {
                                    map.put(s.getFieldName(),dictDTO.getCode());
                                }
                            }
                        }
                        if ("data".equals(s.getFieldType())&&"taxCode".equals(s.getFieldName())){
                            String name = map.get(s.getFieldName());
                            if (StringUtils.isNotEmpty(name)){
                                TaxDTO taxDTO = taxCache.get(name);
                                if (ObjectUtil.isNull(taxDTO)){
                                    throw new DaoException(StrUtil.format("{}:{}，填写有误，请下拉选择，不可自定义填写",StrUtil.isNotEmpty(s.getFieldAlias())?s.getFieldAlias():s.getLabelName(),name));
                                }else {
                                    map.put(s.getFieldName(),taxDTO.getTaxCode());
                                }
                            }
                        }
                    }
                });
            }
            return dataList;
        } catch (IOException e) {
            throw new DaoException("读取Excel失败");
        }
    }

    /**
     * 获取比价小助手需要的物料供应商信息
     *
     * @param inquiryId     询价id
     * @param supplierCodeList 需要查询的供应商
     * @return 比价小助手需要的物料供应商信息
     */
    @Override
    public List<AssistantMaterialSupplierDTO> getAssistantMaterialSupplier(Long inquiryId, Set<String> supplierCodeList) {
        List<AssistantMaterialSupplierPO> inquiryMaterialPOS = inquiryMaterialService.getAssistantMaterialByInquiryId(inquiryId);
        List<AssistantMaterialSupplierDTO> inquiryMaterialDTOS = inquiryMaterialConvert.assistantMaterialSupplierPO2DTOList(inquiryMaterialPOS);
        for (AssistantMaterialSupplierDTO inquiryMaterialDTO : inquiryMaterialDTOS) {
            List<AssistantSupplierPO> supplierPOS = inquiryMaterialSupplierService.getAssistantSupplierByInquiryIdAndInquiryMaterialIdAndSupplierCodeList(inquiryId,inquiryMaterialDTO.getId(),supplierCodeList);
            List<AssistantSupplierDTO> assistantSupplierDTOS = inquiryMaterialSupplierConvert.assistantSupplierPO2DTOList(supplierPOS);
            //标记最低价
            if (assistantSupplierDTOS.size() > 0) {
                assistantSupplierDTOS.forEach(assistantSupplierDTO -> {
                    if (null!=assistantSupplierDTO.getNoTaxPrice()){
                        assistantSupplierDTO.setConversionPrice(assistantSupplierDTO.getNoTaxPrice().multiply(assistantSupplierDTO.getExchangeRate()).divide(BigDecimal.ONE,priceHandle.getPrecision(),Objects.equals(priceHandle.getCutType(), FlagConst.N.getCode()) ? RoundingMode.HALF_UP : RoundingMode.DOWN));
                    }
                });
                Optional<BigDecimal> min = assistantSupplierDTOS.stream()
                        .map(AssistantSupplierDTO::getConversionPrice)
                        .filter(Objects::nonNull)
                        .min(BigDecimal::compareTo);
                if (min.isPresent()){
                    List<AssistantSupplierDTO> list = assistantSupplierDTOS.stream()
                            .filter(s -> Objects.nonNull(s.getConversionPrice())&&s.getConversionPrice().compareTo(min.get()) == 0)
                            .toList();
                    list.forEach(s -> s.setMinPriceFlag(1));
                }
            }

            inquiryMaterialDTO.setAssistantSupplierDTOS(assistantSupplierDTOS);
        }
        return inquiryMaterialDTOS;
    }

    /**
     * 物料供应商数据补充导入
     *
     * @param file 文件
     */
    @Override
    public void dataImport(MultipartFile file) {
        try {
            List<Map<String,String>> dataList = EasyExcelImportUtils.parseExcelToData(file.getInputStream(), 2);
            if (CollectionUtils.isNotEmpty(dataList)){
                //源头导入的时候控制
                //验证供应商类型有效期结束日和有效期起始日不能大于 指定配置日期 2024-11-18 邓京术
                List<DictDTO> dictDTOS = dictClient.getDicByType("supplier_material_quote_expiredate");
                for (Map<String,String> map : dataList){
                    InquiryMaterial inquiryMaterial = inquiryMaterialService.getById(map.get("inquiryMaterialId"));
                    ProductInfoDTO productInfo = productClient.getByMaterialCodeAndFactoryCode(map.get("materialCode"),inquiryMaterial.getFactoryCode());
                    if (ObjectUtil.isEmpty(productInfo)){
                        throw new DaoException(StrUtil.format("物料编码：{}在物料主数据中不存在，无法导入",map.get("materialCode")));
                    }
                    inquiryMaterial.setMaterialCode(map.get("materialCode"));
                    inquiryMaterial.setProductId(productInfo.getId());
                    inquiryMaterial.setMaterialName(productInfo.getMaterialName());
                    inquiryMaterial.setQuoteFromDate(LocalDateTimeUtil.parse(map.get("quoteFromDate"),"yyyy-MM-dd"));
                    inquiryMaterial.setQuoteEndDate(LocalDateTimeUtil.parse(map.get("quoteEndDate"),"yyyy-MM-dd"));
                    inquiryMaterialService.updateById(inquiryMaterial);
                    //更新价格有效期
//                    List<InquiryMaterialSupplier> inquiryMaterialSuppliers = inquiryMaterialSupplierService.list(Wrappers.lambdaQuery(InquiryMaterialSupplier.class).eq(InquiryMaterialSupplier::getInquiryMaterialId,map.get("id")));
//                    if (CollectionUtils.isNotEmpty(inquiryMaterialSuppliers)){
//                        inquiryMaterialSuppliers.forEach(inquiryMaterialSupplier -> {
//                            inquiryMaterialSupplier.setQuoteFromDate(LocalDateTimeUtil.parse(map.get("quoteFromDate"),"yyyy-MM-dd"));
//                            inquiryMaterialSupplier.setQuoteEndDate(LocalDateTimeUtil.parse(map.get("quoteEndDate"),"yyyy-MM-dd"));
//                            inquiryMaterialSupplier.setConfirmDeliveryDate(ObjectUtil.isNotNull(map.get("confirmDeliveryDate"))?Integer.valueOf(map.get("confirmDeliveryDate")):null);
//                            inquiryMaterialSupplier.setMpq(ObjectUtil.isNotNull(map.get("mpq"))?Long.valueOf(map.get("mpq")):null);
//                            inquiryMaterialSupplier.setMoq(ObjectUtil.isNotNull(map.get("moq"))?Long.valueOf(map.get("moq")):null);
//                            inquiryMaterialSupplierService.updateById(inquiryMaterialSupplier);
//                        });
//                    }

                    InquiryMaterialSupplier inquiryMaterialSupplier = inquiryMaterialSupplierService.getById(map.get("id"));
                    if (ObjectUtil.isNotNull(inquiryMaterialSupplier)){
                        inquiryMaterialSupplier.setQuoteFromDate(LocalDateTimeUtil.parse(map.get("quoteFromDate"),"yyyy-MM-dd"));
                        inquiryMaterialSupplier.setQuoteEndDate(LocalDateTimeUtil.parse(map.get("quoteEndDate"),"yyyy-MM-dd"));
                        inquiryMaterialSupplier.setConfirmDeliveryDate(ObjectUtil.isNotNull(map.get("confirmDeliveryDate"))?Integer.valueOf(map.get("confirmDeliveryDate")):null);
                        inquiryMaterialSupplier.setMpq(ObjectUtil.isNotNull(map.get("mpq"))?Long.valueOf(map.get("mpq")):null);
                        inquiryMaterialSupplier.setMoq(ObjectUtil.isNotNull(map.get("moq"))?Long.valueOf(map.get("moq")):null);
                        //验证供应商物料报价有效期，截止日期必须有有效的配置期内。 2024-11-18 邓京术
                        SupplierDTO supplierDTO = supplierClient.getSupplierByCode(inquiryMaterialSupplier.getSupplierCode());
                        dictDTOS.stream().forEach(item -> {
                            //如果字典的类型配置与供应商类型相等，则取出有效期月份
                            if (StringUtils.isNotEmpty(supplierDTO.getAttr()) && item.getName().equals(supplierDTO.getAttr())) {
                                LocalDateTime plusOneMonth = inquiryMaterialSupplier.getQuoteFromDate().plusMonths(Integer.parseInt(item.getCode()));
                                if (inquiryMaterialSupplier.getQuoteEndDate().isAfter(plusOneMonth)) {
                                    throw new DaoException("供应商:" + supplierDTO.getSupplierName() + "有效期结束日和有效期起始日不能大于" + item.getCode() + "个月。");
                                }
                            }
                        });
                        inquiryMaterialSupplierService.updateById(inquiryMaterialSupplier);
                    }
                }
            }
        } catch (IOException e) {
            throw new DaoException("读取Excel失败");
        }
    }

    @Override
    public List<Map<String, String>> fixImport(MultipartFile file) {
        try {
            List<Map<String,String>> dataList = EasyExcelImportUtils.parseExcelToData(file.getInputStream(), 2);
            return dataList;
        } catch (IOException e) {
            throw new DaoException("读取Excel失败");
        }
    }

    /**
     * 计算配额
     *
     * @param calculateQuotaDTOS 待计算配额
     * @return 已计算配额
     */
    @Override
    public List<CalculateQuotaDTO> calculateQuotaClient(List<CalculateQuotaDTO> calculateQuotaDTOS) {
        //付款条件
        List<DictDTO> paymentMethods = dictClient.getDicByType(DictCode.PAYMENT_TERMS.getCode());
        final Map<String, DictDTO> paymentMethodCache = paymentMethods.stream().collect(Collectors.toMap(DictDTO::getCode, a -> a));
        final Set<String> paymentMethodCodes = paymentMethodCache.keySet();
        //报关物流费率
        final String logisticsRate = sysConfigClient.getTextConfig(SysConfigKey.CUSTOMS_DECLARATION_LOGISTICS_RATE.getCode());
        Map<String, List<CalculateQuotaDTO>> skuMap = calculateQuotaDTOS.stream().collect(Collectors.groupingBy(CalculateQuotaDTO::getMaterialAndSupplierCode));
        List<CalculateQuotaDTO> newCalculateQuotaDTOS = new ArrayList<>();
        for (Map.Entry<String, List<CalculateQuotaDTO>> in : skuMap.entrySet()) {
            List<CalculateQuotaDTO> inquiryMaterialSupplierDTOS = in.getValue();
            //设置未税单价为0的数据配额为0
            inquiryMaterialSupplierDTOS.forEach(inquiryMaterialSupplierDTO -> {
                if (inquiryMaterialSupplierDTO.getNoTaxPrice().compareTo(BigDecimal.ZERO) == 0){
                    inquiryMaterialSupplierDTO.setConfirmQuota(BigDecimal.ZERO);
                }
            });
            //过滤掉未税单价为0的数据
            inquiryMaterialSupplierDTOS.removeIf(obj -> obj.getNoTaxPrice().compareTo(BigDecimal.ZERO) == 0);

            //先判断有没有参与报价的供应商
            boolean hasJoinQuote = inquiryMaterialSupplierDTOS.stream().anyMatch(obj -> obj.getJoinQuoteFlag()==1);
//            if(!hasJoinQuote){
//                continue;
//            }
            //开始计算配额
            //计算配额价格
            inquiryMaterialSupplierDTOS.forEach(inquiryMaterialSupplierDTO -> {
                //账期
                DictDTO dictDTO = paymentMethodCache.get(inquiryMaterialSupplierDTO.getPaymentMethod());
                //90-账期
                final BigDecimal accountPeriod = new BigDecimal("90").subtract(new BigDecimal(dictDTO.getRemark()));
                //X=（90-账期）/30的绝对值
                final BigDecimal period = accountPeriod.divide(new BigDecimal("30"),0, RoundingMode.HALF_UP).abs();
                BigDecimal quotaPrice;
                if ("CNY".equals(inquiryMaterialSupplierDTO.getCurrencyCode())){
                    //转换单价
                    BigDecimal convertPrice = inquiryMaterialSupplierDTO.getNoTaxPrice();
                    //当90-账期大于0时 转换单价*1.0032幂X
                    quotaPrice = accountPeriod.compareTo(BigDecimal.ZERO)>0?convertPrice.multiply(new BigDecimal("1.0032").pow(period.intValue())):
                            //当90-账期小于0时 转换单价*0.9968幂X
                            accountPeriod.compareTo(BigDecimal.ZERO)<0?convertPrice.multiply(new BigDecimal("0.9968").pow(period.intValue())):
                                    //当90-账期等于0时 转换单价*1幂X
                                    convertPrice;
                    log.info("90-账期：{}，X=（90-账期）/30的绝对值：{}，转换单价：{}，配额价格：{}",accountPeriod,period,convertPrice,quotaPrice);
//                    quotaPrice = period.multiply((inquiryMaterialSupplierDTO.getNoTaxPrice().multiply(new BigDecimal("0.32")))).add(inquiryMaterialSupplierDTO.getNoTaxPrice());
                }else {
                    BigDecimal exchangeRate;
                    if (inquiryMaterialSupplierDTO.getExchangeRate()==null){
                        exchangeRate = exchangeRateClient.getExchangeRateDefault(inquiryMaterialSupplierDTO.getCurrencyCode());
                        if (exchangeRate==null){
                            throw new DaoException(StrUtil.format("未获取到币种：{}的汇率",inquiryMaterialSupplierDTO.getCurrencyCode()));
                        }
                    }else {
                        exchangeRate = inquiryMaterialSupplierDTO.getExchangeRate();
                    }
                    //转换单价
                    BigDecimal convertPrice = inquiryMaterialSupplierDTO.getNoTaxPrice().multiply(exchangeRate);
                    //当90-账期大于0时 转换单价*1.0032幂X*（1+物流费）
                    quotaPrice = accountPeriod.compareTo(BigDecimal.ZERO)>0?convertPrice.multiply(new BigDecimal("1.0032").pow(period.intValue())).multiply((BigDecimal.ONE.add(new BigDecimal(logisticsRate)))):
                            //当90-账期小于0时 转换单价*0.9968幂X*（1+物流费）
                            accountPeriod.compareTo(BigDecimal.ZERO)<0?convertPrice.multiply(new BigDecimal("0.9968").pow(period.intValue())).multiply((BigDecimal.ONE.add(new BigDecimal(logisticsRate)))):
                                    //当90-账期等于0时 转换单价*1幂X*（1+物流费）
                                    convertPrice.multiply((BigDecimal.ONE.add(new BigDecimal(logisticsRate))));
                    log.info("90-账期：{}，X=（90-账期）/30的绝对值：{}，转换单价：{}，配额价格：{}",accountPeriod,period,convertPrice,quotaPrice);
//                    //配额价格USD:单价*汇率*物流费率(1+0.003)+(90-账期)/30*[(单价*汇率*物流费率(1+0.003))*0.32%]
//                    //单价*汇率*物流费率(1+0.003)
//                    BigDecimal price = inquiryMaterialSupplierDTO.getNoTaxPrice().multiply(exchangeRate).multiply((BigDecimal.ONE.add(new BigDecimal(logisticsRate))));
//                    //[(单价*汇率*物流费率(1+0.003))*0.32%]
//                    BigDecimal price2 = inquiryMaterialSupplierDTO.getNoTaxPrice().multiply(exchangeRate).multiply((BigDecimal.ONE.add(new BigDecimal(logisticsRate)))).multiply(new BigDecimal("0.32"));
//                    quotaPrice = price.add(price2);
                }
                inquiryMaterialSupplierDTO.setQuotaPrice(quotaPrice);
            });
            //配额价格从小到大排序
            List<CalculateQuotaDTO> quotaPriceList = inquiryMaterialSupplierDTOS.stream().sorted(Comparator.comparing(CalculateQuotaDTO::getQuotaPrice)).toList();
            if (quotaPriceList.size()==1){
                quotaPriceList.get(0).setConfirmQuota(new BigDecimal("100"));
            }
            //计算 差额比例=（第2价格-第1价格）/第一价格*100%
            BigDecimal secend = quotaPriceList.size()==1?quotaPriceList.get(0).getQuotaPrice():quotaPriceList.get(1).getQuotaPrice();
            log.info("第2价格：{}",secend);
            log.info("第1价格：{}",quotaPriceList.get(0).getQuotaPrice());
            BigDecimal diffPrice = secend.subtract(quotaPriceList.get(0).getQuotaPrice());
            BigDecimal diffPriceRatio = diffPrice.divide(quotaPriceList.get(0).getQuotaPrice(),4, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
            log.info("差额比例=（第2价格-第1价格）/第一价格*100%：{}",diffPriceRatio);

            if (quotaPriceList.size()==2){
                if (quotaPriceList.get(0).getQuotaPrice().compareTo(quotaPriceList.get(1).getQuotaPrice())==0){
                    quotaPriceList.get(0).setConfirmQuota(new BigDecimal("50"));
                    quotaPriceList.get(1).setConfirmQuota(new BigDecimal("50"));
                }else {
                    if (diffPriceRatio.compareTo(new BigDecimal("5"))==0||diffPriceRatio.compareTo(new BigDecimal("5"))<0){
                        quotaPriceList.get(0).setConfirmQuota(new BigDecimal("60"));
                        quotaPriceList.get(1).setConfirmQuota(new BigDecimal("40"));
                    }else if (diffPriceRatio.compareTo(new BigDecimal("5"))>0&&diffPriceRatio.compareTo(new BigDecimal("8"))<0){
                        quotaPriceList.get(0).setConfirmQuota(new BigDecimal("70"));
                        quotaPriceList.get(1).setConfirmQuota(new BigDecimal("30"));
                    }else if (diffPriceRatio.compareTo(new BigDecimal("8"))>0&&diffPriceRatio.compareTo(new BigDecimal("10"))<0){
                        quotaPriceList.get(0).setConfirmQuota(new BigDecimal("80"));
                        quotaPriceList.get(1).setConfirmQuota(new BigDecimal("20"));
                    }else {
                        quotaPriceList.get(0).setConfirmQuota(new BigDecimal("90"));
                        quotaPriceList.get(1).setConfirmQuota(new BigDecimal("10"));
                    }
                }
            }
            if (quotaPriceList.size()>=3){
                if (quotaPriceList.size()==3&&quotaPriceList.get(0).getQuotaPrice().compareTo(quotaPriceList.get(1).getQuotaPrice())==0&&quotaPriceList.get(1).getQuotaPrice().compareTo(quotaPriceList.get(2).getQuotaPrice())==0){
                    quotaPriceList.get(0).setConfirmQuota(new BigDecimal("40"));
                    quotaPriceList.get(1).setConfirmQuota(new BigDecimal("40"));
                    quotaPriceList.get(2).setConfirmQuota(new BigDecimal("20"));
                }else {
                    if (diffPriceRatio.compareTo(new BigDecimal("5"))==0||diffPriceRatio.compareTo(new BigDecimal("5"))<0){
                        quotaPriceList.get(0).setConfirmQuota(new BigDecimal("50"));
                        quotaPriceList.get(1).setConfirmQuota(new BigDecimal("30"));
                        quotaPriceList.get(2).setConfirmQuota(new BigDecimal("20"));
                    }else if (diffPriceRatio.compareTo(new BigDecimal("5"))>0&&diffPriceRatio.compareTo(new BigDecimal("8"))<0){
                        quotaPriceList.get(0).setConfirmQuota(new BigDecimal("60"));
                        quotaPriceList.get(1).setConfirmQuota(new BigDecimal("30"));
                        quotaPriceList.get(2).setConfirmQuota(new BigDecimal("10"));
                    }else if (diffPriceRatio.compareTo(new BigDecimal("8"))>0&&diffPriceRatio.compareTo(new BigDecimal("10"))<0){
                        quotaPriceList.get(0).setConfirmQuota(new BigDecimal("70"));
                        quotaPriceList.get(1).setConfirmQuota(new BigDecimal("20"));
                        quotaPriceList.get(2).setConfirmQuota(new BigDecimal("10"));
                    }else {
                        quotaPriceList.get(0).setConfirmQuota(new BigDecimal("80"));
                        quotaPriceList.get(1).setConfirmQuota(new BigDecimal("10"));
                        quotaPriceList.get(2).setConfirmQuota(new BigDecimal("10"));
                    }
                }
            }
            if (quotaPriceList.size()>3){
                int index = 0;
                final int numDiff = quotaPriceList.size()-2;
                BigDecimal averageAllNum = BigDecimal.ZERO;
                for (CalculateQuotaDTO inquiryMaterialSupplierDTO : quotaPriceList){
                    if (diffPriceRatio.compareTo(new BigDecimal("5"))==0||diffPriceRatio.compareTo(new BigDecimal("5"))<0){
                        //平均值
                        BigDecimal averageNum = new BigDecimal("0.2").divide(BigDecimal.valueOf(numDiff),2, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
                        if (index>1&&index!=quotaPriceList.size()-1){
                            averageAllNum = averageAllNum.add(averageNum);
                            inquiryMaterialSupplierDTO.setConfirmQuota(averageNum);
                        }
                        //如果是最后一个供应商，配额比例减去平均值总和
                        if (index==quotaPriceList.size()-1){
                            inquiryMaterialSupplierDTO.setConfirmQuota(new BigDecimal("20").subtract(averageNum.multiply(new BigDecimal(numDiff-1))));
                        }
                    }else{
                        //平均值
                        BigDecimal averageNum = new BigDecimal("0.1").divide(BigDecimal.valueOf(numDiff),2, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
                        if (index>1&&index!=quotaPriceList.size()-1){
                            averageAllNum = averageAllNum.add(averageNum);
                            inquiryMaterialSupplierDTO.setConfirmQuota(averageNum);
                        }
                        //如果是最后一个供应商，配额比例减去平均值总和
                        if (index==quotaPriceList.size()-1){
                            inquiryMaterialSupplierDTO.setConfirmQuota(new BigDecimal("10").subtract(averageNum.multiply(new BigDecimal(numDiff-1))));
                        }
                    }
                    index++;
                }
            }
            newCalculateQuotaDTOS.addAll(quotaPriceList);
        }
        return newCalculateQuotaDTOS;
    }

    @Override
    public List<InquiryMaterialSupplierClientDTO> getBidInquiryListByPurchaseApplyCode(String purchaseApplyCode, String itemNo) {
        List<InquiryMaterialSupplierPO> poList = inquiryMaterialSupplierService.getBidInquiryListByPurchaseApplyCode(purchaseApplyCode, itemNo);
        return inquiryMaterialSupplierConvert.po2ClientDTOList(poList);
    }
}
