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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
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.SalesCustomerPartsBean;
import com.gree.mall.manager.bean.SalesCustomerPartsItemBean;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.listvo.material.WorkerStockAccPVO;
import com.gree.mall.manager.bean.listvo.material.WorkerStockAccVO;
import com.gree.mall.manager.bean.listvo.material.WorkerStockPVO;
import com.gree.mall.manager.bean.listvo.material.WorkerStockVO;
import com.gree.mall.manager.bean.material.stock.WorkerStockDTO;
import com.gree.mall.manager.bean.material.worker.OldRefundManageBean;
import com.gree.mall.manager.bean.material.worker.OldRefundManageItemBean;
import com.gree.mall.manager.commonmapper.CommonMapper;
import com.gree.mall.manager.enums.ExamineWorkerStatusEnum;
import com.gree.mall.manager.enums.UserTypeEnum;
import com.gree.mall.manager.enums.material.*;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.inf.ValidGroup;
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.CommonUtils;
import com.gree.mall.manager.utils.ValidateUtil;
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 javax.validation.ValidationException;
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 WorkerStockLogic {

    private final CommonLogic commonLogic;
    private final CommonMapper commonMapper;
    private final WorkerGoodsService workerGoodsService;
    private final WorkerStockService workerStockService;
    private final WorkerStockAccService workerStockAccService;
    private final AdminWebsitService adminWebsitService;
    private final UserService userService;
    private final MaterialGoodsStockLogic materialGoodsStockLogic;
    private final WebsitGoodsService websitGoodsService;
    private final WorkerStockBakService workerStockBakService;
    private final WorkerStockAccBakService workerStockAccBakService;
    private final WebsitUserService websitUserService;
    private final WebsitPartsOldRefundManageService websitPartsOldRefundManageService;
    private final WebsitPartsOldRefundManageItemService websitPartsOldRefundManageItemService;

    /**
     * 师傅辅材库存列表
     *
     * @param zfireParamBean
     * @return
     */
    public IPage<WorkerStockVO> workerStockList(ZfireParamBean zfireParamBean) {
        final AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.materialParam(zfireParamBean, WorkerStockVO.class, adminUser);
        List<String> workers = null;
        if (adminUser.getType() == 0 && CollectionUtil.isNotEmpty(zfireParamBean.getAdminWebsitIds())) {
            List<WebsitUser> workerList = websitUserService.lambdaQuery()
                    .eq(StringUtils.isNotBlank(adminUser.getCompanyWechatId()), WebsitUser::getCompanyWechatId, adminUser.getCompanyWechatId())
                    .in(WebsitUser::getWebsitId, zfireParamBean.getAdminWebsitIds())
                    .in(WebsitUser::getExamineStatus, ExamineWorkerStatusEnum.OK.getKey(), ExamineWorkerStatusEnum.EXPIRED.getKey(), ExamineWorkerStatusEnum.OVERDUE.getKey(), ExamineWorkerStatusEnum.STOP.getKey())
                    .groupBy(WebsitUser::getUserId)
                    .list();
            List<String> userIds = workerList.stream().map(WebsitUser::getUserId).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(userIds)) {
                final List<User> userList = userService.lambdaQuery()
                        .in(User::getUserId, userIds)
                        .groupBy(User::getIdCard)
                        .list();
                workers = userList.stream().map(User::getIdCard).collect(Collectors.toList());
            }
        }
        IPage<WorkerStockVO> page = commonMapper.workerStockList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean, workers);
        return page;
    }

    /**
     * 师傅辅材库存明细
     *
     * @param zfireParamBean
     * @return
     */
    public IPage<WorkerStockAccVO> workerStockAccList(ZfireParamBean zfireParamBean) {
        final AdminUserCom adminUser = commonLogic.getAdminUser();
        zfireParamBean.setCompanyWechatId(commonLogic.getAdminUser().getCompanyWechatId());
        FieldUtils.supplyParam(zfireParamBean, WorkerStockAccVO.class, adminUser);
        IPage<WorkerStockAccVO> page = commonMapper.workerStockAccList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        return page;
    }


    /**
     * 师傅配件库存列表
     *
     * @param zfireParamBean
     * @return
     */
    public IPage<WorkerStockPVO> workerStockPList(ZfireParamBean zfireParamBean) {
        final AdminUserCom adminUser = commonLogic.getAdminUser();
        zfireParamBean.setCompanyWechatId(commonLogic.getAdminUser().getCompanyWechatId());
        FieldUtils.supplyParam(zfireParamBean, WorkerStockPVO.class, adminUser);
        IPage<WorkerStockPVO> page = commonMapper.workerStockPList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        return page;
    }

    /**
     * 师傅配件库存明细
     *
     * @param zfireParamBean
     * @return
     */
    public IPage<WorkerStockAccPVO> workerStockAccPList(ZfireParamBean zfireParamBean) {
        final AdminUserCom adminUser = commonLogic.getAdminUser();
        zfireParamBean.setCompanyWechatId(commonLogic.getAdminUser().getCompanyWechatId());
        FieldUtils.supplyParam(zfireParamBean, WorkerStockAccPVO.class, adminUser);
        IPage<WorkerStockAccPVO> page = commonMapper.workerStockAccPList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        return page;
    }


    /**
     * 导入师傅库存(各个商品只能导第一次)
     *
     * @param datas
     */
    @Transactional
    public void importData(List<Object> datas, WebsitGoodsTypeEnum websitGoodsTypeEnum) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();

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

        if (CollectionUtil.isNotEmpty(adminUser.getAdminWebsitIds()) && adminUser.getAdminWebsitIds().size() > 1) {
            throw new RemoteServiceException("账号绑定多网点编号，无法导入");
        }

        List<WorkerStockDTO> workerStockDTOS = new ArrayList<>();
        final DateTime curDate = DateUtil.date();
        final String idStr = IdWorker.getIdStr();

        String tipsGoodsName = websitGoodsTypeEnum.getKey().equals(WebsitGoodsTypeEnum.M.getKey()) ? "辅材" : "配件";

        final AdminWebsit websit = adminWebsitService.lambdaQuery()
                .eq(AdminWebsit::getCompanyWechatId, adminUser.getCompanyWechatId())
                .eq(AdminWebsit::getWebsitId, adminUser.getAdminWebsitIds().get(0))
                .one();

        for (int i = 0; i < datas.size(); i++) {
            List<String> row = (List<String>) datas.get(i);
            CommonUtils.initList(row, 10);
            if (websitGoodsTypeEnum.getKey().equals(WebsitGoodsTypeEnum.M.getKey())) {
                String goodsId = row.get(0);
                String idCard = row.get(1);
                String qty = row.get(2);
                String price = row.get(3);
                if (StringUtils.isAnyBlank(goodsId, idCard, qty, price)) {
                    throw new RemoteServiceException("第" + (i + 1) + "行请补充完整内容");
                }
                WorkerGoods workerGoods = workerGoodsService.lambdaQuery()
                        .eq(WorkerGoods::getCompanyWechatId, adminUser.getCompanyWechatId())
                        .eq(WorkerGoods::getGoodsId, goodsId)
                        .one();
                if (workerGoods == null) {
                    throw new RemoteServiceException(tipsGoodsName + "编号【" + goodsId + "】不存在");
                }

                //判断师傅信息
                List<User> userList = userService.lambdaQuery()
                        .eq(User::getIdCard, idCard)
                        .eq(User::getType, UserTypeEnum.WORKER.getKey())
                        .eq(User::getStatus, true)
                        .eq(User::getCompanyWechatId, adminUser.getCompanyWechatId())
                        .list();
                if (CollectionUtil.isEmpty(userList)) {
                    throw new RemoteServiceException("师傅身份证【" + idCard + "】不存在");
                }
                User user = userList.get(0);
                Integer count = workerStockService.lambdaQuery()
                        .eq(WorkerStock::getCompanyWechatId, adminUser.getCompanyWechatId())
                        .eq(WorkerStock::getIdentity, user.getIdCard())
                        .eq(WorkerStock::getGoodsId, goodsId)
                        .count();
                if (count > 0) {
                    throw new RemoteServiceException(tipsGoodsName + "编号【" + goodsId + "】的库存记录已存在于系统，导入失败");
                }

                WorkerStockDTO workerStockDTO = new WorkerStockDTO();
                workerStockDTO.setCompanyWechatId(adminUser.getCompanyWechatId());
                workerStockDTO.setCompanyWechatName(adminUser.getCompanyName());
                workerStockDTO.setWebsitId(websit.getWebsitId());
                workerStockDTO.setWebsitName(websit.getName());
                workerStockDTO.setIdentity(user.getIdCard());
                workerStockDTO.setWorkerId(user.getWorkerNumber());
                workerStockDTO.setWorkerName(user.getNickName());
                workerStockDTO.setSdate(curDate);
                workerStockDTO.setGoodsId(goodsId);
                workerStockDTO.setGoodsName(workerGoods.getGoodsName());
                workerStockDTO.setGoodsType(WebsitGoodsTypeEnum.M.getKey());
                workerStockDTO.setPrice(new BigDecimal(price));
                workerStockDTO.setGoodsStockUnit(workerGoods.getSalesUnit());
                workerStockDTO.setRef(idStr);
                workerStockDTO.setRefType("库存导入");
                workerStockDTO.setPartsAttr(PartsAttrEnum.NEW.getKey());
                workerStockDTO.setChangeQty(new BigDecimal(qty));
                workerStockDTO.setDirectFlag(DirectFlagEnum.ADD.getKey());
                workerStockDTO.setFlag(WorkerStockFlagEnum.INIT.getKey());
                workerStockDTO.setObj("师傅");
                workerStockDTO.setWorkerOrderNo("");
                workerStockDTO.setOperateBy(adminUser.getJoinNickName());
                workerStockDTO.setOperateTime(curDate);
                workerStockDTOS.add(workerStockDTO);
            } else {
                String goodsId = row.get(0);
                String stock = row.get(1);
                String oldQty = row.get(2);
                //String websitName = row.get(4);
                String idCard = row.get(4);
                if (StringUtils.isAnyBlank(goodsId, stock, oldQty, idCard)) {
                    throw new RemoteServiceException("第" + (i + 1) + "行请补充完整内容");
                }
                WebsitGoods websitGoods = websitGoodsService.lambdaQuery()
                        .eq(WebsitGoods::getCompanyWechatId, adminUser.getCompanyWechatId())
                        .eq(WebsitGoods::getGoodsType, websitGoodsTypeEnum.getKey())
                        .eq(WebsitGoods::getGoodsCode, goodsId)
                        .one();
                if (websitGoods == null) {
                    throw new RemoteServiceException(tipsGoodsName + "编号【" + goodsId + "】不存在");
                }

                //判断师傅信息
                List<User> userList = userService.lambdaQuery()
                        .eq(User::getIdCard, idCard)
                        .eq(User::getType, UserTypeEnum.WORKER.getKey())
                        .eq(User::getStatus, true)
                        .eq(User::getCompanyWechatId, adminUser.getCompanyWechatId())
                        .list();
                if (CollectionUtil.isEmpty(userList)) {
                    throw new RemoteServiceException("师傅编号【" + idCard + "】不存在");
                }
                User user = userList.get(0);
                Integer count = workerStockService.lambdaQuery()
                        .eq(WorkerStock::getCompanyWechatId, adminUser.getCompanyWechatId())
                        .eq(WorkerStock::getIdentity, user.getIdCard())
                        .eq(WorkerStock::getGoodsId, goodsId)
                        .count();
                if (count > 0) {
                    throw new RemoteServiceException(tipsGoodsName + "编号【" + goodsId + "】的库存记录已存在于系统，导入失败");
                }

                if (new BigDecimal(stock).compareTo(BigDecimal.ZERO) > 0) {
                    WorkerStockDTO workerStockDTO = new WorkerStockDTO();
                    workerStockDTO.setCompanyWechatId(adminUser.getCompanyWechatId());
                    workerStockDTO.setCompanyWechatName(adminUser.getCompanyName());
                    workerStockDTO.setIdentity(user.getIdCard());
                    workerStockDTO.setWorkerId(user.getWorkerNumber());
                    workerStockDTO.setWorkerName(user.getNickName());
                    workerStockDTO.setSdate(curDate);
                    workerStockDTO.setGoodsId(websitGoods.getGoodsId());
                    workerStockDTO.setGoodsName(websitGoods.getGoodsName());
                    workerStockDTO.setGoodsType(WebsitGoodsTypeEnum.P.getKey());
                    workerStockDTO.setGoodsStockUnit(websitGoods.getGoodsSalesUnit());
                    workerStockDTO.setRef(idStr);
                    workerStockDTO.setRefType("库存导入");
                    workerStockDTO.setPartsAttr(PartsAttrEnum.NEW.getKey());
                    workerStockDTO.setChangeQty(new BigDecimal(stock));
                    workerStockDTO.setDirectFlag(DirectFlagEnum.ADD.getKey());
                    workerStockDTO.setFlag(WorkerStockFlagEnum.INIT.getKey());
                    workerStockDTO.setObj("师傅");
                    workerStockDTO.setWorkerOrderNo("");
                    workerStockDTO.setOperateBy(adminUser.getJoinNickName());
                    workerStockDTO.setOperateTime(curDate);
                    workerStockDTOS.add(workerStockDTO);
                }


                if (new BigDecimal(oldQty).compareTo(BigDecimal.ZERO) > 0) {
                    WorkerStockDTO workerStockDTO2 = new WorkerStockDTO();
                    workerStockDTO2.setCompanyWechatId(adminUser.getCompanyWechatId());
                    workerStockDTO2.setCompanyWechatName(adminUser.getCompanyName());
                    workerStockDTO2.setIdentity(user.getIdCard());
                    workerStockDTO2.setWorkerId(user.getWorkerNumber());
                    workerStockDTO2.setWorkerName(user.getNickName());
                    workerStockDTO2.setSdate(curDate);
                    workerStockDTO2.setGoodsId(websitGoods.getGoodsId());
                    workerStockDTO2.setGoodsName(websitGoods.getGoodsName());
                    workerStockDTO2.setGoodsType(WebsitGoodsTypeEnum.P.getKey());
                    workerStockDTO2.setGoodsStockUnit(websitGoods.getGoodsSalesUnit());
                    workerStockDTO2.setRef(idStr);
                    workerStockDTO2.setRefType("库存导入");
                    workerStockDTO2.setPartsAttr(PartsAttrEnum.OLD.getKey());
                    workerStockDTO2.setChangeQty(new BigDecimal(oldQty));
                    workerStockDTO2.setDirectFlag(DirectFlagEnum.ADD.getKey());
                    workerStockDTO2.setFlag(WorkerStockFlagEnum.INIT.getKey());
                    workerStockDTO2.setObj("师傅");
                    workerStockDTO2.setWorkerOrderNo("");
                    workerStockDTO2.setOperateBy(adminUser.getJoinNickName());
                    workerStockDTO2.setOperateTime(curDate);
                    workerStockDTOS.add(workerStockDTO2);
                }

            }
        }
        // 开始处理库存
        materialGoodsStockLogic.handleWorkerStock(workerStockDTOS);
    }

    @Transactional
    public void delStock(List<String> ids) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }
        final List<WorkerStock> stockList = workerStockService.lambdaQuery()
                .eq(WorkerStock::getCompanyWechatId, adminUser.getCompanyWechatId())
                .in(WorkerStock::getId, ids)
                .eq(WorkerStock::getGoodsType, WebsitGoodsTypeEnum.M.getKey())
                .list();

        if (CollectionUtil.isNotEmpty(stockList)) {
            final DateTime curDate = DateUtil.date();
            List<WorkerStockBak> workerStockBakList = new ArrayList<>();
            List<WorkerStockAccBak> workerStockAccBakList = new ArrayList<>();

            List<WorkerStockAcc> workerStockRemoveAccs = new ArrayList<>();
            // 按师傅分组
            final Map<String, List<WorkerStock>> workerGroupMap = stockList.stream()
                    .collect(Collectors.groupingBy(WorkerStock::getIdentity));

            for (Map.Entry<String, List<WorkerStock>> workerStock : workerGroupMap.entrySet()) {
                // 需要删除的商品编号
                final List<String> goodsIds = workerStock.getValue().stream()
                        .map(WorkerStock::getGoodsId)
                        .collect(Collectors.toList());
                final List<WorkerStockAcc> workerStockAccs = workerStockAccService.lambdaQuery()
                        .eq(WorkerStockAcc::getCompanyWechatId, adminUser.getCompanyWechatId())
                        .in(WorkerStockAcc::getGoodsId, goodsIds)
                        .list();

                for (WorkerStock stock : workerStock.getValue()) {
                    WorkerStockBak workerStockBak = new WorkerStockBak();
                    BeanUtils.copyProperties(stock, workerStockBak);
                    workerStockBak.setOperBy(adminUser.getJoinNickName())
                            .setOperTime(curDate);
                    workerStockBakList.add(workerStockBak);
                }

                for (WorkerStockAcc stockAcc : workerStockAccs) {
                    WorkerStockAccBak workerStockaccBak = new WorkerStockAccBak();
                    BeanUtils.copyProperties(stockAcc, workerStockaccBak);
                    workerStockAccBakList.add(workerStockaccBak);
                }

                if (CollectionUtil.isNotEmpty(workerStockAccs)) {
                    workerStockRemoveAccs.addAll(workerStockAccs);
                }
            }

            workerStockService.removeByIds(stockList.stream().map(WorkerStock::getId).collect(Collectors.toList()));
            workerStockAccService.removeByIds(workerStockRemoveAccs.stream().map(WorkerStockAcc::getId).collect(Collectors.toList()));
            workerStockBakService.saveBatch(workerStockBakList);
            workerStockAccBakService.saveBatch(workerStockAccBakList);
        }
    }

    @Transactional
    public String oldRefundManageSyncAdd(SalesCustomerPartsBean bean) throws Exception {
        ValidateUtil.validate(bean, ValidGroup.Add.class);
        for (SalesCustomerPartsItemBean itemBean : bean.getItems()) {
            try {
                ValidateUtil.validate(itemBean, ValidGroup.Add.class);
            } catch (ValidationException e) {
                throw new RemoteServiceException("明细出错原因：" + e.getMessage());
            }
        }
        // 查询接收网点
        AdminWebsit websit = adminWebsitService.lambdaQuery()
                .eq(AdminWebsit::getCompanyWechatId, bean.getCompanyWechatId())
                .eq(AdminWebsit::getWebsitId, bean.getReceiveWebsitId())
                .eq(AdminWebsit::getPartsWebsitId, bean.getReceivePartsWebsitId())
                .one();
        if (Objects.isNull(websit)) {
            throw new RemoteServiceException("接收网点不存在");
        }

        // 查询师傅在接收网点的新件库存
        List<WorkerStock> workerStockList = workerStockService.lambdaQuery()
                .eq(WorkerStock::getCompanyWechatId, bean.getCompanyWechatId())
                .eq(WorkerStock::getIdentity, bean.getIdentity())
                .eq(WorkerStock::getWebsitId, bean.getReceiveWebsitId())
                .eq(WorkerStock::getPartsWebsitId, bean.getReceivePartsWebsitId())
                .in(WorkerStock::getGoodsId, bean.getItems().stream()
                        .map(SalesCustomerPartsItemBean::getPartsNumber)
                        .collect(Collectors.toList()))
                .list();
        if (CollectionUtil.isEmpty(workerStockList)) {
            return "";
//            throw new RemoteServiceException("在“" + websit.getName() + "”未找到新件配件库存");
        }

        // 查询配件资料
        List<WebsitGoods> partsList = websitGoodsService.lambdaQuery()
                .eq(WebsitGoods::getCompanyWechatId, bean.getCompanyWechatId())
                .in(WebsitGoods::getGoodsCode, bean.getItems().stream()
                        .map(SalesCustomerPartsItemBean::getPartsNumber)
                        .collect(Collectors.toList()))
                .list();

        // 检查明细归还的数量必须大于0并且少于等于库存数量
        Map<String, WorkerStock> workerStockMap = workerStockList.stream()
                .collect(Collectors.toMap(WorkerStock::getGoodsId, Function.identity()));
        Map<String, WebsitGoods> partsMap = partsList.stream()
                .collect(Collectors.toMap(WebsitGoods::getGoodsCode, Function.identity()));

        OldRefundManageBean oldRefundManageBean = this.convertBean(bean, websit, partsMap);

        for (OldRefundManageItemBean itemBean : oldRefundManageBean.getOldRefundManageItemBeanList()) {
            WorkerStock workerStock = workerStockMap.get(itemBean.getNewPartsNumber());
            if (Objects.isNull(workerStock)) {
                throw new RemoteServiceException("“" + itemBean.getNewPartsName() + "”新配件未找到库存记录");
            }
            if (itemBean.getQty().compareTo(workerStock.getQty()) > 0) {
                throw new RemoteServiceException("“" + workerStock.getGoodsName() + "”使用新件数量不能大于库存数量");
            }
            if (itemBean.getQty().compareTo(BigDecimal.ZERO) < 1) {
                throw new RemoteServiceException("“" + workerStock.getGoodsName() + "”使用新件数量必须大于0");
            }
            workerStockMap.get(itemBean.getNewPartsNumber()).setQty(workerStock.getQty().subtract(itemBean.getQty()));
        }

        String sheetId = commonLogic.generateMaterialNo(bean.getCompanyWechatId(), "JH", PartsRefTypeEnum.OLD_REFUND.getKey(), 13);
        oldRefundManageBean.setApplyNo(sheetId);

        // 保存主表和明细
        WebsitPartsOldRefundManage partsOldRefundManage = new WebsitPartsOldRefundManage();
        BeanUtils.copyProperties(oldRefundManageBean, partsOldRefundManage);
        // workOrderNo与pgId是同值
        partsOldRefundManage.setPgId(oldRefundManageBean.getWorkOrderNo());

        List<WebsitPartsOldRefundManageItem> partsOldRefundManageItems = new ArrayList<>();
        for (OldRefundManageItemBean itemBean : oldRefundManageBean.getOldRefundManageItemBeanList()) {
            WebsitPartsOldRefundManageItem partsOldRefundManageItem = new WebsitPartsOldRefundManageItem();
            itemBean.setId(IdWorker.getIdStr());
            itemBean.setApplyNo(sheetId);
            BeanUtils.copyProperties(itemBean, partsOldRefundManageItem);
            partsOldRefundManageItem.setNewUnitName(itemBean.getNewGoodsStockUnit());
            partsOldRefundManageItems.add(partsOldRefundManageItem);
        }
        partsOldRefundManage.setCreateBy(partsOldRefundManage.getWorkerName())
                .setUpdateBy(partsOldRefundManage.getWorkerName())
                .insert();

        // 刷新创建人和更新人
        websitPartsOldRefundManageService.lambdaUpdate()
                .set(WebsitPartsOldRefundManage::getCreateBy, partsOldRefundManage.getWorkerName())
                .set(WebsitPartsOldRefundManage::getUpdateBy, partsOldRefundManage.getWorkerName())
                .eq(WebsitPartsOldRefundManage::getApplyNo, sheetId)
                .update();

        websitPartsOldRefundManageItemService.saveBatch(partsOldRefundManageItems);

        // 减去师傅新件库存 增加旧件库存
        String refType = PartsRepairFlagEnum.INNER.getKey().equals(partsOldRefundManage.getRepairFlag()) ?
                PartsRefTypeEnum.OLD_REFUND.getRemark() :
                PartsRefTypeEnum.OUTSIDE_TO_SALES.getRemark();
        List<WorkerStockDTO> workerStockDTOList = this.createWorkerStockDTO(partsOldRefundManage, partsOldRefundManageItems,
                refType, PartsAttrEnum.NEW.getKey(), PartsAttrEnum.OLD.getKey());
        materialGoodsStockLogic.handleWorkerStock(workerStockDTOList);

        return sheetId;
    }

    private OldRefundManageBean convertBean(SalesCustomerPartsBean bean, AdminWebsit websit, Map<String, WebsitGoods> partsMap) {
        OldRefundManageBean oldRefundManageBean = new OldRefundManageBean();
        BeanUtils.copyProperties(bean, oldRefundManageBean);
        if (PartsRepairFlagEnum.INNER.getKey().equals(bean.getRepairFlag())) {
            oldRefundManageBean.setApplyType(PartsRefundApplyTypeEnum.OLD.getKey());
        } else {
            oldRefundManageBean.setApplyType(PartsRefundApplyTypeEnum.NOT.getKey());
        }
        oldRefundManageBean.setReceiveWebsitName(websit.getName());
        oldRefundManageBean.setWebsitAddress(websit.getAddress());
        oldRefundManageBean.setCreateBy(bean.getWorkerName());
        oldRefundManageBean.setCreateTime(DateUtil.date());
        oldRefundManageBean.setUpdateBy(bean.getWorkerName());
        oldRefundManageBean.setUpdateTime(DateUtil.date());
        oldRefundManageBean.setFlag(PartsOrderFlagEnum.SAVE.toString());

        List<OldRefundManageItemBean> oldRefundManageItemBeanList = new ArrayList<>();
        for (SalesCustomerPartsItemBean itemBean : bean.getItems()) {
            OldRefundManageItemBean oldRefundManageItemBean = new OldRefundManageItemBean();
            BeanUtils.copyProperties(itemBean, oldRefundManageItemBean);
            WebsitGoods parts = partsMap.get(itemBean.getPartsNumber());
            if (Objects.isNull(parts)) {
                throw new RemoteServiceException("“" + itemBean.getPartsNumber() + "”配件编码未找到资料记录");
            }
            oldRefundManageItemBean.setOldPartsNumber(itemBean.getOldPartsNumber());
            oldRefundManageItemBean.setOldPartsName(itemBean.getOldPartsName());
            oldRefundManageItemBean.setNewPartsNumber(parts.getGoodsCode());
            oldRefundManageItemBean.setNewPartsName(parts.getGoodsName());
            oldRefundManageItemBean.setNewMaterialGroupName(parts.getMaterialGroupName());
            oldRefundManageItemBean.setNewGoodsStockUnit(parts.getGoodsStockUnit());
            oldRefundManageItemBeanList.add(oldRefundManageItemBean);
        }
        oldRefundManageBean.setOldRefundManageItemBeanList(oldRefundManageItemBeanList);
        return oldRefundManageBean;
    }

    private List<WorkerStockDTO> createWorkerStockDTO(WebsitPartsOldRefundManage partsOldRefundManage,
                                                      List<WebsitPartsOldRefundManageItem> partsOldRefundManageItems,
                                                      String refType, String partsAttr1,
                                                      String partsAttr2) {
        List<WorkerStockDTO> workerStockDTOList = new ArrayList<>();
        if (StringUtils.isNotBlank(partsAttr1)) {
            for (WebsitPartsOldRefundManageItem refundManageItem : partsOldRefundManageItems) {
                WorkerStockDTO workerStockDTO = new WorkerStockDTO();
                workerStockDTO.setCompanyWechatId(partsOldRefundManage.getCompanyWechatId());
                workerStockDTO.setCompanyWechatName(partsOldRefundManage.getCompanyWechatName());
                workerStockDTO.setIdentity(partsOldRefundManage.getIdentity());
                workerStockDTO.setWorkerId(partsOldRefundManage.getWorkerId());
                workerStockDTO.setWorkerName(partsOldRefundManage.getWorkerName());
                workerStockDTO.setWebsitId(partsOldRefundManage.getReceiveWebsitId());
                workerStockDTO.setWebsitName(partsOldRefundManage.getReceiveWebsitName());
                workerStockDTO.setPartsWebsitId(partsOldRefundManage.getReceivePartsWebsitId());
                workerStockDTO.setSdate(DateUtil.date());
                workerStockDTO.setGoodsType(WebsitGoodsTypeEnum.P.toString());
                workerStockDTO.setGoodsId(refundManageItem.getNewPartsNumber());
                workerStockDTO.setGoodsName(refundManageItem.getNewPartsName());
                workerStockDTO.setMaterialGroupName(refundManageItem.getNewMaterialGroupName());
                workerStockDTO.setGoodsStockUnit(refundManageItem.getNewUnitName());
                workerStockDTO.setPrice(BigDecimal.ZERO);
                workerStockDTO.setRef(partsOldRefundManage.getApplyNo());
                workerStockDTO.setRefType(refType);
                workerStockDTO.setPartsAttr(partsAttr1);
                workerStockDTO.setChangeQty(refundManageItem.getQty());
                workerStockDTO.setDirectFlag(DirectFlagEnum.SUB.getKey());
                workerStockDTO.setRemark(refundManageItem.getRemark());
                workerStockDTO.setWorkerOrderNo(partsOldRefundManage.getWorkOrderNo());
                workerStockDTO.setOperateBy(partsOldRefundManage.getWorkerName());
                workerStockDTO.setOperateTime(DateUtil.date());

                workerStockDTOList.add(workerStockDTO);
            }
        }
        if (StringUtils.isNotBlank(partsAttr2)) {
            for (WebsitPartsOldRefundManageItem refundManageItem : partsOldRefundManageItems) {
                WorkerStockDTO workerStockDTO = new WorkerStockDTO();
                workerStockDTO.setCompanyWechatId(partsOldRefundManage.getCompanyWechatId());
                workerStockDTO.setCompanyWechatName(partsOldRefundManage.getCompanyWechatName());
                workerStockDTO.setIdentity(partsOldRefundManage.getIdentity());
                workerStockDTO.setWorkerId(partsOldRefundManage.getWorkerId());
                workerStockDTO.setWorkerName(partsOldRefundManage.getWorkerName());
                workerStockDTO.setWebsitId(partsOldRefundManage.getReceiveWebsitId());
                workerStockDTO.setWebsitName(partsOldRefundManage.getReceiveWebsitName());
                workerStockDTO.setPartsWebsitId(partsOldRefundManage.getReceivePartsWebsitId());
                workerStockDTO.setSdate(DateUtil.date());
                workerStockDTO.setGoodsType(WebsitGoodsTypeEnum.P.toString());
                workerStockDTO.setGoodsId(refundManageItem.getNewPartsNumber());
                workerStockDTO.setGoodsName(refundManageItem.getNewPartsName());
                workerStockDTO.setMaterialGroupName(refundManageItem.getNewMaterialGroupName());
                workerStockDTO.setGoodsStockUnit(refundManageItem.getNewUnitName());
                workerStockDTO.setPrice(BigDecimal.ZERO);
                workerStockDTO.setRef(partsOldRefundManage.getApplyNo());
                workerStockDTO.setRefType(refType);
                workerStockDTO.setPartsAttr(partsAttr2);
                workerStockDTO.setChangeQty(refundManageItem.getQty());
                workerStockDTO.setDirectFlag(DirectFlagEnum.ADD.getKey());
                workerStockDTO.setRemark(refundManageItem.getRemark());
                workerStockDTO.setWorkerOrderNo(partsOldRefundManage.getWorkOrderNo());
                workerStockDTO.setOperateBy(partsOldRefundManage.getWorkerName());
                workerStockDTO.setOperateTime(DateUtil.date());

                workerStockDTOList.add(workerStockDTO);
            }
        }
        return workerStockDTOList;
    }

    @Transactional
    public void fucaiHandleWorkerStock(List<WorkerStockDTO> workerStockDTOS) throws Exception {
        materialGoodsStockLogic.handleWorkerStock(workerStockDTOS);
    }
}
