package com.jwipc.inquiry.logic.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jwipc.contract.base.ContractDetailClientDTO;
import com.jwipc.contract.client.ContractDetailClient;
import com.jwipc.inquiry.service.IInquiryMaterialService;
import com.jwipc.shopping.base.ShoppingCartInfoDTO;
import com.jwipc.shopping.client.ShoppingCartInfoClient;
import com.jwipc.inquiry.convert.InquiryMaterialConvert;
import com.jwipc.inquiry.convert.PurchaseApplyBillDetailConvert;
import com.jwipc.inquiry.dto.*;
import com.jwipc.inquiry.entity.Inquiry;
import com.jwipc.inquiry.entity.PurchaseApplyBill;
import com.jwipc.inquiry.entity.PurchaseApplyBillDetail;
import com.jwipc.inquiry.logic.PriceInfoLogic;
import com.jwipc.inquiry.logic.PurchaseApplyBillDetailLogic;
import com.jwipc.inquiry.model.po.InquiryMaterialPO;
import com.jwipc.inquiry.model.po.PurchaseApplyBillDetailPO;
import com.jwipc.inquiry.model.query.PurchaseApplyBillDetailQuery;
import com.jwipc.inquiry.service.IPurchaseApplyBillDetailService;
import com.jwipc.inquiry.service.IPurchaseApplyBillService;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.sys.client.DictClient;
import com.jwipc.sys.client.SysConfigClient;
import com.jwipc.sys.client.dto.DictDTO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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.stream.Collectors;

import static com.baomidou.dynamic.datasource.support.DdConstants.SLAVE;
import static com.jwipc.constant.SysConfigKey.TENDER_AGREEMENT;

/**
 * @author shenyang.ou
 * @date 2024/2/29 13:25
 * @desc
 */
@Service
@RequiredArgsConstructor
public class PurchaseApplyBillDetailLogicImpl implements PurchaseApplyBillDetailLogic {
    private final IPurchaseApplyBillDetailService purchaseApplyBillDetailService;
    private final IPurchaseApplyBillService purchaseApplyBillService;
    private final PurchaseApplyBillDetailConvert purchaseApplyBillDetailConvert;
    private final InquiryMaterialConvert inquiryMaterialConvert;
    private final IInquiryMaterialService iInquiryMaterialService;
    private final PriceInfoLogic priceInfoLogic;
    private final SysConfigClient sysConfigClient;
    @Lazy
    @Autowired
    private ContractDetailClient contractDetailClient;

    @Lazy
    @Autowired
    private ShoppingCartInfoClient shoppingCartInfoClient;

    @Autowired
    DictClient dictClient;

    @Override
    public PageView findByPage(PurchaseApplyBillDetailQuery query) {
//        if (ObjectUtil.isNotNull(query.getSearchFlag()) && query.getSearchFlag() == 1) {
            if (ObjectUtil.isNotNull(query.getPurchaseMethod()) && query.getPurchaseMethod() == "") {
                query.setPurchaseMethod(null);
            }
//        }

//        if (ObjectUtil.isNotNull(query.getPurchaseMethod()) && query.getPurchaseMethod().equals("Z005")) {
//            query.setPurchaseMethod("");
//        }
        final Page<Inquiry> dbPage = PageUtil.toPage(query);
        List<PurchaseApplyBillDetailPO> purchaseApplyBillDetailPOS = new ArrayList<>();
        //shangCFlag判断是否是商城页面使用
        if(Objects.nonNull(query.getShangCFlag())  && query.getShangCFlag() == 1){
             purchaseApplyBillDetailPOS = purchaseApplyBillDetailService.findPageByQuerySC(
                    dbPage, query);
        }else{
             purchaseApplyBillDetailPOS = purchaseApplyBillDetailService.findPageByQuery(
                    dbPage, query);
        }
        List<PurchaseApplyBillDetailDTO> purchaseApplyBillDetailDTOS = purchaseApplyBillDetailConvert.po2DTOList(
                purchaseApplyBillDetailPOS);
        purchaseApplyBillDetailDTOS.forEach(purchaseApplyBillDetailDTO -> {
            List<ContractDetailClientDTO> contractDetailClientDTOS = contractDetailClient.getDetailListByPurchaseCodeAndeItem(purchaseApplyBillDetailDTO.getBillCode(),purchaseApplyBillDetailDTO.getItemCode());
            if (CollectionUtil.isNotEmpty(contractDetailClientDTOS)) {
                BigDecimal totalAmount = BigDecimal.ZERO;
                //合同编码集合
                List<String> codeList = new ArrayList<>();
                for (ContractDetailClientDTO contractDetailClientDTO : contractDetailClientDTOS){
                    if (contractDetailClientDTO.getPrice()!=null&&contractDetailClientDTO.getNum()!=null){
                        totalAmount = totalAmount.add(contractDetailClientDTO.getPrice().multiply(contractDetailClientDTO.getNum()));
                        codeList.add(contractDetailClientDTO.getContractCode());
                    }
                }
                purchaseApplyBillDetailDTO.setRealityTotalAmount(totalAmount);
                //合同编码集合逗号隔开
                if(CollectionUtil.isNotEmpty(codeList)){
                    //已转合同
                    purchaseApplyBillDetailDTO.setTransferStatus(4);
                    purchaseApplyBillDetailDTO.setContractNo(StringUtils.join(codeList, ","));
                }

                if (purchaseApplyBillDetailDTO.getTotalAmount()!=null){
                    //（实际购买金额-预估总金额）/实际购买行金额
                    BigDecimal chajia = totalAmount.subtract(purchaseApplyBillDetailDTO.getTotalAmount());
                    purchaseApplyBillDetailDTO.setIncreasePrice(chajia.divide(purchaseApplyBillDetailDTO.getTotalAmount(), 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString());
                    purchaseApplyBillDetailDTO.setIncreasePrice(purchaseApplyBillDetailDTO.getIncreasePrice() + "%");
                }
            }
        });

        purchaseApplyBillDetailDTOS.forEach(purchaseApplyBillDetailDTO -> {
            List<DictDTO> subs = dictClient.getDicByType("stock_point");
            Map<String, String> subMap = subs.stream().collect(Collectors.toMap(DictDTO::getCode,DictDTO::getName,(key1, key2)->key2));
            purchaseApplyBillDetailDTO.setStockName(subMap.get(purchaseApplyBillDetailDTO.getStockCode()));
            //实际采购金额，需要把商城采购金额（累计行单价*商品数量），累加进来，商城订单号串入“合同号”，用“,"隔开
            //购物订单页面->查看明细  :　累计所有的采购申请单号　：单价　＊　商品数量，　把所有的关联　订单号拼起来　　2025-03-06 邓京术
            List<ShoppingCartInfoDTO>  shoppingCartInfoDTOList = shoppingCartInfoClient.getShoppingCartInfoListPO(purchaseApplyBillDetailDTO.getBillCode(),purchaseApplyBillDetailDTO.getItemCode());
            if (CollectionUtil.isNotEmpty(shoppingCartInfoDTOList)) {
                BigDecimal totalAmount = BigDecimal.ZERO;
                //合同编码集合
                List<String> codeList = new ArrayList<>();
                for (ShoppingCartInfoDTO shoppingCartInfoDTO : shoppingCartInfoDTOList) {
                    if (shoppingCartInfoDTO.getUnitCost()!=null && shoppingCartInfoDTO.getQty()!=null) {
                        totalAmount = totalAmount.add(shoppingCartInfoDTO.getUnitCost().multiply(shoppingCartInfoDTO.getQty()));
                        if (totalAmount.floatValue() > 0) {
                            codeList.add(shoppingCartInfoDTO.getOrderId());
                        }
                    }
                }
                purchaseApplyBillDetailDTO.setRealityTotalAmount((purchaseApplyBillDetailDTO.getRealityTotalAmount() == null?BigDecimal.ZERO:purchaseApplyBillDetailDTO.getRealityTotalAmount()).add(totalAmount));
                //合同编码集合逗号隔开
                if (codeList.size() > 0) {
                    purchaseApplyBillDetailDTO.setContractNo((StringUtils.isNotEmpty(purchaseApplyBillDetailDTO.getContractNo()) ? (purchaseApplyBillDetailDTO.getContractNo() + ",") : "" ) + StringUtils.join(codeList, ","));
                }
                if (purchaseApplyBillDetailDTO.getTotalAmount() != null) {
                    //（实际购买金额-预估总金额）/实际购买行金额
                    BigDecimal chajia = purchaseApplyBillDetailDTO.getRealityTotalAmount().subtract(purchaseApplyBillDetailDTO.getTotalAmount());
                    purchaseApplyBillDetailDTO.setIncreasePrice(chajia.divide(purchaseApplyBillDetailDTO.getTotalAmount(), 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString());
                    purchaseApplyBillDetailDTO.setIncreasePrice(purchaseApplyBillDetailDTO.getIncreasePrice() + "%");
                }
            }
        });
        return PageUtil.getPV(purchaseApplyBillDetailDTOS, dbPage.getTotal());
    }

    @Override
    public List<PurchaseApplyBillDetailDTO> listAll(PurchaseApplyBillDetailQuery query) {
        List<PurchaseApplyBillDetailPO> purchaseApplyBillDetailPOS = purchaseApplyBillDetailService.findPageByQuery(
                null, query);
        List<PurchaseApplyBillDetailDTO> purchaseApplyBillDetailDTOS = purchaseApplyBillDetailConvert.po2DTOList(purchaseApplyBillDetailPOS);
        purchaseApplyBillDetailDTOS.forEach(purchaseApplyBillDetailDTO -> {
            List<ContractDetailClientDTO> contractDetailClientDTOS = contractDetailClient.getDetailListByPurchaseCodeAndeItem(purchaseApplyBillDetailDTO.getBillCode(),purchaseApplyBillDetailDTO.getItemCode());
            if (CollectionUtil.isNotEmpty(contractDetailClientDTOS)){
                BigDecimal totalAmount = BigDecimal.ZERO;
                //合同编码集合
                List<String> codeList = new ArrayList<>();
                for (ContractDetailClientDTO contractDetailClientDTO : contractDetailClientDTOS){
                    if (contractDetailClientDTO.getPrice()!=null&&contractDetailClientDTO.getNum()!=null){
                        totalAmount = totalAmount.add(contractDetailClientDTO.getPrice().multiply(contractDetailClientDTO.getNum()));
                        codeList.add(contractDetailClientDTO.getContractCode());
                    }
                }
                purchaseApplyBillDetailDTO.setRealityTotalAmount(totalAmount);
                //合同编码集合逗号隔开
                purchaseApplyBillDetailDTO.setContractNo(StringUtils.join(codeList, ","));
                if (purchaseApplyBillDetailDTO.getTotalAmount()!=null){
                    //（实际购买金额-预估总金额）/实际购买行金额
                    BigDecimal chajia = totalAmount.subtract(purchaseApplyBillDetailDTO.getTotalAmount());
                    purchaseApplyBillDetailDTO.setIncreasePrice(chajia.divide(purchaseApplyBillDetailDTO.getTotalAmount(), 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString());
                    purchaseApplyBillDetailDTO.setIncreasePrice(purchaseApplyBillDetailDTO.getIncreasePrice() + "%");
                }
            }
        });

        purchaseApplyBillDetailDTOS.forEach(purchaseApplyBillDetailDTO -> {
            //实际采购金额，需要把商城采购金额（累计行单价*商品数量），累加进来，商城订单号串入“合同号”，用“,"隔开
            //购物订单页面->查看明细  :　累计所有的采购申请单号　：单价　＊　商品数量，　把所有的关联　订单号拼起来　　2025-03-06 邓京术
            List<ShoppingCartInfoDTO>  shoppingCartInfoDTOList = shoppingCartInfoClient.getShoppingCartInfoListPO(purchaseApplyBillDetailDTO.getBillCode(),purchaseApplyBillDetailDTO.getItemCode());
            if (CollectionUtil.isNotEmpty(shoppingCartInfoDTOList)) {
                BigDecimal totalAmount = BigDecimal.ZERO;
                //合同编码集合
                List<String> codeList = new ArrayList<>();
                for (ShoppingCartInfoDTO shoppingCartInfoDTO : shoppingCartInfoDTOList) {
                    if (shoppingCartInfoDTO.getUnitCost()!=null && shoppingCartInfoDTO.getQty()!=null) {
                        totalAmount = totalAmount.add(shoppingCartInfoDTO.getUnitCost().multiply(shoppingCartInfoDTO.getQty()));
                        if (totalAmount.floatValue() > 0) {
                            codeList.add(shoppingCartInfoDTO.getOrderId());
                        }
                    }
                }
                purchaseApplyBillDetailDTO.setRealityTotalAmount((purchaseApplyBillDetailDTO.getRealityTotalAmount() == null?BigDecimal.ZERO:purchaseApplyBillDetailDTO.getRealityTotalAmount()).add(totalAmount));
                //合同编码集合逗号隔开
                if (codeList.size() > 0) {
                    purchaseApplyBillDetailDTO.setContractNo((StringUtils.isNotEmpty(purchaseApplyBillDetailDTO.getContractNo()) ? (purchaseApplyBillDetailDTO.getContractNo() + ",") : "" ) + StringUtils.join(codeList, ","));
                }
                if (purchaseApplyBillDetailDTO.getTotalAmount() != null) {
                    //（实际购买金额-预估总金额）/实际购买行金额
                    BigDecimal chajia = purchaseApplyBillDetailDTO.getRealityTotalAmount().subtract(purchaseApplyBillDetailDTO.getTotalAmount());
                    purchaseApplyBillDetailDTO.setIncreasePrice(chajia.divide(purchaseApplyBillDetailDTO.getTotalAmount(), 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString());
                    purchaseApplyBillDetailDTO.setIncreasePrice(purchaseApplyBillDetailDTO.getIncreasePrice() + "%");
                }
            }
        });
        return purchaseApplyBillDetailDTOS;
    }

    @Override
    @DS(SLAVE)
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public List<InquiryMaterialDTO> makeInquiryMaterial(String purchaseBillDetailIds) {
        List<InquiryMaterialPO> inquiryPOS = purchaseApplyBillDetailService.makeInquiryMaterial(
                Arrays.asList(StringUtils.split(purchaseBillDetailIds, ",")));
        List<InquiryMaterialDTO> inquiryMaterialDTOS = inquiryMaterialConvert.po2DTOList(inquiryPOS);
        inquiryMaterialDTOS.forEach(inquiryMaterialDTO -> {
            //如果为空数据库可采购数量，则去报价单中查询计算一次
            if (null == inquiryMaterialDTO.getEnablePurchaseNum()) {
                if (StringUtils.isNotEmpty(inquiryMaterialDTO.getPurchaseBillCode()) && StringUtils.isNotEmpty(inquiryMaterialDTO.getPurchaseBillItemCode())) {
                    BigDecimal enablePurchaseNum = iInquiryMaterialService.getPurchaseNumAmountByBillNoAndCode(inquiryMaterialDTO.getPurchaseBillCode(),inquiryMaterialDTO.getPurchaseBillItemCode(),null);
                    if (Objects.nonNull(enablePurchaseNum)) {
                        inquiryMaterialDTO.setEnablePurchaseNum(inquiryMaterialDTO.getNumber().subtract(enablePurchaseNum));
                    } else {
                        inquiryMaterialDTO.setEnablePurchaseNum(inquiryMaterialDTO.getNumber());
                    }
                }
            }


            if (StringUtils.isNotEmpty(inquiryMaterialDTO.getMaterialCode()) &&
                    StringUtils.isNotEmpty(inquiryMaterialDTO.getFactoryCode())) {
                HistoryPriceInfoDTO historyPriceInfoDTO = priceInfoLogic.getHistoryLowPrice(
                        inquiryMaterialDTO.getMaterialCode(), inquiryMaterialDTO.getFactoryCode());
                if (ObjectUtil.isNotNull(historyPriceInfoDTO)) {
                    inquiryMaterialDTO.setHistoryPrice(historyPriceInfoDTO.getTaxPrice());
                    inquiryMaterialDTO.setHistoryPriceId(historyPriceInfoDTO.getId());
                }
                HistoryPriceInfoDTO lastBidPriceInfoDTO = priceInfoLogic.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));
//            inquiryMaterialDTO.setAvailableNum(inquiryMaterialDTO.getPurchaseNum());

        });
        return inquiryMaterialDTOS;
    }

    /**
     * 采购申请明细分配采购组
     *
     * @param ids               采购申请明细id集合
     * @param purchaseGroupCode 采购组编码
     */
    @Override
    public void updatePurchaseGroupCode(String ids, String purchaseGroupCode) {
        List<Long> idList = JSON.parseArray(ids, Long.class);
        List<PurchaseApplyBillDetail> purchaseApplyBillDetailS = purchaseApplyBillDetailService.listByIds(idList);
        purchaseApplyBillDetailS.forEach(purchaseApplyBillDetail -> {
            purchaseApplyBillDetail.setPurchaseGroupCode(purchaseGroupCode);
        });
        purchaseApplyBillDetailService.updateBatchById(purchaseApplyBillDetailS);
    }

    @Override
    public void updateDetailRemark(Long id, String detailRemark) {
        PurchaseApplyBillDetail purchaseApplyBillDetail = purchaseApplyBillDetailService.getById(id);
        purchaseApplyBillDetail.setDetailRemark(detailRemark);
        purchaseApplyBillDetailService.updateById(purchaseApplyBillDetail);
    }

    @Override
    public void updateDetailMethod(PurchaseApplyBillDetailDTO detailDTO) {
        PurchaseApplyBillDetail purchaseApplyBillDetail = purchaseApplyBillDetailService.getById(detailDTO.getId());
        purchaseApplyBillDetail.setPurchaseMethod(detailDTO.getPurchaseMethod());
        purchaseApplyBillDetailService.updateById(purchaseApplyBillDetail);
    }

    /**
     * 批量更新采购路径
     *
     * @param  purchaseWay 采购组编码
     * @param ids       采购申请明细ID集合
     */
    @Override
    public void updateDetailWayMethod(String ids , String purchaseWay) {
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::valueOf)
                .collect(Collectors.toList());
        List<PurchaseApplyBillDetail> purchaseApplyBillDetailS = purchaseApplyBillDetailService.listByIds(idList);
        purchaseApplyBillDetailS.forEach(purchaseApplyBillDetail -> {
            purchaseApplyBillDetail.setPurchaseWay(purchaseWay);
        });
        purchaseApplyBillDetailService.updateBatchById(purchaseApplyBillDetailS);
    }

    @Override
    public PurchaseApplyBillDetailDTO selectById(PurchaseApplyBillDetailQuery query) {
        PurchaseApplyBillDetail purchaseApplyBillDetail = purchaseApplyBillDetailService.getById(query.getId());
        return purchaseApplyBillDetailConvert.entity2DTO(purchaseApplyBillDetail);
    }

    /**
     * 转招标查询采购单数据
     *
     * @param query
     * @return
     */
    @Override
    public TenderSaveDTO transferTender(PurchaseApplyBillDetailQuery query) {
        List<PurchaseApplyBillDetailPO> purchaseApplyBillDetailPOS = purchaseApplyBillDetailService.findPageByQuery(
                null, query);
        TenderSaveDTO tenderSaveDTO = new TenderSaveDTO();
        tenderSaveDTO.setType(0);
        TenderBaseDTO tenderBaseDTO = new TenderBaseDTO();
        //模版写死
        tenderBaseDTO.setTypeId(1L);
        tenderBaseDTO.setTemplateId(412L);
        tenderBaseDTO.setCompanyCode(purchaseApplyBillDetailPOS.get(0).getCompanyCode());
        tenderBaseDTO.setPurchaseGroupCode(purchaseApplyBillDetailPOS.get(0).getPurchaseGroupCode());
        final String textConfig = sysConfigClient.getTextConfig(TENDER_AGREEMENT.getCode());
        tenderBaseDTO.setAgreement(textConfig);
        tenderSaveDTO.setTender(tenderBaseDTO);
        tenderBaseDTO.setPurchaseOrgCode("8000");
        purchaseApplyBillDetailPOS.forEach(item ->
        {
            final String s = item.getMaterialName() + item.getMaterialSpec();
            item.setMaterialName(s);
            item.setSourceRowId(item.getId());
            item.setSourceType(1);
            item.setK4(item.getDetailRemark());
        });
        final List<TenderDetailAllDTO> tenderDetails = purchaseApplyBillDetailConvert.poBillMaterial2DetailDTOList(
                purchaseApplyBillDetailPOS);
        for (TenderDetailAllDTO tenderDetail : tenderDetails) {
            //计算可采购数量
            //如果为空数据库可采购数量，则去报价单中查询计算一次
            if (null == tenderDetail.getEnablePurchaseNum()) {
                if (StringUtils.isNotEmpty(tenderDetail.getBillCode()) && StringUtils.isNotEmpty(tenderDetail.getItemCode())) {
                    PurchaseApplyBillDetailClientDTO purchaseApplyBillDetailClientDTO = getByBillCodeAndItemCode(tenderDetail.getBillCode(),tenderDetail.getItemCode());
                    BigDecimal enablePurchaseNum = purchaseApplyBillDetailService.getPurchaseNumAmountByBillNoAndCode(tenderDetail.getBillCode(),tenderDetail.getItemCode(),null);
                    if (Objects.nonNull(enablePurchaseNum)) {
                        tenderDetail.setEnablePurchaseNum(purchaseApplyBillDetailClientDTO.getApprovalNumber().subtract(enablePurchaseNum));
                    } else {
                        tenderDetail.setEnablePurchaseNum(purchaseApplyBillDetailClientDTO.getApprovalNumber());
                    }
                }
            }

            tenderDetail.setUnit("PCS");
        }
        tenderSaveDTO.setTenderDetails(tenderDetails);
        return tenderSaveDTO;
    }

    @Override
    public List<PurchaseApplyBillClientDTO> listByBillCodeList(Collection<? extends Serializable> billCodeList) {
        List<PurchaseApplyBill> billList = purchaseApplyBillService.list(
                new LambdaQueryWrapper<PurchaseApplyBill>().in(PurchaseApplyBill::getBillCode, billCodeList));
        return purchaseApplyBillDetailConvert.billEntity2DTOList(billList);
    }

    @Override
    public PurchaseApplyBillDetailClientDTO getByBillCodeAndItemCode(String billCode, String itemCode) {
        PurchaseApplyBillDetail applyBillDetail = purchaseApplyBillDetailService.getOne(
                new LambdaQueryWrapper<PurchaseApplyBillDetail>().eq(PurchaseApplyBillDetail::getBillCode, billCode)
                        .eq(PurchaseApplyBillDetail::getItemCode, itemCode)
                        .eq(PurchaseApplyBillDetail::getDeleteFlag, 0));
        return purchaseApplyBillDetailConvert.billDetailEntity2DTO(applyBillDetail);
    }

    @Override
    public PurchaseApplyBillDetailClientDTO getByBillCode(String billCode) {
        PurchaseApplyBillDetail applyBillDetail = purchaseApplyBillDetailService.getOne(
                new LambdaQueryWrapper<PurchaseApplyBillDetail>().eq(PurchaseApplyBillDetail::getBillCode, billCode)
                        .eq(PurchaseApplyBillDetail::getDeleteFlag, 0).last(" limit 1"));
        return purchaseApplyBillDetailConvert.billDetailEntity2DTO(applyBillDetail);
    }

    @Override
    public PurchaseApplyBillClientDTO getPurchaseApplyBill(String billCode) {
        PurchaseApplyBill bill = purchaseApplyBillService.getOne(
                new LambdaQueryWrapper<PurchaseApplyBill>().eq(PurchaseApplyBill::getBillCode, billCode));
        return purchaseApplyBillDetailConvert.entity2ClientDTO(bill);
    }

    @Override
    public List<PurchaseApplyBillDetailClientDTO> getPurchaseApplyBillDetail(String billCode, String itemCode) {
        List<PurchaseApplyBillDetail> billDetail = purchaseApplyBillDetailService.list(new LambdaQueryWrapper<PurchaseApplyBillDetail>()
                .eq(PurchaseApplyBillDetail::getBillCode, billCode)
                .eq(PurchaseApplyBillDetail::getItemCode, itemCode));
        return purchaseApplyBillDetailConvert.entities2ClientDetailDTOList(billDetail);
    }

    @Override
    public PageView selectPurchaseForContractList(PurchaseApplyBillDetailQuery query) {
        final Page<PurchaseApplyBill> dbPage = PageUtil.toPage(query);
        if(StringUtils.isNotEmpty(query.getContractType())){
            if("03".equals( query.getContractType())){
                //模具
                query.setApplyBillType("fa_asset_apply_mj");
            }else{
                query.setApplyBillType("fa_asset_apply_fmj");
            }
        }
        List<PurchaseApplyBillDetailPO> purchaseApplyBillDetailPOS = purchaseApplyBillDetailService.selectPurchaseForContractList(
                    dbPage, query);
        List<PurchaseApplyBillDetailDTO> purchaseApplyBillDetailDTOS = purchaseApplyBillDetailConvert.po2DTOList(
                purchaseApplyBillDetailPOS);
     for(PurchaseApplyBillDetailDTO purchaseApplyBillDetailDTO :purchaseApplyBillDetailDTOS){
         List<ContractDetailClientDTO> contractDetailClientDTOS = contractDetailClient.getDetailListByPurchaseCodeAndeItem(purchaseApplyBillDetailDTO.getBillCode(), purchaseApplyBillDetailDTO.getItemCode());
         if (CollectionUtil.isNotEmpty(contractDetailClientDTOS)) {
             List<BigDecimal> numSum = contractDetailClientDTOS.stream().map(ContractDetailClientDTO::getNum).collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(numSum)){
                BigDecimal sum = numSum.stream()
                        .filter(Objects::nonNull)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal subtract = purchaseApplyBillDetailDTO.getPurchaseNum()==null?BigDecimal.ZERO:purchaseApplyBillDetailDTO.getPurchaseNum().subtract(sum);
                purchaseApplyBillDetailDTO.setEnablePurchaseNum(subtract==null?BigDecimal.ZERO:subtract);
            }else{
                purchaseApplyBillDetailDTO.setEnablePurchaseNum(BigDecimal.ZERO);
            }
         }else{
             purchaseApplyBillDetailDTO.setEnablePurchaseNum(purchaseApplyBillDetailDTO.getRequireNum());
         }
     }

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