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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.material.stock.WebsitStockDTO;
import com.gree.mall.manager.bean.material.stock.WorkerStockDTO;
import com.gree.mall.manager.bean.websit.WebsitPartsFactoryRetVO;
import com.gree.mall.manager.bean.websit.WebsitPartsRetAddUp;
import com.gree.mall.manager.bean.websit.WebsitPartsRetDetail;
import com.gree.mall.manager.bean.websit.WebsitPartsRetVO;
import com.gree.mall.manager.commonmapper.WebsitSalesRetCMapper;
import com.gree.mall.manager.enums.ExamineStatusEnum;
import com.gree.mall.manager.enums.IsYesNoEnum;
import com.gree.mall.manager.enums.material.*;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.engin.WebsitGoodsMangerLogic;
import com.gree.mall.manager.logic.material.stock.MaterialGoodsStockLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.StringUtil;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class WebsitPartsRetLogic {

    @Autowired
    WebsitSalesRetCMapper websitSalesRetCMapper;

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    WebsitPartsRetService websitPartsRetService;

    @Autowired
    WebsitPartsRetItemService websitPartsRetItemService;

    @Autowired
    MaterialGoodsStockLogic materialGoodsStockLogic;

    @Autowired
    WebsitSalesService websitSalesService;

    @Autowired
    WebsitSalesItemService websitSalesItemService;

    @Autowired
    WebsitPartsRetOldRecordService websitPartsRetOldRecordService;

    @Autowired
    WebsitGoodsMangerLogic websitGoodsMangerLogic;


    public IPage<WebsitPartsRetVO> pageV2(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> companyWechatIds = adminUser.getCompanyWechatIds();

        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean, WebsitPartsRetVO.class,adminUser);


        IPage<WebsitPartsRetVO> websitPartsRetVOIPage = websitSalesRetCMapper.pagePartsRetV2(new Page(zfireParamBean.getPageNum(),
                        zfireParamBean.getPageSize()),
                zfireParam
                , companyWechatIds);

        return websitPartsRetVOIPage;
    }

    @Transactional(rollbackFor = Exception.class)
    public void save(WebsitPartsRetAddUp websitPartsRetAddUp) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (StringUtils.isBlank(websitPartsRetAddUp.getStorageId())) {
            throw new RemoteServiceException("请选择入库仓库");
        }

        WebsitSales websitSales = websitSalesService.getById(websitPartsRetAddUp.getSalesId());
        if (!websitSales.getFlag().equals("PAY_TAKE"))
            throw new RemoteServiceException("未提货不能退货");
        websitPartsRetAddUp.setWorkerWebsitId(websitSales.getWorkerWebsitId());
        websitPartsRetAddUp.setWorkerWebsitName(websitSales.getWorkerWebsitName());
        websitPartsRetAddUp.setPayTime(websitSales.getPayTime());
        websitPartsRetAddUp.setTotalAmount(websitSales.getTotalAmount());
        websitPartsRetAddUp.setPayNo(websitSales.getPayNo());
        websitPartsRetAddUp.setBuyPeople(websitSales.getBuyPeople());
        websitPartsRetAddUp.setSubmitBy(adminUser.getNickName());
        websitPartsRetAddUp.setSubmitTime(new Date());
        websitPartsRetAddUp.setPayType(websitSales.getPayType().equals(PayTypeEnum.ENGIN.getKey()) ? websitSales.getPayType() : "CASH");
        websitPartsRetAddUp.setCompanyWechatId(adminUser.getCompanyWechatId());
        websitPartsRetAddUp.setCompanyWechatName(adminUser.getCompanyName());
        websitPartsRetAddUp.setPartsRetId(null);
        websitPartsRetAddUp.setSalesType(websitSales.getSalesType());
        websitPartsRetAddUp.setOrderEnginBaseId(websitSales.getOrderEnginBaseId());
        websitPartsRetAddUp.setProjectNo(websitSales.getProjectNo());
        websitPartsRetAddUp.setProjectName(websitSales.getProjectName());
        websitPartsRetAddUp.insert();

        BigDecimal totalRefundAmount = new BigDecimal("0");

        if (CollectionUtils.isEmpty(websitPartsRetAddUp.getWebsitPartsRetItems()))
            throw new RemoteServiceException("没有产品不能提交");

        for (WebsitPartsRetItem websitPartsRetItem : websitPartsRetAddUp.getWebsitPartsRetItems()) {
            websitPartsRetItem.setId(null);

            WebsitSalesItem one = websitSalesItemService.lambdaQuery().eq(WebsitSalesItem::getSalesId, websitSales.getSalesId())
                    .eq(WebsitSalesItem::getGoodsId, websitPartsRetItem.getGoodsId()).last("limit 1")
                    .one();
            if (websitPartsRetAddUp.getType().equals("NEW")) {
                if (websitPartsRetItem.getNewRefundQty().doubleValue() < 1)
                    throw new RemoteServiceException("销售数量不能小于1");
                one.setRetQty(one.getRetQty().add(websitPartsRetItem.getNewRefundQty()));
            } else {
                if (websitPartsRetItem.getOldRefundQty().doubleValue() < 1)
                    throw new RemoteServiceException("销售数量不能小于1");
                one.setOldRefundQty(one.getOldRefundQty().add(websitPartsRetItem.getOldRefundQty()));
            }
            if (one.getRetQty().add(one.getOldRefundQty()).doubleValue() > one.getSalesQty().doubleValue()) {
                throw new RemoteServiceException(websitPartsRetItem.getGoodsName() + "超过销售数量");
            }

            if (websitPartsRetItem.getSaleAmount().doubleValue() < websitPartsRetItem.getRefundAmount().doubleValue()) {
                throw new RemoteServiceException(websitPartsRetItem.getGoodsName() + "超过了销售金额");
            }


            one.updateById();

            websitSales.setRetAmount(websitSales.getRetAmount()
                    .add(websitPartsRetItem.getRefundAmount()));

            if (websitSales.getRetAmount().doubleValue() > websitSales.getTotalAmount().doubleValue())
                throw new RemoteServiceException(websitPartsRetItem.getGoodsName() + "超过了销售金额");

            websitSales.updateById();
            if (websitPartsRetItem.getRefundAmount() != null)
                totalRefundAmount = totalRefundAmount.add(websitPartsRetItem.getRefundAmount());
            websitPartsRetItem.setPartsRetId(websitPartsRetAddUp.getPartsRetId());
        }

        if (!CollectionUtils.isEmpty(websitPartsRetAddUp.getWebsitPartsRetOldRecordList())) {
            for (WebsitPartsRetOldRecord websitPartsRetOldRecord : websitPartsRetAddUp.getWebsitPartsRetOldRecordList()) {
                websitPartsRetOldRecord.setPartsRetId(websitPartsRetAddUp.getPartsRetId());
            }
            websitPartsRetOldRecordService.saveBatch(websitPartsRetAddUp.getWebsitPartsRetOldRecordList());
        }
        websitPartsRetAddUp.setTotalRefundAmount(totalRefundAmount);
        websitPartsRetAddUp.updateById();
        websitPartsRetItemService.saveBatch(websitPartsRetAddUp.getWebsitPartsRetItems());


    }


    @Transactional(rollbackFor = Exception.class)
    public void update(WebsitPartsRetAddUp websitPartsRetAddUp) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if ((StringUtil.isEmpty(websitPartsRetAddUp.getFlag()) || websitPartsRetAddUp.getFlag().equals(ExamineStatusEnum.SUBMIT.getKey()))
            && StringUtils.isBlank(websitPartsRetAddUp.getStorageId())) {
            throw new RemoteServiceException("请选择入库仓库");
        }

        WebsitPartsRet oldRet = websitPartsRetService.getById(websitPartsRetAddUp.getPartsRetId());
        if (StringUtils.isBlank(websitPartsRetAddUp.getSalesId())) {
            websitPartsRetAddUp.setSalesId(oldRet.getSalesId());
        }
        WebsitSales oldWebsitSales = websitSalesService.getById(websitPartsRetAddUp.getSalesId());

        if (Objects.isNull(oldWebsitSales)) {
            throw new RemoteServiceException("销售单不存在");
        }

        websitPartsRetAddUp.setPayType(oldWebsitSales.getPayType().equals(PayTypeEnum.ENGIN.getKey()) ? oldWebsitSales.getPayType() : "CASH");
        websitPartsRetAddUp.updateById();

        websitPartsRetAddUp.setSalesType(oldWebsitSales.getSalesType());
        websitPartsRetAddUp.setOrderEnginBaseId(oldWebsitSales.getOrderEnginBaseId());
        websitPartsRetAddUp.setProjectNo(oldWebsitSales.getProjectNo());
        websitPartsRetAddUp.setProjectName(oldWebsitSales.getProjectName());

        if (!StringUtil.isEmpty(websitPartsRetAddUp.getFlag()) && websitPartsRetAddUp.getFlag().equals(ExamineStatusEnum.OK.getKey())) {

            WebsitPartsRet byId = websitPartsRetService.getById(websitPartsRetAddUp.getPartsRetId());
            if (byId.getType().equals("NEW"))
                this.newAddStockACC(websitPartsRetAddUp.getPartsRetId());
            else
                this.oldAddStockACC(websitPartsRetAddUp.getPartsRetId());

            this.addPayRerod(websitPartsRetAddUp.getPartsRetId());

            websitPartsRetAddUp.setConfirmTime(new Date());
            websitPartsRetAddUp.setConfirmBy(adminUser.getNickName());
            websitPartsRetAddUp.updateById();

            WebsitPartsRet websitSales = websitPartsRetService.getById(websitPartsRetAddUp.getPartsRetId());

            if (websitSales.getSalesType().equals(WebsitSalesTypeEnum.ENGIN.getName())) {
                websitGoodsMangerLogic.givePrice((websitSales.getTotalRefundAmount().multiply(new BigDecimal("-1"))),
                        websitSales.getOrderEnginBaseId(), null, "退货金额记录，退货单号：" + websitSales.getPartsRetId(), websitSales.getPartsRetId(), websitSales.getGoodsType());
                websitGoodsMangerLogic.upManage(websitSales.getOrderEnginBaseId(), websitSales.getGoodsType());
            }
        }

        if (CollectionUtils.isEmpty(websitPartsRetAddUp.getWebsitPartsRetItems()))
            return;

        WebsitSales websitSales = websitSalesService.getById(websitPartsRetAddUp.getSalesId());

        List<WebsitPartsRetItem> list = websitPartsRetItemService.lambdaQuery().eq(WebsitPartsRetItem::getPartsRetId, websitPartsRetAddUp.getPartsRetId()).list();
        for (WebsitPartsRetItem websitPartsRetItem : list) {

            WebsitSalesItem one = websitSalesItemService.lambdaQuery().eq(WebsitSalesItem::getSalesId, websitPartsRetAddUp.getSalesId())
                    .eq(WebsitSalesItem::getGoodsId, websitPartsRetItem.getGoodsId()).last("limit 1")
                    .one();
            if (websitPartsRetAddUp.getType().equals("NEW")) {

                one.setRetQty(one.getRetQty().subtract(websitPartsRetItem.getNewRefundQty()));
            } else {

                one.setOldRefundQty(one.getOldRefundQty().subtract(websitPartsRetItem.getOldRefundQty()));
            }


            one.updateById();

            websitSales.setRetAmount(websitSales.getRetAmount()
                    .subtract(websitPartsRetItem.getRefundAmount()));

            if (websitSales.getRetAmount().doubleValue() > websitSales.getTotalAmount().doubleValue())
                throw new RemoteServiceException(websitPartsRetItem.getGoodsName() + "超过了销售金额");


            websitSales.updateById();

        }
        if (CollectionUtils.isEmpty(websitPartsRetAddUp.getWebsitPartsRetItems()))
            throw new RemoteServiceException("没有产品不能提交");
        websitPartsRetItemService.lambdaUpdate().eq(WebsitPartsRetItem::getPartsRetId, websitPartsRetAddUp.getPartsRetId()).remove();
        for (WebsitPartsRetItem websitPartsRetItem : websitPartsRetAddUp.getWebsitPartsRetItems()) {

            WebsitSalesItem one = websitSalesItemService.lambdaQuery().eq(WebsitSalesItem::getSalesId, websitSales.getSalesId())
                    .eq(WebsitSalesItem::getGoodsId, websitPartsRetItem.getGoodsId()).last("limit 1")
                    .one();
            if (websitPartsRetAddUp.getType().equals("NEW")) {
                if (websitPartsRetItem.getNewRefundQty().doubleValue() < 1)
                    throw new RemoteServiceException("销售数量不能小于1");
                one.setRetQty(one.getRetQty().add(websitPartsRetItem.getNewRefundQty()));
            } else {
                if (websitPartsRetItem.getOldRefundQty().doubleValue() < 1)
                    throw new RemoteServiceException("销售数量不能小于1");
                one.setOldRefundQty(one.getOldRefundQty().add(websitPartsRetItem.getOldRefundQty()));
            }
            if (one.getRetQty().add(one.getOldRefundQty()).doubleValue() > one.getSalesQty().doubleValue()) {
                throw new RemoteServiceException(websitPartsRetItem.getGoodsName() + "超过销售数量");
            }

            one.updateById();

            websitSales.setRetAmount(websitSales.getRetAmount()
                    .add(websitPartsRetItem.getRefundAmount()));

            websitSales.updateById();

            websitPartsRetItem.setPartsRetId(websitPartsRetAddUp.getPartsRetId());
        }
        websitPartsRetOldRecordService.lambdaUpdate().eq(WebsitPartsRetOldRecord::getPartsRetId, websitPartsRetAddUp.getPartsRetId()).remove();

        if (!CollectionUtils.isEmpty(websitPartsRetAddUp.getWebsitPartsRetOldRecordList())) {
            for (WebsitPartsRetOldRecord websitPartsRetOldRecord : websitPartsRetAddUp.getWebsitPartsRetOldRecordList()) {
                websitPartsRetOldRecord.setPartsRetId(websitPartsRetAddUp.getPartsRetId());
            }
            websitPartsRetOldRecordService.saveOrUpdateBatch(websitPartsRetAddUp.getWebsitPartsRetOldRecordList());
        }
        websitPartsRetItemService.saveBatch(websitPartsRetAddUp.getWebsitPartsRetItems());

    }

    private void addPayRerod(String salesRetId) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        WebsitPartsRet websitPartsRet = websitPartsRetService.getById(salesRetId);

        List<WebsitPartsRetItem> websitPartsRetItemList = websitPartsRetItemService.lambdaQuery().eq(WebsitPartsRetItem::getPartsRetId, salesRetId).list();

        WebsitSalesPayOrder websitSalesPayOrder = new WebsitSalesPayOrder();

        WebsitSalesPayOrder order = new WebsitSalesPayOrder();
        order.setCompanyWechatId(websitPartsRet.getCompanyWechatId());
        order.setCompanyWechatName(websitPartsRet.getCompanyWechatName());
        order.setGoodsType(websitPartsRet.getGoodsType());
        order.setWebsitId(websitPartsRet.getWebsitId());
        order.setWebsitName(websitPartsRet.getWebsitName());
        order.setOrderId(websitPartsRet.getPartsRetId());
        order.setOriginOrderId(websitPartsRet.getSalesId());
        order.setOrderCreateTime(websitPartsRet.getCreateTime());
        order.setPayType(websitPartsRet.getPayType());
        order.setPayFlag(IsYesNoEnum.YES.getKey());
        order.setPayTime(websitPartsRet.getPayTime());
        order.setPayValue(websitPartsRet.getTotalRefundAmount());
        order.setOrderType(PayOrderTypeEnum.R.getKey());
        if (websitPartsRet.getType().equals("NEW")) {
            order.setOrderSource(SalesPayOrderSourceEnum.NEW_PARTS_RET.getKey());
        } else {
            order.setOrderSource(SalesPayOrderSourceEnum.OLD_PARTS_RET.getKey());
        }

        order.insert();
    }

    private void oldAddStockACC(String partsRetId) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        WebsitPartsRet websitPartsRet = websitPartsRetService.getById(partsRetId);

        List<WebsitPartsRetOldRecord> websitPartsRetOldRecords = websitPartsRetOldRecordService.lambdaQuery()
                .eq(WebsitPartsRetOldRecord::getPartsRetId, partsRetId).list();

        List<WebsitPartsRetItem> websitPartsRetItems = websitPartsRetItemService.lambdaQuery().eq(WebsitPartsRetItem::getPartsRetId, partsRetId).list();

        List<WorkerStockDTO> workerStockDTOS = new ArrayList<>();
        List<WebsitStockDTO> websitStockDTOS = new ArrayList<>();

        if (websitPartsRet.getBuyPeople().equals(BuyPeopleEnum.WORKER.getKey())) {
            for (WebsitPartsRetItem websitPartsRetItem : websitPartsRetItems) {
                WorkerStockDTO workerStockDTO = new WorkerStockDTO();
                workerStockDTO.setCompanyWechatId(websitPartsRet.getCompanyWechatId());
                workerStockDTO.setCompanyWechatName(websitPartsRet.getCompanyWechatName());
                workerStockDTO.setIdentity(websitPartsRet.getIdentity());
                workerStockDTO.setWorkerId(websitPartsRet.getWorkerId());
                workerStockDTO.setWorkerName(websitPartsRet.getWorkerName());
                workerStockDTO.setWebsitId(websitPartsRet.getWebsitId());
                workerStockDTO.setWebsitName(websitPartsRet.getWebsitName());
                workerStockDTO.setSdate(websitPartsRet.getCreateTime());
                workerStockDTO.setWorkerWebsitId(websitPartsRet.getWorkerWebsitId());
                workerStockDTO.setWorkerWebsitName(websitPartsRet.getWorkerWebsitName());
                workerStockDTO.setGoodsId(websitPartsRetItem.getGoodsId());
                workerStockDTO.setGoodsName(websitPartsRetItem.getGoodsName());
                workerStockDTO.setGoodsType(websitPartsRetItem.getGoodsType());
                workerStockDTO.setPrice(websitPartsRetItem.getPrice());
                workerStockDTO.setGoodsStockUnit(websitPartsRetItem.getGoodsSalesUnit());
                workerStockDTO.setRef(websitPartsRetItem.getPartsRetId());
                workerStockDTO.setRefType("旧件返还");
                workerStockDTO.setPartsAttr(PartsAttrEnum.NEW.getKey());
                workerStockDTO.setChangeQty(websitPartsRetItem.getOldRefundQty());
                workerStockDTO.setDirectFlag(DirectFlagEnum.SUB.getKey());
                workerStockDTO.setFlag(WorkerStockFlagEnum.REFUND_OLD.getKey());
                workerStockDTO.setObj("师傅");
                workerStockDTO.setWorkerOrderNo("");
                workerStockDTO.setRemark(websitPartsRet.getRemark());
                workerStockDTO.setOperateBy(adminUser.getNickName());
                workerStockDTO.setOperateTime(DateUtil.date());
                workerStockDTOS.add(workerStockDTO);

            }
            materialGoodsStockLogic.handleWorkerStock(workerStockDTOS);
        }

        for (WebsitPartsRetOldRecord websitPartsRetOldRecord : websitPartsRetOldRecords) {
            // 入库注值
            WebsitStockDTO websitStockDTO = new WebsitStockDTO();
            websitStockDTO.setCompanyWechatId(websitPartsRet.getCompanyWechatId());
            websitStockDTO.setCompanyWechatName(websitPartsRet.getCompanyWechatName());
            websitStockDTO.setWebsitId(websitPartsRet.getWebsitId());
            websitStockDTO.setWebsitName(websitPartsRet.getWebsitName());
            websitStockDTO.setSdate(websitPartsRet.getCreateTime());
            websitStockDTO.setPartsAttr(PartsAttrEnum.OLD.toString());
            websitStockDTO.setGoodsId(websitPartsRetOldRecord.getGoodsId());
            websitStockDTO.setGoodsName(websitPartsRetOldRecord.getGoodsName());
            websitStockDTO.setGoodsType("P");
            websitStockDTO.setRef(websitPartsRet.getPartsRetId());
            websitStockDTO.setRefType("旧件返还");
            websitStockDTO.setChangeQty(websitPartsRetOldRecord.getQty());
            websitStockDTO.setDirectFlag(DirectFlagEnum.ADD.getKey());
            websitStockDTO.setRemark(websitPartsRet.getRemark());
            websitStockDTO.setOperateBy(adminUser.getNickName());
            websitStockDTO.setOperateTime(new Date());
            websitStockDTO.setObj("供应商");
            websitStockDTO.setStorageId(websitPartsRet.getStorageId());
            websitStockDTOS.add(websitStockDTO);
        }

        materialGoodsStockLogic.handleWebsitStock(websitStockDTOS);

    }


    private void newAddStockACC(String partsRetId) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        WebsitPartsRet websitPartsRet = websitPartsRetService.getById(partsRetId);

        List<WebsitPartsRetItem> websitPartsRetItems = websitPartsRetItemService.lambdaQuery().eq(WebsitPartsRetItem::getPartsRetId, partsRetId).list();

        List<WorkerStockDTO> workerStockDTOS = new ArrayList<>();
        List<WebsitStockDTO> websitStockDTOS = new ArrayList<>();

        for (WebsitPartsRetItem websitPartsRetItem : websitPartsRetItems) {
            WorkerStockDTO workerStockDTO = new WorkerStockDTO();
            workerStockDTO.setCompanyWechatId(websitPartsRet.getCompanyWechatId());
            workerStockDTO.setCompanyWechatName(websitPartsRet.getCompanyWechatName());
            workerStockDTO.setIdentity(websitPartsRet.getIdentity());
            workerStockDTO.setWorkerId(websitPartsRet.getWorkerId());
            workerStockDTO.setWorkerName(websitPartsRet.getWorkerName());
            workerStockDTO.setWebsitId(websitPartsRet.getWebsitId());
            workerStockDTO.setWebsitName(websitPartsRet.getWebsitName());
            workerStockDTO.setSdate(websitPartsRet.getCreateTime());
            workerStockDTO.setWorkerWebsitId(websitPartsRet.getWorkerWebsitId());
            workerStockDTO.setWorkerWebsitName(websitPartsRet.getWorkerWebsitName());
            workerStockDTO.setGoodsId(websitPartsRetItem.getGoodsId());
            workerStockDTO.setGoodsName(websitPartsRetItem.getGoodsName());
            workerStockDTO.setGoodsType(websitPartsRetItem.getGoodsType());
            workerStockDTO.setPrice(websitPartsRetItem.getPrice());
            workerStockDTO.setGoodsStockUnit(websitPartsRetItem.getGoodsSalesUnit());
            workerStockDTO.setRef(websitPartsRetItem.getPartsRetId());
            workerStockDTO.setRefType("新件返还");
            workerStockDTO.setPartsAttr(PartsAttrEnum.NEW.getKey());
            workerStockDTO.setChangeQty(websitPartsRetItem.getNewRefundQty());
            workerStockDTO.setDirectFlag(DirectFlagEnum.SUB.getKey());
            workerStockDTO.setFlag(WorkerStockFlagEnum.REFUND_NEW.getKey());
            workerStockDTO.setObj("师傅");
            workerStockDTO.setWorkerOrderNo("");
            workerStockDTO.setRemark(websitPartsRet.getRemark());
            workerStockDTO.setOperateBy(adminUser.getNickName());
            workerStockDTO.setOperateTime(DateUtil.date());
            workerStockDTOS.add(workerStockDTO);

            // 入库注值
            WebsitStockDTO websitStockDTO = new WebsitStockDTO();
            websitStockDTO.setCompanyWechatId(websitPartsRet.getCompanyWechatId());
            websitStockDTO.setCompanyWechatName(websitPartsRet.getCompanyWechatName());
            websitStockDTO.setWebsitId(websitPartsRet.getWebsitId());
            websitStockDTO.setWebsitName(websitPartsRet.getWebsitName());
            websitStockDTO.setSdate(websitPartsRet.getCreateTime());
            websitStockDTO.setPartsAttr(PartsAttrEnum.NEW.toString());
            websitStockDTO.setGoodsId(websitPartsRetItem.getGoodsId());
            websitStockDTO.setGoodsName(websitPartsRetItem.getGoodsName());
            websitStockDTO.setGoodsType(websitPartsRetItem.getGoodsType());
            websitStockDTO.setPrice(websitPartsRetItem.getPrice());
            websitStockDTO.setRef(websitPartsRet.getPartsRetId());
            websitStockDTO.setRefType("新件返还");
            websitStockDTO.setChangeQty(websitPartsRetItem.getNewRefundQty());
            websitStockDTO.setDirectFlag(DirectFlagEnum.ADD.getKey());
            websitStockDTO.setRemark(websitPartsRet.getRemark());
            websitStockDTO.setOperateBy(adminUser.getNickName());
            websitStockDTO.setOperateTime(new Date());
            websitStockDTO.setObj("供应商");
            websitStockDTO.setStorageId(websitPartsRet.getStorageId());
            websitStockDTOS.add(websitStockDTO);
        }

        materialGoodsStockLogic.handleWebsitStock(websitStockDTOS);
        if (websitPartsRet.getBuyPeople().equals(BuyPeopleEnum.WORKER.getKey())) {
            materialGoodsStockLogic.handleWorkerStock(workerStockDTOS);
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void del(List<String> partsId) {
        websitPartsRetService.lambdaUpdate().in(WebsitPartsRet::getPartsRetId, partsId).remove();
        websitPartsRetItemService.lambdaUpdate().in(WebsitPartsRetItem::getPartsRetId, partsId).remove();
    }

    public WebsitPartsRetDetail detail(String id) {
        WebsitPartsRet websitPartsRet = websitPartsRetService.getById(id);

        WebsitPartsRetDetail websitSalesRetDetail = BeanUtil.toBean(websitPartsRet, WebsitPartsRetDetail.class);

        if (websitPartsRet.getSalesType().equals("工程")) {
            WebsitSales websitSales = websitSalesService.lambdaQuery()
                    .eq(WebsitSales::getSalesId, websitPartsRet.getSalesId())
                    .one();
            websitSalesRetDetail.setManger(websitSales.getManger());
            websitSalesRetDetail.setMobile(websitSales.getMobile());
            websitSalesRetDetail.setStartTime(websitSales.getStartTime());
            websitSalesRetDetail.setEndTime(websitSales.getEndTime());
            websitSalesRetDetail.setProvince(websitSales.getProvince());
            websitSalesRetDetail.setProvinceId(websitSales.getProvinceId());
            websitSalesRetDetail.setCity(websitSales.getCity());
            websitSalesRetDetail.setCityId(websitSales.getCityId());
            websitSalesRetDetail.setArea(websitSales.getArea());
            websitSalesRetDetail.setAreaId(websitSales.getAreaId());
            websitSalesRetDetail.setStreet(websitSales.getStreet());
            websitSalesRetDetail.setStreetId(websitSales.getStreetId());
            websitSalesRetDetail.setAddress(websitSales.getAddress());
        }

        websitSalesRetDetail.setWebsitPartsRetItemList(websitPartsRetItemService.lambdaQuery().eq(WebsitPartsRetItem::getPartsRetId, id).list());
        websitSalesRetDetail.setWebsitPartsRetOldRecordList(websitPartsRetOldRecordService.lambdaQuery().eq(WebsitPartsRetOldRecord::getPartsRetId, id).list());
        return websitSalesRetDetail;
    }

    public IPage<WebsitPartsFactoryRetVO> pageFactoryV2(ZfireParamBean zfireParamBean) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> companyWechatIds = adminUser.getCompanyWechatIds();

        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean, WebsitPartsFactoryRetVO.class,adminUser);


        IPage<WebsitPartsFactoryRetVO> websitPartsRetVOIPage = websitSalesRetCMapper.pagePartsFactoryRetV2(new Page(zfireParamBean.getPageNum(),
                        zfireParamBean.getPageSize()),
                zfireParam
                , companyWechatIds);

        return websitPartsRetVOIPage;
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveFactory(WebsitPartsRetAddUp websitPartsRetAddUp) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (StringUtils.isBlank(websitPartsRetAddUp.getStorageId())) {
            throw new RemoteServiceException("请选择出库仓库");
        }

        websitPartsRetAddUp.setCompanyWechatId(adminUser.getCompanyWechatId());
        websitPartsRetAddUp.setCompanyWechatName(adminUser.getCompanyName());
        websitPartsRetAddUp.setCompanyWechatName(adminUser.getCompanyName());
        websitPartsRetAddUp.setFlag(ExamineStatusEnum.SAVE.getKey());
        websitPartsRetAddUp.insert();

        BigDecimal totalRefundAmount = new BigDecimal("0");

        if (CollectionUtils.isEmpty(websitPartsRetAddUp.getWebsitPartsRetItems()))
            throw new RemoteServiceException("没有产品不能提交");

        for (WebsitPartsRetItem websitPartsRetItem : websitPartsRetAddUp.getWebsitPartsRetItems()) {
            websitPartsRetItem.setPartsRetId(websitPartsRetAddUp.getPartsRetId());
        }

        websitPartsRetItemService.saveBatch(websitPartsRetAddUp.getWebsitPartsRetItems());
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateFactory(WebsitPartsRetAddUp websitPartsRetAddUp) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if ((StringUtil.isEmpty(websitPartsRetAddUp.getFlag()) || websitPartsRetAddUp.getFlag().equals(ExamineStatusEnum.SUBMIT.getKey()))
                && StringUtils.isBlank(websitPartsRetAddUp.getStorageId())) {
            throw new RemoteServiceException("请选择出库仓库");
        }

        websitPartsRetAddUp.setSubmitTime(new Date());
        websitPartsRetAddUp.setSubmitBy(adminUser.getNickName());
        websitPartsRetAddUp.updateById();



/*        if (!StringUtil.isEmpty(websitPartsRetAddUp.getFlag()) && websitPartsRetAddUp.getFlag().equals(ExamineStatusEnum.OK.getKey())){

            return;
        }*/

        if (CollectionUtils.isEmpty(websitPartsRetAddUp.getWebsitPartsRetItems()))
            throw new RemoteServiceException("没有产品不能提交");


        List<WebsitPartsRetItem> list = websitPartsRetItemService.lambdaQuery()
                .eq(WebsitPartsRetItem::getPartsRetId, websitPartsRetAddUp.getPartsRetId())
                .list();


        websitPartsRetItemService.lambdaUpdate().eq(WebsitPartsRetItem::getPartsRetId, websitPartsRetAddUp.getPartsRetId()).remove();

        for (WebsitPartsRetItem websitPartsRetItem : websitPartsRetAddUp.getWebsitPartsRetItems()) {
            websitPartsRetItem.setPartsRetId(websitPartsRetAddUp.getPartsRetId());
        }


        websitPartsRetItemService.saveBatch(websitPartsRetAddUp.getWebsitPartsRetItems());
    }

    @Transactional(rollbackFor = Exception.class)
    public void examine(WebsitPartsRetAddUp websitPartsRetAddUp) throws Exception {

        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (!StringUtil.isEmpty(websitPartsRetAddUp.getFlag()) && websitPartsRetAddUp.getFlag().equals(ExamineStatusEnum.FAIL.getKey())) {
            websitPartsRetAddUp.setFlag(ExamineStatusEnum.SAVE.getKey());
        }

        websitPartsRetAddUp.setConfirmTime(new Date());
        websitPartsRetAddUp.setConfirmBy(adminUser.getNickName());

        websitPartsRetAddUp.updateById();

        if (!StringUtil.isEmpty(websitPartsRetAddUp.getFlag()) && websitPartsRetAddUp.getFlag().equals(ExamineStatusEnum.OK.getKey())) {

            websitPartsRetAddUp.setConfirmTime(new Date());
            websitPartsRetAddUp.setConfirmBy(adminUser.getNickName());
            websitPartsRetAddUp.updateById();

            WebsitPartsRet websitSales = websitPartsRetService.getById(websitPartsRetAddUp.getPartsRetId());

            List<WebsitPartsRetItem> websitPartsRetItems = websitPartsRetItemService.lambdaQuery().eq(WebsitPartsRetItem::getPartsRetId, websitSales.getPartsRetId()).list();

            List<WebsitStockDTO> websitStockDTOS = new ArrayList<>();

            for (WebsitPartsRetItem websitPartsRetItem : websitPartsRetItems) {
                // 入库注值
                WebsitStockDTO websitStockDTO = new WebsitStockDTO();
                websitStockDTO.setCompanyWechatId(websitSales.getCompanyWechatId());
                websitStockDTO.setCompanyWechatName(websitSales.getCompanyWechatName());
                websitStockDTO.setWebsitId(websitSales.getWebsitId());
                websitStockDTO.setWebsitName(websitSales.getWebsitName());
                websitStockDTO.setSdate(websitSales.getCreateTime());
                websitStockDTO.setPartsAttr(PartsAttrEnum.OLD.toString());
                websitStockDTO.setGoodsId(websitPartsRetItem.getGoodsId());
                websitStockDTO.setGoodsName(websitPartsRetItem.getGoodsName());
                websitStockDTO.setGoodsType("P");
                websitStockDTO.setRef(websitSales.getPartsRetId());
                websitStockDTO.setRefType("旧件返厂");
                websitStockDTO.setChangeQty(websitPartsRetItem.getOldRefundQty());
                websitStockDTO.setDirectFlag(DirectFlagEnum.SUB.getKey());
                websitStockDTO.setRemark(websitSales.getRemark());
                websitStockDTO.setOperateBy(adminUser.getNickName());
                websitStockDTO.setOperateTime(new Date());
                websitStockDTO.setObj("供应商");
                websitStockDTO.setStorageId(websitSales.getStorageId());
                websitStockDTOS.add(websitStockDTO);
            }

            materialGoodsStockLogic.handleWebsitStock(websitStockDTOS);


        }

    }
}
