package com.jwipc.inquiry.logic.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jwipc.aggregation.ModelAggregationService;
import com.jwipc.api.constant.RestCode;
import com.jwipc.api.dto.ApiResult;
import com.jwipc.api.dto.OaFileParamDTO;
import com.jwipc.constant.DictCode;
import com.jwipc.constant.OaProcessType;
import com.jwipc.exception.DaoException;
import com.jwipc.inquiry.constant.AuditStatus;
import com.jwipc.inquiry.constant.FixOaClient;
import com.jwipc.inquiry.constant.InquiryStatus;
import com.jwipc.inquiry.constant.SequenceConst;
import com.jwipc.inquiry.convert.PriceInfoAuditConvert;
import com.jwipc.inquiry.convert.PriceInfoAuditDetailConvert;
import com.jwipc.inquiry.dto.*;
import com.jwipc.inquiry.entity.*;
import com.jwipc.inquiry.logic.PriceInfoAuditLogic;
import com.jwipc.inquiry.logic.PriceInfoLogic;
import com.jwipc.inquiry.model.po.PriceInfoAuditPO;
import com.jwipc.inquiry.model.query.PriceInfoAuditQuery;
import com.jwipc.inquiry.service.IPriceInfoAuditDetailService;
import com.jwipc.inquiry.service.IPriceInfoAuditService;
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.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.PurchaseCategoryClientDTO;
import com.jwipc.sys.client.dto.TaxDTO;
import com.jwipc.sys.client.dto.UserDTO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author shenyang.ou
 * @date 2024/3/8 11:24
 * @desc
 */
@Service
@RequiredArgsConstructor
public class PriceInfoAuditLogicImpl implements PriceInfoAuditLogic {
    private final PriceInfoAuditConvert priceInfoAuditConvert;
    private final PriceInfoAuditDetailConvert priceInfoAuditDetailConvert;
    private final IPriceInfoAuditService priceInfoAuditService;
    private final UserClient userClient;
    private final TaxClient taxClient;
    private final ExchangeRateClient exchangeRateClient;
    private final PriceInfoLogic priceInfoLogic;
    private final QuotaManagementClient quotaManagementClient;
    private final FixOaClient fixOaClient;
    private final DictClient dictClient;
    private final SupplierClient supplierClient;
    private final IPriceInfoAuditDetailService priceInfoAuditDetailService;
    private final ModelAggregationService modelAggregationService;
    private final SequenceClient sequenceClient;
    private final PurchaseCategoryClient purchaseCategoryClient;
    private final SysProp sysProp;
    @Override
    public PageView findByPage(PriceInfoAuditQuery query) {
        final Page<PriceInfoAudit> dbPage = PageUtil.toPage(query);
        List<PriceInfoAuditPO> priceInfoAuditPOS = priceInfoAuditService.findPageByQuery(dbPage, query);
        List<PriceInfoAuditDTO> priceInfoAuditDTOS = priceInfoAuditConvert.po2DTOList(priceInfoAuditPOS);
        modelAggregationService.processRelationAggregation(priceInfoAuditDTOS);
        return PageUtil.getPV(priceInfoAuditDTOS, dbPage.getTotal());
    }

    @Override
    public PriceInfoAuditDTO getById(Long id) {
        PriceInfoAudit priceInfoAudit = priceInfoAuditService.getById(id);
        return priceInfoAuditConvert.entity2DTO(priceInfoAudit);
    }

    @Override
    @Transactional
    public void saveOrUpdate(PriceInfoAuditParamDTO param) {
        if (param.getId() == null) {
            param.setAuditCode(sequenceClient.createSequenceNo(SequenceConst.PRICE_INFO_CODE.getCode()));
            param.setStatus(AuditStatus.ADD.getStatus());
            param.setCreateTime(LocalDateTime.now());
            param.setCreateUser(LoginUtil.getUserId());
        } else {
            param.setUpdateTime(LocalDateTime.now());
            param.setUpdateUser(LoginUtil.getUserId());
            //删除明细
            priceInfoAuditDetailService.remove(Wrappers.lambdaQuery(PriceInfoAuditDetail.class).eq(PriceInfoAuditDetail::getAuditId,param.getId()));
        }
        //保存主数据
        PriceInfoAudit priceInfoAudit = priceInfoAuditConvert.DTO2Entity(param);
        priceInfoAuditService.saveOrUpdate(priceInfoAudit);
        //价格延用，要判断供应商类型，如果是自购类型供应商，价格有效期，只能是半年， 其他类型供应商，是1年。
        //把供应商为自购原材料厂商取出来，并取出有效期的月份，一般为6个月，如果没有的默认为12个月，一年。 邓京术 2025-04-16
        List<DictDTO> dictDTOS = dictClient.getDicByType("supplier_material_quote_expiredate");
        DictDTO dictDTO = dictDTOS.get(0);
        SupplierDTO supplierDTO = supplierClient.getSupplierByCode(priceInfoAudit.getSupplierCode());
        Integer plusMonths;
        if (Objects.nonNull(supplierDTO) && StringUtils.isNotEmpty(supplierDTO.getAttr()) && dictDTO.getName().equals(supplierDTO.getAttr())) {
            //如果字典的类型配置与供应商类型相等，则取出有效期月份
            plusMonths = Integer.parseInt(dictDTO.getCode());
        } else {
            plusMonths = 12;
        }
        final List<PriceInfoAuditDetailDTO> priceInfoAuditDetailDTOS = param.getDetailList();
        AtomicInteger index = new AtomicInteger(1);
        priceInfoAuditDetailDTOS.forEach(priceInfoAuditDetailDTO -> {
            priceInfoAuditDetailDTO.setId(null);
            priceInfoAuditDetailDTO.setAuditCode(priceInfoAudit.getAuditCode());
            priceInfoAuditDetailDTO.setAuditId(priceInfoAudit.getId());
            priceInfoAuditDetailDTO.setItemNo(String.valueOf(index));
            priceInfoAuditDetailDTO.setCompanyCode(priceInfoAudit.getCompanyCode());

            LocalDate effectDate = priceInfoAuditDetailDTO.getEffectDate().toLocalDate();
            LocalDate invalidDate = priceInfoAuditDetailDTO.getInvalidDate().toLocalDate();
            LocalDate plusOneMonthDate = effectDate.plusMonths(plusMonths);
            LocalTime noon = LocalTime.NOON;
            //判断失效期是否比原来的失效期早，否则不让设置
            if (plusOneMonthDate.isBefore(invalidDate)) {
                priceInfoAuditDetailDTO.setInvalidDate(LocalDateTime.of(plusOneMonthDate, noon));
            }
            index.getAndIncrement();
        });
        priceInfoAuditDetailService.saveBatch(priceInfoAuditDetailConvert.dto2EntityList(priceInfoAuditDetailDTOS));
    }

    @Override
    public void remove(Long id) {
        priceInfoAuditService.removeById(id);
        //删除明细
        priceInfoAuditDetailService.remove(Wrappers.lambdaQuery(PriceInfoAuditDetail.class).eq(PriceInfoAuditDetail::getAuditId,id));
    }

    @Override
    public void pushOa(Long id) {
        PriceInfoAudit priceInfoAudit = priceInfoAuditService.getById(id);
        PriceImportDTO priceImportDTO = new PriceImportDTO();
        //组装头
        PriceImportDTO.Head head = new PriceImportDTO.Head();
        head.setFd_srmType(String.valueOf(OaProcessType.AUDIT_PRICE.getType()));
        //OA流程ID
        head.setProcessId(StringUtils.isNotEmpty(priceInfoAudit.getProcessId())?priceInfoAudit.getProcessId():"");
        head.setFd_caigouLeiXing("调价");
        //申请人工号
        UserDTO userDTO = userClient.getByUserId(priceInfoAudit.getCreateUser());
        head.setFd_shenQingRenXingMing(ObjectUtil.isNotNull(userDTO)?userDTO.getAccountName():"");
        //SRM单号
        head.setFd_shenQingDanHao(priceInfoAudit.getAuditCode());
        //器件分类
        PurchaseCategoryClientDTO purchaseCategoryClientDTO = purchaseCategoryClient.getByCode(priceInfoAudit.getPurchaseCategoryCode());
        head.setFd_qiJianFenLei(ObjectUtil.isNotNull(purchaseCategoryClientDTO)?purchaseCategoryClientDTO.getFirstLevelPurchaseName():"");
        //是否现货
        head.setFd_isXianHuo(priceInfoAudit.getSpotFlag()==1?"是":"否");
        //事业部是否同意
        head.setFd_shiYeBuShiFuTongYi(priceInfoAudit.getBusinessAgreeFlag()==null?"":priceInfoAudit.getBusinessAgreeFlag()==1?"是":"否");
        //客户是否承担
        head.setFd_keHuShiFuChengDan(priceInfoAudit.getCustomerBearFlag()==null?"":priceInfoAudit.getCustomerBearFlag()==1?"是":"否");
        //承担比例%
        head.setFd_chengDanBiLi(priceInfoAudit.getBearRatio()==null?"":priceInfoAudit.getBearRatio().toPlainString());
        List<OaFileParamDTO> list = new ArrayList<>();
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, "0CoJUm6Qyw8W8jud".getBytes(), "0102030405060708".getBytes());
        String encryptHex = aes.encryptHex(String.valueOf(id));
        OaFileParamDTO build = OaFileParamDTO.builder().fileName("详情页面地址").url(sysProp.getHostUrl()+"/pc/inquiry/price/audit/look?id="+encryptHex).build();
        list.add(build);
        //详情页面地址
        head.setFd_pageUrl(JSON.toJSONString(list));
        //备注
        head.setFd_beiZhu(StringUtils.isNotEmpty(priceInfoAudit.getRemark())?priceInfoAudit.getRemark():"");
        priceImportDTO.setHead(head);

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

        List<PriceInfoAuditDetail> priceInfoAuditDetails = priceInfoAuditDetailService.list(Wrappers.lambdaQuery(PriceInfoAuditDetail.class).eq(PriceInfoAuditDetail::getAuditId,id));

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

            PriceImportDTO.ItemHead.Item item = new PriceImportDTO.ItemHead.Item();
            //供应商代码
            item.setFd_gongYingShangDaiMa(priceInfoAudit.getSupplierCode());
            //供应商名称
            item.setFd_gongYingShangMingChen(priceInfoAudit.getSupplierName());
            //物料编码
            item.setFd_wuLiaoBianMa(priceInfoAuditDetail.getMaterialCode());
            //描述
            item.setFd_miaoShu(priceInfoAuditDetail.getMaterialName());
            //物料单位
            item.setFd_jgdw(priceInfoAuditDetail.getPurchaseUnit());
            //税码（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 = exchangeRateClient.getExchangeRate(priceInfoAuditDetail.getCurrencyCode(),"CNY");
            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)));
            PriceInfoDTO priceInfoDTO = priceInfoLogic.getById(priceInfoAuditDetail.getPriceId());
            //汇率
            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(ObjectUtil.isNotNull(priceInfoDTO)?priceInfoDTO.getQuota():new BigDecimal(100));
            //备注
            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(priceInfoAudit.getPurchaseOrgCode())?priceInfoAudit.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():"");
            }
            if (ObjectUtil.isNotNull(priceInfoDTO)){
                //计划交货时间（L/T）
                item.setFd_jiaoHuoShiJian(priceInfoDTO.getLeadTime()==null?"":String.valueOf(priceInfoDTO.getLeadTime()));
                //最新订单数量（MOQ）
                item.setFd_shuLiang(priceInfoDTO.getMoq()==null?"":String.valueOf(priceInfoDTO.getMoq()));
                //最小包装量（MPQ）
                item.setFd_zuiXiaoBaoZhuangLiang(priceInfoDTO.getMpq()==null?"":String.valueOf(priceInfoDTO.getMpq()));
            }else {
                //计划交货时间（L/T）
                item.setFd_jiaoHuoShiJian("");
                //最新订单数量（MOQ）
                item.setFd_shuLiang("");
                //最小包装量（MPQ）
                item.setFd_zuiXiaoBaoZhuangLiang("");
            }

            //阶梯数量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());
                //上次未税价格
                BigDecimal huansuanhou = priceInfoDTO.getNoTaxPrice().multiply(priceInfoDTO.getExchangeRate());
                item.setFd_shangCiWeiShuiJiaGe(huansuanhou.toPlainString());
                //差价（RMB） $明细表1.是否新料$ * ($明细表1.换算后价格$ - $明细表1.上次未税价格$ )
                final BigDecimal chajia = item.getFd_huanSuanHouJiaGe().subtract(huansuanhou);
                item.setFd_chaJia(chajia.toPlainString());
                //涨幅 $明细表1.是否新料$ * 100 * $明细表1.差价（RMB）$ / $明细表1.上次未税价格$
                item.setFd_zhangFu(chajia.divide(huansuanhou, 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString());
            }else {
                //是否新料
                item.setFd_shiFuXinLiao("是");
                //上次价格币种
                item.setFd_shangCiJiaGeBiZhong("");
                //上次汇率
                item.setFd_shangCiHuiLv("");
                //上次税码
                item.setFd_shangCiShuiMa("");
                //上次价格原价
                item.setFd_shangCiJiaGeYuanJia("");
                //上次未税价格
                item.setFd_shangCiWeiShuiJiaGe("");
                //差价（RMB）
                item.setFd_chaJia("");
                //涨幅
                item.setFd_zhangFu("");
            }
            //潮湿等级
            item.setFd_chaoShiDengJi(StringUtils.isNotEmpty(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 = fixOaClient.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())) {
            priceInfoAudit.setStatus(AuditStatus.APPROVAL.getStatus());
            priceInfoAudit.setProcessId(oaId);
            priceInfoAuditService.updateById(priceInfoAudit);
        }else {
            throw new DaoException("OA接口报错："+orUpdate.getMessage());
        }
    }

    @Override
    @Transactional
    public void pass(Long id) {
        PriceInfoAudit priceInfoAudit = new PriceInfoAudit();
        priceInfoAudit.setId(id);
        priceInfoAudit.setStatus(AuditStatus.PASS.getStatus());
        priceInfoAudit.setUpdateTime(LocalDateTime.now());
        priceInfoAudit.setUpdateUser(LoginUtil.getUserId());
        priceInfoAuditService.updateById(priceInfoAudit);
        //生成价格信息记录
        //根据询价id组装价格信息记录数据
        List<CreatePriceInfoDTO> createPriceInfoDTOS = priceInfoLogic.getByAuditId(id);

        createPriceInfoDTOS.forEach(createPriceInfoDTO -> {
            //获取最新配额
            BigDecimal quota = quotaManagementClient.getQuota(createPriceInfoDTO.getMaterialCode(),createPriceInfoDTO.getFactoryCode(), createPriceInfoDTO.getSupplierCode());
            if(ObjectUtil.isNotNull(quota)){
                createPriceInfoDTO.setQuota(quota);
            }
            createPriceInfoDTO.setId(null);
            createPriceInfoDTO.setCreateUser(LoginUtil.getUserId());
            //获取税率
            BigDecimal exchangeRate = exchangeRateClient.getExchangeRate(createPriceInfoDTO.getCurrencyCode(),"CNY");
            if (exchangeRate==null){
                throw new DaoException(StrUtil.format("未获取到币种：{}的汇率",createPriceInfoDTO.getCurrencyCode()));
            }
            createPriceInfoDTO.setExchangeRate(exchangeRate);
        });
       priceInfoLogic.createPriceInfo(createPriceInfoDTOS);
    }
}
