package com.jwipc.tender.logic.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import 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.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Strings;
import com.jwipc.api.constant.RestCode;
import com.jwipc.api.dto.ApiResult;
import com.jwipc.api.dto.OaFileParamDTO;
import com.jwipc.constant.DictCode;
import com.jwipc.constant.OaProcessType;
import com.jwipc.dto.ExportDataDTO;
import com.jwipc.exception.DaoException;
import com.jwipc.inquiry.client.PriceInfoClient;
import com.jwipc.inquiry.dto.CreatePriceInfoDTO;
import com.jwipc.inquiry.dto.PriceInfoClientDTO;
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.SupplierDTO;
import com.jwipc.supplier.client.SupplierClient;
import com.jwipc.sys.client.*;
import com.jwipc.sys.client.dto.*;
import com.jwipc.tender.constant.QuotaOaClient;
import com.jwipc.tender.convert.QuotaManagementConvert;
import com.jwipc.tender.dto.*;
import com.jwipc.tender.entity.QuotaManagement;
import com.jwipc.tender.logic.QuotaManagementLogic;
import com.jwipc.tender.model.po.QuotaManagementPO;
import com.jwipc.tender.model.query.QuotaEditQuery;
import com.jwipc.tender.model.query.QuotaManagementQuery;
import com.jwipc.tender.service.IQuotaManagementService;
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.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author AL
 * @date 2024/1/31 15:01
 * @desc 配额维护
 */
@Service
@RequiredArgsConstructor
public class QuotaManagementLogicImpl implements QuotaManagementLogic {

    private final IQuotaManagementService quotaManagementService;
    private final QuotaManagementConvert quotaManagementConvert;
    private final PurchaseCategoryClient purchaseCategoryClient;
    private final UserClient userClient;
    private final TaxClient taxClient;
    private final DictClient dictClient;
    private final SysProp sysProp;
    private final SupplierClient supplierClient;
    private final FactoryClient factoryClient;
    private final PriceInfoClient priceInfoClient;
    private final SequenceClient sequenceClient;
    private final FileClient fileClient;
    private final QuotaOaClient quotaOaClient;

    @Override
    public PageView findByPage(QuotaManagementQuery query) {
        final Page<QuotaManagement> dbPage = PageUtil.toPage(query);
        List<QuotaManagementPO> quotaManagementPOS = quotaManagementService.findByPage(dbPage, query);

        return PageUtil.getPV(quotaManagementConvert.po2PageListDTO(quotaManagementPOS), dbPage.getTotal());
    }

    @Override
    public PageView bidFindByPage(QuotaManagementQuery query) {
        final Page<QuotaManagement> dbPage = PageUtil.toPage(query);

        List<QuotaManagementPO> quotaManagementPOS = quotaManagementService.bidFindByPage(dbPage, query);

        return PageUtil.getPV(quotaManagementConvert.po2PageListDTO(quotaManagementPOS), dbPage.getTotal());
    }

    @Override
    public PageView editFindByPage(QuotaEditQuery query) {
        final Page<QuotaManagement> dbPage = PageUtil.toPage(query);
        query.setUserId(LoginUtil.getUserId());
        List<QuotaManagementPO> quotaManagementPOS = quotaManagementService.editFindByPage(dbPage, query);

        return PageUtil.getPV(quotaManagementConvert.po2PageListDTO(quotaManagementPOS), dbPage.getTotal());
    }

    @Override
    public PageView supplierFindByPage(QuotaEditQuery query) {
        final Page<QuotaManagement> dbPage = PageUtil.toPage(query);
        query.setUserId(LoginUtil.getUserId());
        List<QuotaManagementPO> quotaManagementPOS = quotaManagementService.supplierFindByPage(dbPage, query);

        return PageUtil.getPV(quotaManagementConvert.po2PageListDTO(quotaManagementPOS), dbPage.getTotal());
    }

    @Override
    public List<QuotaManagementDTO> findByQuery(QuotaManagementQuery query) {
        //final Page<QuotaManagement> dbPage = PageUtil.toPage(query);

        List<QuotaManagementPO> quotaManagementPOS = quotaManagementService.findByPage(null, query);

        return quotaManagementConvert.po2PageListDTO(quotaManagementPOS);
        // return PageUtil.getPV(quotaManagementConvert.po2PageListDTO(quotaManagementPOS), dbPage.getTotal());
    }
//配额保存

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(@RequestBody List<QuotaManagementSaveDTO> param1) {
        //配额校验
        checkQuota(param1);
        List<QuotaManagement> quotaManagementList = quotaManagementConvert.dto2EntityList(param1);
        quotaManagementList.forEach(quotaManagement -> {
            if (!Objects.isNull(quotaManagement.getId())) {
                quotaManagement.setUpdater(LoginUtil.getUserId());
                quotaManagement.setUpdateTime(LocalDateTime.now());
                quotaManagement.setSyncStatus(0);
                quotaManagement.setAuditStatus(1);
            }
        });
        quotaManagementService.saveOrUpdateBatch(quotaManagementList);
    }


    /**
     * 配额校验
     *
     * @param list
     * @throws Exception
     */
    private void checkQuota(List<QuotaManagementSaveDTO> list) {
        // 按物料分组
        Map<String, List<QuotaManagementSaveDTO>> materialGroup = list.stream()
                .collect(Collectors.groupingBy(QuotaManagementSaveDTO::getMaterialCode));
        for (Map.Entry<String, List<QuotaManagementSaveDTO>> entry : materialGroup.entrySet()) {
            String materialCode = entry.getKey();
            // 物料下的供应商配额数据
            List<QuotaManagementSaveDTO> totalQuotaList = entry.getValue();
            // 按供应商去重
            totalQuotaList = totalQuotaList.stream().collect(Collectors.collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(v -> v.getSupplierCode()))),
                    ArrayList::new));

            // 合计同物料下各供应商的配额
            double quotaAll = totalQuotaList.parallelStream().mapToDouble(obj -> {
                BigDecimal quota = obj.getQuota();
                if (null != quota) {
                    return quota.doubleValue();
                }
                return 0;
            }).sum();
            if (quotaAll != 100 && quotaAll != 0) {
                quotaAll = BigDecimal.valueOf(quotaAll).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
                throw new DaoException(
                        "物料：" + materialCode + "，各供应商的配额合计为" + quotaAll + "%, 要求是100%或0%, 请检查!");
            }
        }
    }

    //列表主数据
    @Override
    public List<QuotaManagementDTO> listAll(QuotaManagementQuery query) {
        List<QuotaManagementPO> quotaManagementPOS = quotaManagementService.findByPage(null, query);
        return quotaManagementConvert.po2PageListDTO(quotaManagementPOS);
    }

    //列表主数据
    @Override
    public List<QuotaManagementDTO> listAllExport(QuotaManagementQuery query) {
        List<QuotaManagementPO> quotaManagementPOS = quotaManagementService.bidFindByPage(null, query);
        return quotaManagementConvert.po2PageListDTO(quotaManagementPOS);
    }

    @Override
    public String importData(MultipartFile file) {
        List<QuotaManagementImportDTO> cachedDataList = ListUtils.newArrayList();
        List<QuotaManagementImportResultDTO> resultDTOS = ListUtils.newArrayList();
        try {
            //工厂
            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();
            EasyExcel.read(file.getInputStream(), QuotaManagementImportDTO.class,
                    new ReadListener<QuotaManagementImportDTO>() {
                        @Override
                        public void invoke(QuotaManagementImportDTO data, AnalysisContext context) {
                            String result = "";
                            if (Strings.isNullOrEmpty(data.getMaterialCode())) {
                                result += "物料为空；";
                            }

                            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.getFactoryCode())) {
                                result += "工厂为空；";
                            } else if (!factoryCodes.contains(data.getFactoryCode())) {
                                result += StrUtil.format("工厂：{}在系统中不存在；", data.getFactoryCode());
                            }
                            if (Strings.isNullOrEmpty(data.getMaterialName())) {
                                result += "物料长文本为空；";
                            }
                            if (Strings.isNullOrEmpty(data.getSupplierName())) {
                                result += "名称 1为空；";
                            }

                            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(",", "")));
                                    data.setAdjustmentQuota(new BigDecimal(data.getQuotaStr().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 (StringUtils.isNotEmpty(data.getMaterialCode()) &&
                                    StringUtils.isNotEmpty(data.getFactoryCode()) &&
                                    StringUtils.isNotEmpty(data.getSupplierCode())) {
                                PriceInfoClientDTO priceInfoClientDTO = priceInfoClient.getLastPrice(
                                        data.getMaterialCode(), data.getFactoryCode(), data.getSupplierCode());
                                if (ObjectUtil.isNull(priceInfoClientDTO)) {
                                    result += StrUtil.format(
                                            "根据物料编码{}、工厂编码{}、供应商编码{}在系统中未找到对应的价格信息记录",
                                            data.getMaterialCode(), data.getFactoryCode(), data.getSupplierCode());
                                } else {
                                    data.setPriceInfoId(priceInfoClientDTO.getId());
                                    data.setInvalidDate(priceInfoClientDTO.getInvalidDate());
                                    data.setPaymentMethod(priceInfoClientDTO.getPaymentMethod());
                                    data.setProcurementType(priceInfoClientDTO.getPurchaseType());
                                }
                            }

                            if (StringUtils.isNotEmpty(result)) {
                                resultDTOS.add(QuotaManagementImportResultDTO.builder()
                                        .materialCode(data.getMaterialCode())
                                        .materialName(data.getMaterialName())
                                        .factoryCode(data.getFactoryCode())
                                        .supplierCode(data.getSupplierCode())
                                        .supplierName(data.getSupplierName())
                                        .quotaStr(data.getQuotaStr())
                                        .result(result)
                                        .build());
                            } else {
//                                String code = sequenceClient.createSequenceNo("quota_seq");
//                                data.setQuotaCode(code);
                                data.setSyncStatus(2);
                                data.setAuditStatus(0);
                                data.setDeleteFlag(0);
                                data.setValidFlag(0);
                                data.setCreater(1L);
                                data.setCreateTime(LocalDateTime.now());
                                cachedDataList.add(data);
                            }
                        }

                        @Override
                        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                        }
                    }).sheet().doRead();
        } catch (IOException e) {
            throw new DaoException("导入失败！");
        }
        if (CollectionUtil.isNotEmpty(cachedDataList)) {
            //根据物料编码和工厂分组
            Map<String, List<QuotaManagementImportDTO>> skuMap = cachedDataList.stream().collect(Collectors.groupingBy(item ->
                    item.getMaterialCode() + "_" + item.getFactoryCode()));
            for (Map.Entry<String, List<QuotaManagementImportDTO>> in : skuMap.entrySet()) {
                //根据物料编码和工厂删除配额
//                this.deleteByMaterialCode(in.getKey());
                String[] key = in.getKey().split("_");
                quotaManagementService.remove(
                        Wrappers.lambdaQuery(QuotaManagement.class).eq(QuotaManagement::getMaterialCode, key[0]).eq(QuotaManagement::getFactoryCode, key[1]));
//                String code = sequenceClient.createSequenceNo("quota_seq");
                String code = sequenceClient.getCodeSequenceNo("quota_seq", 3);
                final List<QuotaManagementImportDTO> list = in.getValue();
                for (QuotaManagementImportDTO createPriceInfoDTO : list){
                    createPriceInfoDTO.setQuotaCode(code);
                }
                List<QuotaManagement> priceInfos = quotaManagementConvert.cachedDTO2EntityList(list);
                quotaManagementService.saveBatch(priceInfos);
            }
        }
        if (CollectionUtil.isNotEmpty(resultDTOS)) {
            //创建导出动态列
            List<ExportDataDTO> exportDataDTOS = new ArrayList<>();
            exportDataDTOS.add(ExportDataDTO.builder().title("物料编码").field("materialCode").build());
            exportDataDTOS.add(ExportDataDTO.builder().title("物料名称").field("materialName").build());
            exportDataDTOS.add(ExportDataDTO.builder().title("工厂").field("factoryCode").build());
            exportDataDTOS.add(ExportDataDTO.builder().title("供应商编码").field("supplierCode").build());
            exportDataDTOS.add(ExportDataDTO.builder().title("供应商名称").field("supplierName").build());
            exportDataDTOS.add(ExportDataDTO.builder().title("配额").field("quotaStr").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 void pushOa(String quotaCode) {
        List<QuotaManagement> quotaManagementList = quotaManagementService.list(
                Wrappers.lambdaQuery(QuotaManagement.class).eq(QuotaManagement::getQuotaCode, quotaCode));
        List<PriceInfoClientDTO> priceInfoClientDTOS = new ArrayList<>();
        for (QuotaManagement quotaManagement : quotaManagementList) {
            if (ObjectUtil.isNull(quotaManagement.getPriceInfoId())) {
                throw new DaoException("价格信息记录不存在，无法提交审批");
            }
            PriceInfoClientDTO priceInfoClientDTO = priceInfoClient.getById(quotaManagement.getPriceInfoId());
            if (ObjectUtil.isNull(priceInfoClientDTO)) {
                throw new DaoException("价格信息记录不存在，无法提交审批");
            }
            priceInfoClientDTO.setQuota(quotaManagement.getQuota());
            priceInfoClientDTOS.add(priceInfoClientDTO);
        }

        PriceImportDTO priceImportDTO = new PriceImportDTO();
        //组装头
        PriceImportDTO.Head head = new PriceImportDTO.Head();
        head.setFd_srmType(String.valueOf(OaProcessType.QUOTA_PRICE.getType()));
        //OA流程ID
        head.setProcessId(StringUtils.isNotEmpty(quotaManagementList.get(0).getProcessId()) ? quotaManagementList.get(0)
                .getProcessId() : "");
        head.setFd_caigouLeiXing("配额");
        //申请人工号
        UserDTO userDTO = userClient.getByUserId(quotaManagementList.get(0).getCreater());
        head.setFd_shenQingRenXingMing(ObjectUtil.isNotNull(userDTO)?userDTO.getAccountName():"");
        //SRM单号
        head.setFd_shenQingDanHao(quotaManagementList.get(0).getQuotaCode());
        //器件分类
        PurchaseCategoryClientDTO purchaseCategoryClientDTO = purchaseCategoryClient.getByCode(
                priceInfoClientDTOS.get(0).getPurchaseCategoryCode());
        head.setFd_qiJianFenLei(ObjectUtil.isNotNull(
                purchaseCategoryClientDTO) ? purchaseCategoryClientDTO.getFirstLevelPurchaseName() : "");
        //是否现货
        head.setFd_isXianHuo(priceInfoClientDTOS.get(0).getSpotFlag()!=null&&priceInfoClientDTOS.get(0).getSpotFlag() == 1 ? "是" : "否");
        //事业部是否同意
        head.setFd_shiYeBuShiFuTongYi(priceInfoClientDTOS.get(0).getBusinessAgreeFlag() == null ? "" :
                priceInfoClientDTOS.get(0).getBusinessAgreeFlag() == 1 ? "是" : "否");
        //客户是否承担
        head.setFd_keHuShiFuChengDan(priceInfoClientDTOS.get(0).getCustomerBearFlag() == null ? "" :
                priceInfoClientDTOS.get(0).getCustomerBearFlag() == 1 ? "是" : "否");
        //承担比例%
        head.setFd_chengDanBiLi(
                priceInfoClientDTOS.get(0).getBearRatio() == null ? "" : priceInfoClientDTOS.get(0).getBearRatio()
                        .toPlainString());
        List<OaFileParamDTO> list = new ArrayList<>();
        OaFileParamDTO build = OaFileParamDTO.builder().fileName("详情页面地址")
                .url(sysProp.getHostUrl() + "/pc/tender/quotaManage/quotaManagement/look?quotaCode=" + quotaCode)
                .build();
        list.add(build);
        //详情页面地址
        head.setFd_pageUrl(JSON.toJSONString(list));
        //备注
        head.setFd_beiZhu(StringUtils.isNotEmpty(priceInfoClientDTOS.get(0).getRemark()) ? priceInfoClientDTOS.get(0)
                .getRemark() : "");
        priceImportDTO.setHead(head);

        //组装明细
        List<TaxDTO> taxDTOS = taxClient.getAll();
        final Map<String, TaxDTO> taxCache = taxDTOS.stream().collect(Collectors.toMap(TaxDTO::getTaxCode, a -> a));

        PriceImportDTO.ItemHead itemHead = new PriceImportDTO.ItemHead();
        List<PriceImportDTO.ItemHead.Item> itemList = new ArrayList<>();
        priceInfoClientDTOS.forEach(priceInfoAuditDetail -> {

            PriceImportDTO.ItemHead.Item item = new PriceImportDTO.ItemHead.Item();
            //供应商代码
            item.setFd_gongYingShangDaiMa(priceInfoAuditDetail.getSupplierCode());
            //供应商名称
            item.setFd_gongYingShangMingChen(priceInfoAuditDetail.getSupplierName());
            //物料编码
            item.setFd_wuLiaoBianMa(priceInfoAuditDetail.getMaterialCode());
            //描述
            item.setFd_miaoShu(priceInfoAuditDetail.getMaterialName());
            //物料单位
            item.setFd_jgdw(priceInfoAuditDetail.getOrderUnit());
            //税码（SAP代码）
            item.setFd_shuiMa(priceInfoAuditDetail.getTaxCode());
            TaxDTO taxDTO = taxCache.get(priceInfoAuditDetail.getTaxCode());
            //税码值
            item.setFd_shuiMaZhi(taxDTO.getTaxValue().multiply(BigDecimal.valueOf(100)).toPlainString());
            //币种
            item.setFd_biZhong(priceInfoAuditDetail.getCurrencyCode());
            //含税价格(PCS)
            item.setFd_hsj(priceInfoAuditDetail.getTaxPrice().stripTrailingZeros());
            BigDecimal exchangeRate = priceInfoAuditDetail.getExchangeRate();
            if (exchangeRate == null) {
                throw new DaoException(StrUtil.format("未获取到币种：{}的汇率", priceInfoAuditDetail.getCurrencyCode()));
            }
            //换算后价格 未税*汇率
            item.setFd_huanSuanHouJiaGe(priceInfoAuditDetail.getNoTaxPrice().multiply(exchangeRate));
            final BigDecimal bigDecimal = priceInfoAuditDetail.getTaxPrice().stripTrailingZeros();
            List<Integer> scaleList = new ArrayList<>();
            scaleList.add(bigDecimal.scale());
            if (priceInfoAuditDetail.getStagePrice1()!=null){
                scaleList.add(priceInfoAuditDetail.getStagePrice1().stripTrailingZeros().scale());
            }
            if (priceInfoAuditDetail.getStagePrice2()!=null){
                scaleList.add(priceInfoAuditDetail.getStagePrice2().stripTrailingZeros().scale());
            }
            if (priceInfoAuditDetail.getStagePrice3()!=null){
                scaleList.add(priceInfoAuditDetail.getStagePrice3().stripTrailingZeros().scale());
            }
            if (priceInfoAuditDetail.getStagePrice4()!=null){
                scaleList.add(priceInfoAuditDetail.getStagePrice4().stripTrailingZeros().scale());
            }
            if (priceInfoAuditDetail.getStagePrice5()!=null){
                scaleList.add(priceInfoAuditDetail.getStagePrice5().stripTrailingZeros().scale());
            }
            //取最大的小数点
            int scale = scaleList.stream().mapToInt(Integer::intValue).max().orElse(1);
            String scaleStr = (scale > 2&&scale<=5)?"1000":scale>5?"10000":"1";
            //价格单位(转换SAP)
            item.setFd_danWei(scaleStr);
            //含税价格(转换SAP)
            item.setFd_jiaGe(bigDecimal.multiply(new BigDecimal(scaleStr)));
            //汇率
            item.setFd_huiLv(exchangeRate.toPlainString());
            //有效期起始日
            item.setFd_youXiaoQiQiShiRi(LocalDateTimeUtil.format(priceInfoAuditDetail.getEffectDate(), "yyyy-MM-dd"));
            //有效期结束日
            item.setFd_zhongZhiRiQi(LocalDateTimeUtil.format(priceInfoAuditDetail.getInvalidDate(), "yyyy-MM-dd"));
            //配额
            item.setFd_peiE(priceInfoAuditDetail.getQuota());
            //备注
            item.setFd_beiZhu(
                    StringUtils.isNotEmpty(priceInfoAuditDetail.getRemark()) ? priceInfoAuditDetail.getRemark() : "");
            //信息类别0标准2寄售3外协
            item.setFd_xinXiLeiBie(priceInfoAuditDetail.getPurchaseType());
            //关税(没有就填0)
            item.setFd_guanShui(
                    priceInfoAuditDetail.getTariff() == null ? BigDecimal.ZERO : priceInfoAuditDetail.getTariff());
            //采购组织代码
            item.setFd_suoShuZuZhi(StringUtils.isNotEmpty(
                    priceInfoAuditDetail.getPurchaseOrgCode()) ? priceInfoAuditDetail.getPurchaseOrgCode() : "");
            //工厂代码
            item.setFd_gongChangCode(priceInfoAuditDetail.getFactoryCode());
            //制造商型号
            item.setFd_zhiZaoXingHao(
                    StringUtils.isNotEmpty(priceInfoAuditDetail.getMpn()) ? priceInfoAuditDetail.getMpn() : "");
            //制造商中文
            item.setFd_zhiZaoShang(StringUtils.isNotEmpty(
                    priceInfoAuditDetail.getManufacturer()) ? priceInfoAuditDetail.getManufacturer() : "");
            //制造商英文
            item.setFd_zhiZaoYingWen(StringUtils.isNotEmpty(
                    priceInfoAuditDetail.getManufacturerEn()) ? priceInfoAuditDetail.getManufacturerEn() : "");
            //国系
            if (StringUtils.isNotEmpty(priceInfoAuditDetail.getCountryName())) {
                DictDTO dictDTO = dictClient.getDictByTypeAndCode(DictCode.COUNTRY_SERIES.getCode(),
                        priceInfoAuditDetail.getCountryName());
                item.setFd_guoXi(dictDTO.getName());
            } else {
                item.setFd_guoXi(StringUtils.isNotEmpty(
                        priceInfoAuditDetail.getCountryName()) ? priceInfoAuditDetail.getCountryName() : "");
            }
            //计划交货时间（L/T）
            item.setFd_jiaoHuoShiJian(priceInfoAuditDetail.getLeadTime() == null ? "" : String.valueOf(
                    priceInfoAuditDetail.getLeadTime()));
            //最新订单数量（MOQ）
            item.setFd_shuLiang(
                    priceInfoAuditDetail.getMoq() == null ? "" : String.valueOf(priceInfoAuditDetail.getMoq()));
            //最小包装量（MPQ）
            item.setFd_zuiXiaoBaoZhuangLiang(
                    priceInfoAuditDetail.getMpq() == null ? "" : String.valueOf(priceInfoAuditDetail.getMpq()));
            //阶梯数量1
            item.setFd_jieTiShuLiang1(
                    priceInfoAuditDetail.getStageNum1() == null ? "" : priceInfoAuditDetail.getStageNum1()
                            .toPlainString());
            //阶梯价格1
            item.setFd_jieTiJiaGe1(
                    priceInfoAuditDetail.getStagePrice1() == null ? "" : priceInfoAuditDetail.getStagePrice1()
                            .multiply(new BigDecimal(scaleStr)).stripTrailingZeros().toPlainString());
            //阶梯数量2
            item.setFd_jieTiShuLiang2(
                    priceInfoAuditDetail.getStageNum2() == null ? "" : priceInfoAuditDetail.getStageNum2()
                            .toPlainString());
            //阶梯价格2
            item.setFd_jieTiJiaGe2(
                    priceInfoAuditDetail.getStagePrice2() == null ? "" : priceInfoAuditDetail.getStagePrice2()
                            .multiply(new BigDecimal(scaleStr)).stripTrailingZeros().toPlainString());
            //阶梯数量3
            item.setFd_jieTiShuLiang3(
                    priceInfoAuditDetail.getStageNum3() == null ? "" : priceInfoAuditDetail.getStageNum3()
                            .toPlainString());
            //阶梯价格3
            item.setFd_jieTiJiaGe3(
                    priceInfoAuditDetail.getStagePrice3() == null ? "" : priceInfoAuditDetail.getStagePrice3()
                            .multiply(new BigDecimal(scaleStr)).stripTrailingZeros().toPlainString());
            //阶梯数量4
            item.setFd_jieTiShuLiang4(
                    priceInfoAuditDetail.getStageNum4() == null ? "" : priceInfoAuditDetail.getStageNum4()
                            .toPlainString());
            //阶梯价格4
            item.setFd_jieTiJiaGe4(
                    priceInfoAuditDetail.getStagePrice4() == null ? "" : priceInfoAuditDetail.getStagePrice4()
                            .multiply(new BigDecimal(scaleStr)).stripTrailingZeros().toPlainString());
            //阶梯数量5
            item.setFd_jieTiShuLiang5(
                    priceInfoAuditDetail.getStageNum5() == null ? "" : priceInfoAuditDetail.getStageNum5()
                            .toPlainString());
            //阶梯价格5
            item.setFd_jieTiJiaGe5(
                    priceInfoAuditDetail.getStagePrice5() == null ? "" : priceInfoAuditDetail.getStagePrice5()
                            .multiply(new BigDecimal(scaleStr)).stripTrailingZeros().toPlainString());
            //状态
            item.setFd_zhuangTai("导入");

//            if (null!=priceInfoAuditDetail.getPriceId()){
//                //是否新料
//                item.setFd_shiFuXinLiao("否");
//                //上次价格币种
//                item.setFd_shangCiJiaGeBiZhong(priceInfoDTO.getCurrencyCode());
//                //上次汇率
//                item.setFd_shangCiHuiLv(priceInfoDTO.getExchangeRate().toPlainString());
//                //上次税码
//                item.setFd_shangCiShuiMa(priceInfoDTO.getTaxCode());
//                //上次价格原价
//                item.setFd_shangCiJiaGeYuanJia(priceInfoDTO.getTaxPrice().toPlainString());
//                //上次未税价格
//                item.setFd_shangCiWeiShuiJiaGe(priceInfoDTO.getNoTaxPrice().toPlainString());
//                //差价（RMB） $明细表1.是否新料$ * ($明细表1.换算后价格$ - $明细表1.上次未税价格$ )
//                final BigDecimal chajia = item.getFd_huanSuanHouJiaGe().subtract(priceInfoDTO.getNoTaxPrice());
//                item.setFd_chaJia(chajia.toPlainString());
//                //涨幅 $明细表1.是否新料$ * 100 * $明细表1.差价（RMB）$ / $明细表1.上次未税价格$
//                item.setFd_zhangFu(chajia.divide(priceInfoDTO.getNoTaxPrice(), 2, RoundingMode.HALF_UP)
//                .toPlainString());
//            }else {
            //是否新料
            item.setFd_shiFuXinLiao("是");
            //上次价格币种
            item.setFd_shangCiJiaGeBiZhong("");
            //上次汇率
            item.setFd_shangCiHuiLv("");
            //上次税码
            item.setFd_shangCiShuiMa("");
            //上次价格原价
            item.setFd_shangCiJiaGeYuanJia("");
            //上次未税价格
            item.setFd_shangCiWeiShuiJiaGe("");
            //差价（RMB）
            item.setFd_chaJia("");
            //涨幅
            item.setFd_zhangFu("");
//            }
            //潮湿等级
            item.setFd_chaoShiDengJi(
                    StringUtils.isNotEmpty(priceInfoAuditDetail.getMsl()) ? priceInfoAuditDetail.getMsl() : "");
            //取消窗
            item.setFd_quXiaoChuang(StringUtils.isNotEmpty(
                    priceInfoAuditDetail.getCancelWindow()) ? priceInfoAuditDetail.getCancelWindow() : "");
            //推迟窗
            item.setFd_tuiChiChuang(StringUtils.isNotEmpty(
                    priceInfoAuditDetail.getDelayWindow()) ? priceInfoAuditDetail.getDelayWindow() : "");
            //ECCN码
            item.setFd_eCCNMa(
                    StringUtils.isNotEmpty(priceInfoAuditDetail.getEccn()) ? priceInfoAuditDetail.getEccn() : "");
            //风险等级
            item.setFd_fengXianDengJi(StringUtils.isNotEmpty(
                    priceInfoAuditDetail.getRiskLevel()) ? priceInfoAuditDetail.getRiskLevel() : "");
            //物流代理费
            item.setFd_daiLiFei("CNY".equals(priceInfoAuditDetail.getCurrencyCode())?BigDecimal.ZERO:priceInfoAuditDetail.getLogisticsAgencyFee() == null ? new BigDecimal(
                    "0.300") : priceInfoAuditDetail.getLogisticsAgencyFee());
            itemList.add(item);
        });
        itemHead.setItem(itemList);
        priceImportDTO.setItem(itemHead);

        final ApiResult<String> orUpdate = quotaOaClient.priceImport(priceImportDTO);
        final String code = orUpdate.getCode();
        final String oaId = orUpdate.getData();
        final String message = orUpdate.getMessage();
//        priceInfoAudit.setProcessResult(message);
//        priceInfoAudit.setProcessTime(LocalDateTime.now());
        if (code.equals(RestCode.SAP_SUCCESS.getCode())) {
            quotaManagementList.forEach(quotaManagement -> {
                quotaManagement.setSyncStatus(1);
                quotaManagement.setProcessId(oaId);
                quotaManagementService.updateById(quotaManagement);
            });

        } else {
            throw new DaoException("OA接口报错：" + orUpdate.getMessage());
        }
    }

    @Override
    public List<QuotaManagement> getByMaterialCodeAndFactoryCode(String materialCode, String factoryCode) {
        List<QuotaManagement> quotaManagements = quotaManagementService.list(
                Wrappers.lambdaQuery(QuotaManagement.class).eq(QuotaManagement::getMaterialCode, materialCode)
                        .eq(QuotaManagement::getFactoryCode, factoryCode));
        return quotaManagements;
    }

    @Override
    public QuotaManagement getByMaterialCodeAndFactoryCodeMaxQuote(String materialCode, String factoryCode) {
        QuotaManagement quotaManagement = quotaManagementService.getOne(
                Wrappers.lambdaQuery(QuotaManagement.class).eq(QuotaManagement::getMaterialCode, materialCode)
                        .eq(QuotaManagement::getFactoryCode, factoryCode).orderByDesc(QuotaManagement::getAdjustmentQuota).last(" limit 1"));
        return quotaManagement;
    }

    @Override
    public QuotaManagement getQuota(String materialCode, String factoryCode, String supplierCode) {
        QuotaManagement quotaManagement = quotaManagementService.getOne(
                Wrappers.lambdaQuery(QuotaManagement.class).eq(QuotaManagement::getMaterialCode, materialCode)
                        .eq(QuotaManagement::getFactoryCode, factoryCode)
                        .eq(QuotaManagement::getSupplierCode, supplierCode).last(" limit 1"));
        return quotaManagement;
    }

    @Override
    public void deleteByMaterialCode(String materialCode) {
        quotaManagementService.remove(
                Wrappers.lambdaQuery(QuotaManagement.class).eq(QuotaManagement::getMaterialCode, materialCode));
    }

    @Override
    public void saveQuota(List<QuotaManagement> quotaManagements) {
        quotaManagementService.saveBatch(quotaManagements);
    }

    @Override
    public void deleteByMaterialCodeAndFactoryCode(String materialCode, String factoryCode) {
        quotaManagementService.remove(
                Wrappers.lambdaQuery(QuotaManagement.class).eq(QuotaManagement::getMaterialCode, materialCode).eq(QuotaManagement::getFactoryCode, factoryCode));
    }

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