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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
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.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.gree.mall.manager.bean.SalesCustomerPartsBean;
import com.gree.mall.manager.bean.SalesCustomerPartsItemBean;
import com.gree.mall.manager.bean.WorkerNormStockBean;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.material.stock.WorkerStockDTO;
import com.gree.mall.manager.bean.settle.SettlementWorkerLogicVO;
import com.gree.mall.manager.bean.settle.SettlementWorkerOrderVO;
import com.gree.mall.manager.bean.websit.SettlementOrderDetail;
import com.gree.mall.manager.bean.websit.SettlementOrderLogicVO;
import com.gree.mall.manager.bean.websit.WorkerSettlementLineVO;
import com.gree.mall.manager.bean.websit.WorkerSettlementVO;
import com.gree.mall.manager.bean.worker.SettlementPgOrderVO;
import com.gree.mall.manager.commonmapper.MaterialGoodsStockCMapper;
import com.gree.mall.manager.commonmapper.MaterialMapper;
import com.gree.mall.manager.commonmapper.WebsitSalesRetCMapper;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.enums.*;
import com.gree.mall.manager.enums.material.NormTypeEnum;
import com.gree.mall.manager.enums.material.PartsAttrEnum;
import com.gree.mall.manager.enums.material.WebsitGoodsTypeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.common.WechatLogic;
import com.gree.mall.manager.logic.material.stock.WorkerStockLogic;
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.SettlementZfireParamBean;
import com.gree.mall.manager.zfire.bean.WorkerParamBean;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.stream.Collectors;

@Service
@Log4j
public class SettlementOrderLogic {

    @Autowired
    WebsitSalesRetCMapper websitSalesRetCMapper;

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    WebsitNormChargeService websitNormChargeService;

    @Autowired
    SettlementOrderService settlementOrderService;

    @Autowired
    SettlementOrderItemService settlementOrderItemService;

    @Autowired
    WithdrawalOrderItemService withdrawalOrderItemService;

    @Autowired
    WorkerSettlementService workerSettlementService;

    @Autowired
    WorkerOrderService workerOrderService;

    @Autowired
    WechatLogic wechatLogic;

    @Autowired
    WorkerOrderItemService workerOrderItemService;

    @Autowired
    PgOrderBaseService pgOrderBaseService;

    @Autowired
    AdminCompanyWechatService adminCompanyWechatService;

    @Autowired
    SettlementOrderManualItemService settlementOrderManualItemService;

    @Autowired
    WorkerSettlementManualService workerSettlementManualService;

    @Autowired
    WebsitNormRecordService websitNormRecordService;

    @Autowired
    AdminWebsitService adminWebsitService;

    @Autowired
    WorkerStockService workerStockService;

    @Autowired
    WebsitGoodsService websitGoodsService;

    @Autowired
    RedisLockRegistry redisLockRegistry;

    @Autowired
    MaterialMapper materialMapper;

    @Autowired
    MaterialGoodsStockCMapper materialGoodsStockCMapper;

    @Autowired
    WorkerStockAccService workerStockAccService;

    @Autowired
    WebsitPartsOldRefundManageService websitPartsOldRefundManageService;

    @Autowired
    WebsitPartsOldRefundManageItemService websitPartsOldRefundManageItemService;

    @Autowired
    WorkerStockLogic workerStockLogic;

    @Autowired
    UserService userService;

    @Autowired
    PartsImportService partsImportService;



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

        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean, SettlementOrderLogicVO.class, adminUser);
        IPage<SettlementOrderLogicVO> settlementOrderLogicVOIPage = websitSalesRetCMapper.pageSettletV2(new Page(zfireParamBean.getPageNum(),
                        zfireParamBean.getPageSize()),
                zfireParam
                , companyWechatIds);

        return settlementOrderLogicVOIPage;
    }

    public SettlementOrderDetail detail(String id) {

        SettlementOrder settlementOrder = settlementOrderService.getById(id);

        SettlementOrderDetail settlementOrderDetail = BeanUtil.toBean(settlementOrder, SettlementOrderDetail.class);

        settlementOrderDetail.setSettlementOrderItemList(settlementOrderItemService.lambdaQuery().eq(SettlementOrderItem::getSettlementOrderId, id).list());
        return settlementOrderDetail;
    }

    @Transactional(rollbackFor = Exception.class)
    public void refund(String id) {


        SettlementOrder settlementOrder = settlementOrderService.getById(id);

        if (settlementOrder.getStatus().equals(SettlementStatusEnum.WAIT.getKey()) || settlementOrder.getStatus().equals(SettlementStatusEnum.WAIT_ING.getKey())) {
            settlementOrder.setStatus(SettlementStatusEnum.REFUND.getKey());
            settlementOrder.updateById();
        }

        if (settlementOrder.getRefundStatus().equals(IsYesNoEnum.YES.getKey()))
            throw new RemoteServiceException("订单已退");

        settlementOrder.setRefundStatus(IsYesNoEnum.YES.getKey());
        settlementOrder.updateById();

        WorkerOrder workerOrder = workerOrderService.getById(settlementOrder.getOrderId());

        workerOrder.setRefundStatus(IsYesNoEnum.YES.getKey());
        workerOrder.updateById();

        List<SettlementOrderItem> list = settlementOrderItemService.lambdaQuery().eq(SettlementOrderItem::getSettlementOrderId, id).list();
        settlementOrder.setSettlementOrderId("TK" + settlementOrder.getSettlementOrderId());
        settlementOrder.setTotalAmount(settlementOrder.getTotalAmount().multiply(Convert.toBigDecimal("-1")));
        settlementOrder.setWebsitAmount(settlementOrder.getWebsitAmount().multiply(Convert.toBigDecimal("-1")));
        settlementOrder.setWorkerAmount(settlementOrder.getWorkerAmount().multiply(Convert.toBigDecimal("-1")));
        settlementOrder.setStatus(SettlementStatusEnum.WAIT_ING.getKey());
        for (SettlementOrderItem settlementOrderItem : list) {
            settlementOrderItem.setId("T" + settlementOrderItem.getId());
            settlementOrderItem.setSettlementOrderId(settlementOrder.getSettlementOrderId());
            settlementOrderItem.setTotalAmount(settlementOrderItem.getGoodsAmount().multiply(Convert.toBigDecimal("-1")));
            settlementOrderItem.setWorkerAmount(settlementOrderItem.getWorkerAmount().multiply(Convert.toBigDecimal("-1")));
            settlementOrderItem.setWebsitAmount(settlementOrderItem.getWebsitAmount().multiply(Convert.toBigDecimal("-1")));
        }
        settlementOrder.insert();
        settlementOrderItemService.saveBatch(list);
    }

    @Transactional(rollbackFor = Exception.class)
    public void settlement(List<String> id) throws WxPayException {
        if (settlementOrderService.lambdaQuery()
                .in(SettlementOrder::getSettlementOrderId, id)
                .notIn(SettlementOrder::getStatus, SettlementStatusEnum.WAIT.getKey())
                .count() > 0) {
            throw new RemoteServiceException("存在非待结算得结算");
        }


        List<SettlementOrder> settlementOrders = settlementOrderService.lambdaQuery().in(SettlementOrder::getSettlementOrderId, id).list();

        for (SettlementOrder settlementOrder : settlementOrders) {
            wechatLogic.shareSettlementAmount(settlementOrder);
        }


    }

    @Transactional(rollbackFor = Exception.class)
    public void over(List<String> id) {
        if (settlementOrderService.lambdaQuery()
                .in(SettlementOrder::getSettlementOrderId, id)
                .notIn(SettlementOrder::getStatus, SettlementStatusEnum.WAIT.getKey(), SettlementStatusEnum.WAIT_ING.getKey())
                .count() > 0) {
            throw new RemoteServiceException("存在正在提现，或已提现得结算");
        }
        List<SettlementOrder> settlementOrders = settlementOrderService.lambdaQuery()
                .in(SettlementOrder::getSettlementOrderId, id)
                .list();

        List<String> websitIds = settlementOrders.stream().map(SettlementOrder::getWebsitId).distinct().collect(Collectors.toList());
        List<String> workerIds = settlementOrders.stream().map(SettlementOrder::getWorkerId).distinct().collect(Collectors.toList());

        for (String workerId : workerIds) {
            //for (String websitId : websitIds) {
            List<SettlementOrder> settlementOrdersList = settlementOrderService.lambdaQuery()
                    .eq(SettlementOrder::getWorkerId, workerId)
                    //.eq(SettlementOrder::getWebsitId, websitId)
                    .in(SettlementOrder::getSettlementOrderId, id)
                    .list();

            if (CollectionUtils.isEmpty(settlementOrdersList))
                continue;

            settlementOrderService.lambdaUpdate()
                    .eq(SettlementOrder::getWorkerId, workerId)
                    //.eq(SettlementOrder::getWebsitId, websitId)
                    .in(SettlementOrder::getSettlementOrderId, id)
                    .set(SettlementOrder::getStatus, SettlementStatusEnum.OVER.getKey())
                    .set(SettlementOrder::getSettlementTime, new Date())
                    .update();


            this.addWithdrawal(settlementOrdersList);
            // }
        }
    }

    private void addWithdrawal(List<SettlementOrder> settlementOrdersList) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        WithdrawalOrder withdrawalOrder = new WithdrawalOrder();
        withdrawalOrder.setId(IdWorker.getIdStr());
        withdrawalOrder.setStatus(1);
        withdrawalOrder.setCompanyWechatId(settlementOrdersList.get(0).getCompanyWechatId());
        withdrawalOrder.setCompanyWechatName(settlementOrdersList.get(0).getCompanyWechatName());
//        withdrawalOrder.setWebsitId(settlementOrdersList.get(0).getWebsitId());
//        withdrawalOrder.setWebsitName(settlementOrdersList.get(0).getWebsitName());
        withdrawalOrder.setWorkerId(settlementOrdersList.get(0).getWorkerId());
        withdrawalOrder.setWorkerName(settlementOrdersList.get(0).getWorkerName());
        withdrawalOrder.setWorkerMobile(settlementOrdersList.get(0).getWorkerMobile());
        withdrawalOrder.setType(1);
        withdrawalOrder.setIdcard(settlementOrdersList.get(0).getIdentity());
        withdrawalOrder.setGrantBy(adminUser.getNickName());
        withdrawalOrder.setGrantTime(new Date());

        BigDecimal amount = new BigDecimal("0");

        List<WithdrawalOrderItem> withdrawalOrderItems = new ArrayList<>();

        for (SettlementOrder settlementOrder : settlementOrdersList) {
            amount = amount.add(settlementOrder.getWorkerAmount());
            WithdrawalOrderItem withdrawalOrderItem = new WithdrawalOrderItem();
            withdrawalOrderItem.setWithdrawalOrderId(withdrawalOrder.getId());
            withdrawalOrderItem.setOrderId(settlementOrder.getSettlementOrderId());
            withdrawalOrderItem.setGoodsType(settlementOrder.getGoodsType());
            withdrawalOrderItem.setNum(settlementOrder.getNum());
            withdrawalOrderItem.setTotalPrice(settlementOrder.getTotalAmount());
            withdrawalOrderItem.setSettlementType(settlementOrder.getSettlementType());
            withdrawalOrderItem.setWorkerAmount(settlementOrder.getWorkerAmount());
            withdrawalOrderItem.setWebsitAmount(settlementOrder.getWebsitAmount());
//            withdrawalOrderItem.setWebsitId(settlementOrder.getWebsitId());
//            withdrawalOrderItem.setWebsitName(settlementOrder.getWebsitName());
            withdrawalOrderItem.setWorkerId(settlementOrder.getWorkerId());
            withdrawalOrderItem.setWorkerMobile(settlementOrder.getWorkerMobile());
            withdrawalOrderItem.setWorkerName(settlementOrder.getWorkerName());
            withdrawalOrderItems.add(withdrawalOrderItem);
        }

        if (CollectionUtils.isEmpty(withdrawalOrderItems))
            return;

        withdrawalOrder.setAmount(amount);
        withdrawalOrder.insert();

        withdrawalOrderItemService.saveBatch(withdrawalOrderItems);

    }

    public IPage<WorkerSettlementVO> workerSettlementPageV2(ZfireParamBean zfireParamBean) {

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

        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean, WorkerSettlementVO.class, adminUser);
        IPage<WorkerSettlementVO> settlementOrderLogicVOIPage = websitSalesRetCMapper.workerSettlementPageV2(new Page(zfireParamBean.getPageNum(),
                        zfireParamBean.getPageSize()),
                zfireParam);

        return settlementOrderLogicVOIPage;
    }

    public void lineSettlement(List<String> id) {
        if (settlementOrderService.lambdaQuery()
                .in(SettlementOrder::getSettlementOrderId, id)
                .eq(SettlementOrder::getPayType, SettlementPayTypeEnum.LINE.getKey())
                .notIn(SettlementOrder::getStatus, SettlementStatusEnum.WAIT.getKey())
                .count() > 0) {
            throw new RemoteServiceException("存在非待结算得结算");
        }
        List<SettlementOrder> list = settlementOrderService.lambdaQuery()
                .in(SettlementOrder::getSettlementOrderId, id)
                .eq(SettlementOrder::getStatus, SettlementStatusEnum.WAIT.getKey())
                .eq(SettlementOrder::getPayType, SettlementPayTypeEnum.LINE.getKey())
                .list();

        for (SettlementOrder settlementOrder : list) {
            WorkerSettlement one = workerSettlementService.lambdaQuery().eq(WorkerSettlement::getWorkerId, settlementOrder.getWorkerId())
                    .eq(WorkerSettlement::getPayType, SettlementPayTypeEnum.LINE.getKey())
                    .eq(WorkerSettlement::getType, "OTHER")
                    .last("limit 1").one();
            one.setGiveAmount(one.getGiveAmount().add(settlementOrder.getWorkerAmount()));

            one.updateById();
        }

        settlementOrderService.lambdaUpdate()
                .in(SettlementOrder::getSettlementOrderId, id)
                .eq(SettlementOrder::getStatus, SettlementStatusEnum.WAIT.getKey())
                .set(SettlementOrder::getStatus, SettlementStatusEnum.OVER.getKey()).update();
    }

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

        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean, WorkerSettlementLineVO.class, adminUser);
        IPage<WorkerSettlementLineVO> settlementOrderLogicVOIPage = websitSalesRetCMapper.pageLineSettlementV2(new Page(zfireParamBean.getPageNum(),
                        zfireParamBean.getPageSize()),
                zfireParam);

        return settlementOrderLogicVOIPage;
    }

    public void lineSettlementOrder(List<String> id) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (settlementOrderService.lambdaQuery()
                .in(SettlementOrder::getSettlementOrderId, id)
                .notIn(SettlementOrder::getStatus, SettlementStatusNewEnum.YC.getKey())
                .count() > 0) {
            throw new RemoteServiceException("存在非异常结算得结算单");
        }

        settlementOrderService.lambdaUpdate()
                .in(SettlementOrder::getSettlementOrderId, id)
                .eq(SettlementOrder::getStatus, SettlementStatusNewEnum.YC.getKey())
                .set(SettlementOrder::getStatus, SettlementStatusNewEnum.LINE.getKey())
                .set(SettlementOrder::getSettlementName, adminUser.getNickName())
                .set(SettlementOrder::getSettlementTime, new Date())
                .update();
    }


    public void sync() throws WxPayException, InterruptedException {

        List<WorkerOrder> workerOrders = workerOrderService.lambdaQuery()
                .eq(WorkerOrder::getPayState, IsYesNoEnum.YES.getKey())
                .ne(WorkerOrder::getPayStatus, PayStatusEnum.PAID.getKey())
                .le(WorkerOrder::getPayNum, 10)
                .list();

        for (WorkerOrder workerOrder : workerOrders) {

            Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_ORDER + workerOrder.getOrderId());
            try {
                if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                    throw new RemoteServiceException("系统繁忙，请稍后再试");
                }
                WxPayService payService = wechatLogic.getPayJaspWebstiService(workerOrder.getConfigId(), "B");

                WxPayOrderQueryResult wxPayOrderQueryResult = payService.queryOrder("", workerOrder.getOrderId());

                workerOrder.setPayNum((workerOrder.getPayNum()==null?0: workerOrder.getPayNum())+1);
                workerOrder.updateById();

                if (!wxPayOrderQueryResult.getReturnCode().equals("SUCCESS")) {
                    continue;
                }


                if (!wxPayOrderQueryResult.getResultCode().equals("SUCCESS")) {
                    continue;
                }

                if (!wxPayOrderQueryResult.getTradeState().equals("SUCCESS")) {
                    continue;
                }

                AdminWebsit adminWebsit = adminWebsitService.getById(workerOrder.getWebsitId());


                List<WorkerOrderItem> workerOrderItems = workerOrderItemService.lambdaQuery().eq(WorkerOrderItem::getOrderId, workerOrder.getOrderId()).list();

                // 身份证为空检查user表
                if (StringUtils.isBlank(workerOrder.getIdentity()) && StringUtils.isNotBlank(workerOrder.getUserId())) {
                    final User user = userService.getById(workerOrder.getUserId());
                    workerOrder.setIdentity(user.getIdCard());
                }

                workerOrder.setTranscationId(wxPayOrderQueryResult.getTransactionId());
                workerOrder.setPayState(IsYesNoEnum.YES.getKey());
                workerOrder.setPayStateTime(new Date());


                workerOrder.setConfigId(adminWebsit.getPayWorkerCodeId());
                workerOrder.updateById();

                workerOrder.setSource("小程序");

                workerOrder.setPayTime(new Date());
                workerOrder.setPayType("WECHAT");
                workerOrder.setPayNum((workerOrder.getPayNum()==null?0: workerOrder.getPayNum())+1);
                workerOrder.setPayStatus(PayStatusEnum.PAID.getKey());
                workerOrder.updateById();


                //插入手工结算数据
                if (workerOrder.getManualAmount() != null && workerOrder.getManualAmount().doubleValue() > 0) {
                    this.addManualSettlementOrder(workerOrder, workerOrderItems);
                    this.addSettlementManaulWorker(workerOrder, workerOrderItems);
                }
                //todo 辅材扣除


                //插入使用记录
                this.addNormRecord(workerOrder, workerOrderItems);

                // this.addSettlementWorker(workerOrder,workerOrderItems);


                // 定时任务辅材逻辑
                if (StringUtils.isNotBlank(workerOrder.getIdentity())) {
                    // 配件扣库存
                    try {
                        if (workerOrder.getGoodsType().equals("P")) {

                            List<WorkerOrderItem> inner = workerOrderItems.stream().filter(item -> item.getRepairFlag().equals("INNER")).collect(Collectors.toList());
                            List<WorkerOrderItem> OUTSIDE = workerOrderItems.stream().filter(item -> item.getRepairFlag().equals("OUTSIDE")).collect(Collectors.toList());

                            List<SalesCustomerPartsBean> salesCustomerPartsBeans = new ArrayList<>();

                            if (!CollectionUtils.isEmpty(inner)) {
                                SalesCustomerPartsBean salesCustomerPartsBean = new SalesCustomerPartsBean();
                                salesCustomerPartsBean.setCompanyWechatId(workerOrder.getCompanyWechatId());
                                salesCustomerPartsBean.setCompanyWechatName(workerOrder.getCompanyWechatName());
                                salesCustomerPartsBean.setRepairFlag("INNER");
                                salesCustomerPartsBean.setIdentity(workerOrder.getIdentity());
                                salesCustomerPartsBean.setWorkerNumber(workerOrder.getWorkerNumber());
                                salesCustomerPartsBean.setWorkerName(workerOrder.getWorkerName());
                                salesCustomerPartsBean.setWorkOrderNo(workerOrder.getWorkerOrderId());
                                salesCustomerPartsBean.setCustomerName(workerOrder.getUserName());
                                salesCustomerPartsBean.setCustomerTel(workerOrder.getUserMobile());
                                salesCustomerPartsBean.setReceiveWebsitId(adminWebsit.getWebsitId());
                                salesCustomerPartsBean.setReceivePartsWebsitId(adminWebsit.getPartsWebsitId());
                                salesCustomerPartsBean.setRemark(workerOrder.getRemark());


                                List<SalesCustomerPartsItemBean> salesCustomerPartsItemBeans = new ArrayList<>();

                                for (WorkerOrderItem workerOrderItem : inner) {
                                    if (workerOrderItem.getChargeType().equals("SERV")) {
                                        continue;
                                    }
                                    SalesCustomerPartsItemBean salesCustomerPartsItemBean = new SalesCustomerPartsItemBean();

                                    salesCustomerPartsItemBean.setOldPartsName(workerOrderItem.getOldPartsName());
                                    salesCustomerPartsItemBean.setOldPartsNumber(workerOrderItem.getOldPartsNumber());
                                    salesCustomerPartsItemBean.setPartsNumber(workerOrderItem.getGoodsCode());
                                    salesCustomerPartsItemBean.setQty(workerOrderItem.getNum());
                                    salesCustomerPartsItemBean.setWorkerOrderItemId(workerOrderItem.getId());

                                    salesCustomerPartsItemBeans.add(salesCustomerPartsItemBean);

                                }

                                salesCustomerPartsBean.setItems(salesCustomerPartsItemBeans);

                                salesCustomerPartsBeans.add(salesCustomerPartsBean);

                            }


                            if (!CollectionUtils.isEmpty(OUTSIDE)) {
                                SalesCustomerPartsBean salesCustomerPartsBean = new SalesCustomerPartsBean();
                                salesCustomerPartsBean.setCompanyWechatId(workerOrder.getCompanyWechatId());
                                salesCustomerPartsBean.setCompanyWechatName(workerOrder.getCompanyWechatName());
                                salesCustomerPartsBean.setRepairFlag("OUTSIDE");
                                salesCustomerPartsBean.setIdentity(workerOrder.getIdentity());
                                salesCustomerPartsBean.setWorkerNumber(workerOrder.getWorkerNumber());
                                salesCustomerPartsBean.setWorkerName(workerOrder.getWorkerName());
                                salesCustomerPartsBean.setWorkOrderNo(workerOrder.getWorkerOrderId());
                                salesCustomerPartsBean.setCustomerName(workerOrder.getUserName());
                                salesCustomerPartsBean.setCustomerTel(workerOrder.getUserMobile());
                                salesCustomerPartsBean.setReceiveWebsitId(adminWebsit.getWebsitId());
                                salesCustomerPartsBean.setReceivePartsWebsitId(adminWebsit.getPartsWebsitId());
                                salesCustomerPartsBean.setRemark(workerOrder.getRemark());


                                List<SalesCustomerPartsItemBean> salesCustomerPartsItemBeans = new ArrayList<>();

                                for (WorkerOrderItem workerOrderItem : OUTSIDE) {
                                    if (workerOrderItem.getChargeType().equals("SERV")) {
                                        continue;
                                    }
                                    SalesCustomerPartsItemBean salesCustomerPartsItemBean = new SalesCustomerPartsItemBean();

                                    salesCustomerPartsItemBean.setOldPartsName(workerOrderItem.getOldPartsName());
                                    salesCustomerPartsItemBean.setOldPartsNumber(workerOrderItem.getOldPartsNumber());
                                    salesCustomerPartsItemBean.setPartsNumber(workerOrderItem.getGoodsCode());
                                    salesCustomerPartsItemBean.setQty(workerOrderItem.getNum());
                                    salesCustomerPartsItemBean.setWorkerOrderItemId(workerOrderItem.getId());

                                    salesCustomerPartsItemBeans.add(salesCustomerPartsItemBean);

                                }

                                salesCustomerPartsBean.setItems(salesCustomerPartsItemBeans);

                                salesCustomerPartsBeans.add(salesCustomerPartsBean);

                            }


                            if (CollectionUtil.isNotEmpty(salesCustomerPartsBeans)) {
                                // 开始处理库存
                                for (SalesCustomerPartsBean salesCustomerPartsBean : salesCustomerPartsBeans) {
                                    workerStockLogic.oldRefundManageSyncAdd(salesCustomerPartsBean);
                                }

                            }
                        }

                    } catch (Exception e) {
                        log.error(workerOrder.getOrderId() + " 师傅配件扣自有库存失败: ", e);
                        workerOrder.setExRemark(workerOrder.getOrderId() + " 师傅配件扣自有库存失败: " + e.getMessage());

                    }

                    // 辅材扣库存
                    try {
                        if (workerOrder.getGoodsType().equals(WebsitGoodsTypeEnum.M.toString())) {
                            List<WorkerStockDTO> workerStockDTOS = new ArrayList<>();
                            this.makeSubStockData(workerOrder, workerOrderItems, workerStockDTOS);

                            if (CollectionUtil.isNotEmpty(workerStockDTOS)) {
                                // 开始处理库存
                                workerStockLogic.fucaiHandleWorkerStock(workerStockDTOS);
                            }
                        }
                    } catch (Exception e) {
                        log.error(workerOrder.getOrderId() + " 师傅辅材扣库存失败: ", e);
                        throw new RemoteServiceException("师傅辅材扣库存失败,没有库存");
                    }
                }


                //插入结算数据
                this.addSettlementOrder(workerOrder, workerOrderItems);


            } finally {
                obtain.unlock();
            }
        }

    }

    private void makeSubStockData(WorkerOrder workerOrder, List<WorkerOrderItem> workerOrderItems, List<WorkerStockDTO> workerStockDTOS) {
        Map<String, WorkerNormStockBean> workerStockMap = new HashMap<>();
        for (WorkerOrderItem item : workerOrderItems) {
            WebsitNormCharge websitNormCharge = websitNormChargeService.getById(item.getGoodsId());
            if (Objects.nonNull(websitNormCharge) && websitNormCharge.getNormType().equals(NormTypeEnum.M.getKey())) {
                // 获取当前关联师傅库存记录
                List<WorkerNormStockBean> stockBeanList = materialMapper.queryWorkerStockQty(item.getGoodsId(), workerOrder.getIdentity());
                if (CollectionUtil.isNotEmpty(stockBeanList)) {
                    BigDecimal totalNum = item.getNum();
                    for (WorkerNormStockBean stockBean : stockBeanList) {
                        // 当前订单收费标准扣总数量
                        BigDecimal useTotalQty = totalNum.multiply(stockBean.getQty());
                        if (!workerStockMap.containsKey(stockBean.getWorkerGoodsId() + item.getGoodsAmount())) {
                            WorkerNormStockBean bean = new WorkerNormStockBean();
                            BeanUtils.copyProperties(stockBean, bean);
                            bean.setRealQty(BigDecimal.ZERO);
                            workerStockMap.put(bean.getWorkerGoodsId() + item.getGoodsAmount(), bean);
                        }
                        WorkerNormStockBean stock = workerStockMap.get(stockBean.getWorkerGoodsId() + item.getGoodsAmount());
                        stock.setRealQty(stock.getRealQty().add(useTotalQty));
                        stock.setNormPrice(item.getGoodsAmount());

                        // 7、收费标准如果和辅材没有对应关系，不判断库存；从总部同步下来订单，如果师傅的库存不足，不限制支付；（允许负库存）
//                        if (!stockBean.getIsSmall() && stock.getRealQty().compareTo(stockBean.getStockQty()) > 0) {
//                            throw new RemoteServiceException("收费标准关联的 " + stockBean.getGoodsName() + "库存数量"
//                                    + stock.getStockQty() + ", 需扣" + stock.getRealQty() + ", 库存数量不够扣减");
//                        }
                    }
                }
            }
        }

        for (Map.Entry<String, WorkerNormStockBean> entry : workerStockMap.entrySet()) {
            final WorkerNormStockBean bean = entry.getValue();
            // 库存减少
            WorkerStockDTO workerStockDTO = new WorkerStockDTO();
            workerStockDTO.setCompanyWechatId(workerOrder.getCompanyWechatId());
            workerStockDTO.setCompanyWechatName(workerOrder.getCompanyWechatName());
            workerStockDTO.setIdentity(workerOrder.getIdentity());
            workerStockDTO.setWorkerId(workerOrder.getWorkerNumber());
            workerStockDTO.setWorkerName(workerOrder.getWorkerName());
            workerStockDTO.setWebsitId(workerOrder.getWebsitId());
            workerStockDTO.setWebsitName(workerOrder.getWebsitName());
            workerStockDTO.setSdate(workerOrder.getCreateTime());
            workerStockDTO.setWorkerWebsitId(workerOrder.getWebsitId());
            workerStockDTO.setWorkerWebsitName(workerOrder.getWebsitName());
            workerStockDTO.setGoodsId(bean.getWorkerGoodsId());
            workerStockDTO.setGoodsName(bean.getGoodsName());
            workerStockDTO.setGoodsType(WebsitGoodsTypeEnum.M.toString());
            workerStockDTO.setPrice(bean.getNormPrice());
            workerStockDTO.setGoodsStockUnit(bean.getSalesUnit());
            workerStockDTO.setRef(workerOrder.getOrderId());
            workerStockDTO.setRefType("辅材销售");
            workerStockDTO.setPartsAttr(PartsAttrEnum.NEW.toString());
            workerStockDTO.setChangeQty(bean.getRealQty());
            workerStockDTO.setDirectFlag("SUB");
            workerStockDTO.setFlag("USED");
            workerStockDTO.setObj("客户");
            workerStockDTO.setWorkerOrderNo(workerOrder.getWorkerOrderId());
            workerStockDTO.setRemark(workerOrder.getRemark());
            workerStockDTO.setOperateBy(workerOrder.getWorkerName());
            workerStockDTO.setOperateTime(DateUtil.date());

            workerStockDTOS.add(workerStockDTO);
        }
    }

    private void addNormRecord(WorkerOrder workerOrder, List<WorkerOrderItem> workerOrderItems) {
        List<WebsitNormRecord> websitNormRecords = new ArrayList<>();
        for (WorkerOrderItem workerOrderItem : workerOrderItems) {
            WebsitNormRecord websitNormRecord = new WebsitNormRecord();
            websitNormRecord.setCompanyWechatId(workerOrder.getCompanyWechatId());
            websitNormRecord.setCompanyWechatName(workerOrder.getCompanyWechatName());
            websitNormRecord.setGoodsType(workerOrder.getGoodsType());
            websitNormRecord.setWorkerId(workerOrder.getUserId());
            websitNormRecord.setWorkerNumber(workerOrder.getWorkerNumber());
            websitNormRecord.setWorkerName(workerOrder.getWorkerName());
            websitNormRecord.setOrderId(workerOrder.getWorkerOrderId());
            websitNormRecord.setRefOrder(workerOrder.getOrderId());
            websitNormRecord.setWebsitId(workerOrder.getWebsitId());
            websitNormRecord.setWebsitName(workerOrder.getWebsitName());
            websitNormRecord.setUseTime(new Date());
            websitNormRecord.setCreateTime(new Date());
            websitNormRecord.setGoodsName(workerOrderItem.getGoodsName());
            websitNormRecord.setGoodsCode(workerOrderItem.getGoodsCode());
            websitNormRecord.setNormAmount(workerOrderItem.getNormAmount());
            websitNormRecord.setUnit(workerOrderItem.getUnit());
            websitNormRecord.setUseQty(Convert.toBigDecimal(workerOrderItem.getNum()));
            websitNormRecords.add(websitNormRecord);
        }

        websitNormRecordService.saveBatch(websitNormRecords);
    }


    private void addSettlementOrder(WorkerOrder workerOrder, List<WorkerOrderItem> workerOrderItems) {
        AdminCompanyWechat adminCompanyWechat = adminCompanyWechatService.getById(workerOrder.getCompanyWechatId());

        SettlementOrder settlementOrder = BeanUtil.toBean(workerOrder, SettlementOrder.class);

        settlementOrder.setTranscationId(workerOrder.getTranscationId());
        settlementOrder.setOpenId(workerOrder.getOpenId());

        if (!StringUtil.isEmpty(workerOrder.getWorkerOrderId())) {
            PgOrderBase pgOrderBase = pgOrderBaseService.getById(workerOrder.getWorkerOrderId());
            if (pgOrderBase != null) {
                settlementOrder.setSaleType(pgOrderBase.getSaleType());
            }
        }

        settlementOrder.setAmount(settlementOrder.getTotalAmount());
        if (adminCompanyWechat.getDayNum() != null) {
            DateTime dateTime = DateUtil.offsetDay(new Date(), adminCompanyWechat.getDayNum());
            String format = DateUtil.format(dateTime, "yyyy-MM-dd");
            String formatDate = format + " " + adminCompanyWechat.getHourTime();
            DateTime parse = DateUtil.parse(formatDate);
            settlementOrder.setChangeTime(parse);
        } else {
            DateTime dateTime = DateUtil.offsetDay(new Date(), 1);
            settlementOrder.setChangeTime(dateTime);
        }

        if (settlementOrderService.lambdaQuery()
                .eq(SettlementOrder::getOrderId,settlementOrder.getOrderId()).count() > 0)
            throw new RemoteServiceException(settlementOrder.getOrderId()+"订单已生成");

        settlementOrder.insert();
        List<SettlementOrderItem> settlementOrderItems = BeanUtil.copyToList(workerOrderItems, SettlementOrderItem.class);
        for (SettlementOrderItem settlementOrderItem : settlementOrderItems) {
            settlementOrderItem.setSettlementOrderId(settlementOrder.getSettlementOrderId());
            settlementOrderItem.setWebsitId(settlementOrder.getWebsitId());
            settlementOrderItem.setWebsitName(settlementOrder.getWebsitName());
            settlementOrderItem.setGoodsType(settlementOrder.getGoodsType());
        }
        settlementOrderItemService.saveBatch(settlementOrderItems);

    }


    private void addSettlementManaulWorker(WorkerOrder workerOrder, List<WorkerOrderItem> workerOrderItems) {
        AdminCompanyWechat adminCompanyWechat = adminCompanyWechatService.getById(workerOrder.getCompanyWechatId());
        WorkerSettlementManual one = workerSettlementManualService.lambdaQuery()
                .eq(WorkerSettlementManual::getCompanyWechatId, adminCompanyWechat.getCompanyWechatId())
                .eq(WorkerSettlementManual::getWebsitId, workerOrder.getWebsitId())
                .eq(WorkerSettlementManual::getWorkerId, workerOrder.getWorkerNumber())
                .last("limit 1").one();
        if (one != null) {
            one.setWorkerAmount(workerOrder.getManualAmount().add(one.getWorkerAmount()));
            one.setWaitAmount(workerOrder.getManualAmount().add(one.getWaitAmount()));
            one.setTotalAmount(workerOrder.getManualAmount().add(one.getTotalAmount()));
            one.setTotalNum(one.getTotalNum().add(Convert.toBigDecimal("1")));
            one.updateById();
        } else {
            WorkerSettlementManual workerSettlement = new WorkerSettlementManual();
            workerSettlement.setCompanyWechatId(adminCompanyWechat.getCompanyWechatId());
            workerSettlement.setCompanyWechatName(adminCompanyWechat.getCompanyName());
            workerSettlement.setWebsitId(workerOrder.getWebsitId());
            workerSettlement.setWebsitName(workerOrder.getWebsitName());
            workerSettlement.setWorkerId(workerOrder.getWorkerNumber());
            workerSettlement.setWorkerName(workerOrder.getWorkerName());
            workerSettlement.setWorkerMobile(workerOrder.getWorkerMobile());
            workerSettlement.setIdentity(workerOrder.getIdentity());
            workerSettlement.setTotalAmount(workerOrder.getTotalAmount());
            workerSettlement.setTotalNum(Convert.toBigDecimal("1"));
            workerSettlement.setWaitAmount(workerOrder.getManualAmount());
            workerSettlement.setWorkerAmount(workerOrder.getManualAmount());
            workerSettlement.setTotalAmount(workerOrder.getManualAmount());
            workerSettlement.insert();
        }

    }


    private void addManualSettlementOrder(WorkerOrder workerOrder, List<WorkerOrderItem> workerOrderItems) {
        AdminCompanyWechat adminCompanyWechat = adminCompanyWechatService.getById(workerOrder.getCompanyWechatId());

        SettlementOrderManual settlementOrder = BeanUtil.toBean(workerOrder, SettlementOrderManual.class);

        if (!StringUtil.isEmpty(workerOrder.getWorkerOrderId())) {
            PgOrderBase pgOrderBase = pgOrderBaseService.getById(workerOrder.getWorkerOrderId());
            if (pgOrderBase != null) {
                settlementOrder.setSaleType(pgOrderBase.getSaleType());
                settlementOrder.setUserName(pgOrderBase.getUserName());
            }
        }

        if (adminCompanyWechat.getDayNum() != null) {
            DateTime dateTime = DateUtil.offsetDay(new Date(), adminCompanyWechat.getDayNum());
            String format = DateUtil.format(dateTime, "yyyy-MM-dd");
            String formatDate = format + " " + adminCompanyWechat.getHourTime();
            DateTime parse = DateUtil.parse(formatDate);
            settlementOrder.setChangeTime(parse);
        } else {
            DateTime dateTime = DateUtil.offsetDay(new Date(), 1);
            settlementOrder.setChangeTime(dateTime);
        }

        settlementOrder.insert();
        List<SettlementOrderManualItem> settlementOrderItems = BeanUtil.copyToList(workerOrderItems, SettlementOrderManualItem.class);
        for (SettlementOrderManualItem settlementOrderItem : settlementOrderItems) {
            settlementOrderItem.setSettlementOrderId(settlementOrder.getSettlementOrderId());
            settlementOrderItem.setWebsitId(settlementOrder.getWebsitId());
            settlementOrderItem.setWebsitName(settlementOrder.getWebsitName());
            settlementOrderItem.setGoodsType(settlementOrder.getGoodsType());
        }
        settlementOrderManualItemService.saveBatch(settlementOrderItems);
    }

    public IPage<SettlementPgOrderVO> pgOrder(WorkerParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> companyWechatIds = adminUser.getCompanyWechatIds();

        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean, SettlementPgOrderVO.class, adminUser);
        IPage<SettlementPgOrderVO> settlementOrderLogicVOIPage = websitSalesRetCMapper.pgOrderList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()),
                zfireParam,
                zfireParamBean.getOverTime(),
                zfireParamBean.getOverEndTime()
               );

        if (CollectionUtils.isEmpty(settlementOrderLogicVOIPage.getRecords()))
            return new Page<>();

        List<PgOrderBase> pgOrderBases = pgOrderBaseService.lambdaQuery()
                .between(PgOrderBase::getOverTime, zfireParamBean.getOverTime(), zfireParamBean.getOverEndTime())
                .in(PgOrderBase::getOrderStatus,"YWG","GCSZX","WDWG","YWGO","YJS","LRCD")
                .select(PgOrderBase::getId,PgOrderBase::getOrderSmallTypeText,PgOrderBase::getWebsitId,PgOrderBase::getTotalNum,PgOrderBase::getWorkerNumber)
                .list();

        List<String> orderBaseIds = pgOrderBases.stream().map(PgOrderBase::getId).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(orderBaseIds))
            return settlementOrderLogicVOIPage;

        List<WorkerOrder> workerOrders = workerOrderService.lambdaQuery()
                .in(WorkerOrder::getWorkerOrderId, orderBaseIds)
                .isNotNull(WorkerOrder::getWebsitId)
                .isNotNull(WorkerOrder::getWorkerNumber)
                .ne(WorkerOrder::getWorkerOrderId,"")
                .eq(WorkerOrder::getPayStatus,"PAID")
                .list();


        for (SettlementPgOrderVO record : settlementOrderLogicVOIPage.getRecords()) {

            List<PgOrderBase> pgOrderBaseList = pgOrderBases.stream().filter(item ->
                    item.getOrderSmallTypeText().equals(record.getOrderSmallTypeText())
                            && !StringUtil.isEmpty(item.getWorkerNumber())
                    && item.getWorkerNumber().equals(record.getWorkerNumber())
                    && item.getWebsitId().equals(record.getWebsitId())
            ).collect(Collectors.toList());

            List<String> orderBaseIdWorker = pgOrderBaseList.stream().map(PgOrderBase::getId).collect(Collectors.toList());

            if (CollectionUtils.isEmpty(orderBaseIdWorker))
                continue;

            record.setZgds(pgOrderBaseList.size());
            record.setSbzts(pgOrderBaseList.stream().mapToInt(PgOrderBase::getTotalNum).sum());

            if (CollectionUtils.isEmpty(workerOrders))
                continue;

            List<WorkerOrder> workerOrderList = workerOrders.stream().filter(
                    item -> item.getWorkerNumber().equals(record.getWorkerNumber())
                            && item.getWebsitId().equals(record.getWebsitId())
                            && orderBaseIdWorker.contains(item.getWorkerOrderId())
            ).collect(Collectors.toList());

            List<String> orderWorkerIds = workerOrderList.stream().map(WorkerOrder::getWorkerOrderId).distinct().collect(Collectors.toList());

            if (CollectionUtils.isEmpty(orderWorkerIds))
                continue;

            List<PgOrderBase> pgOrderBaseList1 = pgOrderBases.stream().filter(item -> orderWorkerIds.contains(item.getId()))
                    .collect(Collectors.toList());

            if (CollectionUtils.isEmpty(pgOrderBaseList1))
                continue;



            record.setDzzfs(pgOrderBaseList1.size());
            int sum = pgOrderBaseList1.stream().mapToInt(PgOrderBase::getTotalNum).sum();

            record.setDzzfsbts(sum);

            BigDecimal bigDecimal = workerOrderList.stream().map(WorkerOrder::getWorkerAmount).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);

            record.setDzzfzje(bigDecimal);
            record.setDzzfpjfy(record.getDzzfsbts() > 0 ?bigDecimal.divide(Convert.toBigDecimal(record.getDzzfsbts()),2,BigDecimal.ROUND_HALF_UP):BigDecimal.ZERO);
            record.setDzzfzpjfy(record.getDzzfsbts() > 0 ?bigDecimal.divide(Convert.toBigDecimal(record.getDzzfsbts()),2,BigDecimal.ROUND_HALF_UP):BigDecimal.ZERO);


        }

        return settlementOrderLogicVOIPage;

    }

    public IPage<SettlementWorkerLogicVO> pageV3(SettlementZfireParamBean zfireParamBean) {

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

        List<String> orderBaseIds = new ArrayList<>();
/*        List<String> mName = new ArrayList<>();

        List<PartsImport> partsImportList = partsImportService.lambdaQuery()
                .select(PartsImport::getPartName)
                .list();

        List<WebsitNormCharge> chargeList = websitNormChargeService.lambdaQuery()
                .eq(WebsitNormCharge::getNormType, "M")
                .select(WebsitNormCharge::getNormName)
                .list();

        mName.addAll(partsImportList.stream().map(PartsImport::getPartName).collect(Collectors.toList()));
        mName.addAll(chargeList.stream().map(WebsitNormCharge::getNormName).collect(Collectors.toList()));*/

        if (!StringUtil.isEmpty(zfireParamBean.getStartTime())) {
            List<PgOrderBase> pgOrderBaseList = pgOrderBaseService.lambdaQuery()
                    .between(PgOrderBase::getOverTime, zfireParamBean.getStartTime(), zfireParamBean.getEndTime())
                    .select(PgOrderBase::getId).list();

            orderBaseIds.addAll(pgOrderBaseList.stream().map(PgOrderBase::getId).collect(Collectors.toList()));
        }


        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean, SettlementWorkerLogicVO.class, adminUser);
        IPage<SettlementWorkerLogicVO> settlementOrderLogicVOIPage = websitSalesRetCMapper.pageV3(new Page(zfireParamBean.getPageNum(),
                        zfireParamBean.getPageSize()),
                zfireParam
                , companyWechatIds,orderBaseIds,zfireParamBean.getValue());

        return settlementOrderLogicVOIPage;
    }

    public IPage<SettlementWorkerOrderVO> pageV4(SettlementZfireParamBean zfireParamBean) {


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

        List<String> orderBaseIds = new ArrayList<>();

        if (!StringUtil.isEmpty(zfireParamBean.getStartTime())) {
            List<PgOrderBase> pgOrderBaseList = pgOrderBaseService.lambdaQuery()
                    .between(PgOrderBase::getOverTime, zfireParamBean.getStartTime(), zfireParamBean.getEndTime())
                    .select(PgOrderBase::getId).list();

            orderBaseIds.addAll(pgOrderBaseList.stream().map(PgOrderBase::getId).collect(Collectors.toList()));
        }

        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean, SettlementWorkerLogicVO.class, adminUser);
        IPage<SettlementWorkerOrderVO> settlementOrderLogicVOIPage = websitSalesRetCMapper.pageV4(new Page(zfireParamBean.getPageNum(),
                        zfireParamBean.getPageSize()),
                zfireParam
                , companyWechatIds,orderBaseIds,zfireParamBean.getValue());

        return settlementOrderLogicVOIPage;
    }

/*

    private void addSettlementOrder(WorkerOrder workerOrder, List<WorkerOrderItem> workerOrderItems) {
        AdminCompanyWechat adminCompanyWechat = adminCompanyWechatService.getById(workerOrder.getCompanyWechatId());

        SettlementOrder settlementOrder = BeanUtil.toBean(workerOrder, SettlementOrder.class);

        settlementOrder.setTranscationId(workerOrder.getTranscationId());
        settlementOrder.setOpenId(workerOrder.getOpenId());

        if (!StringUtil.isEmpty(workerOrder.getWorkerOrderId())){
            PgOrderBase pgOrderBase = pgOrderBaseService.getById(workerOrder.getWorkerOrderId());
            if (pgOrderBase != null){
                settlementOrder.setSaleType(pgOrderBase.getSaleType());
            }
        }

        settlementOrder.setAmount(settlementOrder.getTotalAmount());
        if (adminCompanyWechat.getDayNum() != null) {
            DateTime dateTime = DateUtil.offsetDay(new Date(), adminCompanyWechat.getDayNum());
            String format = DateUtil.format(dateTime, "yyyy-MM-dd");
            String formatDate = format+" "+adminCompanyWechat.getHourTime();
            DateTime parse = DateUtil.parse(formatDate);
            settlementOrder.setChangeTime(parse);
        }else {
            DateTime dateTime = DateUtil.offsetDay(new Date(), 1);
            settlementOrder.setChangeTime(dateTime);
        }

        settlementOrder.insert();
        List<SettlementOrderItem> settlementOrderItems = BeanUtil.copyToList(workerOrderItems, SettlementOrderItem.class);
        for (SettlementOrderItem settlementOrderItem : settlementOrderItems) {
            settlementOrderItem.setSettlementOrderId(settlementOrder.getSettlementOrderId());
            settlementOrderItem.setWebsitId(settlementOrder.getWebsitId());
            settlementOrderItem.setWebsitName(settlementOrder.getWebsitName());
            settlementOrderItem.setGoodsType(settlementOrder.getGoodsType());
        }
        settlementOrderItemService.saveBatch(settlementOrderItems);

    }

    */
/**
 * 单个师傅库存处理
 *
 * @param stockList
 * @throws Exception
 *//*

    public void handleWorkerStock(List<WorkerStockDTO> stockList) throws Exception {
        if (!TransactionSynchronizationManager.isSynchronizationActive()) {
            throw new RemoteServiceException("请先开启事务");
        }
        if (CollectionUtil.isEmpty(stockList)) {
            return;
        }
        // 检查传入的参数
        for (int i = 0; i < stockList.size(); i++) {
            WorkerStockDTO workerStockDTO = stockList.get(i);
            try {
                ValidateUtil.validate(workerStockDTO);
                if (workerStockDTO.getChangeQty().compareTo(BigDecimal.ZERO) <= 0) {
                    throw new RuntimeException("变动数量不能少于0");
                }
            } catch (ValidationException ve) {
                throw new RemoteServiceException("第" + (i + 1) + "行" + ve.getMessage());
            }
        }
        // 锁定师傅配件库存
        WorkerStockDTO workerStockDTO = stockList.get(0);
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.MATERIAL_STOCK_LOCK +
                workerStockDTO.getCompanyWechatId() + ":" +
                workerStockDTO.getWorkerId() + ":" +
                workerStockDTO.getGoodsType());
        if (!obtain.tryLock(10, TimeUnit.SECONDS)) {
            throw new RemoteServiceException("库存已冻结:" + workerStockDTO.getWorkerName());
        }
        // 处理师傅库存
        try {
            this.saveWorkerStock(workerStockDTO, stockList);
        } finally {
            this.txCallUnlockWorker(obtain);
        }
    }


    private void addNormRecord(WorkerOrder workerOrder, List<WorkerOrderItem> workerOrderItems) {
        List<WebsitNormRecord> websitNormRecords = new ArrayList<>();
        for (WorkerOrderItem workerOrderItem : workerOrderItems) {
            WebsitNormRecord websitNormRecord = new WebsitNormRecord();
            websitNormRecord.setCompanyWechatId(workerOrder.getCompanyWechatId());
            websitNormRecord.setCompanyWechatName(workerOrder.getCompanyWechatName());
            websitNormRecord.setGoodsType(workerOrder.getGoodsType());
            websitNormRecord.setWorkerId(workerOrder.getWorkerId());
            websitNormRecord.setWorkerName(workerOrder.getWorkerName());
            websitNormRecord.setOrderId(workerOrder.getWorkerOrderId());
            websitNormRecord.setRefOrder(workerOrder.getOrderId());
            websitNormRecord.setWebsitId(workerOrder.getWebsitId());
            websitNormRecord.setWebsitName(workerOrder.getWebsitName());
            websitNormRecord.setUseTime(new Date());
            websitNormRecord.setCreateTime(new Date());
            websitNormRecord.setGoodsName(workerOrderItem.getGoodsName());
            websitNormRecord.setGoodsCode(workerOrderItem.getGoodsCode());
            websitNormRecord.setNormAmount(workerOrderItem.getNormAmount());
            websitNormRecord.setUnit(workerOrderItem.getUnit());
            websitNormRecord.setUseQty(Convert.toBigDecimal(workerOrderItem.getNum()));
            websitNormRecords.add(websitNormRecord);
        }

        websitNormRecordService.saveBatch(websitNormRecords);

    }


    private void addManualSettlementOrder(WorkerOrder workerOrder, List<WorkerOrderItem> workerOrderItems) {
        AdminCompanyWechat adminCompanyWechat = adminCompanyWechatService.getById(workerOrder.getCompanyWechatId());

        SettlementOrderManual settlementOrder = BeanUtil.toBean(workerOrder, SettlementOrderManual.class);

        if (!StringUtil.isEmpty(workerOrder.getWorkerOrderId())) {
            PgOrderBase pgOrderBase = pgOrderBaseService.getById(workerOrder.getWorkerOrderId());
            if (pgOrderBase != null) {
                settlementOrder.setSaleType(pgOrderBase.getSaleType());
                settlementOrder.setUserName(pgOrderBase.getUserName());
            }
        }

        if (adminCompanyWechat.getDayNum() != null) {
            DateTime dateTime = DateUtil.offsetDay(new Date(), adminCompanyWechat.getDayNum());
            String format = DateUtil.format(dateTime, "yyyy-MM-dd");
            String formatDate = format + " " + adminCompanyWechat.getHourTime();
            DateTime parse = DateUtil.parse(formatDate);
            settlementOrder.setChangeTime(parse);
        } else {
            DateTime dateTime = DateUtil.offsetDay(new Date(), 1);
            settlementOrder.setChangeTime(dateTime);
        }

        settlementOrder.insert();
        List<SettlementOrderManualItem> settlementOrderItems = BeanUtil.copyToList(workerOrderItems, SettlementOrderManualItem.class);
        for (SettlementOrderManualItem settlementOrderItem : settlementOrderItems) {
            settlementOrderItem.setSettlementOrderId(settlementOrder.getSettlementOrderId());
            settlementOrderItem.setWebsitId(settlementOrder.getWebsitId());
            settlementOrderItem.setWebsitName(settlementOrder.getWebsitName());
            settlementOrderItem.setGoodsType(settlementOrder.getGoodsType());
        }
        settlementOrderManualItemService.saveBatch(settlementOrderItems);
    }


    private void addSettlementManaulWorker(WorkerOrder workerOrder, List<WorkerOrderItem> workerOrderItems) {
        AdminCompanyWechat adminCompanyWechat = adminCompanyWechatService.getById(workerOrder.getCompanyWechatId());
        WorkerSettlementManual one = workerSettlementManualService.lambdaQuery()
                .eq(WorkerSettlementManual::getCompanyWechatId, adminCompanyWechat.getCompanyWechatId())
                .eq(WorkerSettlementManual::getWebsitId, workerOrder.getWebsitId())
                .eq(WorkerSettlementManual::getWorkerId, workerOrder.getWorkerId())
                .last("limit 1").one();
        if (one != null) {
            one.setWorkerAmount(workerOrder.getManualAmount().add(one.getWorkerAmount()));
            one.setWaitAmount(workerOrder.getManualAmount().add(one.getWaitAmount()));
            one.setTotalAmount(workerOrder.getManualAmount().add(one.getTotalAmount()));
            one.setTotalNum(one.getTotalNum().add(Convert.toBigDecimal("1")));
            one.updateById();
        } else {
            WorkerSettlementManual workerSettlement = new WorkerSettlementManual();
            workerSettlement.setCompanyWechatId(adminCompanyWechat.getCompanyWechatId());
            workerSettlement.setCompanyWechatName(adminCompanyWechat.getCompanyName());
            workerSettlement.setWebsitId(workerOrder.getWebsitId());
            workerSettlement.setWebsitName(workerOrder.getWebsitName());
            workerSettlement.setWorkerId(workerOrder.getWorkerId());
            workerSettlement.setWorkerName(workerOrder.getWorkerName());
            workerSettlement.setWorkerMobile(workerOrder.getWorkerMobile());
            workerSettlement.setIdentity(workerOrder.getIdentity());
            workerSettlement.setTotalAmount(workerOrder.getTotalAmount());
            workerSettlement.setTotalNum(Convert.toBigDecimal("1"));
            workerSettlement.setWaitAmount(workerOrder.getManualAmount());
            workerSettlement.setWorkerAmount(workerOrder.getManualAmount());
            workerSettlement.setTotalAmount(workerOrder.getManualAmount());
            workerSettlement.insert();
        }

    }


    @Transactional
    public String add(SalesCustomerPartsBean bean) throws Exception {
//        try {
        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)) {
            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());
        this.materialGoodsStockLogichandleWorkerStock(workerStockDTOList);

        return sheetId;
//        } catch (Exception e) {
//            WorkerSalesCustomerInfo info = workerSalesCustomerInfoService.lambdaQuery()
//                    .eq(WorkerSalesCustomerInfo::getCompanyWechatId, bean.getCompanyWechatId())
//                    .eq(WorkerSalesCustomerInfo::getWorkOrderNo, bean.getWorkOrderNo())
//                    .eq(WorkerSalesCustomerInfo::getRepairFlag, bean.getRepairFlag())
//                    .one();
//
//            if (Objects.isNull(info)) {
//                info = new WorkerSalesCustomerInfo();
//                info.setErr(e.getMessage())
//                        .setSalesCustomerJson(JSONUtil.toJsonStr(bean))
//                        .setIdentity(bean.getIdentity())
//                        .setCompanyWechatId(bean.getCompanyWechatId())
//                        .insert();
//            } else {
//                info.setErr(e.getMessage())
//                        .updateById();
//            }
//        }
//        return null;
    }
    */
/**
 * 单个师傅库存处理
 *
 * @param stockList
 * @throws Exception
 *//*

    public void materialGoodsStockLogichandleWorkerStock(List<WorkerStockDTO> stockList) throws Exception {
        if (!TransactionSynchronizationManager.isSynchronizationActive()) {
            throw new RemoteServiceException("请先开启事务");
        }
        if (CollectionUtil.isEmpty(stockList)) {
            return;
        }
        // 检查传入的参数
        for (int i = 0; i < stockList.size(); i++) {
            WorkerStockDTO workerStockDTO = stockList.get(i);
            try {
                ValidateUtil.validate(workerStockDTO);
                if (workerStockDTO.getChangeQty().compareTo(BigDecimal.ZERO) <= 0) {
                    throw new RuntimeException("变动数量不能少于0");
                }
            } catch (ValidationException ve) {
                throw new RemoteServiceException("第" + (i + 1) + "行" + ve.getMessage());
            }
        }
        // 锁定师傅配件库存
        WorkerStockDTO workerStockDTO = stockList.get(0);
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.MATERIAL_STOCK_LOCK +
                workerStockDTO.getCompanyWechatId() + ":" +
                workerStockDTO.getWorkerId() + ":" +
                workerStockDTO.getGoodsType());
        if (!obtain.tryLock(10, TimeUnit.SECONDS)) {
            throw new RemoteServiceException("库存已冻结:" + workerStockDTO.getWorkerName());
        }
        // 处理师傅库存
        try {
            this.saveWorkerStock(workerStockDTO, stockList);
        } finally {
            this.txCallUnlockWorker(obtain);
        }
    }


    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;
    }



    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 void makeSubStockData(WorkerOrder workerOrder, List<WorkerOrderItem> workerOrderItems, List<WorkerStockDTO> workerStockDTOS) {
        Map<String, WorkerNormStockBean> workerStockMap = new HashMap<>();
        for (WorkerOrderItem item : workerOrderItems) {
            WebsitNormCharge websitNormCharge = websitNormChargeService.getById(item.getGoodsId());
            if (websitNormCharge.getNormType().equals(NormTypeEnum.M.getKey())) {
                // 获取当前关联师傅库存记录
                List<WorkerNormStockBean> stockBeanList = materialMapper.queryWorkerStockQty(item.getGoodsId(), workerOrder.getWorkerId());
                if (CollectionUtil.isNotEmpty(stockBeanList)) {
                    BigDecimal totalNum = item.getNum();
                    for (WorkerNormStockBean stockBean : stockBeanList) {
                        // 当前订单收费标准扣总数量
                        BigDecimal useTotalQty = totalNum.multiply(stockBean.getQty());
                        if (!workerStockMap.containsKey(stockBean.getWorkerGoodsId() + item.getGoodsAmount())) {
                            WorkerNormStockBean bean = new WorkerNormStockBean();
                            BeanUtils.copyProperties(stockBean, bean);
                            bean.setRealQty(BigDecimal.ZERO);
                            workerStockMap.put(bean.getWorkerGoodsId() + item.getGoodsAmount(), bean);
                        }
                        WorkerNormStockBean stock = workerStockMap.get(stockBean.getWorkerGoodsId() + item.getGoodsAmount());
                        stock.setRealQty(stock.getRealQty().add(useTotalQty));
                        stock.setNormPrice(item.getGoodsAmount());

                        // 7、收费标准如果和辅材没有对应关系，不判断库存；从总部同步下来订单，如果师傅的库存不足，不限制支付；（允许负库存）
//                        if (!stockBean.getIsSmall() && stock.getRealQty().compareTo(stockBean.getStockQty()) > 0) {
//                            throw new RemoteServiceException("收费标准关联的 " + stockBean.getGoodsName() + "库存数量"
//                                    + stock.getStockQty() + ", 需扣" + stock.getRealQty() + ", 库存数量不够扣减");
//                        }
                    }
                }
            }
        }

        for (Map.Entry<String, WorkerNormStockBean> entry : workerStockMap.entrySet()) {
            final WorkerNormStockBean bean = entry.getValue();
            // 库存减少
            WorkerStockDTO workerStockDTO = new WorkerStockDTO();
            workerStockDTO.setCompanyWechatId(workerOrder.getCompanyWechatId());
            workerStockDTO.setCompanyWechatName(workerOrder.getCompanyWechatName());
            workerStockDTO.setIdentity(workerOrder.getIdentity());
            workerStockDTO.setWorkerId(workerOrder.getWorkerId());
            workerStockDTO.setWorkerName(workerOrder.getWorkerName());
            workerStockDTO.setWebsitId(workerOrder.getWebsitId());
            workerStockDTO.setWebsitName(workerOrder.getWebsitName());
            workerStockDTO.setSdate(workerOrder.getCreateTime());
            workerStockDTO.setWorkerWebsitId(workerOrder.getWebsitId());
            workerStockDTO.setWorkerWebsitName(workerOrder.getWebsitName());
            workerStockDTO.setGoodsId(bean.getWorkerGoodsId());
            workerStockDTO.setGoodsName(bean.getGoodsName());
            workerStockDTO.setGoodsType(WebsitGoodsTypeEnum.M.toString());
            workerStockDTO.setPrice(bean.getNormPrice());
            workerStockDTO.setGoodsStockUnit(bean.getSalesUnit());
            workerStockDTO.setRef(workerOrder.getOrderId());
            workerStockDTO.setRefType("辅材销售");
            workerStockDTO.setPartsAttr("NEW");
            workerStockDTO.setChangeQty(bean.getRealQty());
            workerStockDTO.setDirectFlag("SUB");
            workerStockDTO.setFlag("USED");
            workerStockDTO.setObj("客户");
            workerStockDTO.setWorkerOrderNo(workerOrder.getWorkerOrderId());
            workerStockDTO.setRemark(workerOrder.getRemark());
            workerStockDTO.setOperateBy(workerOrder.getWorkerName());
            workerStockDTO.setOperateTime(DateUtil.date());

            workerStockDTOS.add(workerStockDTO);
        }
    }


    */
/**
 * 单个师傅库存处理
 *
 * @param stockList
 * @throws Exception
 *//*

    public void uhandleWorkerStock(List<WorkerStockDTO> stockList) throws Exception {
        if (!TransactionSynchronizationManager.isSynchronizationActive()) {
            throw new RemoteServiceException("请先开启事务");
        }
        if (CollectionUtil.isEmpty(stockList)) {
            return;
        }
        // 检查传入的参数
        for (int i = 0; i < stockList.size(); i++) {
            WorkerStockDTO workerStockDTO = stockList.get(i);
            try {
                ValidateUtil.validate(workerStockDTO);
                if (workerStockDTO.getChangeQty().compareTo(BigDecimal.ZERO) <= 0) {
                    throw new RuntimeException("变动数量不能少于0");
                }
            } catch (ValidationException ve) {
                throw new RemoteServiceException("第" + (i + 1) + "行" + ve.getMessage());
            }
        }
        // 锁定师傅配件库存
        WorkerStockDTO workerStockDTO = stockList.get(0);
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.MATERIAL_STOCK_LOCK +
                workerStockDTO.getCompanyWechatId() + ":" +
                workerStockDTO.getWorkerId() + ":" +
                workerStockDTO.getGoodsType());
        if (!obtain.tryLock(10, TimeUnit.SECONDS)) {
            throw new RemoteServiceException("库存已冻结:" + workerStockDTO.getWorkerName());
        }
        // 处理师傅库存
        try {
            this.saveWorkerStock(workerStockDTO, stockList);
        } finally {
            this.txCallUnlockWorker(obtain);
        }
    }

    private void saveWorkerStock(WorkerStockDTO workerStockDTO, List<WorkerStockDTO> stockList) throws Exception {
        // 查询存在的商品库存
        List<WorkerStock> existWorkerStockList = materialGoodsStockCMapper.queryExistWorkerStockList(workerStockDTO.getCompanyWechatId()
                , workerStockDTO.getWorkerId(), stockList);
        // 全部商品库存
        Map<String, WorkerStock> existWorkerStockMap = this.createNotExistWorkerStock(workerStockDTO.getGoodsType(), stockList, existWorkerStockList);
        // 计算商品库存
        List<WorkerStockAcc> workerStockAccList = new ArrayList<>();
        this.computeWorkerStock(stockList, existWorkerStockMap, null, workerStockAccList);

        if (CollectionUtil.isEmpty(workerStockAccList)) {
            throw new RemoteServiceException("师傅配件库存处理失败");
        }

        workerStockService.saveOrUpdateBatch(existWorkerStockMap.values());
        workerStockAccService.saveBatch(workerStockAccList);
    }


    private void computeWorkerStock(List<WorkerStockDTO> stockList, Map<String, WorkerStock> existWorkerStockMap,
                                    List<WorkerStock> workerStockList, List<WorkerStockAcc> workerStockAccList) throws Exception {
        for (WorkerStockDTO workerStockDTO : stockList) {
            WorkerStock workerStock = existWorkerStockMap.get(workerStockDTO.getGoodsId());
            if (workerStockDTO.getGoodsType().equals(WebsitGoodsTypeEnum.P.toString())) {
                workerStock = existWorkerStockMap.get(workerStockDTO.getCompanyWechatId() + workerStockDTO.getWebsitId() + workerStockDTO.getPartsWebsitId() + workerStockDTO.getGoodsId());
            }
            WorkerStockAcc workerStockAcc = new WorkerStockAcc();
            workerStockDTO.computeWorkerStock(workerStock, workerStockAcc);
            workerStockAccList.add(workerStockAcc);
        }
    }


    private Map<String, WorkerStock> createNotExistWorkerStock(String goodsType, List<WorkerStockDTO> stockList, List<WorkerStock> existWorkerStockList) {
        // 已存在的商品库存转成Map
        Map<String, WorkerStock> existShopStockMap;

        if (goodsType.equals(WebsitGoodsTypeEnum.M.toString())) {
            existShopStockMap = existWorkerStockList.stream()
                    .collect(Collectors.toMap(WorkerStock::getGoodsId, Function.identity()));
        } else {
            existShopStockMap = existWorkerStockList.stream()
                    .collect(Collectors.toMap(o -> o.getCompanyWechatId() + o.getWebsitId() + o.getPartsWebsitId() + o.getGoodsId(), Function.identity()));
        }

        // 找出不存在的商品库存并存入新商品库存List
        for (WorkerStockDTO workerStockDTO : stockList) {
            WorkerStock workerStock = existShopStockMap.get(workerStockDTO.getGoodsId());
            if (goodsType.equals(WebsitGoodsTypeEnum.P.toString())) {
                workerStock = existShopStockMap.get(workerStockDTO.getCompanyWechatId() + workerStockDTO.getWebsitId() + workerStockDTO.getPartsWebsitId() + workerStockDTO.getGoodsId());
            }

            if (Objects.isNull(workerStock)) {
                workerStock = workerStockDTO.createWorkerStock();
                if (goodsType.equals(WebsitGoodsTypeEnum.M.toString())) {
                    existShopStockMap.put(workerStockDTO.getGoodsId(), workerStock);
                } else {
                    existShopStockMap.put(workerStockDTO.getCompanyWechatId() + workerStockDTO.getWebsitId() + workerStockDTO.getPartsWebsitId() + workerStockDTO.getGoodsId(), workerStock);
                }
            }
        }
        return existShopStockMap;
    }


    public void txCallUnlockWorker(Lock obtain) {
        //事务提交完成后才释放锁,此方法禁止执行mysql相关操作,否则将导致重大问题。
        if (TransactionSynchronizationManager.isActualTransactionActive()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCompletion(int status) {

                    if (TransactionSynchronization.STATUS_COMMITTED == status) {
                        log.info("=========【师傅库存】======事务提交==============");
                    } else if (TransactionSynchronization.STATUS_ROLLED_BACK == status) {
                        log.info("========【师傅库存】=========事务回滚============");
                    }

                    obtain.unlock();
                }
            });
        } else {
            log.info("【师傅库存】====没有事务===释放锁");
            obtain.unlock();
        }
    }
*/

}
