package com.fjhx.purchase.service.purchase.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.common.constant.SourceConstant;
import com.fjhx.common.entity.documentary.bo.DocumentaryData;
import com.fjhx.common.enums.CodingRuleEnum;
import com.fjhx.common.service.coding.CodingRuleService;
import com.fjhx.common.service.documentary.GetDocumentaryBusinessTemplate;
import com.fjhx.item.entity.product.vo.ProductInfoVo;
import com.fjhx.item.service.product.ProductInfoService;
import com.fjhx.purchase.entity.invoice.vo.InvoiceDetailsVo;
import com.fjhx.purchase.entity.pay.vo.PayDetailVo;
import com.fjhx.purchase.entity.purchase.bo.PurchaseDocumentaryBo;
import com.fjhx.purchase.entity.purchase.dto.PurchaseDto;
import com.fjhx.purchase.entity.purchase.dto.PurchaseSelectDto;
import com.fjhx.purchase.entity.purchase.enums.PurchaseStatusEnum;
import com.fjhx.purchase.entity.purchase.po.Purchase;
import com.fjhx.purchase.entity.purchase.po.PurchaseDetail;
import com.fjhx.purchase.entity.purchase.po.PurchasePayRecordDetail;
import com.fjhx.purchase.entity.purchase.vo.PurchaseDocumentaryVo;
import com.fjhx.purchase.entity.purchase.vo.PurchaseVo;
import com.fjhx.purchase.entity.subscribe.po.Subscribe;
import com.fjhx.purchase.entity.subscribe.po.SubscribeDetail;
import com.fjhx.purchase.mapper.purchase.PurchaseMapper;
import com.fjhx.purchase.service.arrival.ArrivalDetailService;
import com.fjhx.purchase.service.invoice.InvoiceDetailsService;
import com.fjhx.purchase.service.pay.PayDetailService;
import com.fjhx.purchase.service.purchase.PurchaseDetailService;
import com.fjhx.purchase.service.purchase.PurchasePayRecordDetailService;
import com.fjhx.purchase.service.purchase.PurchaseService;
import com.fjhx.purchase.service.subscribe.SubscribeDetailService;
import com.fjhx.purchase.service.subscribe.SubscribeService;
import com.fjhx.supply.entity.supplier.po.SupplierInfo;
import com.fjhx.supply.service.supplier.SupplierInfoService;
import com.fjhx.wms.entity.warehouse.po.Warehouse;
import com.fjhx.wms.service.warehouse.WarehouseService;
import com.ruoyi.common.core.domain.BaseIdPo;
import com.ruoyi.common.core.domain.BaseSelectDto;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.wrapper.IWrapper;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 采购 服务实现类
 * </p>
 *
 * @author
 * @since 2023-04-06
 */
@DS(SourceConstant.PURCHASE)
@Service
public class PurchaseServiceImpl extends ServiceImpl<PurchaseMapper, Purchase>
        implements PurchaseService, GetDocumentaryBusinessTemplate {

    @Autowired
    private SupplierInfoService supplierInfoService;

    @Autowired
    private InvoiceDetailsService invoiceDetailsService;

    @Autowired
    private PayDetailService payDetailService;

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private ArrivalDetailService arrivalDetailService;

    @Autowired
    private WarehouseService warehouseService;

    @Autowired
    private SubscribeDetailService subscribeDetailService;

    @Autowired
    private SubscribeService subscribeService;

    @Autowired
    private CodingRuleService codingRuleService;

    @Autowired
    private PurchasePayRecordDetailService purchasePayRecordDetailService;

    /**
     * 列表
     *
     * @param dto
     * @return
     */
    @Override
    public Page<PurchaseVo> getPage(PurchaseSelectDto dto) {
        IWrapper<Purchase> wrapper = getWrapper();

        wrapper.eq("p", Purchase::getPurchaseStatus, dto.getPurchaseStatus());
        wrapper.eq("p", Purchase::getArrivalStatus, dto.getArrivalStatus());
        wrapper.eq("p", Purchase::getPayStatus, dto.getPayStatus());
        wrapper.like("p", Purchase::getCode, dto.getCode());// 采购单号
        wrapper.eq("p", Purchase::getSupplyId, dto.getSupplyId());// 供应商ID
        wrapper.eq("p", Purchase::getCode, dto.getKeyword());// 根据采购单号关键字搜索
        wrapper.ge("p", Purchase::getAmount, dto.getStartAmount());// 采购开始金额
        wrapper.le("p", Purchase::getAmount, dto.getEndAmount());// 采购结束金额
        wrapper.ge("P", Purchase::getCreateTime, dto.getBeginTime());// 采购开始时间
        wrapper.le("p", Purchase::getCreateTime, dto.getEndTime());// 采购结束时间

        wrapper.orderByDesc("p", Purchase::getCreateTime);

        Page<PurchaseVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        List<PurchaseVo> list = page.getRecords();

        if (CollectionUtils.isEmpty(list)) {
            return page;
        }

        supplierInfoService.attributeAssign(list, PurchaseVo::getSupplyId, (item, supplierInfo) -> {
            item.setSupplyName(supplierInfo.getName());
        });

        return page;
    }

    @Override
    public Page<PurchaseVo> getPageByWdly(PurchaseSelectDto dto) {
        IWrapper<Purchase> wrapper = getWrapper();

        //过滤维多利亚数据
        wrapper.isNotNull("p.victoriatourist_json");

        wrapper.orderByDesc("p", Purchase::getCreateTime);
        if (ObjectUtils.isNotEmpty(dto.getPurchaseStatus())) {
            wrapper.eq("p", Purchase::getPurchaseStatus, dto.getPurchaseStatus());
        }
        if (ObjectUtils.isNotEmpty(dto.getArrivalStatus())) {
            wrapper.eq("p", Purchase::getArrivalStatus, dto.getArrivalStatus());
        }
        if (ObjectUtils.isNotEmpty(dto.getPayStatus())) {
            wrapper.eq("p", Purchase::getPayStatus, dto.getPayStatus());
        }

        //采购单号 供应商 采购人
        if (ObjectUtils.isNotEmpty(dto.getKeyword())) {
            //供应商
            List<Long> supplierInfoIds = supplierInfoService.listObject(SupplierInfo::getId, q -> q.eq(SupplierInfo::getName, dto.getKeyword()));
            wrapper.and(q -> q.like("json_unquote(p.victoriatourist_json -> '$.contractCode')", dto.getKeyword())
                    .or().in("p", Purchase::getSupplyId, supplierInfoIds)
                    .or().like("p", Purchase::getPurchaseName, dto.getKeyword())
            );
        }
        //高级检索
        //采购单号
        if (ObjectUtils.isNotEmpty(dto.getContractCode())) {
            wrapper.like("json_unquote(p.victoriatourist_json -> '$.contractCode')", dto.getContractCode());
        }
        //供应商
        wrapper.eq("p", Purchase::getSupplyId, dto.getSupplyId());
        //收货仓库
        if (ObjectUtils.isNotEmpty(dto.getReceiptWarehouseId())) {
            wrapper.like("json_unquote(p.victoriatourist_json -> '$.receiptWarehouseId')", dto.getReceiptWarehouseId());
        }
        //采购金额
        wrapper.ge(Purchase::getAmount, dto.getStartAmount());
        wrapper.le(Purchase::getAmount, dto.getEndAmount());
        //采购人
        wrapper.eq(Purchase::getCreateUser, dto.getPurchaseUserId());
        //采购时间
        wrapper.ge(Purchase::getCreateTime, dto.getPurchaseStartTime());
        wrapper.le(Purchase::getCreateTime, dto.getPurchaseEndTime());


        Page<PurchaseVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        List<PurchaseVo> list = page.getRecords();
        if (ObjectUtils.isEmpty(list)) {
            return page;
        }

        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> supplyIds = list.stream().map(PurchaseVo::getSupplyId).collect(Collectors.toList());
            List<SupplierInfo> supplierInfoList = supplierInfoService.list(Wrappers.<SupplierInfo>query().lambda().in(SupplierInfo::getId, supplyIds));
            Map<Long, List<SupplierInfo>> supplyMap = supplierInfoList.stream().distinct().collect(Collectors.groupingBy(SupplierInfo::getId));
            if (MapUtils.isNotEmpty(supplyMap)) {
                for (PurchaseVo p : list) {
                    List<SupplierInfo> supplys = supplyMap.getOrDefault(p.getSupplyId(), null);
                    p.setSupplyName(supplys == null ? null : supplys.get(0).getName());
                }
            }
        }
        //-------------------------------------------------
        if (CollectionUtils.isNotEmpty(list)) {
            //维多利亚 赋值收货仓库名称
            List<Long> wids = new ArrayList<>();
            for (PurchaseVo purchaseVo : list) {
                String victoriatouristJson = purchaseVo.getVictoriatouristJson();
                if (ObjectUtils.isNotEmpty(victoriatouristJson)) {
                    JSONObject json = JSONObject.parseObject(victoriatouristJson);
                    wids.add(json.getLong("receiptWarehouseId"));
                }
            }
            if (ObjectUtils.isEmpty(wids)) {
                return page;
            }
            List<Warehouse> warehouses = warehouseService.listByIds(wids);
            Map<Long, String> warehousesMap = warehouses.stream().collect(Collectors.toMap(Warehouse::getId, Warehouse::getName));
            for (PurchaseVo purchaseVo : list) {
                String victoriatouristJson = purchaseVo.getVictoriatouristJson();
                if (ObjectUtils.isNotEmpty(victoriatouristJson)) {
                    JSONObject json = JSONObject.parseObject(victoriatouristJson);
                    String warehouseName = warehousesMap.get(json.getLong("receiptWarehouseId"));
                    json.put("receiptWarehouseName", warehouseName);
                    purchaseVo.setVictoriatouristJson(JSONObject.toJSONString(json, JSONWriter.Feature.WriteLongAsString));
                }
            }
            //赋值到货状态
//            List<Long> pids = list.stream().map(PurchaseVo::getId).collect(Collectors.toList());
//            List<Arrival> arrivalList = arrivalService.list(q -> q.in(Arrival::getPurchaseId, pids));
//            Map<Long, List<Arrival>> arrivalMap = arrivalList.stream().collect(Collectors.groupingBy(Arrival::getPurchaseId));
//            for (PurchaseVo purchaseVo : list) {
//                List<Arrival> list1 = arrivalMap.get(purchaseVo.getId());
//                if(ObjectUtils.isEmpty(list1)){
//                    purchaseVo.setArrivalStatus(0);
//                    continue;
//                }
//                List<Arrival> arrivalCount = list1.stream().filter(q -> q.equals(1)).collect(Collectors.toList());
//                if(arrivalCount.size()==0){
//                    //未到货
//                    purchaseVo.setArrivalStatus(0);
//                }else if(arrivalCount.size()<=list1.size()){
//                    //部分到货
//                    purchaseVo.setArrivalStatus(1);
//                }else{
//                    //完全到货
//                    purchaseVo.setArrivalStatus(2);
//                }
//            }
        }
        //赋值已付款金额
        List<Long> purchaseIds = list.stream().map(PurchaseVo::getId).collect(Collectors.toList());
        Map<Long, List<PurchasePayRecordDetail>> PayRecordMap = purchasePayRecordDetailService.mapKGroup(PurchasePayRecordDetail::getPurchaseId,
                q -> q.in(PurchasePayRecordDetail::getPurchaseId, purchaseIds));
        for (PurchaseVo purchaseVo : list) {
            List<PurchasePayRecordDetail> purchasePayRecords = PayRecordMap.get(purchaseVo.getId());
            if (ObjectUtils.isEmpty(purchasePayRecords)) {
                purchaseVo.setPaidAmount(BigDecimal.ZERO);
                continue;
            }
            //求和已付款
            BigDecimal paidAmount = purchasePayRecords.stream().map(PurchasePayRecordDetail::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            purchaseVo.setPaidAmount(paidAmount);
        }

        return page;
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @Override
    public PurchaseVo detail(Long id) {
        Purchase purchase = this.getById(id);
        if (ObjectUtils.isEmpty(purchase)) {
            throw new ServiceException("采购单不存在");
        }
        //查询出供应商名称
        SupplierInfo info = supplierInfoService.getById(purchase.getSupplyId());
        PurchaseVo result = BeanUtil.toBean(purchase, PurchaseVo.class);
        result.setSupplyName(info.getName());
        //查询出采购明细列表
        List<PurchaseDetail> purchaseDetailList = purchaseDetailService.
                list(Wrappers.<PurchaseDetail>query().lambda().eq(PurchaseDetail::getPurchaseId, id));
        //查询出产品
        if (CollectionUtils.isNotEmpty(purchaseDetailList)) {
            //赋值申购编号
            PurchaseDetail purchaseDetail = purchaseDetailList.get(0);
            SubscribeDetail subscribeDetail = subscribeDetailService.getById(purchaseDetail.getSubscribeDetailId());
            if (ObjectUtils.isNotEmpty(subscribeDetail)) {
                Subscribe subscribe = subscribeService.getById(subscribeDetail.getSubscribeId());
                if (ObjectUtils.isNotEmpty(subscribe)) {
                    result.setSubscribeCode(subscribe.getCode());
                }
            }

            List<Long> productIds = purchaseDetailList.stream().map(PurchaseDetail::getBussinessId).collect(Collectors.toList());
            List<ProductInfoVo> productInfos = productInfoService.getListByProductIds(productIds);
            Map<Long, List<ProductInfoVo>> productMap = productInfos.stream().distinct().collect(Collectors.groupingBy(ProductInfoVo::getId));
            if (MapUtils.isNotEmpty(productMap)) {
                for (PurchaseDetail p : purchaseDetailList) {
                    //查询出到货总量
                    BigDecimal sumArrivalCount = arrivalDetailService.getSumCount(p.getId(), p.getBussinessId());
                    p.setSumArrivalCount(sumArrivalCount);
                    List<ProductInfoVo> productInfoVos = productMap.getOrDefault(p.getBussinessId(), null);
                    ProductInfoVo vo = productInfoVos.get(0);
                    p.setProductCode(vo.getCode());
                    p.setProductName(vo.getName());
                    p.setProductType(vo.getType());
                    p.setProductCategory(vo.getClassifyName());
                    p.setProductUnit(vo.getUnit());
                    p.setProductSpec(vo.getSpec());
                    p.setProductCustomCode(vo.getCustomCode());
                }
            }
        }
        result.setPurchaseDetailList(purchaseDetailList);
        return result;
    }

    /**
     * 采购新增
     *
     * @param purchase
     */
    @Override
    public void add(Purchase purchase) {
        PurchaseService purchaseService = SpringUtil.getBean(PurchaseService.class);
        PurchaseDetailService purchaseDetailService = SpringUtil.getBean(PurchaseDetailService.class);
//        purchase.setCode(CodeEnum.PURCHASE.getCode());
        purchase.setCode(codingRuleService.createCode(CodingRuleEnum.PURCHASE.getKey(), null));
        purchase.setPurchaseStatus(PurchaseStatusEnum.UNDER_REVIEW.getKey());
        purchaseService.save(purchase);
        if (CollectionUtils.isNotEmpty(purchase.getPurchaseDetailList())) {
            for (PurchaseDetail s : purchase.getPurchaseDetailList()) {
                s.setPurchaseId(purchase.getId());
            }
            purchaseDetailService.saveBatch(purchase.getPurchaseDetailList());
        }
    }

    @Override
    public void edit(PurchaseDto purchaseDto) {
        this.updateById(purchaseDto);
    }

    @Override
    public void delete(Long id) {
        this.removeById(id);
    }

    /**
     * 根据供应商查询无发票的采购合同
     *
     * @param supplyId
     * @return
     */
    @Override
    public List<Purchase> getNoInvoiceListBySupplyId(String supplyId) {
        if (StringUtils.isEmpty(supplyId)) {
            throw new ServiceException("供应商ID不能为空");
        }
        List<Purchase> list = this.list(Wrappers.<Purchase>query().lambda().eq(Purchase::getSupplyId, supplyId).eq(Purchase::getPurchaseStatus, PurchaseStatusEnum.PASS.getKey()).ne(Purchase::getInvoiceType,"0"));
        List<Long> ids = list.stream().distinct().map(Purchase::getId).collect(Collectors.toList());
        List<InvoiceDetailsVo> invoiceDetailsList = invoiceDetailsService.getSumMoneyByPurchaseIds(ids);
        Map<Long, BigDecimal> invoiceMap = invoiceDetailsList.stream().collect(Collectors.toMap(InvoiceDetailsVo::getPurchaseId, InvoiceDetailsVo::getSumMoney));
        List<PayDetailVo> payDetailVoList = payDetailService.getSumMoneyByPurchaseIds(ids);
        Map<Long, BigDecimal> payMap = payDetailVoList.stream().collect(Collectors.toMap(PayDetailVo::getPurchaseId, PayDetailVo::getSumMoney));
        for (Purchase p : list) {
            if (MapUtils.isNotEmpty(invoiceMap)) {
                p.setSumInvoiceMoney(invoiceMap.getOrDefault(p.getId(), BigDecimal.ZERO));
            } else {
                p.setSumInvoiceMoney(BigDecimal.ZERO);
            }
            if (MapUtils.isNotEmpty(payMap)) {
                p.setSumPayMoney(payMap.getOrDefault(p.getId(), BigDecimal.ZERO));
            } else {
                p.setSumPayMoney(BigDecimal.ZERO);
            }
        }

        return list;
    }
    /**
     * 根据供应商查询无发票的采购合同
     *
     * @param supplyId
     * @return
     */
    @Override
    public List<Purchase> getListBySupplyId(String supplyId) {
        if (StringUtils.isEmpty(supplyId)) {
            throw new ServiceException("供应商ID不能为空");
        }
        List<Purchase> list = this.list(Wrappers.<Purchase>query().lambda().eq(Purchase::getSupplyId, supplyId).eq(Purchase::getPurchaseStatus, PurchaseStatusEnum.PASS.getKey()));
        List<Long> ids = list.stream().distinct().map(Purchase::getId).collect(Collectors.toList());
        List<InvoiceDetailsVo> invoiceDetailsList = invoiceDetailsService.getSumMoneyByPurchaseIds(ids);
        Map<Long, BigDecimal> invoiceMap = invoiceDetailsList.stream().collect(Collectors.toMap(InvoiceDetailsVo::getPurchaseId, InvoiceDetailsVo::getSumMoney));
        List<PayDetailVo> payDetailVoList = payDetailService.getSumMoneyByPurchaseIds(ids);
        Map<Long, BigDecimal> payMap = payDetailVoList.stream().collect(Collectors.toMap(PayDetailVo::getPurchaseId, PayDetailVo::getSumMoney));
        for (Purchase p : list) {
            if (MapUtils.isNotEmpty(invoiceMap)) {
                p.setSumInvoiceMoney(invoiceMap.getOrDefault(p.getId(), BigDecimal.ZERO));
            } else {
                p.setSumInvoiceMoney(BigDecimal.ZERO);
            }
            if (MapUtils.isNotEmpty(payMap)) {
                p.setSumPayMoney(payMap.getOrDefault(p.getId(), BigDecimal.ZERO));
            } else {
                p.setSumPayMoney(BigDecimal.ZERO);
            }
        }

        return list;
    }

    /**
     * 货款账单
     */
    @Override
    public Page<PurchaseDto> paymentBill(PurchaseSelectDto purchaseDto) {

        QueryWrapper<Object> query = Wrappers.query();
        query.eq(ObjectUtil.isNotEmpty(purchaseDto.getSupplyId()), "pu.supply_id", purchaseDto.getSupplyId());
        query.eq(ObjectUtil.isNotEmpty(purchaseDto.getPayStatus()), "pu.pay_status", purchaseDto.getPayStatus());
        query.like(StringUtils.isNotEmpty(purchaseDto.getKeyword()), "pu.code", purchaseDto.getKeyword());
        query.eq("pu.purchase_status", PurchaseStatusEnum.PASS.getKey());
        query.groupBy("pu.id");
        //查询采购信息与已收发票
        Page<PurchaseDto> page = baseMapper.paymentBill(purchaseDto.getPage(), query);
        List<PurchaseDto> records = page.getRecords();
        if (records.size() == 0) {
            return page;
        }

        //获取到所有的采购订单ID
        List<Long> ids = records.stream().map(BaseIdPo::getId).collect(Collectors.toList());
        QueryWrapper<Object> wrapper = Wrappers.query();
        wrapper.in("sw.business_id", ids);
        wrapper.eq("sw.type", 1);
        wrapper.groupBy("sw.business_id");
        //查询到货金额(已入库的采购数量*采购单价)
        List<PurchaseDto> purchaseDtos = baseMapper.arrivalAmount(wrapper);
        Map<Long, List<PurchaseDto>> arrivalMap = purchaseDtos.stream().collect(Collectors.groupingBy(PurchaseDto::getId));

        // 查询已付款金额（）
        QueryWrapper<Object> queryWrapper = Wrappers.query();
        queryWrapper.in("pd.purchase_id", ids);
        queryWrapper.eq("p.status", 30);
        queryWrapper.groupBy("pd.purchase_id");
        List<PurchaseDto> purchaseDtos1 = baseMapper.paidAmount(queryWrapper);
        Map<Long, List<PurchaseDto>> paidMap = purchaseDtos1.stream().collect(Collectors.groupingBy(PurchaseDto::getId));

        //赋值到货金额与已付款金额
        for (PurchaseDto record : records) {
            //初始化到货金额与已付款金额
            record.setArrivalAmount(new BigDecimal(0));
            record.setPaidAmount(new BigDecimal(0));
            //到货中没有币种选择（使用合同的币种）
            record.setArrivalCurrency(record.getCurrency());
            //已付款金额币种默认合同币种
            record.setPaidCurrency(record.getCurrency());
            //赋值到货金额
            List<PurchaseDto> arrivalList = arrivalMap.get(record.getId());
            if (ObjectUtils.isNotEmpty(arrivalList)) {
                record.setArrivalAmount(arrivalList.get(0).getAmount());
            }

            //赋值已付款金额
            List<PurchaseDto> paidList = paidMap.get(record.getId());
            if (ObjectUtils.isNotEmpty(paidList)) {
                record.setPaidAmount(paidList.get(0).getAmount());
                record.setPaidCurrency(paidList.get(0).getCurrency());
            }
        }

        return page;
    }

    /**
     * 采购统计（采购列表）
     */
    @Override
    public Map<String, Object> purchaseStatistics(PurchaseSelectDto dto) {
        //存放到货状态
        List<Integer> arrivalStatus = Arrays.asList(0, 10, 20);//到货状态 0未到货  10 部分到货  20已到货

        //存放采购统计数据
        Map<String, Object> map = new HashMap<>();
        //存放采购统计详情
        List<Map<String, Object>> list = new ArrayList<>();

        QueryWrapper<Purchase> query = Wrappers.query();
        query.select("count(*) count,sum(amount) amount,ifnull(arrival_status,-1) arrivalStatus");
        query.groupBy("arrival_status");
        List<Purchase> purchaseList = baseMapper.selectList(query);
        //计算合计订单数
        Integer count = purchaseList.stream().map(Purchase::getCount).reduce(Integer::sum).orElse(0);
        map.put("count", count);
        //计算合计采购金额
        BigDecimal amount = purchaseList.stream().map(Purchase::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        map.put("amount", amount);
        Map<Integer, List<Purchase>> purchaseMap = purchaseList.stream().collect(Collectors.groupingBy(Purchase::getArrivalStatus));

        //获取到每个到货状态的值
        for (Integer status : arrivalStatus) {
            //赋值初始值
            Map<String, Object> statusMap = new HashMap<>();
            statusMap.put("arrivalStatus", status);
            statusMap.put("purchaseCount", 0);
            statusMap.put("purchaseAmount", 0);

            //赋值
            List<Purchase> purchases = purchaseMap.get(status);
            if (CollectionUtils.isNotEmpty(purchases)) {
                statusMap.put("purchaseCount", purchases.get(0).getCount());
                statusMap.put("purchaseAmount", purchases.get(0).getAmount());
            }
            list.add(statusMap);
        }
        map.put("purchaseList", list);
        return map;
    }

    /**
     * 批量查询
     * @param ids
     * @return
     */
    @Override
    public List<Purchase> getListInId(List<Long> ids) {
        List<Purchase> list = this.list(Wrappers.<Purchase>query().lambda().in(Purchase::getId,ids));
        return list;
    }

    @Override
    public Page<? extends DocumentaryData> getDocumentaryPage(JSONObject selectData, BaseSelectDto
            dto, List<Long> excludeBusinessId) {
        PurchaseDocumentaryBo bo = selectData.toJavaObject(PurchaseDocumentaryBo.class);

        IWrapper<Purchase> wrapper = IWrapper.getWrapper();
        wrapper.like(Purchase::getCode, bo.getCode());
        wrapper.eq(Purchase::getCreateUser, bo.getUserId());
        wrapper.eq(Purchase::getPurchaseStatus, 30);
        wrapper.notIn(Purchase::getId, excludeBusinessId);
        wrapper.orderByDesc(Purchase::getId);

        Page<Purchase> itemPage = page(dto.getPage(), wrapper);
        Page<PurchaseDocumentaryVo> page = PageUtils.copyPage(itemPage, PurchaseDocumentaryVo.class);
        List<PurchaseDocumentaryVo> records = page.getRecords();

        if (records.size() == 0) {
            return page;
        }

        // 供应商名称
        supplierInfoService.attributeAssign(records, Purchase::getSupplyId, (item, supplier) -> {
            item.setSupplyName(supplier.getName());
        });

        return page;
    }

}
