package com.gree.mall.manager.logic.goods;

import cn.hutool.core.bean.BeanUtil;
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.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.goods.*;
import com.gree.mall.manager.commonmapper.CommonMapper;
import com.gree.mall.manager.enums.ExamineStatusEnum;
import com.gree.mall.manager.enums.IsYesNoEnum;
import com.gree.mall.manager.enums.base.BaseEnum;
import com.gree.mall.manager.enums.material.GoodsMaterialTypeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.excel.ExcelUtils;
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 org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service
public class GoodsPurchaseRetLogic {

    private final CommonLogic commonLogic;
    private final CommonMapper commonMapper;
    private final GoodsPurchaseRetService goodsPurchaseRetService;
    private final GoodsPurchaseRetItemService goodsPurchaseRetItemService;
    private final GoodsPurchaseRetCodeService goodsPurchaseRetCodeService;
    private final GoodsPurchaseService goodsPurchaseService;
    private final GoodsPurchaseItemService goodsPurchaseItemService;
    private final GoodsPurchaseCodeService goodsPurchaseCodeService;
    private final GoodsMaterialService goodsMaterialService;
    private final GoodsMaterialItemService goodsMaterialItemService;
    private final GoodsCodeService goodsCodeService;
    private final JxGoodsLogic jxGoodsLogic;
    private final GoodsMaterialStorageService goodsMaterialStorageService;

    public IPage<GoodsPurchaseRetVO> page(ZfireParamBean zfireParamBean) {
        FieldUtils.supplyParam(zfireParamBean, GoodsPurchaseRetVO.class, commonLogic.getAdminUser());
        IPage<GoodsPurchaseRetVO> page = commonMapper.goodsPurchaseRetList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);

        return page;
    }

    public IPage<GoodsPurchaseRetItemVO> itemPage(ZfireParamBean zfireParamBean) {
        FieldUtils.supplyParam(zfireParamBean, GoodsPurchaseRetItemVO.class, commonLogic.getAdminUser());
        IPage<GoodsPurchaseRetItemVO> page = commonMapper.goodsPurchaseRetItemList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);

        return page;
    }

    public IPage<GoodsPurchaseRetCodeVO> codePage(ZfireParamBean zfireParamBean) {
        FieldUtils.supplyParam(zfireParamBean, GoodsPurchaseRetCodeVO.class, commonLogic.getAdminUser());
        IPage<GoodsPurchaseRetCodeVO> page = commonMapper.goodsPurchaseRetCodeList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);

        return page;
    }

    public GoodsPurchaseRetBean detail(String id) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String companyId = null;
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            companyId = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }
        GoodsPurchaseRetBean bean = new GoodsPurchaseRetBean();
        GoodsPurchaseRet purchaseRet = goodsPurchaseRetService.lambdaQuery()
                .eq(StringUtils.isNotBlank(companyId), GoodsPurchaseRet::getCompanyWechatId, companyId)
                .eq(GoodsPurchaseRet::getId, id)
                .one();

        if (Objects.nonNull(purchaseRet)) {
            List<GoodsPurchaseRetItem> items = goodsPurchaseRetItemService.lambdaQuery()
                    .eq(GoodsPurchaseRetItem::getGoodsPurchaseRetId, purchaseRet.getId())
                    .list();
            List<GoodsPurchaseRetItemBean> itemBeans = BeanUtil.copyToList(items, GoodsPurchaseRetItemBean.class);
            bean.setItems(itemBeans);

            BeanUtils.copyProperties(purchaseRet, bean);
        }

        return bean;
    }

    public GoodsPurchaseBean getPurchaseDetail(String purchaseId) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String companyId = null;
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            companyId = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }
        GoodsPurchaseBean bean = new GoodsPurchaseBean();
        GoodsPurchase purchase = goodsPurchaseService.lambdaQuery()
                .eq(StringUtils.isNotBlank(companyId), GoodsPurchase::getCompanyWechatId, companyId)
                .eq(GoodsPurchase::getId, purchaseId)
                .one();

        if (Objects.nonNull(purchase)) {
            List<GoodsPurchaseItem> items = goodsPurchaseItemService.lambdaQuery()
                    .eq(GoodsPurchaseItem::getGoodsPurchaseId, purchase.getId())
                    .list();

            List<GoodsMaterial> materialList = goodsMaterialService.lambdaQuery()
                    .in(GoodsMaterial::getId, items.stream()
                            .map(GoodsPurchaseItem::getGoodsMaterialId).collect(Collectors.toList()))
                    .list();

            Map<String, Integer> materialMap = materialList.stream()
                    .collect(Collectors.toMap(GoodsMaterial::getId, GoodsMaterial::getStockQty));

            List<GoodsPurchaseItemBean> itemBeans = BeanUtil.copyToList(items, GoodsPurchaseItemBean.class);

            for (GoodsPurchaseItemBean itemBean : itemBeans) {
                if (materialMap.containsKey(itemBean.getGoodsMaterialId())) {
                    itemBean.setStockQty(materialMap.get(itemBean.getGoodsMaterialId()));
                }
            }

            bean.setItems(itemBeans);

            BeanUtils.copyProperties(purchase, bean);
        }

        return bean;
    }

    @Transactional(rollbackFor = Exception.class)
    public GoodsPurchaseRetBean add(GoodsPurchaseRetBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            bean.setCompanyWechatId(adminUser.getAdminCompanyWechat().getCompanyWechatId());
            bean.setCompanyWechatName(adminUser.getAdminCompanyWechat().getCompanyName());
        }

        if (StringUtils.isBlank(bean.getVenderId())) {
            throw new RemoteServiceException("请选择供应商");
        }

        if (StringUtils.isBlank(bean.getGoodsPurchaseId())) {
            throw new RemoteServiceException("请选择商品采购入库单");
        }

        GoodsPurchase goodsPurchase = goodsPurchaseService.lambdaQuery()
                .eq(GoodsPurchase::getId, bean.getGoodsPurchaseId())
                .eq(GoodsPurchase::getCompanyWechatId, bean.getCompanyWechatId())
                .eq(GoodsPurchase::getStatus, ExamineStatusEnum.OK.getKey())
                .one();

        if (Objects.isNull(goodsPurchase)) {
            throw new RemoteServiceException("商品采购入库单不存在或非\"审核\"状态");
        }

        // 检查采购入库单号只允许在一张未处理退货单上使用
        GoodsPurchaseRet existRet = goodsPurchaseRetService.lambdaQuery()
                .eq(GoodsPurchaseRet::getGoodsPurchaseId, bean.getGoodsPurchaseId())
                .in(GoodsPurchaseRet::getStatus, ExamineStatusEnum.SAVE.getKey(), ExamineStatusEnum.WAIT.getKey())
                .last("limit 1")
                .one();

        if (Objects.nonNull(existRet)) {
            throw new RemoteServiceException("发现已有一张待处理的退货单: \"" + existRet.getId() + "\"引入, 请先处理后再新增！");
        }

        if (CollectionUtil.isEmpty(bean.getItems())) {
            throw new RemoteServiceException("商品信息不能为空");
        }

        bean.setId(IdWorker.getIdStr())
                .setJoinCode(goodsPurchase.getJoinCode())
                .setStatus(ExamineStatusEnum.SAVE.getKey());

        // 检查商品信息唯一
        checkItemUnique(bean);

        List<GoodsPurchaseRetItem> items = this.handleItemMethod(bean.getItems(), bean.getId(), bean.getGoodsPurchaseId(), true);


        goodsPurchaseRetItemService.saveBatch(items);

        Integer totalQty = items.stream().mapToInt(GoodsPurchaseRetItem::getRetQty).sum();
        double totalAmount = items.stream().mapToDouble(v -> v.getRetAmount().doubleValue()).sum();

        bean.setTotalQty(totalQty)
                .setTotalAmount(BigDecimal.valueOf(totalAmount))
                .insert();

        return bean;
    }

    private List<GoodsPurchaseRetItem> handleItemMethod(List<GoodsPurchaseRetItemBean> itemBeans, String purchaseRetId, String purchaseId, boolean initImportQty) {
        List<GoodsPurchaseRetItem> items = new ArrayList<>();
        // 入库单商品信息
        List<GoodsPurchaseItem> goodsPurchaseItemList = goodsPurchaseItemService.lambdaQuery()
                .eq(GoodsPurchaseItem::getGoodsPurchaseId, purchaseId)
                .in(GoodsPurchaseItem::getGoodsMaterialId, itemBeans.stream()
                        .map(GoodsPurchaseRetItemBean::getGoodsMaterialId)
                        .filter(StringUtils::isNotBlank)
                        .collect(Collectors.toList()))
                .list();

        Map<String, GoodsPurchaseItem> materialMap = goodsPurchaseItemList.stream()
                .collect(Collectors.toMap(GoodsPurchaseItem::getGoodsMaterialId, Function.identity()));

        // 商品子物料信息
        List<GoodsMaterialItem> goodsMaterialItems = goodsMaterialItemService.lambdaQuery()
                .in(GoodsMaterialItem::getGoodsMaterialId, materialMap.keySet())
                .list();

        Map<String, List<GoodsMaterialItem>> materialItemMap = goodsMaterialItems.stream()
                .collect(Collectors.groupingBy(GoodsMaterialItem::getGoodsMaterialId));

        for (GoodsPurchaseRetItemBean itemBean : itemBeans) {
            if (StringUtils.isBlank(itemBean.getGoodsMaterialId())) {
                throw new RemoteServiceException("第" + itemBean.getIndex() + "行, 请选商品");
            }
            if (Objects.isNull(itemBean.getQty()) || itemBean.getRetQty() <= 0) {
                throw new RemoteServiceException("第" + itemBean.getIndex() + "行, 请填写有效数量");
            }

            if (Objects.isNull(itemBean.getPrice()) || itemBean.getPrice().compareTo(BigDecimal.ZERO) < 0) {
                throw new RemoteServiceException("第" + itemBean.getIndex() + "行, 请填写有效采购价格");
            }

            GoodsPurchaseItem goodsMaterial = materialMap.get(itemBean.getGoodsMaterialId());
            if (Objects.isNull(goodsMaterial)) {
                throw new RemoteServiceException("第" + itemBean.getIndex() + "行, 商品信息不存在");
            }

            if (itemBean.getRetQty() > goodsMaterial.getOrigQty()) {
                throw new RemoteServiceException("第" + itemBean.getIndex() + "行, 商品退货数量不能大于剩余采购数量");
            }

            List<GoodsMaterialItem> materialItems = materialItemMap.get(goodsMaterial.getGoodsMaterialId());

            int innerQty = 0;
            int outQty = 0;
            int partsQty = 0;

            for (GoodsMaterialItem materialItem : materialItems) {
                if (materialItem.getType().equals(GoodsMaterialTypeEnum.INSIDE.getKey())) {
                    innerQty = innerQty + materialItem.getQty() * itemBean.getRetQty();
                } else if (materialItem.getType().equals(GoodsMaterialTypeEnum.OUT.getKey())) {
                    outQty = outQty + materialItem.getQty() * itemBean.getRetQty();
                } else {
                    partsQty = partsQty + materialItem.getQty() * itemBean.getRetQty();
                }
            }

            itemBean.setGoodsPurchaseRetId(purchaseRetId)
                    .setBrandId(goodsMaterial.getBrandId())
                    .setBrandName(goodsMaterial.getBrandName())
                    .setMainId(goodsMaterial.getMainId())
                    .setMainName(goodsMaterial.getMainName())
                    .setSmallId(goodsMaterial.getSmallId())
                    .setSmallName(goodsMaterial.getSmallName())
                    .setGoodsMaterialName(goodsMaterial.getGoodsMaterialName())
                    .setSeriesName(goodsMaterial.getSeriesName())
                    .setSpecsName(goodsMaterial.getSpecsName())
                    .setUnit(goodsMaterial.getUnit())
                    .setInsideQty(goodsMaterial.getInsideQty())
                    .setOutQty(goodsMaterial.getOutQty())
                    .setPartsQty(goodsMaterial.getPartsQty())
                    .setRetInsideQty(innerQty)
                    .setRetOutQty(outQty)
                    .setRetPartsQty(partsQty)
                    .setAmount(goodsMaterial.getAmount())
                    .setRetAmount(itemBean.getPrice().multiply(BigDecimal.valueOf(itemBean.getRetQty())));

            if (initImportQty) {
                itemBean.setInsideCodeQty(0)
                        .setOutCodeQty(0)
                        .setPartsCodeQty(0);
            }

            items.add(itemBean);
        }
        return items;
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(GoodsPurchaseRetBean bean, AdminUserCom adminUser) {
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            bean.setCompanyWechatId(adminUser.getAdminCompanyWechat().getCompanyWechatId());
            bean.setCompanyWechatName(adminUser.getAdminCompanyWechat().getCompanyName());
        }

        GoodsPurchaseRet oldPurchase = goodsPurchaseRetService.lambdaQuery()
                .eq(GoodsPurchaseRet::getCompanyWechatId, bean.getCompanyWechatId())
                .eq(GoodsPurchaseRet::getId, bean.getId())
                .one();

        if (Objects.isNull(oldPurchase)) {
            throw new RemoteServiceException("商品采购退货单不存在");
        }

        if (!oldPurchase.getGoodsPurchaseId().equals(bean.getGoodsPurchaseId())) {
            throw new RemoteServiceException("\"编辑\"状态不能变更商品采购入库单号");
        }

        if (CollectionUtil.isEmpty(bean.getItems())) {
            throw new RemoteServiceException("商品信息不能为空");
        }

        // 检查商品信息唯一
        checkItemUnique(bean);

        // 处理商品明细
        List<GoodsPurchaseRetItem> handleAfterItems = new ArrayList<>();

        List<GoodsPurchaseRetItem> goodsPurchaseItemList = goodsPurchaseRetItemService.lambdaQuery()
                .eq(GoodsPurchaseRetItem::getGoodsPurchaseRetId, bean.getId())
                .list();

        Map<String, GoodsPurchaseRetItem> oldPurchaseItemMap = goodsPurchaseItemList.stream()
                .collect(Collectors.toMap(GoodsPurchaseRetItem::getGoodsMaterialId, Function.identity()));

        // 过滤出旧明细记录已删除记录
        List<String> beanItemList = bean.getItems().stream().map(GoodsPurchaseRetItemBean::getId)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toList());
        for (GoodsPurchaseRetItem purchaseItem : goodsPurchaseItemList) {
            List<String> itemIdList = new ArrayList<>();
            if (!beanItemList.contains(purchaseItem.getId())) {
                itemIdList.add(purchaseItem.getId());
            }
            goodsPurchaseRetItemService.lambdaUpdate()
                    .in(GoodsPurchaseRetItem::getId, itemIdList)
                    .remove();
            goodsPurchaseRetCodeService.lambdaUpdate()
                    .in(GoodsPurchaseRetCode::getGoodsPurchaseRetItemId, itemIdList)
                    .remove();
        }

        // 过滤出明细id不为空并且商品编号不一致的商品, 清空已变更商品子物料条码
        List<GoodsPurchaseRetItemBean> changeItemList = bean.getItems().stream()
                .filter(v -> StringUtils.isNotBlank(v.getId()) && !oldPurchaseItemMap.containsKey(v.getGoodsMaterialId()))
                .collect(Collectors.toList());

        if (CollectionUtil.isNotEmpty(changeItemList)) {
            // 按商品明细id清空已变更商品子物料条码
            goodsPurchaseRetCodeService.lambdaUpdate()
                    .eq(GoodsPurchaseRetCode::getGoodsPurchaseRetItemId, changeItemList.stream()
                            .map(GoodsPurchaseRetItemBean::getId)
                            .collect(Collectors.toList()))
                    .remove();

            // 重新设置商品明细内容
            handleAfterItems.addAll(this.handleItemMethod(changeItemList, oldPurchase.getId(), oldPurchase.getGoodsPurchaseId(), true));
        }

        // 过滤出明细id不为空并且商品编号一致的商品
        List<GoodsPurchaseRetItemBean> updateItemList = bean.getItems().stream()
                .filter(v -> StringUtils.isNotBlank(v.getId()) && oldPurchaseItemMap.containsKey(v.getGoodsMaterialId()))
                .collect(Collectors.toList());

        if (CollectionUtil.isNotEmpty(updateItemList)) {
            // 重新设置商品明细内容
            handleAfterItems.addAll(this.handleItemMethod(changeItemList, oldPurchase.getId(), oldPurchase.getGoodsPurchaseId(), false));
        }

        // 过滤出新增的商品
        List<GoodsPurchaseRetItemBean> addItemList = bean.getItems().stream()
                .filter(v -> StringUtils.isBlank(v.getId()))
                .collect(Collectors.toList());

        if (CollectionUtil.isNotEmpty(addItemList)) {
            // 添加商品明细内容
            handleAfterItems.addAll(this.handleItemMethod(changeItemList, oldPurchase.getId(), oldPurchase.getGoodsPurchaseId(), true));
        }

        goodsPurchaseRetItemService.saveOrUpdateBatch(handleAfterItems);

        Integer totalQty = handleAfterItems.stream().mapToInt(GoodsPurchaseRetItem::getRetQty).sum();
        double totalAmount = handleAfterItems.stream().mapToDouble(v -> v.getRetAmount().doubleValue()).sum();

        oldPurchase.setTotalQty(totalQty)
                .setTotalAmount(BigDecimal.valueOf(totalAmount))
                .setVenderId(oldPurchase.getVenderId())
                .setVenderName(oldPurchase.getVenderName())
                .setFileUrl(oldPurchase.getFileUrl())
                .setRemark(oldPurchase.getRemark())
                .updateById();
    }

    private void checkItemUnique(GoodsPurchaseRetBean bean) {
        Map<String, List<GoodsPurchaseRetItemBean>> materialGroup = bean.getItems().stream()
                .collect(Collectors.groupingBy(GoodsPurchaseRetItemBean::getGoodsMaterialId));

        for (Map.Entry<String, List<GoodsPurchaseRetItemBean>> entry : materialGroup.entrySet()) {
            if (entry.getValue().size() > 1) {
                throw new RemoteServiceException("发现重复的商品, 请检查!");
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void submit(String id) throws Exception {
        this.commonHandlePurchase(id, ExamineStatusEnum.WAIT);
    }

    private void commonHandlePurchase(String id, ExamineStatusEnum statusEnum) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        String companyId = null;
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            companyId = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }
        GoodsPurchaseRet purchase = goodsPurchaseRetService.lambdaQuery()
                .eq(GoodsPurchaseRet::getId, id)
                .eq(GoodsPurchaseRet::getCompanyWechatId, companyId)
                .one();

        if (Objects.isNull(purchase)) {
            throw new RemoteServiceException("单据不存在, 提交失败");
        }

        if (statusEnum.getKey().equals(ExamineStatusEnum.WAIT.getKey())
                && !purchase.getStatus().equals(ExamineStatusEnum.SAVE.getKey())) {
            throw new RemoteServiceException("当前单据: \"" +
                    BaseEnum.keyToEnumNotNull(ExamineStatusEnum.class, purchase.getStatus()).getRemark() + "\"状态, 提交失败");
        }

        if (!statusEnum.getKey().equals(ExamineStatusEnum.WAIT.getKey())
                && !purchase.getStatus().equals(ExamineStatusEnum.WAIT.getKey())) {
            throw new RemoteServiceException("当前单据: \"" +
                    BaseEnum.keyToEnumNotNull(ExamineStatusEnum.class, purchase.getStatus()).getRemark() + "\"状态, 审核失败");
        }

        /*
            检查商品子物料的条码数量是否对应
         */

        // 查询退货单商品明细
        List<GoodsPurchaseRetItem> purchaseItemList = goodsPurchaseRetItemService.lambdaQuery()
                .eq(GoodsPurchaseRetItem::getGoodsPurchaseRetId, id)
                .list();

        // 查出子物料信息
        List<GoodsMaterialItem> materialItemList = goodsMaterialItemService.lambdaQuery()
                .in(GoodsMaterialItem::getGoodsMaterialId, purchaseItemList.stream()
                        .map(GoodsPurchaseRetItem::getGoodsMaterialId)
                        .collect(Collectors.toList()))
                .list();

        Map<String, List<GoodsMaterialItem>> materialItemGroupMap = materialItemList.stream()
                .collect(Collectors.groupingBy(GoodsMaterialItem::getGoodsMaterialId));

        /*
            审核或提交时检查采购入库单商品和条码是否一致
         */

        // 查询入库单商品明细
        List<GoodsPurchaseItem> goodsPurchaseItemList = goodsPurchaseItemService.lambdaQuery()
                .eq(GoodsPurchaseItem::getGoodsPurchaseId, purchase.getGoodsPurchaseId())
                .list();
        Map<String, GoodsPurchaseItem> goodsPurchaseItemMap = goodsPurchaseItemList.stream()
                .collect(Collectors.toMap(GoodsPurchaseItem::getGoodsMaterialId, Function.identity()));

        // 查询入库单商品明细条码
        List<GoodsPurchaseCode> goodsPurchaseCodeList = goodsPurchaseCodeService.lambdaQuery()
                .eq(GoodsPurchaseCode::getGoodsPurchaseId, purchase.getGoodsPurchaseId())
                .list();
        Map<String, GoodsPurchaseCode> goodsPurchaseCodeMap = goodsPurchaseCodeList.stream()
                .collect(Collectors.toMap(v -> v.getGoodsMaterialId() + "-" + v.getGoodsMaterialItemId() + "-" + v.getCode(), Function.identity()));

        // 查询商品库存
        List<GoodsMaterial> goodsMaterialList = goodsMaterialService.lambdaQuery()
                .in(GoodsMaterial::getId, goodsPurchaseItemList.stream()
                        .map(GoodsPurchaseItem::getGoodsMaterialId)
                        .collect(Collectors.toList()))
                .list();

        Map<String, GoodsMaterial> goodsMaterialMap = goodsMaterialList.stream()
                .collect(Collectors.toMap(GoodsMaterial::getId, Function.identity()));

        // 查询商品条码库存
        List<GoodsCode> goodsCodeList = goodsCodeService.lambdaQuery()
                .eq(GoodsCode::getOrderId, purchase.getGoodsPurchaseId())
                .list();

        Map<String, GoodsCode> goodsCodeMap = goodsCodeList.stream()
                .collect(Collectors.toMap(v -> v.getGoodsMaterialId() + "-" + v.getGoodsMaterialItemType()
                        + "-" + v.getMaterialName() + "-" + v.getMaterialCode(), Function.identity()));

        // 关联条码时检查商品子物料的条码数量
        if (purchase.getJoinCode().equals("CODE")) {
            // 查询退货单所有条码
            List<GoodsPurchaseRetCode> purchaseCodeList = goodsPurchaseRetCodeService.lambdaQuery()
                    .eq(GoodsPurchaseRetCode::getGoodsPurchaseRetId, id)
                    .list();

            Map<String, List<GoodsPurchaseRetCode>> codeGroupMap = purchaseCodeList.stream()
                    .collect(Collectors.groupingBy(v -> v.getGoodsPurchaseRetItemId() + "-" + v.getGoodsMaterialItemId()));

            for (GoodsPurchaseRetItem item : purchaseItemList) {
                // 检查条码数量
                this.checkRetCodeQty(item, materialItemGroupMap, codeGroupMap);
            }

            for (GoodsPurchaseRetCode retCode : purchaseCodeList) {
                if (!goodsPurchaseCodeMap.containsKey(retCode.getGoodsMaterialId() + "-" + retCode.getGoodsMaterialItemId() + "-" + retCode.getCode())) {
                    throw new RemoteServiceException(retCode.getGoodsMaterialItemName() + " 商品子物料名称在商品采购入库条码信息不存在");
                }

                // 检查商品库存数量
                GoodsCode goodsCode = goodsCodeMap.get(retCode.getGoodsMaterialId() + "-" + retCode.getGoodsMaterialItemType()
                        + "-" + retCode.getGoodsMaterialItemName() + "-" + retCode.getCode());
                if (Objects.nonNull(goodsCode) && (goodsCode.getStockQty() - retCode.getCodeQty()) < 0) {
                    throw new RemoteServiceException(" 商品子物料名称\"" + retCode.getGoodsMaterialItemName()
                            + "\", 条码\"" + retCode.getCode() + "\" 退货数量已超剩余库存数量");
                }

                // 检查入库单采购条码数量
                GoodsPurchaseCode purchaseCode = goodsPurchaseCodeMap.get(retCode.getGoodsMaterialId() + "-" + retCode.getGoodsMaterialItemId() + "-" + retCode.getCode());
                purchaseCode.setOrigCodeQty(purchaseCode.getOrigCodeQty() - retCode.getCodeQty());
                if (purchaseCode.getOrigCodeQty() < 0) {
                    throw new RemoteServiceException(" 商品子物料名称\"" + purchaseCode.getGoodsMaterialItemName()
                            + "\", 条码\"" + purchaseCode.getCode() + "\" 在商品采购入库条码可退数量不能少于0");
                }
            }
        }

        for (GoodsPurchaseRetItem retItem : purchaseItemList) {
            if (!goodsPurchaseItemMap.containsKey(retItem.getGoodsMaterialId())) {
                throw new RemoteServiceException(retItem.getGoodsMaterialName() + " 商品在商品采购入库商品信息不存在");
            }

            // 检查商品库存数量
            GoodsMaterial goodsMaterial = goodsMaterialMap.get(retItem.getGoodsMaterialId());


            GoodsMaterialStorage goodsMaterialStorage = goodsMaterialStorageService.lambdaQuery()
                    .eq(GoodsMaterialStorage::getGoodsMaterialId, retItem.getGoodsMaterialId())
                    .eq(GoodsMaterialStorage::getStorageId, purchase.getStorageId()).last("limit 1").one();

            if (Objects.nonNull(goodsMaterial) && (goodsMaterialStorage.getStockQty() - retItem.getRetQty()) < 0) {
                throw new RemoteServiceException(retItem.getGoodsMaterialName() + " 商品库存数量 " + goodsMaterialStorage.getStockQty() + ", 退货数量已超剩余库存数量");
            }

            // 检查入库单采购数量
            GoodsPurchaseItem purchaseItem = goodsPurchaseItemMap.get(retItem.getGoodsMaterialId());
            purchaseItem.setOrigQty(purchaseItem.getOrigQty() - retItem.getRetQty());
            if (purchaseItem.getOrigQty() < 0) {
                throw new RemoteServiceException(retItem.getGoodsMaterialName() + " 商品可退采购数量 " + purchaseItem.getOrigQty() + ", 退货数量已超剩余采购数量");
            }
        }


        // 更新商品采购退货单状态
        goodsPurchaseRetService.lambdaUpdate()
                .set(GoodsPurchaseRet::getStatus, statusEnum.getKey().equals(ExamineStatusEnum.FAIL.getKey()) ? ExamineStatusEnum.SAVE.getKey() : statusEnum.getKey())
                .set(statusEnum.getKey().equals(ExamineStatusEnum.WAIT.getKey()), GoodsPurchaseRet::getSubmitBy, adminUser.getNickName())
                .set(statusEnum.getKey().equals(ExamineStatusEnum.WAIT.getKey()), GoodsPurchaseRet::getSubmitTime, DateUtil.date())
                .set(statusEnum.getKey().equals(ExamineStatusEnum.OK.getKey())
                        || statusEnum.getKey().equals(ExamineStatusEnum.FAIL.getKey()),
                        GoodsPurchaseRet::getExamineBy, adminUser.getNickName())
                .set(statusEnum.getKey().equals(ExamineStatusEnum.OK.getKey())
                        || statusEnum.getKey().equals(ExamineStatusEnum.FAIL.getKey()),
                        GoodsPurchaseRet::getExamineTime, DateUtil.date())
                .eq(GoodsPurchaseRet::getId, id)
                .eq(GoodsPurchaseRet::getCompanyWechatId, companyId)
                .update();

        if (statusEnum.getKey().equals(ExamineStatusEnum.OK.getKey())) {
            goodsPurchaseItemService.saveOrUpdateBatch(goodsPurchaseItemList);
            if (purchase.getJoinCode().equals("CODE")) {
                goodsPurchaseCodeService.saveOrUpdateBatch(goodsPurchaseCodeList);
            }
            //处理库存
            jxGoodsLogic.refundStockQty(id);
        }
    }

    private void checkRetCodeQty(GoodsPurchaseRetItem item, Map<String, List<GoodsMaterialItem>> materialItemGroupMap, Map<String, List<GoodsPurchaseRetCode>> codeGroupMap) {
        List<GoodsMaterialItem> materialItems = materialItemGroupMap.get(item.getGoodsMaterialId());
        for (GoodsMaterialItem materialItem : materialItems) {
            int totalNeedQty = item.getRetQty() * materialItem.getQty();

            int codeQty = 0;
            List<GoodsPurchaseRetCode> codeList = codeGroupMap.get(item.getId() + "-" + materialItem.getId());
            if (CollectionUtil.isNotEmpty(codeList)) {
                codeQty = codeList.stream().mapToInt(GoodsPurchaseRetCode::getCodeQty).sum();
            }

            if (codeQty != totalNeedQty) {
                throw new RemoteServiceException("\"" + item.getGoodsMaterialName() + "\"商品所需要条码数量与物料类型: \""
                        + BaseEnum.keyToEnumNotNull(GoodsMaterialTypeEnum.class, materialItem.getType()).getRemark() + "\" 物料名称: \""
                        + materialItem.getName() + "\"条码数量不一致");
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void confirm(String id, ExamineStatusEnum statusEnum) throws Exception {
        this.commonHandlePurchase(id, statusEnum);
    }

    @Transactional(rollbackFor = Exception.class)
    public void itemAddCode(GoodsPurchaseRetItemBean itemBean, AdminUserCom adminUser) {

        String companyId = null;
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            companyId = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }

        if (CollectionUtil.isEmpty(itemBean.getCodeList())) {
            throw new RemoteServiceException("条码记录不为空");
        }

        GoodsPurchaseRetCode purchaseCode = itemBean.getCodeList().get(0);

        if (StringUtils.isBlank(purchaseCode.getGoodsMaterialItemId())) {
            throw new RemoteServiceException("商品子物料信息不能为空");
        }

        if (StringUtils.isBlank(purchaseCode.getCode())) {
            throw new RemoteServiceException("条码不为空");
        }
        // 去前后空
        purchaseCode.setCode(StrUtil.trim(purchaseCode.getCode()));

        if (Objects.isNull(purchaseCode.getCodeQty()) || purchaseCode.getCodeQty() < 0) {
            throw new RemoteServiceException("请填写有效的数量");
        }

        if (StringUtils.isNotBlank(purchaseCode.getId())) {
            GoodsPurchaseRetCode oldPurchaseCode = goodsPurchaseRetCodeService.getById(purchaseCode.getId());
            if (Objects.isNull(oldPurchaseCode)) {
                throw new RemoteServiceException("编辑的条码记录编号有误");
            }
            if (!oldPurchaseCode.getGoodsPurchaseRetId().equals(purchaseCode.getGoodsPurchaseRetId())) {
                throw new RemoteServiceException("编辑的条码记录商品入库单号有误");
            }
        }

        GoodsPurchaseRet purchase = goodsPurchaseRetService.lambdaQuery()
                .eq(GoodsPurchaseRet::getId, purchaseCode.getGoodsPurchaseRetId())
                .eq(GoodsPurchaseRet::getCompanyWechatId, companyId)
                .eq(GoodsPurchaseRet::getStatus, ExamineStatusEnum.SAVE.getKey())
                .one();

        if (Objects.isNull(purchase)) {
            throw new RemoteServiceException("商品采购入库单不存在");
        }

        if (!purchase.getJoinCode().equals("CODE")) {
            throw new RemoteServiceException("单据不需要关联条码");
        }

        GoodsPurchaseRetItem purchaseItem = goodsPurchaseRetItemService.lambdaQuery()
                .eq(GoodsPurchaseRetItem::getGoodsPurchaseRetId, purchase.getId())
                .eq(GoodsPurchaseRetItem::getGoodsMaterialId, purchaseCode.getGoodsMaterialId())
                .one();

        if (Objects.isNull(purchaseItem)) {
            throw new RemoteServiceException("商品记录不存在");
        }

        GoodsMaterialItem materialItem = goodsMaterialItemService.lambdaQuery()
                .eq(GoodsMaterialItem::getGoodsMaterialId, purchaseCode.getGoodsMaterialId())
                .eq(GoodsMaterialItem::getId, purchaseCode.getGoodsMaterialItemId())
                .one();

        if (Objects.isNull(materialItem)) {
            throw new RemoteServiceException("商品子物料不存在");
        }

        if (StringUtils.isBlank(purchaseCode.getId())) {
            GoodsPurchaseRetCode existCode = goodsPurchaseRetCodeService.lambdaQuery()
                    .eq(GoodsPurchaseRetCode::getGoodsPurchaseRetId, purchase.getId())
                    .eq(GoodsPurchaseRetCode::getGoodsPurchaseRetItemId, purchaseItem.getId())
                    .eq(GoodsPurchaseRetCode::getGoodsMaterialId, materialItem.getGoodsMaterialId())
                    .eq(GoodsPurchaseRetCode::getGoodsMaterialItemId, materialItem.getId())
                    .eq(GoodsPurchaseRetCode::getCode, StrUtil.trim(purchaseCode.getCode()))
                    .eq(GoodsPurchaseRetCode::getUniqueCode, IsYesNoEnum.NO.getKey())
                    .one();
            if (Objects.nonNull(existCode)) {
                // 发现存在相同物料类型、物料名称、条码就相加数量并注入相同的条码记录id
                purchaseCode.setId(existCode.getId())
                        .setCodeQty(existCode.getCodeQty() + purchaseCode.getCodeQty());
            }
        }

        purchaseCode.setGoodsPurchaseRetId(purchase.getId())
                .setGoodsPurchaseRetItemId(purchaseItem.getId())
                .setGoodsMaterialId(materialItem.getGoodsMaterialId())
                .setGoodsMaterialItemId(materialItem.getId())
                .setGoodsMaterialItemType(materialItem.getType())
                .setGoodsMaterialItemName(materialItem.getName())
                .setUniqueCode(materialItem.getUniqueCode());

        purchaseCode.insertOrUpdate();

        // 统计条码数量
        this.computeImportCodeQty(purchase, purchaseItem);

    }

    private void computeImportCodeQty(GoodsPurchaseRet purchase, GoodsPurchaseRetItem purchaseItem) {
        int insideCodeQty = 0;
        int outCodeQty = 0;
        int partsCodeQty = 0;
        List<GoodsPurchaseRetCode> purchaseCodeList = goodsPurchaseRetCodeService.lambdaQuery()
                .eq(GoodsPurchaseRetCode::getGoodsPurchaseRetId, purchase.getId())
                .eq(GoodsPurchaseRetCode::getGoodsPurchaseRetItemId, purchaseItem.getId())
                .eq(GoodsPurchaseRetCode::getGoodsMaterialId, purchaseItem.getGoodsMaterialId())
                .list();
        Map<String, List<GoodsPurchaseRetCode>> codeGroupMap = purchaseCodeList.stream()
                .collect(Collectors.groupingBy(GoodsPurchaseRetCode::getGoodsMaterialItemType));
        for (Map.Entry<String, List<GoodsPurchaseRetCode>> entry : codeGroupMap.entrySet()) {
            if (entry.getKey().equals(GoodsMaterialTypeEnum.INSIDE.getKey())) {
                insideCodeQty = entry.getValue().stream().mapToInt(GoodsPurchaseRetCode::getCodeQty).sum();
            } else if (entry.getKey().equals(GoodsMaterialTypeEnum.OUT.getKey())) {
                outCodeQty = entry.getValue().stream().mapToInt(GoodsPurchaseRetCode::getCodeQty).sum();
            } else {
                partsCodeQty = entry.getValue().stream().mapToInt(GoodsPurchaseRetCode::getCodeQty).sum();
            }
        }

        goodsPurchaseRetItemService.lambdaUpdate()
                .set(GoodsPurchaseRetItem::getInsideCodeQty, insideCodeQty)
                .set(GoodsPurchaseRetItem::getOutCodeQty, outCodeQty)
                .set(GoodsPurchaseRetItem::getPartsCodeQty, partsCodeQty)
                .eq(GoodsPurchaseRetItem::getId, purchaseItem.getId())
                .update();
    }

    @Transactional(rollbackFor = Exception.class)
    public void itemDelCode(String id, String codeId, AdminUserCom adminUser) {
        String companyId = null;
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            companyId = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }

        GoodsPurchaseRet purchase = goodsPurchaseRetService.lambdaQuery()
                .eq(GoodsPurchaseRet::getId, id)
                .eq(GoodsPurchaseRet::getCompanyWechatId, companyId)
                .eq(GoodsPurchaseRet::getStatus, ExamineStatusEnum.SAVE.getKey())
                .one();

        if (Objects.isNull(purchase)) {
            throw new RemoteServiceException("商品采购退货单据已发生变更, 删除条码失败");
        }

        goodsPurchaseRetCodeService.lambdaUpdate()
                .eq(GoodsPurchaseRetCode::getId, codeId)
                .eq(GoodsPurchaseRetCode::getGoodsPurchaseRetId, id)
                .remove();
    }

    @Transactional(rollbackFor = Exception.class)
    public void itemImportCode(MultipartFile file, String id, String purchaseRetItemId, AdminUserCom adminUser) throws IOException {
        String companyWechatId = Objects.nonNull(adminUser.getAdminCompanyWechat()) ? adminUser.getAdminCompanyWechat().getCompanyWechatId() : null;

        List<Object> objects = ExcelUtils.importExcel(file);
        List<GoodsPurchaseRetCode> codeList = new ArrayList<>();

        if (CollectionUtil.isEmpty(objects)) {
            throw new RemoteServiceException("导入条码记录为0, 请检查");
        }

        // 查找入库商品明细记录
        GoodsPurchaseRetItem purchaseItem = goodsPurchaseRetItemService.lambdaQuery()
                .eq(GoodsPurchaseRetItem::getGoodsPurchaseRetId, id)
                .eq(GoodsPurchaseRetItem::getId, purchaseRetItemId)
                .one();

        if (Objects.isNull(purchaseItem)) {
            throw new RemoteServiceException("商品记录不存在, 请检查");
        }

        // 查找退货单记录
        GoodsPurchaseRet goodsPurchase = goodsPurchaseRetService.lambdaQuery()
                .eq(GoodsPurchaseRet::getId, id)
                .eq(GoodsPurchaseRet::getCompanyWechatId, companyWechatId)
                .eq(GoodsPurchaseRet::getStatus, ExamineStatusEnum.SAVE.getKey())
                .one();

        if (Objects.isNull(goodsPurchase)) {
            throw new RemoteServiceException("商品采购退货单状态非保存状态, 请检查");
        }

        if (!goodsPurchase.getJoinCode().equals("CODE")) {
            throw new RemoteServiceException("单据不需要关联条码");
        }

        // 查找商品子物料列表
        List<GoodsMaterialItem> materialItemList = goodsMaterialItemService.lambdaQuery()
                .eq(GoodsMaterialItem::getGoodsMaterialId, purchaseItem.getGoodsMaterialId())
                .list();

        Map<String, GoodsMaterialItem> materialItemMap = materialItemList.stream()
                .collect(Collectors.toMap(v -> v.getType() + "-" + v.getName(), Function.identity()));

        Map<String, List<GoodsMaterialItem>> materialItemGroupMap = materialItemList.stream()
                .collect(Collectors.groupingBy(GoodsMaterialItem::getGoodsMaterialId));

        // 查找退货商品条码列表
        List<GoodsPurchaseRetCode> purchaseCodeList = goodsPurchaseRetCodeService.lambdaQuery()
                .eq(GoodsPurchaseRetCode::getGoodsPurchaseRetId, goodsPurchase.getId())
                .eq(GoodsPurchaseRetCode::getGoodsPurchaseRetItemId, purchaseItem.getId())
                .eq(GoodsPurchaseRetCode::getGoodsMaterialId, purchaseItem.getGoodsMaterialId())
                .list();

        Map<String, GoodsPurchaseRetCode> purchaseCodeMap = purchaseCodeList.stream()
                .collect(Collectors.toMap(v -> v.getGoodsMaterialItemType() + "-"
                        + v.getGoodsMaterialItemName() + "-" + v.getCode(), Function.identity()));

        for (int i = 0; i < objects.size(); i++) {
            List<Object> row = (List<Object>) objects.get(i);
            if (Objects.isNull(row.get(0))) {
                throw new RemoteServiceException("第" + (i + 1) + "行, 物料类型不能为空");
            }
            if (Objects.isNull(row.get(1))) {
                throw new RemoteServiceException("第" + (i + 1) + "行, 物料名称不能为空");
            }
            if (Objects.isNull(row.get(2))) {
                throw new RemoteServiceException("第" + (i + 1) + "行, 条码不能为空");
            }
            if (Objects.isNull(row.get(3))) {
                throw new RemoteServiceException("第" + (i + 1) + "行, 数量不能为空");
            }

            String typeStr = (String) row.get(0);
            String nameStr = (String) row.get(1);
            String codeStr = (String) row.get(2);
            String qtyStr = (String) row.get(3);

            String type = "";
            if (GoodsMaterialTypeEnum.INSIDE.getRemark().equals(StrUtil.trimToEmpty(typeStr))) {
                type = GoodsMaterialTypeEnum.INSIDE.getKey();
            } else if (GoodsMaterialTypeEnum.OUT.getRemark().equals(StrUtil.trimToEmpty(typeStr))) {
                type = GoodsMaterialTypeEnum.OUT.getKey();
            } else if (GoodsMaterialTypeEnum.PARTS.getRemark().equals(StrUtil.trimToEmpty(typeStr))) {
                type = GoodsMaterialTypeEnum.PARTS.getKey();
            }

            if (StringUtils.isBlank(type)) {
                throw new RemoteServiceException("第" + (i + 1) + "行, 物料类型匹配不到子物料");
            }

            nameStr = StrUtil.trimToEmpty(nameStr);
            if (!materialItemMap.containsKey(type + "-" + nameStr)) {
                throw new RemoteServiceException("第" + (i + 1) + "行, 物料名称匹配不到子物料");
            }

            if (StringUtils.isBlank(codeStr)) {
                throw new RemoteServiceException("第" + (i + 1) + "行, 条码不能为空");
            }
            // 去前后空
            codeStr = StrUtil.trim(codeStr);

            if (StringUtils.isBlank(qtyStr) || Integer.parseInt(qtyStr) < 0) {
                throw new RemoteServiceException("第" + (i + 1) + "行, 请填写有效数量");
            }

            GoodsMaterialItem materialItem = materialItemMap.get(type + "-" + nameStr);
            int qty = Integer.parseInt(qtyStr);

            GoodsPurchaseRetCode purchaseCode = new GoodsPurchaseRetCode();

            if (purchaseCodeMap.containsKey(materialItem.getType() + "-" + materialItem.getName() + "-" + codeStr)) {
                // 存在相同物料类型、物料名称、条码并且非一物一码就相加数量
                GoodsPurchaseRetCode code = purchaseCodeMap.get(materialItem.getType() + "-" + materialItem.getName() + "-" + codeStr);
                if (code.getUniqueCode().equals(IsYesNoEnum.NO.getKey())) {
                    purchaseCode.setId(code.getId());
                    qty = code.getCodeQty() + qty;
                }
            }

            purchaseCode.setGoodsPurchaseRetId(goodsPurchase.getId())
                    .setGoodsPurchaseRetItemId(purchaseItem.getId())
                    .setGoodsMaterialId(materialItem.getGoodsMaterialId())
                    .setGoodsMaterialItemId(materialItem.getId())
                    .setGoodsMaterialItemType(materialItem.getType())
                    .setGoodsMaterialItemName(materialItem.getName())
                    .setUniqueCode(materialItem.getUniqueCode())
                    .setCode(codeStr)
                    .setCodeQty(materialItem.getUniqueCode().equals(IsYesNoEnum.YES.getKey()) ? 1 : qty);

            codeList.add(purchaseCode);
        }

        // 检查是否存在一物一码的重复导入
        if (CollectionUtil.isNotEmpty(codeList)) {
            List<GoodsPurchaseRetCode> purchaseCodes = codeList.stream()
                    .filter(v -> v.getUniqueCode().equals(IsYesNoEnum.YES.getKey()))
                    .collect(Collectors.toList());
            for (GoodsPurchaseRetCode purchaseCode : purchaseCodes) {
                int count = 0;
                for (GoodsPurchaseRetCode code : codeList) {
                    if (code.getUniqueCode().equals(IsYesNoEnum.NO.getKey())) {
                        continue;
                    }
                    if (code.getCode().equals(purchaseCode.getCode())) {
                        count++;
                    }
                    if (count > 1) {
                        throw new RemoteServiceException("物料类型: \""
                                + BaseEnum.keyToEnumNotNull(GoodsMaterialTypeEnum.class, purchaseCode.getGoodsMaterialItemType()).getRemark()
                                + "\" 物料名称: \"" + purchaseCode.getGoodsMaterialItemName() + "\" 条码为一物一码, 导入模板有重复记录");
                    }
                }
            }
        }

        goodsPurchaseRetCodeService.saveOrUpdateBatch(codeList);

        purchaseCodeList = goodsPurchaseRetCodeService.lambdaQuery()
                .eq(GoodsPurchaseRetCode::getGoodsPurchaseRetId, goodsPurchase.getId())
                .eq(GoodsPurchaseRetCode::getGoodsPurchaseRetItemId, purchaseItem.getId())
                .eq(GoodsPurchaseRetCode::getGoodsMaterialId, purchaseItem.getGoodsMaterialId())
                .list();
        Map<String, List<GoodsPurchaseRetCode>> codeGroupMap = purchaseCodeList.stream()
                .collect(Collectors.groupingBy(v -> v.getGoodsPurchaseRetItemId() + "-" + v.getGoodsMaterialItemId()));

        // 检查条码数量
        this.checkRetCodeQty(purchaseItem, materialItemGroupMap, codeGroupMap);

        // 计算导入条码数量
        this.computeImportCodeQty(goodsPurchase, purchaseItem);
    }

    public void del(String id) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        boolean remove = goodsPurchaseRetService.lambdaUpdate()
                .eq(GoodsPurchaseRet::getId, id)
                .eq(GoodsPurchaseRet::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(GoodsPurchaseRet::getStatus, ExamineStatusEnum.SAVE.getKey())
                .remove();
        if (remove) {
            goodsPurchaseRetItemService.lambdaUpdate()
                    .eq(GoodsPurchaseRetItem::getGoodsPurchaseRetId, id)
                    .remove();
            goodsPurchaseRetCodeService.lambdaUpdate()
                    .eq(GoodsPurchaseRetCode::getGoodsPurchaseRetId, id)
                    .remove();
        }
    }
}
