package com.jwipc.inquiry.logic.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.jwipc.constant.DictCode;
import com.jwipc.contract.base.ContractDetailClientDTO;
import com.jwipc.contract.client.ContractDetailClient;
import com.jwipc.exception.DaoException;
import com.jwipc.inquiry.constant.*;
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.PriceInfoLogic;
import com.jwipc.inquiry.model.po.*;
import com.jwipc.inquiry.model.query.InquiryConvertContractQuery;
import com.jwipc.inquiry.model.query.InquiryQuery;
import com.jwipc.inquiry.service.*;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.prop.SysProp;
import com.jwipc.security.LoginUtil;
import com.jwipc.supplier.clent.dto.SupplierAvlBaseDTO;
import com.jwipc.supplier.clent.dto.SupplierContactsDTO;
import com.jwipc.supplier.clent.dto.SupplierDTO;
import com.jwipc.supplier.clent.dto.SupplierPurchaseCategoryDTO;
import com.jwipc.supplier.client.QuotaManagementClient;
import com.jwipc.supplier.client.SupplierClient;
import com.jwipc.sys.client.*;
import com.jwipc.sys.client.dto.DictDTO;
import com.jwipc.sys.client.dto.EmailTmpSingleSendDTO;
import com.jwipc.sys.client.dto.ProductGroupDTO;
import com.jwipc.sys.client.dto.ProductInfoDTO;
import com.jwipc.sys.entity.FinancialShareContract;
import com.jwipc.sys.service.IFinancialShareContractService;
import com.jwipc.sys.util.FinancialShareUtil;
import com.jwipc.tender.client.dto.QuotaManagementClientDTO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.jwipc.constant.SysConfigKey.INQUIRY_FIX_NO_OA_PURCHASE_CATEGORY_CODE;

/**
 * @author shenyang.ou
 * @date 2024/2/18 14:59
 * @desc 询价
 */
@Service
@RequiredArgsConstructor
public class InquiryLogicImpl implements InquiryLogic {
    private final IInquiryService inquiryService;
    private final IInquiryMaterialService inquiryMaterialService;
    private final IInquiryMaterialExtendService inquiryMaterialExtendService;
    private final IInquirySupplierService inquirySupplierService;
    private final EmailSendClient emailSendClient;
    private final IInquirySupplierQuoteLogService inquirySupplierQuoteLogService;
    private final IInquiryMaterialSupplierService inquiryMaterialSupplierService;
    private final IPurchaseApplyBillDetailService purchaseApplyBillDetailService;
    private final IInquiryMaterialSupplierExtendService inquiryMaterialSupplierExtendService;
    private final InquiryConvert inquiryConvert;
    private final InquiryMaterialConvert inquiryMaterialConvert;
    private final InquiryMaterialExtendConvert inquiryMaterialExtendConvert;
    private final InquirySupplierConvert inquirySupplierConvert;
    private final InquiryMaterialSupplierConvert inquiryMaterialSupplierConvert;
    private final InquiryMaterialSupplierExtendConvert inquiryMaterialSupplierExtendConvert;
    private final SequenceClient sequenceClient;
    private final SysConfigClient sysConfigClient;
    private final ProductClient productClient;
    private final PriceInfoLogic priceInfoLogic;
    private final IPriceInfoService priceInfoService;
    private final SupplierClient supplierClient;
    private final DictClient dictClient;
    private final QuotaManagementClient quotaManagementClient;
    private final FileClient fileClient;
    private final SysProp sysProp;
    private final ProductGroupClient productGroupClient;
    private final ExchangeRateClient exchangeRateClient;
    private final IFinancialShareContractService financialShareContractService;
    private final FinancialShareUtil financialShareUtil;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    private ContractDetailClient contractDetailClient;

    @Override
    public PageView findByPage(InquiryQuery query) {
        if(CollectionUtil.isNotEmpty(query.getStatusList())){
            if(query.getStatusList().contains("0")){//包含全部
                query.setStatusList(null);
            }
        }
        final Page<Inquiry> dbPage = PageUtil.toPage(query);
        //转合同情况 查询支持查询多种情况  2024-11-07 邓京术
        //1 全部已转 2 部分转 3 未转
        // 1+2+3 = 6 查所有的
        //1 + 3 = 4 查全部已转 + 未转的
        //2+3 = 5  查部分转和未转的
        // 1 + 2 = 3  index(,) != 0  传 7  查全部已转 + 部分转的。
        if (null == query.getStateTurned()) {
            query.setStateTurned("6");
        } else if (query.getStateTurned().indexOf(",") > 0) {
            String[] arr = query.getStateTurned().split(",");
            final Integer[] total = {0};
            Arrays.stream(arr).forEach(item -> {
                total[0] = total[0] + Integer.parseInt(item);
            });
            query.setStateTurned(String.valueOf(total[0]));
            if (total[0] == 3) {
                query.setStateTurned("7");
            }
        }
        List<InquiryPO> inquiryPOS = inquiryService.findPageByQuery(dbPage, query);
        //把报价情况和转合同情况，单独抽出来重新查询
        inquiryPOS.stream().forEach(item -> {
            //,
            //            (select COALESCE(COUNT(id),0) from t_inquiry_material_supplier where inquiry_id = ti.id and bargain_flag in (1)) bargainNum,
            //            CONCAT((select COALESCE(COUNT(id),0) from t_inquiry_supplier where inquiry_id = ti.id AND quote_flag = 1),'/',
            //                (select COALESCE(COUNT(id),0) from t_inquiry_supplier where inquiry_id = ti.id)) AS quoteInfo,
            //        CONCAT((select COALESCE(COUNT(id),0) from t_inquiry_supplier where inquiry_id = ti.id AND state_turned = 1),'/',
            //        (select COALESCE(COUNT(distinct supplier_id),0) from t_inquiry_material_supplier where inquiry_id = ti.id AND bid_flag = 1)) AS stateTurnedInfo
            //把以上查询语句从Sql中拆出来。
            List<InquiryMaterialSupplier> inquiryMaterialSuppliers = inquiryMaterialSupplierService.list(Wrappers.lambdaQuery(InquiryMaterialSupplier.class).eq(InquiryMaterialSupplier::getInquiryId,item.getId()));

            //议价中的数量
            int bargainNum = inquiryMaterialSuppliers.stream().filter(inquiryMaterialSupplier -> inquiryMaterialSupplier.getBargainFlag()==1).collect(Collectors.toList()).size();

            List<InquirySupplier> inquirySuppliers = inquirySupplierService.list(Wrappers.lambdaQuery(InquirySupplier.class).eq(InquirySupplier::getInquiryId,item.getId()));
            //已转合同的数量
            List<InquiryDetailByIdPO> xjSuppliers = inquiryService.getConvertedContractByInquiryId(item.getId());

//            int contractTurnedNum = inquirySuppliers.stream().filter(inquirySupplier -> inquirySupplier.getStateTurned()==1).collect(Collectors.toList()).size();
//            contractTurnedNum += costContractList.size();
            int contractTurnedNum=xjSuppliers.size();
            //已报价将转合同的数量
            List<InquiryMaterialSupplier> bidFlagList = inquiryMaterialSuppliers.stream().filter(inquiryMaterialSupplier -> inquiryMaterialSupplier.getBidFlag()==1).collect(Collectors.toList());
            final Map<Long, InquiryMaterialSupplier> inquiryMaterialSupplierMap = Maps.newHashMap();
            bidFlagList.stream().forEach(oo -> {
                if (!inquiryMaterialSupplierMap.keySet().contains(oo.getSupplierId())) {
                    inquiryMaterialSupplierMap.put(oo.getSupplierId(), oo);
                }
            });
            int bidFlagNum = inquiryMaterialSupplierMap.size();

            //总的参与的供应商数量
            int quoteNum = inquirySuppliers.size();
            //已提交报价的数量
            int quoteFlagNum = inquirySuppliers.stream().filter(inquirySupplier -> inquirySupplier.getQuoteFlag()==1).collect(Collectors.toList()).size();
            item.setBargainNum(bargainNum);
            item.setQuoteInfo(quoteFlagNum + "/" + quoteNum);
            item.setStateTurnedInfo(contractTurnedNum + "/" + bidFlagNum);
        });

        List<InquiryDTO> inquiryDTOS = inquiryConvert.po2DTOList(inquiryPOS);
        return PageUtil.getPV(inquiryDTOS, dbPage.getTotal());
    }

    @Override
    public InquiryDTO getById(Long id) {
        Inquiry inquiry = inquiryService.getById(id);
        return inquiryConvert.entity2DTO(inquiry);
    }

    @Override
    @Transactional
    public void saveOrUpdate(InquiryParamDTO param) {
        final Long userId = Objects.requireNonNull(LoginUtil.getCurrentUser()).getUserId();
        if (param.getId() == null) {
            param.setInquiryCode(sequenceClient.getCodeSequenceNo(SequenceConst.INQUIRY_CODE.getCode(), 5));
            param.setStatus(InquiryStatus.ADD.getStatus());
            param.setCreateTime(LocalDateTime.now());
            param.setCreateUser(userId);
        } else {
            param.setUpdateTime(LocalDateTime.now());
            param.setUpdateUser(userId);
            //删除询价物料
            inquiryMaterialService.remove(Wrappers.lambdaQuery(InquiryMaterial.class).eq(InquiryMaterial::getInquiryId,param.getId()));
            inquiryMaterialExtendService.remove(Wrappers.lambdaQuery(InquiryMaterialExtend.class).eq(InquiryMaterialExtend::getInquiryId,param.getId()));
            //删除询价供应商
            inquirySupplierService.remove(Wrappers.lambdaQuery(InquirySupplier.class).eq(InquirySupplier::getInquiryId,param.getId()));
            //删除询价物料供应商
            inquiryMaterialSupplierService.remove(Wrappers.lambdaQuery(InquiryMaterialSupplier.class).eq(InquiryMaterialSupplier::getInquiryId,param.getId()));
            inquiryMaterialSupplierExtendService.remove(Wrappers.lambdaQuery(InquiryMaterialSupplierExtend.class).eq(InquiryMaterialSupplierExtend::getInquiryId,param.getId()));
        }
        //如果为采购申请明细创建
        List<PurchaseApplyBillDetail> purchaseApplyBillDetails = new ArrayList<>();
        if (param.getDataSource()== InquiryDataSource.PURCHASE_APPLY_DETAIL.getStatus()){
            //更新采购申请明细中询价单号
            purchaseApplyBillDetails = purchaseApplyBillDetailService.listByIds(Arrays.asList(StringUtils.split(param.getPurchaseBillDetailIds(), ",")));
            purchaseApplyBillDetails.forEach(purchaseApplyBillDetail -> {
                purchaseApplyBillDetail.setEnquiryCode(param.getInquiryCode());
                purchaseApplyBillDetail.setInquiryFlag(1);
            });
        }
       //如果为价格信息记录创建
        List<PriceInfo> priceInfos = new ArrayList<>();
        if (param.getDataSource()== InquiryDataSource.PRICE_INFO_DETAIL.getStatus()){
            //更新价格信息记录中询价单号
            priceInfos = priceInfoService.listByIds(Arrays.asList(StringUtils.split(param.getPriceInfoIds(), ",")));
            priceInfos.forEach(priceInfo -> {
                priceInfo.setEnquiryCode(param.getInquiryCode());
                priceInfo.setInquiryFlag(1);
            });
        }
        //保存询价主数据
        Inquiry inquiry = inquiryConvert.DTO2Entity(param);
        inquiryService.saveOrUpdate(inquiry);
        //保存询价物料
        List<InquiryMaterial> inquiryMaterials = new ArrayList<>(param.getInquiryMaterialList().size());
        //询价物料扩展
        List<InquiryMaterialExtend> inquiryMaterialExtends = new ArrayList<>(param.getInquiryMaterialList().size());
        final List<InquiryMaterialDTO> inquiryMaterialDTOS = param.getInquiryMaterialList();
        AtomicInteger index = new AtomicInteger(1);
        for (InquiryMaterialDTO inquiryMaterialDTO : inquiryMaterialDTOS){
            Long id = IdWorker.getId();
            inquiryMaterialDTO.setId(id);
            //行项目
            String itemNo = StringUtils.leftPad(String.valueOf(index.get()*10), 5, "0");
            if (CollectionUtil.isNotEmpty(purchaseApplyBillDetails)){
                //更新采购明细询价行项目
                purchaseApplyBillDetails.forEach(purchaseApplyBillDetail -> {
                    if (purchaseApplyBillDetail.getBillCode().equals(inquiryMaterialDTO.getPurchaseBillCode())&&purchaseApplyBillDetail.getItemCode().equals(inquiryMaterialDTO.getPurchaseBillItemCode())){
                        purchaseApplyBillDetail.setEnquiryItemCode(itemNo);
                        purchaseApplyBillDetail.setPurchaseMethod("Z0011");
                    }
                });
            }
            if (CollectionUtil.isNotEmpty(priceInfos)){
                //更新价格信息记录询价行项目
                priceInfos.forEach(priceInfo -> {
                    if (priceInfo.getId().equals(inquiryMaterialDTO.getMakePriceInfoId())){
                        priceInfo.setEnquiryItemCode(itemNo);
                    }
                });
            }
            inquiryMaterialDTO.setItemNo(itemNo);
            inquiryMaterialDTO.setInquiryId(inquiry.getId());
            inquiryMaterialDTO.setCreateTime(LocalDateTime.now());
            inquiryMaterialDTO.setCreateUser(userId);
            InquiryMaterial inquiryMaterial = inquiryMaterialConvert.DTO2Entity(inquiryMaterialDTO);
            if (inquiry.getSupplierMaterialFlag() != null && inquiry.getSupplierMaterialFlag()==1&&StringUtils.isEmpty(inquiryMaterial.getMaterialDesc())){
                if (StringUtils.isNotEmpty(inquiryMaterial.getMaterialCode())){
                    ProductInfoDTO productInfoDTO = productClient.getByMaterialCodeAndFactoryCode(inquiryMaterial.getMaterialCode(),inquiryMaterial.getFactoryCode());
                    if (ObjectUtil.isNotNull(productInfoDTO)){
                        inquiryMaterial.setMaterialDesc(StringUtils.isNotEmpty(productInfoDTO.getMaterialDesc())?productInfoDTO.getMaterialDesc():inquiryMaterial.getMaterialName());
                    }else {
                        inquiryMaterial.setMaterialDesc(inquiryMaterial.getMaterialName());
                    }
                }

            }
            inquiryMaterials.add(inquiryMaterial);
            InquiryMaterialExtend inquiryMaterialExtend = inquiryMaterialExtendConvert.DTO2Entity(inquiryMaterialDTO);
            //询价物料扩展信息
            if (ObjectUtil.isNotEmpty(inquiryMaterialExtend)){
                inquiryMaterialExtend.setInquiryId(inquiry.getId());
                inquiryMaterialExtend.setInquiryMaterialId(id);
                inquiryMaterialExtend.setInquiryMaterialId(id);
                inquiryMaterialExtends.add(inquiryMaterialExtend);
            }
            index.getAndIncrement();
        }
        inquiryMaterialService.saveBatch(inquiryMaterials);
        inquiryMaterialExtendService.saveBatch(inquiryMaterialExtends);
        if (CollectionUtil.isNotEmpty(purchaseApplyBillDetails)){
            purchaseApplyBillDetailService.updateBatchById(purchaseApplyBillDetails);
        }
        if (CollectionUtil.isNotEmpty(priceInfos)){
            priceInfoService.updateBatchById(priceInfos);
        }
        //询价物料供应商
        List<InquiryMaterialSupplier> inquiryMaterialSuppliers = new ArrayList<>();
        //询价供应商扩展
        List<InquiryMaterialSupplierExtend> inquiryMaterialSupplierExtends = new ArrayList<>();
        final List<InquiryMaterialSupplierDTO> inquiryMaterialSupplierDTOS = param.getInquirySupplierList();

        inquiryMaterialSupplierDTOS.forEach(inquiryMaterialSupplierDTO -> {
            //物料组和品类关系是否存在
            AtomicBoolean materialGroupWithCategoryFlag = new AtomicBoolean(false);
            inquiryMaterials.forEach(inquiryMaterial -> {
                //校验物料组和品类关系是否存在
                List<SupplierPurchaseCategoryDTO> supplierPurchaseCategoryDTOS = supplierClient.getList(String.valueOf(inquiryMaterialSupplierDTO.getSupplierId()));
                if (CollectionUtil.isNotEmpty(supplierPurchaseCategoryDTOS)){
                    supplierPurchaseCategoryDTOS.forEach(supplierPurchaseCategoryDTO -> {
                        ProductGroupDTO productGroupDTO = productGroupClient.getByCodeAndCategory(inquiryMaterial.getMaterialGroupCode(),supplierPurchaseCategoryDTO.getPurchaseCategoryCode());
                        if (ObjectUtil.isNotNull(productGroupDTO)){
                            materialGroupWithCategoryFlag.set(true);
                        }
                    });
                }
                //校验物料组的品类是不是MRO,如果是所有供应商都可以报
                //无需oa审批的采购品类
                final String noOaPurchaseCategoryCode = sysConfigClient.getTextConfig(INQUIRY_FIX_NO_OA_PURCHASE_CATEGORY_CODE.getCode());
                ProductGroupDTO productGroupDTO1 = productGroupClient.getByCode(inquiryMaterial.getMaterialGroupCode());
                if (ObjectUtil.isNull(productGroupDTO1)||StrUtil.isEmpty(productGroupDTO1.getCategoryCode())){
                    materialGroupWithCategoryFlag.set(true);
                }else {
                    if (ObjectUtil.isNotNull(productGroupDTO1)&&noOaPurchaseCategoryCode.contains(productGroupDTO1.getCategoryCode())){
                        materialGroupWithCategoryFlag.set(true);
                    }
                }
            });
            if (!materialGroupWithCategoryFlag.get()){
                throw new DaoException(StrUtil.format("报价供应商：{}采购品类和物料组关系不匹配",inquiryMaterialSupplierDTO.getSupplierName()));
            }
        });

        for (InquiryMaterial inquiryMaterial : inquiryMaterials){
            for (InquiryMaterialSupplierDTO inquiryMaterialSupplierDTO : inquiryMaterialSupplierDTOS){
                //如果供应商
                if (!inquiryMaterialSupplierDTO.getCompanyCode().equals(inquiry.getCompanyCode())){
                    throw new DaoException(StrUtil.format("报价供应商：{}公司与签约主体关系不匹配",inquiryMaterialSupplierDTO.getSupplierName()));
                }
                Long id = IdWorker.getId();
                inquiryMaterialSupplierDTO.setId(id);
                inquiryMaterialSupplierDTO.setInquiryId(inquiry.getId());
                inquiryMaterialSupplierDTO.setInquiryMaterialId(inquiryMaterial.getId());
                inquiryMaterialSupplierDTO.setQuoteFromDate(inquiryMaterial.getQuoteFromDate());
                inquiryMaterialSupplierDTO.setQuoteEndDate(inquiryMaterial.getQuoteEndDate());
                inquiryMaterialSupplierDTO.setCreateTime(LocalDateTime.now());
                inquiryMaterialSupplierDTO.setCreateUser(userId);
                inquiryMaterialSupplierDTO.setConfirmQuota(new BigDecimal(100));
                //如果不参与报价
                if (inquiryMaterialSupplierDTO.getJoinQuoteFlag()==0){
                    PriceInfoDTO priceInfoDTO = new PriceInfoDTO();
                    //根据物料编码和工厂编码和供应商编码取最新价格信息记录
                    priceInfoDTO = priceInfoLogic.getSupplierLastBidPrice(inquiryMaterialSupplierDTO.getSupplierCode(),inquiryMaterial.getMaterialCode(),inquiryMaterial.getFactoryCode());
                    if (ObjectUtil.isNotEmpty(priceInfoDTO)){
                        //设为中标
                        inquiryMaterialSupplierDTO.setBidFlag(1);
                        inquiryMaterialSupplierDTO.setBidTime(LocalDateTime.now());
                        inquiryMaterialSupplierDTO.setPriceInfoId(priceInfoDTO.getId());
                        inquiryMaterialSupplierDTO.setTaxPrice(priceInfoDTO.getTaxPrice());
                        inquiryMaterialSupplierDTO.setFirstTaxPrice(priceInfoDTO.getTaxPrice());
                        inquiryMaterialSupplierDTO.setNoTaxPrice(priceInfoDTO.getNoTaxPrice());
                        inquiryMaterialSupplierDTO.setFirstNoTaxPrice(priceInfoDTO.getNoTaxPrice());
                        inquiryMaterialSupplierDTO.setTaxPriceFlag(1);
                        inquiryMaterialSupplierDTO.setQuoteFlag(1);
                        inquiryMaterialSupplierDTO.setLastBidPrice(priceInfoDTO.getTaxPrice());
                        inquiryMaterialSupplierDTO.setStageNum1(priceInfoDTO.getStageNum1());
                        inquiryMaterialSupplierDTO.setStageNum2(priceInfoDTO.getStageNum2());
                        inquiryMaterialSupplierDTO.setStageNum3(priceInfoDTO.getStageNum3());
                        inquiryMaterialSupplierDTO.setStageNum4(priceInfoDTO.getStageNum4());
                        inquiryMaterialSupplierDTO.setStageNum5(priceInfoDTO.getStageNum5());
                        inquiryMaterialSupplierDTO.setStagePrice1(priceInfoDTO.getStagePrice1());
                        inquiryMaterialSupplierDTO.setStagePrice2(priceInfoDTO.getStagePrice2());
                        inquiryMaterialSupplierDTO.setStagePrice3(priceInfoDTO.getStagePrice3());
                        inquiryMaterialSupplierDTO.setStagePrice4(priceInfoDTO.getStagePrice4());
                        inquiryMaterialSupplierDTO.setStagePrice5(priceInfoDTO.getStagePrice5());
                        inquiryMaterialSupplierDTO.setTaxTotalPrice(priceInfoDTO.getTaxPrice().multiply(inquiryMaterial.getPurchaseNum()));
                        inquiryMaterialSupplierDTO.setNoTaxTotalPrice(priceInfoDTO.getNoTaxPrice().multiply(inquiryMaterial.getPurchaseNum()));
                        inquiryMaterialSupplierDTO.setConfirmDeliveryDate(priceInfoDTO.getLeadTime()==null?90:Math.toIntExact(priceInfoDTO.getLeadTime()));
                        inquiryMaterialSupplierDTO.setMoq(priceInfoDTO.getMoq());
                        inquiryMaterialSupplierDTO.setMpq(priceInfoDTO.getMpq());
                        //赋值Avl信息
                        if (StringUtils.isNotEmpty(inquiryMaterialSupplierDTO.getMaterialCode())){
                            SupplierAvlBaseDTO supplierAvlBaseDTO = supplierClient.findSupplierAvlItem(inquiryMaterialSupplierDTO.getSupplierCode(),inquiryMaterialSupplierDTO.getMaterialCode());
                            if (ObjectUtil.isNotNull(supplierAvlBaseDTO)){
                                inquiryMaterialSupplierDTO.setMpn(supplierAvlBaseDTO.getMpn());
                                inquiryMaterialSupplierDTO.setManufacturer(supplierAvlBaseDTO.getProductName());
                                inquiryMaterialSupplierDTO.setManufacturerEn(supplierAvlBaseDTO.getProductNameEn());
                                inquiryMaterialSupplierDTO.setCountryName(supplierAvlBaseDTO.getCountryName());
                                inquiryMaterialSupplierDTO.setMsl(supplierAvlBaseDTO.getMsl());
                            }
                        }
                    }else {
                        //设为中标
                        inquiryMaterialSupplierDTO.setBidFlag(0);
                        inquiryMaterialSupplierDTO.setBidTime(null);
                        inquiryMaterialSupplierDTO.setPriceInfoId(null);
                        inquiryMaterialSupplierDTO.setTaxPrice(null);
                        inquiryMaterialSupplierDTO.setFirstTaxPrice(null);
                        inquiryMaterialSupplierDTO.setNoTaxPrice(null);
                        inquiryMaterialSupplierDTO.setFirstNoTaxPrice(null);
                        inquiryMaterialSupplierDTO.setTaxPriceFlag(0);
                        inquiryMaterialSupplierDTO.setQuoteFlag(0);
                        inquiryMaterialSupplierDTO.setLastBidPrice(null);
                        inquiryMaterialSupplierDTO.setStageNum1(null);
                        inquiryMaterialSupplierDTO.setStageNum2(null);
                        inquiryMaterialSupplierDTO.setStageNum3(null);
                        inquiryMaterialSupplierDTO.setStageNum4(null);
                        inquiryMaterialSupplierDTO.setStageNum5(null);
                        inquiryMaterialSupplierDTO.setStagePrice1(null);
                        inquiryMaterialSupplierDTO.setStagePrice2(null);
                        inquiryMaterialSupplierDTO.setStagePrice3(null);
                        inquiryMaterialSupplierDTO.setStagePrice4(null);
                        inquiryMaterialSupplierDTO.setStagePrice5(null);
                        inquiryMaterialSupplierDTO.setTaxTotalPrice(null);
                        inquiryMaterialSupplierDTO.setNoTaxTotalPrice(null);
                        inquiryMaterialSupplierDTO.setConfirmDeliveryDate(null);
                        inquiryMaterialSupplierDTO.setMoq(null);
                        inquiryMaterialSupplierDTO.setMpq(null);
                        inquiryMaterialSupplierDTO.setMpn(null);
                        inquiryMaterialSupplierDTO.setManufacturer(null);
                        inquiryMaterialSupplierDTO.setManufacturerEn(null);
                        inquiryMaterialSupplierDTO.setCountryName(null);
                        inquiryMaterialSupplierDTO.setMsl(null);
                    }
                }
                InquiryMaterialSupplier inquiryMaterialSupplier = inquiryMaterialSupplierConvert.DTO2Entity(inquiryMaterialSupplierDTO);
                inquiryMaterialSuppliers.add(inquiryMaterialSupplier);
                InquiryMaterialSupplierExtend inquiryMaterialSupplierExtend = inquiryMaterialSupplierExtendConvert.DTO2Entity(inquiryMaterialSupplierDTO);
                //询价物料扩展信息
                if (ObjectUtil.isNotEmpty(inquiryMaterialSupplierExtend)){
                    if (inquiryMaterialSupplierDTO.getJoinQuoteFlag()==0){
                        inquiryMaterialSupplierExtend.setLogisticsAgencyFee(BigDecimal.valueOf(0.3));
                    }
                    inquiryMaterialSupplierExtend.setInquiryId(inquiry.getId());
                    inquiryMaterialSupplierExtend.setInquirySupplierId(id);
                    inquiryMaterialSupplierExtends.add(inquiryMaterialSupplierExtend);
                }
            }
        }

        //保存询价供应商
        List<InquirySupplier> inquirySuppliers = new ArrayList<>(inquiryMaterialSupplierDTOS.size());
        inquiryMaterialSupplierDTOS.forEach(inquirySupplierDTO -> {
            InquirySupplier inquirySupplier = new InquirySupplier();
            inquirySupplier.setInquiryId(inquiry.getId());
            inquirySupplier.setInquirySupplierStatus(inquirySupplierDTO.getBidFlag()!=null&&inquirySupplierDTO.getBidFlag()==1?InquirySupplierStatus.QUOTE_FINISH.getStatus():InquirySupplierStatus.ADD.getStatus());
            inquirySupplier.setQuoteFlag(inquirySupplierDTO.getBidFlag());
            inquirySupplier.setJoinQuoteFlag(inquirySupplierDTO.getJoinQuoteFlag());
            inquirySupplier.setSupplierId(inquirySupplierDTO.getSupplierId());
            inquirySupplier.setSupplierCode(inquirySupplierDTO.getSupplierCode());
            inquirySupplier.setCreateTime(LocalDateTime.now());
            inquirySupplier.setCreateUser(userId);
            inquirySuppliers.add(inquirySupplier);
        });
        inquirySupplierService.saveBatch(inquirySuppliers);
        final long limitNum = Long.parseLong(sysConfigClient.getTextConfig(SysConfigKey.INQUIRY_MATERIAL_RIDE_SUPPLIER_NUM.getCode()));
        if (inquiryMaterialSuppliers.size()>limitNum){
            throw new DaoException(StrUtil.format("所选择的物料*供应商数据超过{}条，请拆单询价",limitNum));
        }
        inquiryMaterialSupplierService.saveBatch(inquiryMaterialSuppliers);
        inquiryMaterialSupplierExtendService.saveBatch(inquiryMaterialSupplierExtends);
    }

    /**
     * 发布
     *
     * @param id 询价id
     */
    @Override
    @Transactional
    public void publish(Long id) {
        Inquiry inquiry = inquiryService.getById(id);
        //如果状态不为新建不允许发布
        if (inquiry.getStatus()!=InquiryStatus.ADD.getStatus()){
            throw new DaoException("只有新建状态的询价单才能发布");
        }
        final Long userId = Objects.requireNonNull(LoginUtil.getCurrentUser()).getUserId();
        inquiry.setStatus(InquiryStatus.PUBLISH.getStatus());
        inquiry.setUpdateTime(LocalDateTime.now());
        inquiry.setUpdateUser(Objects.requireNonNull(LoginUtil.getCurrentUser()).getUserId());
        inquiryService.updateById(inquiry);
        //询价供应商表状态更改为报价中
        List<InquirySupplier> inquirySuppliers = inquirySupplierService.list(Wrappers.lambdaQuery(InquirySupplier.class).eq(InquirySupplier::getInquiryId,id));
        if (CollectionUtil.isEmpty(inquirySuppliers)){
            throw new DaoException("请添加报价供应商");
        }
        inquirySuppliers.forEach(inquirySupplier -> {
            inquirySupplier.setInquirySupplierStatus(InquirySupplierStatus.QUOTE_ING.getStatus());
            inquirySupplier.setUpdateTime(LocalDateTime.now());
            inquirySupplier.setUpdateUser(userId);
        });
        inquirySupplierService.updateBatchById(inquirySuppliers);
        //发送供应商邮箱 //不参与报价的供应商不发送邮件 2024-08-02 邓京术 只查参与报价的供应商发邮件
        List<InquiryMaterialSupplier> inquiryMaterialSuppliers = inquiryMaterialSupplierService.list(Wrappers.lambdaQuery(InquiryMaterialSupplier.class)
                .eq(InquiryMaterialSupplier::getInquiryId,id).eq(InquiryMaterialSupplier::getJoinQuoteFlag, 1));
        Map<String,String> map = new HashMap<>();
        for (InquiryMaterialSupplier inquiryMaterialSupplier : inquiryMaterialSuppliers){
            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_050");
                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);
            }
        }
    }

    /**
     * 截止
     *
     * @param id 询价id
     */
    @Override
    @Transactional
    public void end(Long id) {
        Inquiry inquiry = inquiryService.getById(id);
        //如果状态不为新建不允许发布
        if (inquiry.getStatus()!=InquiryStatus.PUBLISH.getStatus()){
            throw new DaoException("只有发布状态的询价单才能截止");
        }
        inquiry.setStatus(InquiryStatus.END.getStatus());
        inquiry.setUpdateTime(LocalDateTime.now());
        inquiry.setUpdateUser(LoginUtil.getUserId());
        inquiryService.updateById(inquiry);
        //询价供应商表状态更改为询价截止
        List<InquirySupplier> inquirySuppliers = inquirySupplierService.list(Wrappers.lambdaQuery(InquirySupplier.class).eq(InquirySupplier::getInquiryId,id));
        inquirySuppliers.forEach(inquirySupplier -> {
            inquirySupplier.setInquirySupplierStatus(InquirySupplierStatus.END.getStatus());
            inquirySupplier.setUpdateTime(LocalDateTime.now());
            inquirySupplier.setUpdateUser(LoginUtil.getUserId());
        });
        inquirySupplierService.updateBatchById(inquirySuppliers);

        //询价物料供应商表更新汇率
        List<InquiryMaterialSupplier> inquiryMaterialSuppliers = inquiryMaterialSupplierService.list(Wrappers.lambdaQuery(InquiryMaterialSupplier.class).eq(InquiryMaterialSupplier::getInquiryId,id));
        inquiryMaterialSuppliers.forEach(inquiryMaterialSupplier -> {
            if (!"CNY".equals(inquiryMaterialSupplier.getCurrencyCode())){
                BigDecimal exchangeRate = exchangeRateClient.getExchangeRate(inquiryMaterialSupplier.getCurrencyCode(),"CNY");
                if (exchangeRate==null){
                    throw new DaoException(StrUtil.format("未获取到币种：{}的汇率,请更新本月汇率",inquiryMaterialSupplier.getCurrencyCode()));
                }
                inquiryMaterialSupplier.setExchangeRate(exchangeRate);
                inquiryMaterialSupplierService.updateById(inquiryMaterialSupplier);
            }
        });
    }

    /**
     * 截止
     *
     * @param id 询价id
     */
    @Override
    @Transactional
    public void close(Long id) {
        Inquiry inquiry = inquiryService.getById(id);
        //如果状态为截止才允许不定价关闭
        if (inquiry.getStatus()!=InquiryStatus.END.getStatus()){
            throw new DaoException("只有截止状态的询价单才能不定价关闭");
        }
        inquiry.setStatus(InquiryStatus.CLOSE.getStatus());
        inquiry.setUpdateTime(LocalDateTime.now());
        inquiry.setUpdateUser(LoginUtil.getUserId());
        //价格信息设为无需生成
        inquiry.setGenPriceInfo(2);
        inquiry.setFinishTime(LocalDateTime.now());
        inquiryService.updateById(inquiry);
    }

    @Override
    public List<InquiryMaterialQuoteDTO> materialQuoteList(Long inquiryId) {
        List<InquiryMaterialQuotePO> inquiryMaterialQuotePOS = inquiryService.materialQuoteList(inquiryId);
        return inquiryConvert.materialQuotePO2DTOList(inquiryMaterialQuotePOS);
    }

    /**
     * 作废
     *
     * @param id           询价id
     * @param cancelRemark 作废原因
     */
    @Override
    @Transactional
    public void cancel(Long id, String cancelRemark) {
        Inquiry inquiry = inquiryService.getById(id);
        inquiry.setStatus(InquiryStatus.CANCEL.getStatus());
        inquiry.setCancelRemark(cancelRemark);
        inquiry.setUpdateTime(LocalDateTime.now());
        inquiry.setUpdateUser(LoginUtil.getUserId());
        inquiryService.updateById(inquiry);
        //询价供应商表状态更改为完成
        List<InquirySupplier> inquirySuppliers = inquirySupplierService.list(Wrappers.lambdaQuery(InquirySupplier.class).eq(InquirySupplier::getInquiryId,id));
        inquirySuppliers.forEach(inquirySupplier -> {
            inquirySupplier.setInquirySupplierStatus(InquirySupplierStatus.FINISH.getStatus());
            inquirySupplier.setUpdateTime(LocalDateTime.now());
            inquirySupplier.setUpdateUser(LoginUtil.getUserId());
        });

        if (inquiry.getDataSource()==InquiryDataSource.PURCHASE_APPLY_DETAIL.getStatus()){
            //更新采购申请明细中询价单号
            List<PurchaseApplyBillDetail> purchaseApplyBillDetails = purchaseApplyBillDetailService.listByIds(Arrays.asList(StringUtils.split(inquiry.getPurchaseBillDetailIds(), ",")));
            purchaseApplyBillDetails.forEach(purchaseApplyBillDetail -> {
                purchaseApplyBillDetail.setEnquiryCode(null);
                purchaseApplyBillDetail.setInquiryFlag(0);
            });
            purchaseApplyBillDetailService.updateBatchById(purchaseApplyBillDetails);
        }
        if (inquiry.getDataSource()==InquiryDataSource.PRICE_INFO_DETAIL.getStatus()){
            //更新价格信息记录中询价单号
            List<PriceInfo> priceInfos = priceInfoService.listByIds(Arrays.asList(StringUtils.split(inquiry.getPriceInfoIds(), ",")));
            priceInfos.forEach(priceInfo -> {
                priceInfo.setEnquiryCode(null);
                priceInfo.setInquiryFlag(0);
            });
            priceInfoService.updateBatchById(priceInfos);
        }
        inquirySupplierService.updateBatchById(inquirySuppliers);
    }

    /**
     * 删除
     *
     * @param id 询价id
     */
    @Override
    @Transactional
    public void remove(Long id) {
        Inquiry inquiry = inquiryService.getById(id);
        //删除主表
        inquiryService.removeById(id);
        //删除询价物料
        inquiryMaterialService.remove(Wrappers.lambdaQuery(InquiryMaterial.class).eq(InquiryMaterial::getInquiryId,id));
        //删除询价物料扩展
        inquiryMaterialExtendService.remove(Wrappers.lambdaQuery(InquiryMaterialExtend.class).eq(InquiryMaterialExtend::getInquiryId,id));
        //删除询价供应商
        inquirySupplierService.remove(Wrappers.lambdaQuery(InquirySupplier.class).eq(InquirySupplier::getInquiryId,id));
        //删除询价物料供应商
        inquiryMaterialSupplierService.remove(Wrappers.lambdaQuery(InquiryMaterialSupplier.class).eq(InquiryMaterialSupplier::getInquiryId,id));
        //删除询价物料扩展
        inquiryMaterialSupplierExtendService.remove(Wrappers.lambdaQuery(InquiryMaterialSupplierExtend.class).eq(InquiryMaterialSupplierExtend::getInquiryId,id));
        //删除报价日志
        inquirySupplierQuoteLogService.remove(Wrappers.lambdaQuery(InquirySupplierQuoteLog.class).eq(InquirySupplierQuoteLog::getInquiryId,id));
        if (inquiry.getDataSource()==InquiryDataSource.PURCHASE_APPLY_DETAIL.getStatus()){
            //更新采购申请明细中询价单号
            List<PurchaseApplyBillDetail> purchaseApplyBillDetails = purchaseApplyBillDetailService.listByIds(Arrays.asList(StringUtils.split(inquiry.getPurchaseBillDetailIds(), ",")));
            purchaseApplyBillDetails.forEach(purchaseApplyBillDetail -> {
                purchaseApplyBillDetail.setEnquiryCode("");
                purchaseApplyBillDetail.setPurchaseMethod("");
                purchaseApplyBillDetail.setInquiryFlag(0);
            });
            purchaseApplyBillDetailService.updateBatchById(purchaseApplyBillDetails);
        }
        if (inquiry.getDataSource()==InquiryDataSource.PRICE_INFO_DETAIL.getStatus()){
            //更新价格信息记录中询价单号
            List<PriceInfo> priceInfos = priceInfoService.listByIds(Arrays.asList(StringUtils.split(inquiry.getPriceInfoIds(), ",")));
            priceInfos.forEach(priceInfo -> {
                priceInfo.setEnquiryCode("");
                priceInfo.setInquiryFlag(0);
            });
            priceInfoService.updateBatchById(priceInfos);
        }
    }

    /**
     * 更新询价物料和供应商数据
     *
     * @param inquiryMaterialId         询价物料id
     * @param inquiryMaterialSupplierId 询价物料供应商id
     * @param materialCode              物料编码
     * @param quoteFromDate             有效期起始日
     * @param quoteEndDate              有效期结束日
     */
    @Override
    @Transactional
    public void updateMaterialAndSupplierData(Long inquiryMaterialId, Long inquiryMaterialSupplierId, String materialCode, String quoteFromDate, String quoteEndDate,Integer confirmDeliveryDate,Long mpq,Long moq,String supplierCode) {
        InquiryMaterial inquiryMaterial = inquiryMaterialService.getById(inquiryMaterialId);
        ProductInfoDTO productInfo = productClient.getByMaterialCodeAndFactoryCode(materialCode,inquiryMaterial.getFactoryCode());
        if (ObjectUtil.isEmpty(productInfo)){
            throw new DaoException("物料编码在物料主数据中不存在，无法补充");
        }
        inquiryMaterial.setMaterialCode(materialCode);
        inquiryMaterial.setProductId(productInfo.getId());
        inquiryMaterial.setMaterialName(productInfo.getMaterialName());
        inquiryMaterial.setQuoteFromDate(LocalDateTimeUtil.parse(quoteFromDate,"yyyy-MM-dd"));
        inquiryMaterial.setQuoteEndDate(LocalDateTimeUtil.parse(quoteEndDate,"yyyy-MM-dd"));
        inquiryMaterialService.updateById(inquiryMaterial);
        //更新价格有效期
        InquiryMaterialSupplier inquiryMaterialSupplier = new InquiryMaterialSupplier();
        inquiryMaterialSupplier.setId(inquiryMaterialSupplierId);
        inquiryMaterialSupplier.setQuoteFromDate(LocalDateTimeUtil.parse(quoteFromDate,"yyyy-MM-dd"));
        inquiryMaterialSupplier.setQuoteEndDate(LocalDateTimeUtil.parse(quoteEndDate,"yyyy-MM-dd"));
        inquiryMaterialSupplier.setConfirmDeliveryDate(confirmDeliveryDate);
        inquiryMaterialSupplier.setMoq(moq);
        inquiryMaterialSupplier.setMpq(mpq);
        //验证供应商类型有效期结束日和有效期起始日不能大于 指定配置日期 2024-11-18 邓京术
        SupplierDTO supplierDTO = supplierClient.getSupplierByCode(supplierCode);
        List<DictDTO> dictDTOS = dictClient.getDicByType("supplier_material_quote_expiredate");
        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);
    }

    @Override
    public List<InquiryEditSupplierDTO> supplierListByInquiryId(Long inquiryId) {
        List<InquiryEditSupplierPO> inquiryPOS = inquiryService.supplierListByInquiryId(inquiryId);
        return inquiryConvert.editSupplierPo2DTOList(inquiryPOS);
    }

    @Override
    public List<InquiryEditSupplierDTO> supplierCopyListByInquiryId(Long inquiryId) {
        List<InquiryEditSupplierPO> inquiryPOS = inquiryService.supplierListByInquiryId(inquiryId);
        List<InquiryMaterial> inquiryMaterials = inquiryMaterialService.list(Wrappers.lambdaQuery(InquiryMaterial.class).eq(InquiryMaterial::getInquiryId,inquiryId));
        for (InquiryEditSupplierPO inquiryEditSupplierPO:inquiryPOS){
            inquiryEditSupplierPO.setQuotaSupplierFlag("");
            for (InquiryMaterial inquiryMaterial:inquiryMaterials){
                if (StringUtils.isNotEmpty(inquiryMaterial.getMaterialCode())){
                    BigDecimal quota = quotaManagementClient.getQuota(inquiryMaterial.getMaterialCode(),inquiryMaterial.getFactoryCode(),inquiryEditSupplierPO.getSupplierCode());
                    if (ObjectUtil.isNotNull(quota)){
                        inquiryEditSupplierPO.setQuotaSupplierFlag(inquiryMaterial.getMaterialCode()+"_"+inquiryMaterial.getFactoryCode());
                        break;
                    }
                }
            }
        }
        return inquiryConvert.editSupplierPo2DTOList(inquiryPOS);
    }

    /**
     * 导入物料信息
     *
     * @param file
     */
    @Override
    public List<InquiryMaterialImportDTO> importMaterialData(MultipartFile file) {
        List<InquiryMaterialImportDTO> cachedDataList = ListUtils.newArrayList();
        //物料组
        List<ProductGroupDTO> productGroupDTOS = productGroupClient.getAll();
        productGroupDTOS = productGroupDTOS.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()
                -> new TreeSet<>(Comparator.comparing(ProductGroupDTO::getMaterialGroup))), ArrayList::new));
        final Map<String, ProductGroupDTO> productGroupCache = productGroupDTOS.stream()
                .collect(Collectors.toMap(ProductGroupDTO::getMaterialGroup, a -> a));
        final Set<String> productGroupCodes = productGroupCache.keySet();

        //币种
        List<DictDTO> currencys = dictClient.getDicByType(DictCode.CURRENCY.getCode());
        final Map<String, DictDTO> currencyCache = currencys.stream().collect(Collectors.toMap(DictDTO::getCode, a -> a));
        final Set<String> currencyCodes = currencyCache.keySet();
        try {
            EasyExcel.read(file.getInputStream(), InquiryMaterialImportDTO.class,
                    new ReadListener<InquiryMaterialImportDTO>() {
                        @Override
                        public void invoke(InquiryMaterialImportDTO data, AnalysisContext context) {
                            final String materialName = data.getMaterialName();
                            final String materialCode = data.getMaterialCode();
                            final String materialGroupCode = data.getMaterialGroupCode();
                            final String currencyCode = data.getCurrencyCode();
                            final String factoryCode = data.getFactoryCode();
                            final String purchaseUnit = data.getPurchaseUnit();
                            final BigDecimal purchaseNum = data.getPurchaseNum();
                            final LocalDateTime quoteFromDate = data.getQuoteFromDate();
                            final LocalDateTime quoteEndDate = data.getQuoteEndDate();
                            if (StringUtils.isEmpty(materialCode)&&StringUtils.isEmpty(materialName)) {
                                throw new DaoException("物料编码和物料名称最少填写一项!");
                            }
//                            if (Strings.isNullOrEmpty(materialGroupCode)) {
//                                throw new DaoException("物料组编码不能为空!");
//                            }
//                            if (Strings.isNullOrEmpty(currencyCode)) {
//                                throw new DaoException("币种不能为空!");
//                            }
                            if (Strings.isNullOrEmpty(factoryCode)) {
                                throw new DaoException("工厂编码不能为空!");
                            }
//                            if (Strings.isNullOrEmpty(purchaseUnit)) {
//                                throw new DaoException("采购单位编码不能为空!");
//                            }
//                            if (purchaseNum==null) {
//                                throw new DaoException("采购数量不能为空!");
//                            }
//                            if (quoteFromDate==null) {
//                                throw new DaoException("有效期起始日不能为空!");
//                            }
//                            if (quoteEndDate==null) {
//                                throw new DaoException("有效期结束日不能为空!");
//                            }
                            if (StringUtils.isNotEmpty(materialGroupCode)&&!productGroupCodes.contains(materialGroupCode)){
                                throw new DaoException(StrUtil.format("物料组编码：{}在系统中不存在",materialGroupCode));
                            }
                            data.setMaterialGroupCode(materialGroupCode);
                            ProductGroupDTO productGroupDTO = productGroupCache.get(materialGroupCode);
                            if (ObjectUtil.isNotNull(productGroupDTO)){
                                data.setMaterialGroupName(productGroupDTO.getMaterialDesc());
                            }
                            if (StringUtils.isNotEmpty(currencyCode)&&!currencyCodes.contains(currencyCode)){
                                throw new DaoException(StrUtil.format("币种：{}在系统中不存在",currencyCode));
                            }
                            if (!Strings.isNullOrEmpty(materialCode)){
                                ProductInfoDTO productInfoDTO = productClient.getByMaterialCodeAndFactoryCode(materialCode,factoryCode);
                                if (ObjectUtil.isNotEmpty(productInfoDTO)){
                                    data.setProductId(productInfoDTO.getId());
                                    data.setMaterialName(productInfoDTO.getMaterialName());
                                    data.setMaterialDesc(productInfoDTO.getMaterialDesc());
                                    data.setMaterialGroupCode(productInfoDTO.getMaterialGroupCode());
                                    data.setMaterialGroupName(productInfoDTO.getMaterialGroupName());
                                    data.setMaterialUnit(productInfoDTO.getBasisUnit());
                                    data.setPurchaseUnit(productInfoDTO.getOrderUnit());
                                    //查询历史最低价
                                    HistoryPriceInfoDTO historyPriceInfoDTO = priceInfoLogic.getHistoryLowPrice(productInfoDTO.getMaterialCode(),productInfoDTO.getFactoryCode());
                                    if (ObjectUtil.isNotNull(historyPriceInfoDTO)){
                                        data.setHistoryPriceId(historyPriceInfoDTO.getId());
                                        data.setHistoryPrice(historyPriceInfoDTO.getTaxPrice());
                                    }
                                    //查询上次中标价
                                    HistoryPriceInfoDTO historyPriceInfoDTO1 = priceInfoLogic.getLastBidPrice(productInfoDTO.getMaterialCode(),productInfoDTO.getFactoryCode());
                                    if (ObjectUtil.isNotNull(historyPriceInfoDTO1)){
                                        data.setLastBidPriceId(historyPriceInfoDTO.getId());
                                        data.setLastBidPrice(historyPriceInfoDTO.getTaxPrice());
                                    }
                                }else {
                                    throw new DaoException(StrUtil.format("物料编码：{}在系统中不存在，请先维护该物料!",materialCode));
                                }
                            }

                            cachedDataList.add(data);
                        }
                        @Override
                        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                        }
                    }).sheet().doRead();
        } catch (IOException e) {
            throw new DaoException("导入失败！");
        }
        return cachedDataList;
    }

    /**
     * 导入供应商信息
     *
     * @param file
     * @param companyCode
     */
    @Override
    public List<InquirySupplierImportDTO> importSupplierData(MultipartFile file, String companyCode) {
        List<InquirySupplierImportDTO> cachedDataList = ListUtils.newArrayList();
        try {
            EasyExcel.read(file.getInputStream(), InquirySupplierImportDTO.class,
                    new ReadListener<InquirySupplierImportDTO>() {
                        @Override
                        public void invoke(InquirySupplierImportDTO data, AnalysisContext context) {
                            final String supplierCode = data.getSupplierCode();
                            if (Strings.isNullOrEmpty(supplierCode)) {
                                throw new DaoException("供应商编码不能为空!");
                            }
                            List<SupplierDTO> supplierDTOS = supplierClient.getSupplierByCodes(ListUtil.list(false,supplierCode));
                            if (CollectionUtil.isEmpty(supplierDTOS)){
                                throw new DaoException(StrUtil.format("供应商编码：{}在系统中不存在!",supplierCode));
                            }
                            data.setSupplierName(supplierDTOS.get(0).getSupplierName());
                            data.setSupplierId(supplierDTOS.get(0).getId());
                            Pair<String, SupplierPurchaseCategoryDTO> supplierPurchaseCategory = supplierClient.getSupplierPurchaseCategory(supplierCode,companyCode);
                            final SupplierPurchaseCategoryDTO supplierPurchaseCategoryDTO = supplierPurchaseCategory.getValue();
                            if (ObjectUtil.isNotEmpty(supplierPurchaseCategoryDTO)){
                                data.setCurrencyCode(supplierPurchaseCategoryDTO.getCurrencyCode());
                                data.setTaxCode(supplierPurchaseCategoryDTO.getTaxCode());
                                data.setPaymentMethod(supplierPurchaseCategoryDTO.getPaymentTerms());
                                data.setPurchaseCategoryCode(supplierPurchaseCategoryDTO.getPurchaseCategoryCode());
                                data.setPurchaseCategoryName(supplierPurchaseCategoryDTO.getPurchaseCategoryName());
                                data.setCompanyCode(supplierPurchaseCategoryDTO.getCompanyCode());
                            }else {
                                throw new DaoException(StrUtil.format("供应商编码：{}品类信息在系统中不存在!",supplierCode));
                            }

                            cachedDataList.add(data);
                        }
                        @Override
                        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                        }
                    }).sheet().doRead();
        } catch (IOException e) {
            throw new DaoException("导入失败！");
        }
        return cachedDataList;
    }

    /**
     * 根据物料编码和工厂编码获取配额供应商
     *
     * @param materialCode 物料编码
     * @param factoryCode  工厂编码
     */
    @Override
    public List<InquirySupplierImportDTO> getSupplierByMaterialCodeAndFactoryCode(String materialCode, String factoryCode, String companyCode) {
        List<QuotaManagementClientDTO> quotaManagementClientDTOS = quotaManagementClient.getByMaterialCodeAndFactoryCode(materialCode,factoryCode);
        if (CollectionUtil.isNotEmpty(quotaManagementClientDTOS)){
            List<String> strings = quotaManagementClientDTOS.stream().map(QuotaManagementClientDTO::getSupplierCode).toList();
            List<InquirySupplierImportDTO> inquirySupplierImportDTOS = new ArrayList<>(strings.size());
            for (String supplierCode : strings){
                SupplierDTO supplierDTO = supplierClient.getSupplierByCode(supplierCode);

                if (ObjectUtil.isNotNull(supplierDTO)){
                    InquirySupplierImportDTO supplierImportDTO = new InquirySupplierImportDTO();
                    supplierImportDTO.setSupplierId(supplierDTO.getId());
                    supplierImportDTO.setId(supplierDTO.getId());
                    supplierImportDTO.setSupplierCode(supplierCode);
                    supplierImportDTO.setSupplierName(supplierDTO.getSupplierName());
                    Pair<String, SupplierPurchaseCategoryDTO> supplierPurchaseCategory = supplierClient.getSupplierPurchaseCategory(supplierCode,companyCode);
                    final SupplierPurchaseCategoryDTO supplierPurchaseCategoryDTO = supplierPurchaseCategory.getValue();
                    if (ObjectUtil.isNotEmpty(supplierPurchaseCategoryDTO)){
                        supplierImportDTO.setCurrencyCode(supplierPurchaseCategoryDTO.getCurrencyCode());
                        supplierImportDTO.setTaxCode(supplierPurchaseCategoryDTO.getTaxCode());
                        supplierImportDTO.setPaymentMethod(supplierPurchaseCategoryDTO.getPaymentTerms());
                        supplierImportDTO.setPurchaseCategoryCode(supplierPurchaseCategoryDTO.getPurchaseCategoryCode());
                        supplierImportDTO.setPurchaseCategoryName(supplierPurchaseCategoryDTO.getPurchaseCategoryName());
                        supplierImportDTO.setCompanyCode(supplierPurchaseCategoryDTO.getCompanyCode());
                    }
                    SupplierContactsDTO supplierContactsDTO = supplierClient.getDefaultContact(supplierCode,"12");
                    if (ObjectUtil.isNotEmpty(supplierContactsDTO)){
                        supplierImportDTO.setSupplierEmail(supplierContactsDTO.getEmail());
                        supplierImportDTO.setSupplierContactsName(supplierContactsDTO.getContactsName());
                    }
                    inquirySupplierImportDTOS.add(supplierImportDTO);
                }
            }
            if (CollectionUtil.isNotEmpty(inquirySupplierImportDTOS)){
                inquirySupplierImportDTOS = inquirySupplierImportDTOS.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()
                        -> new TreeSet<>(Comparator.comparing(InquirySupplierImportDTO::getSupplierCode))), ArrayList::new));
            }
            return inquirySupplierImportDTOS;
        }


        return null;
    }

    @Override
    public List<InquiryDetailByIdPO> xjlistFindByList(Long xjId, Integer type) {
        // 转合同情况
        if (type == 2) {
            List<InquiryDetailByIdPO> xjSuppliers = inquiryService.getConvertedContractByInquiryId(xjId);
            xjSuppliers.forEach(item -> {
                if (StringUtils.isNotEmpty(item.getContractId())) {
                    // 费用类合同
                    item.setContractUrl(financialShareUtil.getFinancialShareFormUrl("er_contractbill", item.getContractId()));
                    item.setContractType("费用合同");
                } else {
                    // 资产类合同
                    item.setContractType("合同");
                }
            });
            return xjSuppliers;
        }
        List<InquiryDetailByIdPO> xjSuppliers = inquiryService.xjlistFindByList(xjId);
        if(xjSuppliers!=null){
            List<String> ids = xjSuppliers.stream().map(InquiryDetailByIdPO::getSupplierId).distinct().collect(Collectors.toList());
            List<SupplierDTO> supps = supplierClient.getSupplierByIds(ids);
            Long keys = System.currentTimeMillis();

            Map<Long, List<SupplierDTO>> spMap = null;
            if(supps!=null) {
                spMap = supps.stream().collect(Collectors.groupingBy(SupplierDTO::getId));
            }
            Map<Long, List<SupplierDTO>> finalSpMap = spMap;
            xjSuppliers.stream().forEach(a->{
                List<SupplierDTO> dtos = finalSpMap!=null&&finalSpMap.containsKey(Long.valueOf(a.getSupplierId()))?finalSpMap.get(Long.valueOf(a.getSupplierId())):null;
                a.setSupplierCode(dtos!=null?dtos.get(0).getSupplierCode():"");
                a.setSupplierName(dtos!=null?dtos.get(0).getSupplierName():"");
                a.setUuidKey(keys);
                a.setDataSources(2);
            });
            redisTemplate.opsForValue().set(String.valueOf(keys), JSON.toJSONString(xjSuppliers),1, TimeUnit.HOURS);
        }
        return xjSuppliers;
    }

    @Override
    public List<InquiryDetailByIdDetailClientDTO> formMaterialDeatilById(Long xjId, String supplierId) {
        List<InquiryDetailByIdDetailPO> inquiryDetailByIdDetailPOS = inquiryService.formMaterialDeatilById(xjId,supplierId);
        List<InquiryDetailByIdDetailClientDTO> inquiryDetailByIdDetailClientDTOS = inquiryConvert.inquiryDetailByIdDetailPO2DTOList(inquiryDetailByIdDetailPOS);
        for(InquiryDetailByIdDetailClientDTO inquiryDetailByIdDetailClientDTO :inquiryDetailByIdDetailClientDTOS){
            List<ContractDetailClientDTO> contractDetailClientDTOS = contractDetailClient.getDetailListByPurchaseCodeAndeItem(inquiryDetailByIdDetailClientDTO.getPurchaseCode(), inquiryDetailByIdDetailClientDTO.getItemCode());
            if (CollectionUtil.isNotEmpty(contractDetailClientDTOS)) {
                List<BigDecimal> numSum = contractDetailClientDTOS.stream().map(ContractDetailClientDTO::getNum).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(numSum)){
                    BigDecimal sum = numSum.stream()
                            .filter(Objects::nonNull)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal subtract = inquiryDetailByIdDetailClientDTO.getApprovalNumber()==null?BigDecimal.ZERO:inquiryDetailByIdDetailClientDTO.getApprovalNumber().subtract(sum);
                    inquiryDetailByIdDetailClientDTO.setEnablePurchaseNum(subtract==null?BigDecimal.ZERO:subtract);
                }else{
                    inquiryDetailByIdDetailClientDTO.setEnablePurchaseNum(BigDecimal.ZERO);
                }
            }else{
                inquiryDetailByIdDetailClientDTO.setEnablePurchaseNum(inquiryDetailByIdDetailClientDTO.getApprovalNumber());
            }
        }
        return inquiryDetailByIdDetailClientDTOS;
    }

    @Override
    public List<InquiryDTO> inquiryContractList(InquiryConvertContractQuery query) {
        List<InquiryPO> inquiryPOS = inquiryService.inquiryContractList(query);
        return inquiryConvert.po2DTOList(inquiryPOS);
    }

    @Override
    public List<InquiryDetailByIdDetailClientDTO> formDetailByMaterialSupplierId(List<String> inquiryIdList, String supplierId) {
        List<InquiryDetailByIdDetailPO> inquiryDetailByIdDetailPOS = inquiryService.formDetailByMaterialSupplierId(inquiryIdList,supplierId);
        return inquiryConvert.inquiryDetailByIdDetailPO2DTOList(inquiryDetailByIdDetailPOS);
    }

    @Override
    public void updateConStateByNos(String dataSourcesNos,String supplierCode, Integer state) {
        List<String> noList = StrUtil.split(dataSourcesNos,",");
        for (String no : noList){
            Inquiry inquiry = inquiryService.getOne(Wrappers.lambdaQuery(Inquiry.class).eq(Inquiry::getInquiryCode,no));
            inquirySupplierService.update(new LambdaUpdateWrapper<InquirySupplier>().set(InquirySupplier::getStateTurned,state).eq(InquirySupplier::getInquiryId,inquiry.getId()).eq(InquirySupplier::getSupplierCode,supplierCode));
        }
    }

    @Override
    public List<InquiryCostContractDTO> getInquiryCostContractList(InquiryConvertContractQuery query) {
        List<InquiryCostContractPO> inquiryCostContractPOS = inquiryService.getInquiryCostContractList(query);
        return inquiryConvert.inquiryCostContractPO2DTOList(inquiryCostContractPOS);
    }
}
