package com.gree.mall.manager.logic.material.manage;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.material.manage.WebsitMPurchaseBean;
import com.gree.mall.manager.bean.material.manage.WebsitMPurchaseItemBean;
import com.gree.mall.manager.bean.material.manage.WebsitPurchaseApplyVO;
import com.gree.mall.manager.bean.material.vender.WebsitPurchaseCheckVO;
import com.gree.mall.manager.bean.material.vender.WebsitVenderGoodsRelaVO;
import com.gree.mall.manager.commonmapper.MaterialMapper;
import com.gree.mall.manager.enums.IsEnum;
import com.gree.mall.manager.enums.IsYesNoEnum;
import com.gree.mall.manager.enums.material.MaterialFlagEnum;
import com.gree.mall.manager.enums.material.StateEnum;
import com.gree.mall.manager.enums.material.WebsitGoodsTypeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.material.stock.WebitPurchaseStockLogic;
import com.gree.mall.manager.logic.material.vender.VenderGoodsLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.zfire.bean.QueryParamBean;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Slf4j
@Service
@RequiredArgsConstructor
public class WebsitMPurchaseLogic {

    private final CommonLogic commonLogic;
    private final MaterialMapper materialMapper;
    private final WebsitPurchaseService websitPurchaseService;
    private final WebsitPurchaseItemService websitPurchaseItemService;
    private final VenderGoodsLogic venderGoodsLogic;
    private final WebsitVenderService websitVenderService;
    private final StorageService storageService;
    private final WebitPurchaseStockLogic webitPurchaseStockLogic;
    private final WebsitGoodsService websitGoodsService;
    private final WebsitGoodsPriceService websitGoodsPriceService;

    public IPage<WebsitPurchaseApplyVO> page(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.materialParam(zfireParamBean, WebsitPurchaseApplyVO.class, adminUser);

        return materialMapper.websitPurchaseApplyPage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }

    public WebsitMPurchaseBean detail(String purchaseId) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        WebsitMPurchaseBean bean = new WebsitMPurchaseBean();
        WebsitPurchase purchase = websitPurchaseService.getById(purchaseId);
        BeanUtils.copyProperties(purchase, bean);
        bean.setImageUrl(purchase.getImageUrl());
        String companyId = Objects.isNull(adminUser.getAdminCompanyWechat()) ? null : adminUser.getAdminCompanyWechat().getCompanyWechatId();
        List<WebsitMPurchaseItemBean> list = websitPurchaseItemService.lambdaQuery()
                .eq(StringUtils.isNotBlank(companyId), WebsitPurchaseItem::getCompanyWechatId, companyId)
                .eq(WebsitPurchaseItem::getPurchaseId, purchaseId)
                .list()
                .stream()
                .map(v -> {
                    WebsitMPurchaseItemBean item = new WebsitMPurchaseItemBean();
                    BeanUtils.copyProperties(v, item);
                    return item;
                }).collect(Collectors.toList());
        bean.setItems(list);

        return bean;
    }

    @Transactional
    public void add(WebsitMPurchaseBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁用操作");
        }

        bean.setCompanyWechatId(adminUser.getAdminCompanyWechat().getCompanyWechatId());
        bean.setCompanyWechatName(adminUser.getAdminCompanyWechat().getCompanyName());
        bean.setGoodsType(WebsitGoodsTypeEnum.M.getKey());
        bean.setFlag(MaterialFlagEnum.SAVE.getKey());
        bean.setTotalAmount(BigDecimal.ZERO);

        // 检查参数值
        this.validApplyParams(bean);

        WebsitPurchase purchase = new WebsitPurchase();
        BeanUtils.copyProperties(bean, purchase);

        purchase.insert();

        List<WebsitPurchaseItem> itemList = new ArrayList<>();
        for (WebsitMPurchaseItemBean beanItem : bean.getItems()) {
            WebsitPurchaseItem item = new WebsitPurchaseItem();
            BeanUtils.copyProperties(beanItem, item);
            item.setPurchaseId(purchase.getPurchaseId())
                    .setCompanyWechatId(bean.getCompanyWechatId())
                    .setWebsitId(bean.getWebsitId())
                    .setWebsitName(bean.getWebsitName())
                    .setGoodsType(WebsitGoodsTypeEnum.M.getKey());
            itemList.add(item);
        }

        websitPurchaseItemService.saveBatch(itemList);
    }

    public void edit(WebsitMPurchaseBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        bean.setGoodsType(WebsitGoodsTypeEnum.M.getKey());
        bean.setFlag(MaterialFlagEnum.SAVE.getKey());
        bean.setTotalAmount(BigDecimal.ZERO);

        final WebsitPurchase oldPurchase = websitPurchaseService.getById(bean.getPurchaseId());

        if (Objects.isNull(oldPurchase)) {
            throw new RemoteServiceException("单据不存在");
        }

        // 检查参数值
        this.validApplyParams(bean);

        WebsitPurchase purchase = new WebsitPurchase();
        BeanUtils.copyProperties(bean, purchase);
        purchase.setCreateBy(oldPurchase.getCreateBy())
                .setCreateTime(oldPurchase.getCreateTime());

        purchase.updateById();

        List<WebsitPurchaseItem> itemList = new ArrayList<>();
        websitPurchaseItemService.lambdaUpdate()
                .eq(WebsitPurchaseItem::getPurchaseId, bean.getPurchaseId())
                .remove();
        for (WebsitMPurchaseItemBean beanItem : bean.getItems()) {
            WebsitPurchaseItem item = new WebsitPurchaseItem();
            BeanUtils.copyProperties(beanItem, item);
            item.setPurchaseId(purchase.getPurchaseId())
                    .setCompanyWechatId(bean.getCompanyWechatId())
                    .setWebsitId(bean.getWebsitId())
                    .setWebsitName(bean.getWebsitName())
                    .setGoodsType(WebsitGoodsTypeEnum.M.getKey());
            itemList.add(item);
        }

        websitPurchaseItemService.saveBatch(itemList);
    }

    private void validApplyParams(WebsitMPurchaseBean bean) {
        if (StringUtils.isBlank(bean.getWebsitId()) || StringUtils.isBlank(bean.getWebsitName())) {
            throw new RemoteServiceException("请选择网点");
        }
        if (StringUtils.isBlank(bean.getVenderId()) || StringUtils.isBlank(bean.getVenderName())) {
            throw new RemoteServiceException("请选择供应商");
        }
        if (CollectionUtil.isEmpty(bean.getItems())) {
            throw new RemoteServiceException("请先添加明细");
        }

        for (int i = 0; i < bean.getItems().size(); i++) {
            WebsitMPurchaseItemBean itemBean = bean.getItems().get(i);
            String preStr = "第" + (i+1) + "行, ";
            if (StringUtils.isBlank(itemBean.getGoodsId()) || StringUtils.isBlank(itemBean.getGoodsName())) {
                throw new RemoteServiceException(preStr + "辅材编号不能为空");
            }
            if (Objects.isNull(itemBean.getApplyCost())) {
                throw new RemoteServiceException(preStr + "预估进价不能为空");
            }
            if (Objects.isNull(itemBean.getApplyQty()) || itemBean.getApplyQty().compareTo(BigDecimal.ZERO) <= 0) {
                throw new RemoteServiceException(preStr + "申请数量不能为空或少于等于0");
            }
        }

        // 检查明细重复辅材编号
        Map<String, List<WebsitMPurchaseItemBean>> goodsGroup = bean.getItems().stream().collect(Collectors.groupingBy(WebsitMPurchaseItemBean::getGoodsId));
        for (Map.Entry<String, List<WebsitMPurchaseItemBean>> entry : goodsGroup.entrySet()) {
            if (entry.getValue().size() > 1) {
                throw new RemoteServiceException("明细有重复的辅材编号 " + entry.getKey());
            }
        }

        // 获取供应商商品记录
        List<WebsitVenderGoodsRelaVO> relaList = this.queryVenderGoods(bean);
        final Map<String, WebsitVenderGoodsRelaVO> relaMap = relaList.stream()
                .collect(Collectors.toMap(WebsitVenderGoodsRelaVO::getGoodsId, Function.identity()));

        // 校验供应商商品
        this.validVendorGoods(bean, relaMap);
    }

    private void validVendorGoods(WebsitMPurchaseBean bean, Map<String, WebsitVenderGoodsRelaVO> relaMap) {
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (int i = 0; i < bean.getItems().size(); i++) {
            WebsitMPurchaseItemBean itemBean = bean.getItems().get(i);
            String preStr = "第" + (i+1) + "行, ";
            final WebsitVenderGoodsRelaVO relaGoods = relaMap.get(itemBean.getGoodsId());
            if (Objects.isNull(relaGoods)) {
                throw new RemoteServiceException(preStr + "供应商辅材不存在或无效");
            }
            if (StrUtil.equals(relaGoods.getStatus().getKey(), StateEnum.OFF.getKey())) {
                throw new RemoteServiceException(preStr + "供应商辅材资料无效");
            }
            if (bean.getFlag().equals(MaterialFlagEnum.SAVE.getKey())) {
                // 检查进价范围值
                if (Objects.nonNull(relaGoods.getCostRangeMini())
                        && relaGoods.getCostRangeMini().compareTo(BigDecimal.ZERO) > 0
                        && itemBean.getApplyCost().compareTo(relaGoods.getCostRangeMini()) < 0) {
                    throw new RemoteServiceException(preStr + "不能低于辅材资料最小进价范围值" + relaGoods.getCostRangeMini());
                }
                if (Objects.nonNull(relaGoods.getCostRangeMax())
                        && relaGoods.getCostRangeMax().compareTo(BigDecimal.ZERO) > 0
                        && itemBean.getApplyCost().compareTo(relaGoods.getCostRangeMax()) > 0) {
                    throw new RemoteServiceException(preStr + "不能高于辅材资料最大进价范围值" + relaGoods.getCostRangeMax());
                }
                // 申请进价*申请数量=申请进价金额
                itemBean.setApplyCostValue(itemBean.getApplyCost().multiply(itemBean.getApplyQty()).setScale(2, BigDecimal.ROUND_DOWN));
                itemBean.setCheckQty(itemBean.getApplyQty());
                itemBean.setGoodsCode(relaGoods.getGoodsCode());
                itemBean.setGoodsSpecification(relaGoods.getGoodsSpecification());
                itemBean.setGoodsStockUnit(relaGoods.getGoodsStockUnit());
                itemBean.setParentCategoryId(relaGoods.getParentCategoryId());
                itemBean.setParentCategoryName(relaGoods.getParentCategoryName());
                itemBean.setGoodsCategoryId(relaGoods.getGoodsCategoryId());
                itemBean.setGoodsCategoryName(relaGoods.getCategoryName());
                totalAmount = totalAmount.add(itemBean.getApplyCostValue());
            } else if (bean.getFlag().equals(MaterialFlagEnum.SUBMIT.getKey())) {
                // 检查进价范围值
                if (Objects.nonNull(relaGoods.getCostRangeMini())
                        && relaGoods.getCostRangeMini().compareTo(BigDecimal.ZERO) > 0
                        && itemBean.getCost().compareTo(relaGoods.getCostRangeMini()) < 0) {
                    throw new RemoteServiceException(preStr + "不能低于辅材资料最小进价范围值" + relaGoods.getCostRangeMini());
                }
                if (Objects.nonNull(relaGoods.getCostRangeMax())
                        && relaGoods.getCostRangeMax().compareTo(BigDecimal.ZERO) > 0
                        && itemBean.getCost().compareTo(relaGoods.getCostRangeMax()) > 0) {
                    throw new RemoteServiceException(preStr + "不能高于辅材资料最大进价范围值" + relaGoods.getCostRangeMax());
                }
                itemBean.setInStockCost(itemBean.getCost());
                itemBean.setInStockQty(itemBean.getRecQty().add(itemBean.getRecGiftQty()));
                itemBean.setCostValue(itemBean.getRecQty().multiply(itemBean.getCost()).setScale(2, BigDecimal.ROUND_DOWN));
                totalAmount = totalAmount.add(itemBean.getCostValue());
            }

        }
        bean.setTotalAmount(totalAmount);
    }

    private List<WebsitVenderGoodsRelaVO> queryVenderGoods(WebsitMPurchaseBean bean) {
        ZfireParamBean zfireParamBean = new ZfireParamBean();
        zfireParamBean.setPageNum(1);
        zfireParamBean.setPageSize(-1);
        zfireParamBean.setParams(new ArrayList<>());
        QueryParamBean paramBean = new QueryParamBean();
        paramBean.setParam("a.vender_id").setCompare("=").setValue(bean.getVenderId());
        QueryParamBean paramBean2 = new QueryParamBean();
        paramBean2.setParam("a.rela_status").setCompare("=").setValue(StateEnum.ON.getKey());
        zfireParamBean.getParams().add(paramBean);
        zfireParamBean.getParams().add(paramBean2);

        final IPage<WebsitVenderGoodsRelaVO> page = venderGoodsLogic.ralaPage(zfireParamBean);
        if (CollectionUtil.isEmpty(page.getRecords())) {
            throw new RemoteServiceException(bean.getVenderName() + "供应商没有可供应的辅材记录");
        }
        return page.getRecords();
    }

    @Transactional
    public void batchDel(List<String> purchaseIds) {
        if (CollectionUtil.isEmpty(purchaseIds)) {
            throw new RemoteServiceException("请选择记录");
        }

        websitPurchaseService.lambdaUpdate()
                .in(WebsitPurchase::getPurchaseId, purchaseIds)
                .remove();

        websitPurchaseItemService.lambdaUpdate()
                .in(WebsitPurchaseItem::getPurchaseId, purchaseIds)
                .remove();
    }

    @Transactional
    public void revoke(String purchaseId, int position) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (!websitPurchaseService.lambdaUpdate()
                .eq(WebsitPurchase::getPurchaseId, purchaseId)
                .eq(WebsitPurchase::getFlag, MaterialFlagEnum.SUBMIT.getKey())
                .eq(WebsitPurchase::getIsRecheck, IsYesNoEnum.NO.getKey())
                .set(WebsitPurchase::getFlag, MaterialFlagEnum.SAVE.getKey())
                .set(position == 2, WebsitPurchase::getCheckBy, adminUser.getNickName())
                .set(position == 2, WebsitPurchase::getCheckTime, DateUtil.date())
                .update()) {
            throw new RemoteServiceException("撤消失败，单据状态已发生变化，非“提交待核实”");
        }
    }

    @Transactional
    public void submit(String purchaseId) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        WebsitPurchase purchase = websitPurchaseService.getById(purchaseId);

        if (Objects.isNull(purchase) || !StrUtil.equals(purchase.getFlag(), MaterialFlagEnum.SAVE.getKey())) {
            throw new RemoteServiceException("单据不存在或状态已发生变化");
        }

        final WebsitVender vender = websitVenderService.getById(purchase.getVenderId());

        // 供应商为自动审核时
        if (StrUtil.equals(vender.getIsAuto(), IsYesNoEnum.YES.getKey())) {
            purchase.setIsRecheck(IsYesNoEnum.YES.getKey())
                    .setCheckBy(adminUser.getNickName())
                    .setCheckTime(DateUtil.date());
        }

        purchase.setFlag(MaterialFlagEnum.SUBMIT.getKey())
                .setSubmitBy(adminUser.getNickName())
                .setSubmitTime(DateUtil.date())
                .updateById();
    }

    public IPage<WebsitPurchaseCheckVO> checkPage(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (CollectionUtil.isEmpty(zfireParamBean.getParams())) {
            zfireParamBean.setParams(new ArrayList<>());
        }

        if (adminUser.getIsVender()) {
            QueryParamBean paramBean = new QueryParamBean();
            paramBean.setParam("a.vender_id").setCompare("=").setValue(adminUser.getVenderId());
            zfireParamBean.getParams().add(paramBean);
        }
        FieldUtils.materialParam(zfireParamBean, WebsitPurchaseCheckVO.class, adminUser);

        return materialMapper.websitPurchaseCheckPage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);

    }

    @Transactional
    public void checkUpdate(WebsitMPurchaseBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        WebsitPurchase purchase = websitPurchaseService.getById(bean.getPurchaseId());
        purchase.setCheckRemark(bean.getCheckRemark())
                .updateById();

        List<WebsitPurchaseItem> items = websitPurchaseItemService.lambdaQuery()
                .eq(WebsitPurchaseItem::getPurchaseId, purchase.getPurchaseId())
                .list();

        final Map<String, BigDecimal> checkItemMap = bean.getItems().stream()
                .collect(Collectors.toMap(WebsitMPurchaseItemBean::getGoodsId, WebsitMPurchaseItemBean::getCheckQty));

        for (WebsitPurchaseItem item : items) {
            BigDecimal checkQty = checkItemMap.get(item.getGoodsId());
            if (Objects.nonNull(checkQty)) {
                item.setCheckQty(checkQty);
            }
        }

        websitPurchaseItemService.saveOrUpdateBatch(items);
    }

    @Transactional
    public void verify(String purchaseId) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        websitPurchaseService.lambdaUpdate()
                .eq(WebsitPurchase::getPurchaseId, purchaseId)
                .eq(adminUser.getIsVender(), WebsitPurchase::getVenderId, adminUser.getVenderId())
                .eq(WebsitPurchase::getFlag, MaterialFlagEnum.SUBMIT.getKey())
                .eq(WebsitPurchase::getIsRecheck, IsYesNoEnum.NO.getKey())
                .set(WebsitPurchase::getIsRecheck, IsYesNoEnum.YES.getKey())
                .set(WebsitPurchase::getCheckBy, adminUser.getNickName())
                .set(WebsitPurchase::getCheckTime, DateUtil.date())
                .update();
    }

    @Transactional
    public void orderUpdate(WebsitMPurchaseBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        WebsitPurchase purchase = websitPurchaseService.getById(bean.getPurchaseId());

        if (Objects.isNull(purchase)) {
            throw new RemoteServiceException("单据不存在或状态已发生变化");
        }

        if (StringUtils.isBlank(bean.getImageUrl())) {
            throw new RemoteServiceException("请添加附件图片");
        }

        if (Objects.isNull(bean.getPurchaseTime())) {
            throw new RemoteServiceException("请选择采购日期");
        }

        final Storage storage = storageService.lambdaQuery()
                .eq(Storage::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(Storage::getWebsitId, purchase.getWebsitId())
                .eq(Storage::getIsDefault, IsEnum.Y.getValue())
                .one();

        List<WebsitPurchaseItem> purchaseItems = websitPurchaseItemService.lambdaQuery()
                .eq(WebsitPurchaseItem::getPurchaseId, purchase.getPurchaseId())
                .list();

        if (StringUtils.isBlank(bean.getStorageId())) {
            bean.setStorageId(storage.getStorageId());
            bean.setStorageName(storage.getStorageName());
        }

        bean.setFlag(purchase.getFlag());
        this.convertOrderParams(bean, purchase, purchaseItems);

        purchase.updateById();
        websitPurchaseItemService.saveOrUpdateBatch(purchaseItems);
    }

    @Transactional
    public void orderRevoke(String purchaseId) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        websitPurchaseService.lambdaUpdate()
                .eq(WebsitPurchase::getPurchaseId, purchaseId)
                .eq(WebsitPurchase::getFlag, MaterialFlagEnum.SUBMIT.getKey())
                .eq(WebsitPurchase::getIsRecheck, IsYesNoEnum.YES.getKey())
                .set(WebsitPurchase::getUpdateBy, adminUser.getNickName())
                .set(WebsitPurchase::getUpdateTime, DateUtil.date())
                .set(WebsitPurchase::getFlag, MaterialFlagEnum.CANCEL.getKey())
                .update();
    }

    private void convertOrderParams(WebsitMPurchaseBean bean, WebsitPurchase purchase, List<WebsitPurchaseItem> purchaseItems) {
        BigDecimal totalAmount = BigDecimal.ZERO;
        // 获取供应商商品记录
        List<WebsitVenderGoodsRelaVO> relaList = this.queryVenderGoods(bean);
        final Map<String, WebsitVenderGoodsRelaVO> relaMap = relaList.stream()
                .collect(Collectors.toMap(WebsitVenderGoodsRelaVO::getGoodsId, Function.identity()));

        // 校验供应商商品
        this.validVendorGoods(bean, relaMap);

        final Map<String, WebsitMPurchaseItemBean> itemBeanMap = bean.getItems().stream()
                .collect(Collectors.toMap(WebsitMPurchaseItemBean::getGoodsId, Function.identity()));

        for (WebsitPurchaseItem item : purchaseItems) {
            final WebsitMPurchaseItemBean itemBean = itemBeanMap.get(item.getGoodsId());
            if (Objects.nonNull(itemBean)) {
                item.setRecQty(itemBean.getRecQty())
                        .setRecGiftQty(itemBean.getRecGiftQty())
                        .setCost(itemBean.getCost())
                        .setCostValue(itemBean.getCostValue())
                        .setInStockCost(itemBean.getInStockCost())
                        .setInStockQty(itemBean.getInStockQty());
            }
            totalAmount = totalAmount.add(item.getCostValue());
        }

        purchase.setImageUrl(bean.getImageUrl())
                .setTotalAmount(totalAmount)
                .setPurchaseTime(bean.getPurchaseTime())
                .setConfirmRemark(bean.getConfirmRemark());
    }

    @Transactional
    public void orderConfirm(String purchaseId) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        WebsitPurchase purchase = websitPurchaseService.getById(purchaseId);
        if (Objects.isNull(purchase)
                || !(StrUtil.equals(purchase.getFlag(), MaterialFlagEnum.SUBMIT.getKey())
                && StrUtil.equals(purchase.getIsRecheck(), IsYesNoEnum.YES.getKey()))) {
            throw new RemoteServiceException("单据不存在或状态已发生变化");
        }

        final List<WebsitPurchaseItem> purchaseItems = websitPurchaseItemService.lambdaQuery()
                .eq(WebsitPurchaseItem::getPurchaseId, purchase.getPurchaseId())
                .list();

        final Storage storage = storageService.lambdaQuery()
                .eq(Storage::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(Storage::getWebsitId, purchase.getWebsitId())
                .eq(Storage::getIsDefault, IsEnum.Y.getValue())
                .one();

        this.checkPurchaseItemsCount(purchase, purchaseItems);

        if (StringUtils.isBlank(purchase.getStorageId())) {
            purchase.setStorageId(storage.getStorageId());
            purchase.setStorageName(storage.getStorageName());
        }

        purchase.setFlag(MaterialFlagEnum.OK.getKey())
                .setConfirmBy(adminUser.getNickName())
                .setConfirmTime(DateUtil.date())
                .updateById();

        // 库存处理
        webitPurchaseStockLogic.newInStock(purchase, purchaseItems, "采购入库");

        // 没有入库过的辅材增加售价为0记录
        if (purchase.getGoodsType().equals(WebsitGoodsTypeEnum.M.getKey())) {
            List<WebsitGoods> goodsList = websitGoodsService.lambdaQuery()
                    .eq(WebsitGoods::getCompanyWechatId, purchase.getCompanyWechatId())
                    .in(WebsitGoods::getGoodsId, purchaseItems.stream()
                            .map(WebsitPurchaseItem::getGoodsId)
                            .collect(Collectors.toList()))
                    .list();

            List<WebsitGoodsPrice> priceList = websitGoodsPriceService.lambdaQuery()
                    .eq(WebsitGoodsPrice::getCompanyWechatId, purchase.getCompanyWechatId())
                    .eq(WebsitGoodsPrice::getWebsitId, purchase.getWebsitId())
                    .in(WebsitGoodsPrice::getGoodsId, purchaseItems.stream()
                            .map(WebsitPurchaseItem::getGoodsId)
                            .collect(Collectors.toList()))
                    .list();
            // 数量不相等
            if (priceList.size() != purchaseItems.size()) {
                List<WebsitGoodsPrice> createPriceList = new ArrayList<>();

                Map<String, WebsitGoodsPrice> goodsPriceMap = priceList.stream()
                        .collect(Collectors.toMap(WebsitGoodsPrice::getGoodsId, Function.identity(), (key1,key2) -> key2));

                Map<String, BigDecimal> goodsMap = goodsList.stream()
                        .collect(Collectors.toMap(WebsitGoods::getGoodsId, WebsitGoods::getMarketPrice, (key1,key2) -> key2));

                for (WebsitPurchaseItem item : purchaseItems) {
                    if (!goodsPriceMap.containsKey(item.getGoodsId())) {
                        WebsitGoodsPrice price = new WebsitGoodsPrice();
                        BigDecimal salesPrice = goodsMap.getOrDefault(item.getGoodsId(), BigDecimal.ZERO);
                        price.setCompanyWechatId(item.getCompanyWechatId());
                        price.setWebsitId(item.getWebsitId());
                        price.setWebsitName(item.getWebsitName());
                        price.setGoodsType(item.getGoodsType());
                        price.setGoodsId(item.getGoodsId());
                        price.setPrice(salesPrice);
                        price.setSheetId("");
                        price.setRemark(purchase.getRemark());

                        createPriceList.add(price);
                    }
                }

                if (CollectionUtil.isNotEmpty(createPriceList)) {
                    websitGoodsPriceService.saveBatch(createPriceList);
                }
            }
        }
    }

    private void checkPurchaseItemsCount(WebsitPurchase purchase, List<WebsitPurchaseItem> purchaseItems) {
        BigDecimal zero = new BigDecimal("0");
        List<WebsitPurchaseItem> zeroItems = purchaseItems.stream()
                .filter(item -> item.getInStockQty().compareTo(zero) == 0)
                .collect(Collectors.toList());

        List<WebsitPurchaseItem> purchaseItemList = purchaseItems.stream()
                .filter(item -> item.getRecQty().compareTo(item.getApplyQty()) > 0)
                .collect(Collectors.toList());

        if (zeroItems.size() == purchaseItems.size()) {
            throw new RemoteServiceException("辅材验收数量为0，审核失败");
        }

        if (CollectionUtil.isNotEmpty(purchaseItemList)) {
            throw new RemoteServiceException(purchaseItemList.get(0).getGoodsName() + " 辅材验收数量不能大于订货数量，审核失败");
        }

        BigDecimal rateQty = new BigDecimal("5");
        for (WebsitPurchaseItem item : purchaseItems) {
            BigDecimal resultRateQty = Optional.ofNullable(item.getRecGiftQty()).orElse(BigDecimal.ZERO)
                    .divide(item.getApplyQty(), 4, BigDecimal.ROUND_HALF_UP)
                    .multiply(new BigDecimal("100"));
            if (resultRateQty.compareTo(rateQty) > 0) {
                throw new RemoteServiceException(item.getGoodsName() + "的赠品数量不能超过订货数量的5%，审核失败");
            }
        }
    }
}
