package com.jwipc.inquiry.logic.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
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.exception.ExcelDataConvertException;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
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.io.Files;
import com.jwipc.constant.DictCode;
import com.jwipc.constant.FlagConst;
import com.jwipc.dto.ExportDataDTO;
import com.jwipc.exception.DaoException;
import com.jwipc.inquiry.constant.PriceInfoStatus;
import com.jwipc.inquiry.constant.SequenceConst;
import com.jwipc.inquiry.constant.SysConfigKey;
import com.jwipc.inquiry.convert.InquiryMaterialConvert;
import com.jwipc.inquiry.convert.PriceInfoConvert;
import com.jwipc.inquiry.dto.*;
import com.jwipc.inquiry.entity.Inquiry;
import com.jwipc.inquiry.entity.PriceInfo;
import com.jwipc.inquiry.logic.PriceInfoLogic;
import com.jwipc.inquiry.model.po.CreatePriceInfoPO;
import com.jwipc.inquiry.model.po.HistoryPriceInfoPO;
import com.jwipc.inquiry.model.po.InquiryMaterialPO;
import com.jwipc.inquiry.model.po.PriceInfoPO;
import com.jwipc.inquiry.model.query.PriceInfoQuery;
import com.jwipc.inquiry.model.query.PriceWarningQuery;
import com.jwipc.inquiry.service.IPriceInfoService;
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.SupplierDTO;
import com.jwipc.supplier.clent.dto.SupplierPurchaseCategoryDTO;
import com.jwipc.supplier.client.SupplierClient;
import com.jwipc.sys.client.*;
import com.jwipc.sys.client.dto.*;
import com.jwipc.util.DateUtils;
import com.jwipc.util.EasyExcelUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
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.File;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.baomidou.mybatisplus.core.toolkit.StringPool.DASH;

/**
 * @author shenyang.ou
 * @date 2024/2/28 11:06
 * @desc 价格信息记录
 */
@Service
@RequiredArgsConstructor
public class PriceInfoLogicImpl implements PriceInfoLogic {
    private final PriceInfoConvert priceInfoConvert;
    private final IPriceInfoService priceInfoService;
    private final SequenceClient sequenceClient;
    private final SupplierClient supplierClient;
    private final InquiryMaterialConvert inquiryMaterialConvert;
    private final SysConfigClient sysConfigClient;
    private final ProductGroupClient productGroupClient;
    private final PurchaseGroupClient purchaseGroupClient;
    private final PurchaseOrgClient purchaseOrgClient;
    private final FactoryClient factoryClient;
    private final DictClient dictClient;
    private final TaxClient taxClient;
    private final PriceHandle priceHandle;
    private final SysProp sysProp;
    private final FileClient fileClient;
    /**
     * 生成价格信息记录
     *
     * @param list 信息记录
     * @return 结果
     */
    @Override
    public void createPriceInfo(List<CreatePriceInfoDTO> list) {
        List<PriceInfo> priceInfos = priceInfoConvert.dto2EntityList(list);

        List<String> supplierCodes = priceInfos.stream()
                .map(PriceInfo::getSupplierCode)
                .filter(code -> code != null) // 过滤掉 null 值
                .collect(Collectors.toList());
        //到供应商信息主表里查询供应商信息
        Map<String, String> supplierMap = getSupplierInfoList(supplierCodes);
        final String pricePurchaseOrg = sysConfigClient.getTextConfig(SysConfigKey.PRICE_PURCHASE_ORG.getCode());
        final String pricePurchaseOrgCreateFactoryCode = sysConfigClient.getTextConfig(SysConfigKey.PRICE_PURCHASE_ORG_CREATE_FACTORY_CODE.getCode());
        final String[] factoryCodeList = StringUtils.split(pricePurchaseOrgCreateFactoryCode, ",");
        for (PriceInfo priceInfo : priceInfos){
            priceInfo.setPriceCode(sequenceClient.createSequenceNo(SequenceConst.PRICE_INFO_CODE.getCode()));
            if (priceInfo.getNoTaxPrice()==null){
                throw new DaoException("未税价格为空");
            }
            if (priceInfo.getExchangeRate()==null){
                throw new DaoException("汇率为空");
            }
            priceInfo.setConversionPrice(priceInfo.getNoTaxPrice().multiply(priceInfo.getExchangeRate()));
            priceInfo.setCreateTime(LocalDateTime.now());
            //判断采购组是否为2开头，并且供应商主数据是否有配置该工厂的物料信息
            if (priceInfo.getPurchaseGroupCode().startsWith("2")) {
                //查询该供应商下的物料配置表是否包含该工厂 2024-11-21 邓京术
                Pair<String, SupplierPurchaseCategoryDTO> purchaseCategoryDTOPair = supplierClient.getSupplierPurchaseCategory(priceInfo.getSupplierCode(), priceInfo.getFactoryCode());
                if (ObjectUtil.isNotEmpty(purchaseCategoryDTOPair.getValue()) && purchaseCategoryDTOPair.getValue().getCompanyCode().equals(priceInfo.getFactoryCode())){
                    priceInfoService.save(priceInfo);
                }
            } else {
                priceInfoService.save(priceInfo);
            }
             String[] newfactoryCodeList = factoryCodeList;
            String supplierGroup = supplierMap.get(priceInfo.getSupplierCode());
            if(priceInfo.getSupplierCode().length() > 4){
                if(StringUtils.isNotEmpty(supplierGroup) && "Z001".equals(supplierGroup)){//供应商分组等于Z001集团内供应商时，需要在扩充的工厂数组中删除等于供应商编码后四位的工厂，不进行改工厂扩充
                    //获取供应商工厂
                    String lastFourChars = priceInfo.getSupplierCode().substring(priceInfo.getSupplierCode().length() - 4);
                     newfactoryCodeList  =  getZ001ExpandFactory(factoryCodeList,lastFourChars);
                }
            }
            if (pricePurchaseOrg.equals(priceInfo.getPurchaseOrgCode())&& "1000".equals(priceInfo.getFactoryCode())){
                for (String factoryCode: newfactoryCodeList){
                    //排除1000工厂的报价信息
                    boolean su = priceInfos.stream().anyMatch(f -> priceInfo.getMaterialCode().equals(f.getMaterialCode())
                            &&priceInfo.getSupplierCode().equals(f.getSupplierCode())
                            &&pricePurchaseOrg.equals(f.getPurchaseOrgCode())
                            &&factoryCode.equals(f.getFactoryCode()));
                    //判断采购组是否为2开头，并且供应商主数据是否有配置该工厂的物料信息
                    if (priceInfo.getPurchaseGroupCode().startsWith("2")) {
                        //查询该供应商下的物料配置表是否包含该工厂 2024-11-21 邓京术
                        Pair<String, SupplierPurchaseCategoryDTO> purchaseCategoryDTOPair = supplierClient.getSupplierPurchaseCategory(priceInfo.getSupplierCode(), priceInfo.getFactoryCode());
                        if (ObjectUtil.isEmpty(purchaseCategoryDTOPair.getValue()) || !purchaseCategoryDTOPair.getValue().getCompanyCode().equals(priceInfo.getFactoryCode())){
                            if (!su) {
                                su = true;
                            }
                        }
                    //对于采购组不是2开头的且如果工厂是1500，不同步报价信息到1500
                    } else if (factoryCode.equals("1500")){
                        if (!su) {
                            su = true;
                        }
                    }
                    if (!su){
                        PriceInfo priceInfo1 = new PriceInfo();
                        BeanUtil.copyProperties(priceInfo,priceInfo1);
                        priceInfo1.setId(IdWorker.getId());
                        priceInfo1.setFactoryCode(factoryCode);
                        priceInfo1.setPriceCode(sequenceClient.createSequenceNo(SequenceConst.PRICE_INFO_CODE.getCode()));
                        priceInfoService.save(priceInfo1);
                    }
                }
            }
        }
    }

    @Override
    public PageView findByPage(PriceInfoQuery query) {
        final Page<Inquiry> dbPage = PageUtil.toPage(query);
        List<PriceInfoPO> priceInfoPOS = priceInfoService.findPageByQuery(dbPage, query);
        priceInfoPOS.forEach(priceInfoPO -> {
            priceInfoPO.setConversionPrice(priceInfoPO.getNoTaxPrice().multiply(priceInfoPO.getExchangeRate()));
        });
        List<PriceInfoDTO> priceInfoDTOS = priceInfoConvert.po2DTOList(priceInfoPOS);
        return PageUtil.getPV(priceInfoDTOS, dbPage.getTotal());
    }

    @Override
    public List<PriceInfoDTO> listAll(PriceInfoQuery query) {
        List<PriceInfoPO> priceInfoPOS = priceInfoService.findPageByQuery(null, query);
        return priceInfoConvert.po2DTOList(priceInfoPOS);
    }

    /**
     * 更新状态
     *
     * @param id      价格记录id
     * @param optType 操作类型；0-生效；1-失效；2-关闭
     */
    @Override
    public void updateStatus(Long id, Integer optType,String invalidRemark) {
        PriceInfo priceInfo = priceInfoService.getById(id);
        priceInfo.setStatus(optType==0? PriceInfoStatus.EFFECT.getStatus() : optType==1 ? PriceInfoStatus.EFFICACY.getStatus() : PriceInfoStatus.CLOSE.getStatus());
        priceInfo.setInvalidRemark(invalidRemark);
        priceInfoService.updateById(priceInfo);
    }

    /**
     * 根据调价id组装价格信息记录
     *
     * @param id 调价id
     * @return 价格信息记录
     */
    @Override
    public List<CreatePriceInfoDTO> getByAuditId(Long id) {
        List<CreatePriceInfoPO> createPriceInfoPOS = priceInfoService.getByAuditId(id);
        return priceInfoConvert.po2DtoList(createPriceInfoPOS);
    }

    @Override
    public PriceInfoDTO getById(Long id) {
        PriceInfo priceInfo = priceInfoService.getById(id);
        return priceInfoConvert.entity2DTO(priceInfo);
    }

    /**
     * 根据物料编码和工厂获取历史最低价
     *
     * @param materialCode 物料编码
     * @param factoryCode 工厂编码
     * @return 历史最低价
     */
    @Override
    public HistoryPriceInfoDTO getHistoryLowPrice(String materialCode, String factoryCode) {
        HistoryPriceInfoPO historyPriceInfoPO = priceInfoService.getHistoryLowPrice(materialCode,factoryCode);
        if (ObjectUtil.isNotNull(historyPriceInfoPO)){
            historyPriceInfoPO.setTaxPrice(historyPriceInfoPO.getNoTaxPrice().multiply(historyPriceInfoPO.getExchangeRate()));
        }
        return priceInfoConvert.historyPriceInfoPO2DtoList(historyPriceInfoPO);
    }

    /**
     * 根据物料编码和工厂获取上次中标价
     *
     * @param materialCode 物料编码
     * @param factoryCode 工厂编码
     * @return 上次中标价
     */
    @Override
    public HistoryPriceInfoDTO getLastBidPrice(String materialCode, String factoryCode) {
        HistoryPriceInfoPO historyPriceInfoPO = priceInfoService.getLastBidPrice(materialCode,factoryCode);
        if (ObjectUtil.isNotNull(historyPriceInfoPO)){
            historyPriceInfoPO.setTaxPrice(historyPriceInfoPO.getNoTaxPrice().multiply(historyPriceInfoPO.getExchangeRate()));
        }
        return priceInfoConvert.historyPriceInfoPO2DtoList(historyPriceInfoPO);
    }

    /**
     * 根据供应商编码和物料编码和工厂获取上次中标价
     *
     * @param supplierCode 供应商编码
     * @param materialCode 物料编码
     * @param factoryCode 工厂编码
     * @return 上次中标价
     */
    @Override
    public PriceInfoDTO getSupplierLastBidPrice(String supplierCode, String materialCode, String factoryCode) {
        PriceInfoPO priceInfo = priceInfoService.getSupplierLastBidPrice(supplierCode,materialCode,factoryCode);
        return priceInfoConvert.po2DTO(priceInfo);
    }

    /**
     * 组装转询价物料列表
     *
     * @param priceInfoIds 价格信息记录ids
     * @return 询价物料列表
     */
    @Override
    public List<InquiryMaterialDTO> makeInquiryMaterial(String priceInfoIds) {
        List<InquiryMaterialPO> inquiryPOS = priceInfoService.makeInquiryMaterial(Arrays.asList(StringUtils.split(priceInfoIds, ",")));
        List<InquiryMaterialDTO> inquiryMaterialDTOS = inquiryMaterialConvert.po2DTOList(inquiryPOS);
        inquiryMaterialDTOS.forEach(inquiryMaterialDTO -> {
            if (StringUtils.isNotEmpty(inquiryMaterialDTO.getMaterialCode())&&StringUtils.isNotEmpty(inquiryMaterialDTO.getFactoryCode())){
                HistoryPriceInfoDTO historyPriceInfoDTO = this.getHistoryLowPrice(inquiryMaterialDTO.getMaterialCode(),inquiryMaterialDTO.getFactoryCode());
                if (ObjectUtil.isNotNull(historyPriceInfoDTO)){
                    inquiryMaterialDTO.setHistoryPrice(historyPriceInfoDTO.getTaxPrice());
                    inquiryMaterialDTO.setHistoryPriceId(historyPriceInfoDTO.getId());
                }
                HistoryPriceInfoDTO lastBidPriceInfoDTO = this.getLastBidPrice(inquiryMaterialDTO.getMaterialCode(),inquiryMaterialDTO.getFactoryCode());
                if (ObjectUtil.isNotNull(lastBidPriceInfoDTO)){
                    inquiryMaterialDTO.setLastBidPrice(historyPriceInfoDTO.getTaxPrice());
                    inquiryMaterialDTO.setLastBidPriceId(historyPriceInfoDTO.getId());
                }
            }
            inquiryMaterialDTO.setQuoteFromDate(LocalDateTime.now());
            inquiryMaterialDTO.setQuoteEndDate(LocalDateTimeUtil.offset(LocalDateTime.now(),1, ChronoUnit.YEARS));
        });
        return inquiryMaterialDTOS;
    }

    public Map<String, String> getSupplierInfoList(List<String> cods){
        List<SupplierDTO> supplierByCodes = supplierClient.getSupplierByCodes(cods);
        //转化成 供应商code , supplier_group
        Map<String, String> supplierMap = supplierByCodes.stream().filter(dto -> dto.getSupplierCode() != null && dto.getSupplierGroup() != null).collect(Collectors.toMap(
                SupplierDTO::getSupplierCode,
                SupplierDTO::getSupplierGroup,
                (oldValue, newValue) -> newValue));
        return  supplierMap;
    }

    /**
     *
     * @return
     */
    public String[] getZ001ExpandFactory(String[] factoryCodeList,String target){
        String[] newArray = Arrays.stream(factoryCodeList)
                .filter(element -> !element.equals(target))
                .toArray(String[]::new);
        return newArray;
    }

    @Override
    public String importData(MultipartFile file) {
        List<PriceInfoImportDTO> cachedDataList = ListUtils.newArrayList();
        List<PriceInfoImportDTO> cachedUpdateDataList = ListUtils.newArrayList();
        List<PriceInfoImportResultDTO> resultDTOS = ListUtils.newArrayList();
        try {
            //国系
            List<DictDTO> countrySeries = dictClient.getDicByType(DictCode.COUNTRY_SERIES.getCode());
            final Map<String, DictDTO> countrySeriesCache = countrySeries.stream().collect(Collectors.toMap(DictDTO::getName, a -> a));
            final Set<String> countrySeriesNames = countrySeriesCache.keySet();

            //工厂
            final List<FactoryDTO> all = factoryClient.getAll();
            final Map<String, FactoryDTO> factoryCache = all.stream()
                    .collect(Collectors.toMap(FactoryDTO::getFactory, a -> a));
            final Set<String> factoryCodes = factoryCache.keySet();

            //物料组
            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();

            //采购组
            final List<PurchaseGroupDTO> purchaseGroupDTOS = purchaseGroupClient.getAll();
            final Map<String, PurchaseGroupDTO> purchaseGroupCache = purchaseGroupDTOS.stream()
                    .collect(Collectors.toMap(PurchaseGroupDTO::getPurchaseGroupCode, a -> a));
            final Set<String> purchaseGroupCodes = purchaseGroupCache.keySet();

            //采购组织
            final List<PurchaseOrgDTO> purchaseOrgDTOS = purchaseOrgClient.getAll();
            final Map<String, PurchaseOrgDTO> purchaseOrgCache = purchaseOrgDTOS.stream()
                    .collect(Collectors.toMap(PurchaseOrgDTO::getPurchaseOrgCode, a -> a));
            final Set<String> purchaseOrgCodes = purchaseOrgCache.keySet();

            //税率
            final List<TaxDTO> taxDTOS = taxClient.getAll();
            final Map<String, TaxDTO> taxCache = taxDTOS.stream().collect(Collectors.toMap(TaxDTO::getTaxCode, a -> a));
            final Set<String> taxCodes = taxCache.keySet();
            EasyExcel.read(file.getInputStream(), PriceInfoImportDTO.class,
                    new ReadListener<PriceInfoImportDTO>() {
                        @Override
                        public void invoke(PriceInfoImportDTO data, AnalysisContext context) {
                            String result = "";
                            if (Strings.isNullOrEmpty(data.getPriceCode())) {
                                result+="定价记录号为空；";
                            }
                            if (Strings.isNullOrEmpty(data.getMaterialCode())) {
                                result+="物料编码为空；";
                            }
                            if (Strings.isNullOrEmpty(data.getOrderUnit())) {
                                result+="订单单位为空；";
                            }
                            if (Strings.isNullOrEmpty(data.getMaterialName())) {
                                result+="描述为空；";
                            }
                            if (Strings.isNullOrEmpty(data.getFactoryCode())) {
                                result+="工厂为空；";
                            } else if (!factoryCodes.contains(data.getFactoryCode())){
                                result+=StrUtil.format("工厂：{}在系统中不存在；",data.getFactoryCode());
                            }
                            if (Strings.isNullOrEmpty(data.getPurchaseGroupCode())) {
                                result+="采购组为空；";
                            } else if (!purchaseGroupCodes.contains(data.getPurchaseGroupCode())){
                                result+=StrUtil.format("采购组：{}在系统中不存在；",data.getPurchaseGroupCode());
                            }
                            if (Strings.isNullOrEmpty(data.getPurchaseOrgCode())) {
                                result+="采购组织为空；";
                            } else if (!purchaseOrgCodes.contains(data.getPurchaseOrgCode())){
                                result+=StrUtil.format("采购组织：{}在系统中不存在；",data.getPurchaseOrgCode());
                            }
                            if (Strings.isNullOrEmpty(data.getSupplierCode())) {
                                result+="供应商为空；";
                            }else {
                                SupplierDTO supplierDTO = supplierClient.getSupplierByCode(data.getSupplierCode());
                                if (ObjectUtil.isEmpty(supplierDTO)){
                                    result+=StrUtil.format("供应商编码：{}在系统中不存在；",data.getSupplierCode());
                                }
                            }
                            if (Strings.isNullOrEmpty(data.getSupplierName())) {
                                result+="供应商名称为空；";
                            }
                            if (Strings.isNullOrEmpty(data.getPurchaseType())) {
                                result+="信息类别为空；";
                            }else if ("标准".equals(data.getPurchaseType())){
                                data.setPurchaseType("0");
                            }else if ("寄售".equals(data.getPurchaseType())){
                                data.setPurchaseType("2");
                            }else if ("委外".equals(data.getPurchaseType())){
                                data.setPurchaseType("3");
                            }else {
                                result+=StrUtil.format("信息类别：{}在系统中不存在；",data.getPurchaseType());
                            }
                            if (Strings.isNullOrEmpty(data.getLastPriceStr())) {
                                result+="采购原币价格（含税）为空；";
                            }else {
                                if (!isValidCurrency(data.getLastPriceStr().replaceAll(",",""))){
                                    result+=StrUtil.format("采购原币价格（含税）：{}格式不正确；",data.getLastPriceStr());
                                }else {
                                    data.setLastPrice(new BigDecimal(data.getLastPriceStr().replaceAll(",","")));
                                }
                            }
                            if (Strings.isNullOrEmpty(data.getPriceUnitStr())) {
                                result+="价格单位为空；";
                            }else {
                                if (!isValidCurrency(data.getPriceUnitStr().replaceAll(",",""))){
                                    result+=StrUtil.format("价格单位：{}格式不正确；",data.getPriceUnitStr());
                                }else {
                                    data.setPriceUnit(Integer.valueOf(data.getPriceUnitStr().replaceAll(",","")));
                                }
                            }
                            if (Strings.isNullOrEmpty(data.getTaxCode())) {
                                result+="税代码为空；";
                            } else if (!taxCodes.contains(data.getTaxCode())){
                                result+=StrUtil.format("税代码：{}在系统中不存在；",data.getTaxCode());
                            }
                            if (Strings.isNullOrEmpty(data.getConversionPriceStr())) {
                                result+="本币未税价格为空；";
                            }else {
                                if (!isValidCurrency(data.getConversionPriceStr().replaceAll(",",""))){
                                    result+=StrUtil.format("本币（CNY）未税价格：{}格式不正确；",data.getConversionPriceStr());
                                }else {
                                    data.setConversionPrice(new BigDecimal(data.getConversionPriceStr().replaceAll(",","")));
                                }
                            }
                            if (Strings.isNullOrEmpty(data.getQuotaStr())) {
                                result+="配额为空；";
                            }else {
                                if (!isValidCurrency(data.getQuotaStr().replaceAll(",",""))){
                                    result+=StrUtil.format("配额：{}格式不正确；",data.getQuotaStr());
                                }else {
                                    data.setQuota(new BigDecimal(data.getQuotaStr().replaceAll(",","")));
                                }
                            }
                            if (Strings.isNullOrEmpty(data.getCurrencyCode())) {
                                result+="币种为空；";
                            }
                            if (Strings.isNullOrEmpty(data.getExchangeRateStr())) {
                                result+="汇率为空；";
                            }else {
                                if (!isValidCurrency(data.getExchangeRateStr().replaceAll(",",""))){
                                    result+=StrUtil.format("汇率：{}格式不正确；",data.getExchangeRateStr());
                                }else {
                                    data.setExchangeRate(new BigDecimal(data.getExchangeRateStr().replaceAll(",","")));
                                }
                            }
                            if (!Strings.isNullOrEmpty(data.getLogisticsAgencyFeeStr())) {
                                if (!isValidCurrency(data.getLogisticsAgencyFeeStr().replaceAll(",",""))){
                                    result+=StrUtil.format("物流服务费：{}格式不正确；",data.getLogisticsAgencyFeeStr());
                                }else {
                                    data.setLogisticsAgencyFee(new BigDecimal(data.getLogisticsAgencyFeeStr().replaceAll(",","")));
                                }
                            }
                            if (!Strings.isNullOrEmpty(data.getTariffStr())) {
                                if (!isValidCurrency(data.getTariffStr().replaceAll(",",""))){
                                    result+=StrUtil.format("关税：{}格式不正确；",data.getTariffStr());
                                }else {
                                    data.setTariff(new BigDecimal(data.getTariffStr().replaceAll(",","")));
                                }
                            }
                            if (!Strings.isNullOrEmpty(data.getStageNum1Str())) {
                                if (!isValidCurrency(data.getStageNum1Str().replaceAll(",",""))){
                                    result+=StrUtil.format("阶梯1数量：{}格式不正确；",data.getStageNum1Str());
                                }else {
                                    data.setStageNum1(new BigDecimal(data.getStageNum1Str().replaceAll(",","")));
                                }
                            }
                            if (!Strings.isNullOrEmpty(data.getStageNum2Str())) {
                                if (!isValidCurrency(data.getStageNum2Str().replaceAll(",",""))){
                                    result+=StrUtil.format("阶梯2数量：{}格式不正确；",data.getStageNum2Str());
                                }else {
                                    data.setStageNum2(new BigDecimal(data.getStageNum2Str().replaceAll(",","")));
                                }
                            }
                            if (!Strings.isNullOrEmpty(data.getStageNum3Str())) {
                                if (!isValidCurrency(data.getStageNum3Str().replaceAll(",",""))){
                                    result+=StrUtil.format("阶梯3数量：{}格式不正确；",data.getStageNum3Str());
                                }else {
                                    data.setStageNum3(new BigDecimal(data.getStageNum3Str().replaceAll(",","")));
                                }
                            }
                            if (!Strings.isNullOrEmpty(data.getStageNum4Str())) {
                                if (!isValidCurrency(data.getStageNum4Str().replaceAll(",",""))){
                                    result+=StrUtil.format("阶梯4数量：{}格式不正确；",data.getStageNum4Str());
                                }else {
                                    data.setStageNum4(new BigDecimal(data.getStageNum4Str().replaceAll(",","")));
                                }
                            }
                            if (!Strings.isNullOrEmpty(data.getStageNum5Str())) {
                                if (!isValidCurrency(data.getStageNum5Str().replaceAll(",",""))){
                                    result+=StrUtil.format("阶梯5数量：{}格式不正确；",data.getStageNum5Str());
                                }else {
                                    data.setStageNum5(new BigDecimal(data.getStageNum5Str().replaceAll(",","")));
                                }
                            }
                            if (!Strings.isNullOrEmpty(data.getStagePrice1Str())) {
                                if (!isValidCurrency(data.getStagePrice1Str().replaceAll(",",""))){
                                    result+=StrUtil.format("阶梯1价格：{}格式不正确；",data.getStagePrice1Str());
                                }else {
                                    data.setStagePrice1(new BigDecimal(data.getStagePrice1Str().replaceAll(",","")));
                                }
                            }
                            if (!Strings.isNullOrEmpty(data.getStagePrice2Str())) {
                                if (!isValidCurrency(data.getStagePrice2Str().replaceAll(",",""))){
                                    result+=StrUtil.format("阶梯2价格：{}格式不正确；",data.getStagePrice2Str());
                                }else {
                                    data.setStagePrice2(new BigDecimal(data.getStagePrice2Str().replaceAll(",","")));
                                }
                            }
                            if (!Strings.isNullOrEmpty(data.getStagePrice3Str())) {
                                if (!isValidCurrency(data.getStagePrice3Str().replaceAll(",",""))){
                                    result+=StrUtil.format("阶梯3价格：{}格式不正确；",data.getStagePrice3Str());
                                }else {
                                    data.setStagePrice3(new BigDecimal(data.getStagePrice3Str().replaceAll(",","")));
                                }
                            }
                            if (!Strings.isNullOrEmpty(data.getStagePrice4Str())) {
                                if (!isValidCurrency(data.getStagePrice4Str().replaceAll(",",""))){
                                    result+=StrUtil.format("阶梯4价格：{}格式不正确；",data.getStagePrice4Str());
                                }else {
                                    data.setStagePrice4(new BigDecimal(data.getStagePrice4Str().replaceAll(",","")));
                                }
                            }
                            if (!Strings.isNullOrEmpty(data.getStagePrice5Str())) {
                                if (!isValidCurrency(data.getStagePrice5Str().replaceAll(",",""))){
                                    result+=StrUtil.format("阶梯3价格：{}格式不正确；",data.getStagePrice5Str());
                                }else {
                                    data.setStagePrice5(new BigDecimal(data.getStagePrice5Str().replaceAll(",","")));
                                }
                            }
                            if (Strings.isNullOrEmpty(data.getEffectDateStr())) {
                                result+="有效期起始日为空；";
                            }else {
                                try {
                                    data.setEffectDate(LocalDateTimeUtil.of(DateUtil.parse(data.getEffectDateStr(),"yyyy/MM/dd")));
                                }catch (Exception e){
                                    result+=StrUtil.format("有效期起始日：{}格式不正确，请输入yyyy/MM/dd格式；",data.getEffectDateStr());
                                }
                            }
                            if (Strings.isNullOrEmpty(data.getInvalidDateStr())) {
                                result+="有效截至日为空；";
                            }else {
                                try {
                                    data.setInvalidDate(LocalDateTimeUtil.of(DateUtil.parse(data.getInvalidDateStr(),"yyyy/MM/dd")));
                                }catch (Exception e){
                                    result+=StrUtil.format("有效截至日：{}格式不正确，请输入yyyy/MM/dd格式；",data.getInvalidDateStr());
                                }
                            }
                            if(StringUtils.isNotEmpty(data.getCountryName())){
                                if (!countrySeriesNames.contains(data.getCountryName())){
                                    result+=StrUtil.format("国系：{}在系统中不存在；",data.getCountryName());
                                }else {
                                    DictDTO dictDTO = countrySeriesCache.get(data.getCountryName());
                                    data.setCountryName(dictDTO.getCode());
                                }
                            }
                            if (Strings.isNullOrEmpty(data.getPaymentMethod())) {
                                result+="付款条件为空；";
                            }
                            if (Strings.isNullOrEmpty(data.getMaterialGroupCode())) {
                                result+="物料组为空；";
                            }
                            if (StringUtils.isNotEmpty(result)){
                                resultDTOS.add(PriceInfoImportResultDTO.builder().priceCode(data.getPriceCode()).result(result).build());
                            }else {
//                                data.setLastPrice(data.getLastPrice().divide(new BigDecimal(data.getPriceUnit()),priceHandle.getPrecision(),Objects.equals(priceHandle.getCutType(), FlagConst.N.getCode()) ? RoundingMode.HALF_UP : RoundingMode.DOWN));
                                if (data.getPriceUnit()!=null){
                                    data.setLastPrice(data.getLastPrice().divide(new BigDecimal(data.getPriceUnit()), 6,
                                            Objects.equals(priceHandle.getCutType(), FlagConst.N.getCode()) ? RoundingMode.HALF_UP : RoundingMode.DOWN));
                                }
//                                data.setConversionPrice(data.getConversionPrice().divide(new BigDecimal(data.getPriceUnit()),priceHandle.getPrecision(),Objects.equals(priceHandle.getCutType(), FlagConst.N.getCode()) ? RoundingMode.HALF_UP : RoundingMode.DOWN));
                                if (data.getStagePrice1()!=null){
                                    data.setStagePrice1(data.getStagePrice1().divide(new BigDecimal(data.getPriceUnit()),priceHandle.getPrecision(),Objects.equals(priceHandle.getCutType(), FlagConst.N.getCode()) ? RoundingMode.HALF_UP : RoundingMode.DOWN));
                                }
                                if (data.getStagePrice2()!=null){
                                    data.setStagePrice2(data.getStagePrice2().divide(new BigDecimal(data.getPriceUnit()),priceHandle.getPrecision(),Objects.equals(priceHandle.getCutType(), FlagConst.N.getCode()) ? RoundingMode.HALF_UP : RoundingMode.DOWN));
                                }
                                if (data.getStagePrice3()!=null){
                                    data.setStagePrice3(data.getStagePrice3().divide(new BigDecimal(data.getPriceUnit()),priceHandle.getPrecision(),Objects.equals(priceHandle.getCutType(), FlagConst.N.getCode()) ? RoundingMode.HALF_UP : RoundingMode.DOWN));
                                }
                                if (data.getStagePrice4()!=null){
                                    data.setStagePrice4(data.getStagePrice4().divide(new BigDecimal(data.getPriceUnit()),priceHandle.getPrecision(),Objects.equals(priceHandle.getCutType(), FlagConst.N.getCode()) ? RoundingMode.HALF_UP : RoundingMode.DOWN));
                                }
                                if (data.getStagePrice5()!=null){
                                    data.setStagePrice5(data.getStagePrice5().divide(new BigDecimal(data.getPriceUnit()),priceHandle.getPrecision(),Objects.equals(priceHandle.getCutType(), FlagConst.N.getCode()) ? RoundingMode.HALF_UP : RoundingMode.DOWN));
                                }
                                data.setTaxPrice(data.getLastPrice());
                                TaxDTO taxDTO = taxCache.get(data.getTaxCode());
                                //计算未税价格
                                data.setNoTaxPrice(data.getTaxPrice()
                                        .divide(taxDTO.getTaxValue().add(BigDecimal.ONE), 6,
                                                Objects.equals(priceHandle.getCutType(), FlagConst.N.getCode()) ? RoundingMode.HALF_UP : RoundingMode.DOWN));
                                data.setConversionPrice(data.getNoTaxPrice().multiply(data.getExchangeRate()));
                                data.setTaxPrice(data.getLastPrice());
                                data.setSourceType(3);
                                data.setSourceCode(data.getPriceCode());
                                data.setStatus(4);
                                data.setCompanyCode(data.getFactoryCode());
                                data.setCreateTime(LocalDateTime.now());
                                data.setCreateUser(LoginUtil.getUserId());
                                PriceInfo priceInfo = priceInfoService.getOne(Wrappers.lambdaQuery(PriceInfo.class).eq(PriceInfo::getPriceCode,data.getPriceCode()).last(" limit 1"));
                                if (ObjectUtil.isNotNull(priceInfo)){
                                    data.setId(priceInfo.getId());
                                    cachedUpdateDataList.add(data);
                                }else {
                                    cachedDataList.add(data);
                                }
                            }
                        }
                        @Override
                        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                        }
                    }).sheet().doRead();
        } catch (IOException e) {
            throw new DaoException("导入失败！");
        }
        if (CollectionUtil.isNotEmpty(cachedDataList)){
            List<PriceInfo> priceInfos = priceInfoConvert.cachedDTO2EntityList(cachedDataList);
            //去除重复的价格信息记录编号
            priceInfos = priceInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(PriceInfo::getPriceCode))), ArrayList::new));
            priceInfoService.saveBatch(priceInfos);
        }
        if (CollectionUtil.isNotEmpty(cachedUpdateDataList)){
            List<PriceInfo> priceInfos = priceInfoConvert.cachedDTO2EntityList(cachedUpdateDataList);
            priceInfoService.updateBatchById(priceInfos);
        }
        if (CollectionUtil.isNotEmpty(resultDTOS)){
            //创建导出动态列
            List<ExportDataDTO> exportDataDTOS = new ArrayList<>();
            exportDataDTOS.add(ExportDataDTO.builder().title("定价记录号").field("priceCode").build());
            exportDataDTOS.add(ExportDataDTO.builder().title("错误信息").field("result").build());
            try {
                //创建导出文件
                File file1 = fileClient.createFile("价格信息导入错误记录-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN)+".xlsx");
                //写入错误信息到excel文件
                EasyExcelUtils.trendsModelWriteFile(file1,"sheet", resultDTOS, exportDataDTOS);
                //上传文件
                FileResposeCDTO fileResposeCDTO = fileClient.uploadFile(file1);
                //返回文件id供下载
                return String.valueOf(fileResposeCDTO.getId());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }else {
            return "ok";
        }
    }

    @Override
    public PriceInfoDTO getLastPrice(String materialCode, String factoryCode, String supplierCode) {
        PriceInfoPO priceInfoPO = priceInfoService.getLastPrice(materialCode,factoryCode,supplierCode);
        return priceInfoConvert.po2DTO(priceInfoPO);
    }

    @Override
    public List<PriceInfoDTO> getList(Collection<? extends Serializable> idList) {
        List<PriceInfo> priceInfos =  priceInfoService.listByIds(idList);
        return priceInfoConvert.entity2DTOList(priceInfos);
    }

    @Override
    public List<PriceInfoDTO> getEffectiveMinPrice(List<String> materialCodes, Date date) {
       //根据时间和物料编号查找价格最小的值
        List<PriceInfo> effectiveMinPrice = priceInfoService.getEffectiveMinPrice(materialCodes, date);
        return priceInfoConvert.entity2DTOList(effectiveMinPrice);
    }

    public boolean isValidCurrency(String value) {
        try {
            new BigDecimal(value);
            return true;
        }catch (Exception e){
            return false;
        }
    }
}
