package com.gree.mall.miniapp.logic.order;

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.extension.plugins.pagination.Page;
import com.gree.mall.miniapp.bean.material.parts.PartsWorkerStockBean;
import com.gree.mall.miniapp.bean.material.parts.SalesCustomerPartsBean;
import com.gree.mall.miniapp.bean.material.parts.SalesCustomerPartsItemBean;
import com.gree.mall.miniapp.bean.material.stock.WorkerNormStockBean;
import com.gree.mall.miniapp.bean.material.stock.WorkerStockDTO;
import com.gree.mall.miniapp.bean.order.OrderCount;
import com.gree.mall.miniapp.bean.order.SettlementOrderDetail;
import com.gree.mall.miniapp.bean.order.WorkerOrderBuy;
import com.gree.mall.miniapp.bean.order.WorkerOrderDetail;
import com.gree.mall.miniapp.bean.user.CurrentCompanyWechat;
import com.gree.mall.miniapp.commonmapper.MaterialMapper;
import com.gree.mall.miniapp.enums.*;
import com.gree.mall.miniapp.enums.material.PartsAttrEnum;
import com.gree.mall.miniapp.enums.material.WebsitGoodsTypeEnum;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.logic.common.CommonLogic;
import com.gree.mall.miniapp.logic.common.outside.WechatLogic;
import com.gree.mall.miniapp.logic.material.parts.OldRefundManageLogic;
import com.gree.mall.miniapp.logic.material.parts.WorkerPartsStockLogic;
import com.gree.mall.miniapp.logic.material.stock.MaterialGoodsStockLogic;
import com.gree.mall.miniapp.plus.entity.*;
import com.gree.mall.miniapp.plus.service.*;
import com.gree.mall.miniapp.utils.DateUtils;
import com.gree.mall.miniapp.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PayOrderLogic {

    @Autowired
    WebsitNormChargeService websitNormChargeService;

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    WorkerOrderItemService workerOrderItemService;

    @Autowired
    WorkerOrderService workerOrderService;

    @Autowired
    WebsitGoodsService websitGoodsService;

    @Autowired
    WebsitGoodsCategoryService websitGoodsCategoryService;

    @Autowired
    SysDictCompanyService sysDictCompanyService;

    @Autowired
    GoodsCategoryService goodsCategoryService;

    @Autowired
    WechatLogic wechatLogic;

    @Autowired
    SettlementOrderService settlementOrderService;

    @Autowired
    SettlementOrderItemService settlementOrderItemService;

    @Autowired
    WebsitNormRecordService websitNormRecordService;

    @Autowired
    MaterialGoodsStockLogic materialGoodsStockLogic;

    @Autowired
    AdminCompanyWechatService adminCompanyWechatService;

    @Autowired
    WorkerStockService workerStockService;

    @Autowired
    BrandService brandService;

    @Autowired
    WorkerSettlementService workerSettlementService;

    @Autowired
    PgOrderBaseService pgOrderBaseService;

    @Autowired
    RpProjectRepairItemService rpProjectRepairItemService;

    @Autowired
    SettlementOrderManualService settlementOrderManualService;

    @Autowired
    SettlementOrderManualItemService settlementOrderManualItemService;

    @Autowired
    WorkerSettlementManualService workerSettlementManualService;

    @Autowired
    AdminWebsitService adminWebsitService;

    @Autowired
    MaterialMapper materialMapper;

    @Autowired
    OldRefundManageLogic oldRefundManageLogic;

    @Autowired
    WorkerPartsStockLogic workerPartsStockLogic;

    public Page<WebsitNormCharge> pageCharge(String name, String categoryId, String orderId,Integer pageNum, Integer pageSize) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        Page<WebsitNormCharge> list = websitNormChargeService.lambdaQuery()
                .like(!StringUtil.isEmpty(name), WebsitNormCharge::getNormName, name)
                .eq(!StringUtil.isEmpty(categoryId), WebsitNormCharge::getCategoryId, categoryId)
                .in(WebsitNormCharge::getCompanyWechatId, currentCompanyWechat.getCompanyWechatId())
                .eq(WebsitNormCharge::getStatus, "ON")
                .page(new Page<>(pageNum, pageSize));

        if (!StringUtil.isEmpty(orderId)){
            PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderId);
            if (pgOrderBase != null && !StringUtil.isEmpty(pgOrderBase.getRpProjectRepairId())){
                for (WebsitNormCharge record : list.getRecords()) {
                    BigDecimal bigDecimal = this.normPrice(record.getNormId(), pgOrderBase.getRpProjectRepairId());

                    record.setNormAmount(bigDecimal == null?record.getNormAmount():bigDecimal);
                }
            }
        }

        return list;
    }

    public BigDecimal normPrice(String goodsId,String rpProjectRepairId){

        if (StringUtil.isEmpty(rpProjectRepairId))
            return null;


        List<RpProjectRepairItem> rpProjectRepairItems = rpProjectRepairItemService.lambdaQuery()
                .eq(RpProjectRepairItem::getProjectRepairId, rpProjectRepairId)
                .eq(RpProjectRepairItem::getGoodsId, goodsId)
                .list();

        List<RpProjectRepairItem> rpProjectRepairItemList = rpProjectRepairItems.stream()
                .filter(item -> item.getGoodsId().equals(goodsId)).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(rpProjectRepairItemList))
            return null;

        return rpProjectRepairItemList.get(0).getNormAmount();

    }


    @Transactional(rollbackFor = Exception.class)
    public String buy(WorkerOrderBuy workerOrderBuy, String ip, HttpServletRequest request) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        workerOrderBuy.setCompanyWechatId(currentCompanyWechat.getCompanyWechatId());
        workerOrderBuy.setCompanyWechatName(currentCompanyWechat.getCompanyName());
        workerOrderBuy.setWorkerId(currentCompanyWechat.getUser().getWorkerNumber());
        workerOrderBuy.setWorkerName(currentCompanyWechat.getUser().getNickName());
        workerOrderBuy.setWorkerMobile(currentCompanyWechat.getUser().getMobile());
        workerOrderBuy.setCreateBy(currentCompanyWechat.getUser().getNickName());
        workerOrderBuy.setCreateTime(new Date());
        workerOrderBuy.setIdentity(currentCompanyWechat.getUser().getIdCard());
        workerOrderBuy.setUserId(currentCompanyWechat.getUser().getUserId());

        if (StringUtil.isEmpty(workerOrderBuy.getCategoryId()))
            workerOrderBuy.setGoodsType("M");
        else
            workerOrderBuy.setGoodsType("P");
        workerOrderBuy.insert();

        BigDecimal totalAmount = new BigDecimal("0");
        BigDecimal workerAmount = new BigDecimal("0");

        BigDecimal workerProceAmount = new BigDecimal("0");
        BigDecimal manualAmount = new BigDecimal("0");


        BigDecimal num = new BigDecimal("0");

        Map<String, WorkerNormStockBean> workerStockMap = new HashMap<>();
        for (WorkerOrderItem workerOrderItem : workerOrderBuy.getWorkerOrderItems()) {

            workerOrderItem.setOrderId(workerOrderBuy.getOrderId());
            workerOrderItem.setSettlementType(workerOrderBuy.getSettlementType());

            if (StringUtil.isEmpty(workerOrderBuy.getCategoryId()))
                this.addFuCai(workerStockMap, workerOrderItem, workerOrderBuy);
            else
                this.addPeiJian(workerOrderItem,workerOrderBuy);


            totalAmount = totalAmount.add(workerOrderItem.getTotalAmount());
            workerAmount = workerAmount.add(workerOrderItem.getWorkerAmount());

            workerProceAmount = workerProceAmount.add(workerOrderItem.getWorkerProceAmount());
            manualAmount = manualAmount.add(Objects.isNull(workerOrderItem.getManualAmount()) ? BigDecimal.ZERO : workerOrderItem.getManualAmount());
            num = num.add(workerOrderItem.getNum());
        }

        if (workerOrderBuy.getServicePrice() != null){

            totalAmount.add(workerOrderBuy.getServicePrice());

            BigDecimal workerServiceProceAmount = workerOrderBuy.getServicePrice().multiply(Convert.toBigDecimal("0.006"));


            if (workerServiceProceAmount.doubleValue() > 0.01) {
                workerProceAmount.add(workerServiceProceAmount.setScale(2, BigDecimal.ROUND_HALF_UP));

            }else {
                workerProceAmount.add(Convert.toBigDecimal("0.01"));
            }
        }


        if (workerOrderBuy.getOtherPrice() != null){

            totalAmount.add(workerOrderBuy.getOtherPrice());
            BigDecimal workerOtherProceAmount = workerOrderBuy.getOtherPrice().multiply(Convert.toBigDecimal("0.006"));


            if (workerOtherProceAmount.doubleValue() > 0.01) {
                workerProceAmount.add(workerOtherProceAmount.setScale(2, BigDecimal.ROUND_HALF_UP));

            }else {
                workerProceAmount.add(Convert.toBigDecimal("0.01"));
            }

        }


        if (CollectionUtil.isNotEmpty(workerStockMap)) {
            // 检查辅材物料收费类型的库存是否够扣
            for (Map.Entry<String, WorkerNormStockBean> entry : workerStockMap.entrySet()) {
                final WorkerNormStockBean stockBean = entry.getValue();
                if (!stockBean.getIsSmall()
                        && (Objects.isNull(stockBean.getStockQty()) || stockBean.getRealQty().compareTo(stockBean.getStockQty()) > 0)) {
                    WebsitNormCharge websitNormCharge = websitNormChargeService.getById(stockBean.getNormId());
                    throw new RemoteServiceException("”" + websitNormCharge.getNormName() + "“收费标准关联的" +  stockBean.getGoodsName() + "库存数量不够使用");
                }
            }
        }


        if (workerProceAmount.doubleValue() > 0.01) {
            workerOrderBuy.setWorkerProceAmount(workerProceAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
        }else {
            workerOrderBuy.setWorkerProceAmount(Convert.toBigDecimal("0.01"));
        }
        workerOrderBuy.setWorkerProceAmount(workerProceAmount);
        workerOrderBuy.setCommissionAmount(workerProceAmount);
        workerOrderBuy.setTotalAmount(totalAmount);
        workerOrderBuy.setWorkerAmount(workerAmount);
        workerOrderBuy.setManualAmount(manualAmount);

        workerOrderBuy.setNum(num);
        workerOrderBuy.updateById();

        workerOrderItemService.saveBatch(workerOrderBuy.getWorkerOrderItems());

        return workerOrderBuy.getOrderId();
    }

    private void addPeiJian(WorkerOrderItem workerOrderItem,WorkerOrderBuy workerOrderBuy) {

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

        List<PartsWorkerStockBean> partsWorkerStockBeans = workerPartsStockLogic.existWorkerStockList(workerOrderBuy.getIdentity(), workerOrderBuy.getWebsitId(),
                adminWebsit.getPartsWebsitId(), "NEW", workerOrderItem.getGoodsCode(), null, null);

        if (CollectionUtils.isEmpty(partsWorkerStockBeans))
            throw new RemoteServiceException("传参有误");


        PartsWorkerStockBean partsWorkerStockBean = partsWorkerStockBeans.get(0);



        workerOrderItem.setGoodsCode(partsWorkerStockBean.getGoodsId());


        workerOrderItem.setNormAmount(partsWorkerStockBean.getMarketPrice());

        workerOrderItem.setGoodsAmount(workerOrderItem.getNormAmount());


        workerOrderItem.setTotalAmount(workerOrderItem.getNormAmount().multiply(Convert.toBigDecimal(workerOrderItem.getNum())));

        workerOrderItem.setUnit(partsWorkerStockBean.getGoodsStockUnit());


        workerOrderItem.setChargeType("ACC");
        workerOrderItem.setWorkerAmount(workerOrderItem.getNormAmount().multiply(Convert.toBigDecimal(workerOrderItem.getNum())));



        BigDecimal workerProceAmount = workerOrderItem.getWorkerAmount().multiply(Convert.toBigDecimal("0.006"));


        if (workerProceAmount.doubleValue() > 0.01) {
            workerOrderItem.setWorkerProceAmount(workerProceAmount.setScale(2, BigDecimal.ROUND_HALF_UP));

        }else {
            workerOrderItem.setWorkerProceAmount(Convert.toBigDecimal("0.01"));
        }

        workerOrderItem.setWorkerAmount(workerOrderItem.getWorkerAmount().subtract(workerOrderItem.getWorkerProceAmount()));


        if (workerOrderItem.getWorkerAmount().doubleValue() < 0){
            workerOrderItem.setWorkerProceAmount(Convert.toBigDecimal("0"));
            workerOrderItem.setWorkerAmount(Convert.toBigDecimal("0"));
        }
    }

    private void addFuCai(Map<String, WorkerNormStockBean> workerStockMap, WorkerOrderItem workerOrderItem, WorkerOrderBuy workerOrderBuy) {
        WebsitNormCharge websitNormCharge = websitNormChargeService.getById(workerOrderItem.getGoodsId());
        if (websitNormCharge.getNormType().equals("M")) {
            // 获取当前关联师傅库存记录
            List<WorkerNormStockBean> stockBeanList = materialMapper.queryWorkerStockQty(workerOrderItem.getGoodsId(), workerOrderBuy.getWorkerId());
            if (CollectionUtil.isNotEmpty(stockBeanList)) {
                // 获取待支付的师傅收费订单
                final List<WorkerOrder> workerOrderList = workerOrderService.lambdaQuery()
                        .eq(WorkerOrder::getCompanyWechatId, workerOrderBuy.getCompanyWechatId())
                        .eq(WorkerOrder::getWorkerId, workerOrderBuy.getWorkerId())
                        .eq(WorkerOrder::getPayStatus, PayStatusEnum.WAIT.getKey())
                        .list();
                final List<WorkerOrderItem> orderItemList = workerOrderItemService.lambdaQuery()
                        .in(WorkerOrderItem::getOrderId, workerOrderList.stream().map(WorkerOrder::getOrderId).collect(Collectors.toList()))
                        .eq(WorkerOrderItem::getGoodsId, workerOrderItem.getGoodsId())
                        .list();

                BigDecimal totalNum = workerOrderItem.getNum();
                if (CollectionUtil.isNotEmpty(orderItemList)) {
                    for (WorkerOrderItem orderItem : orderItemList) {
                        totalNum = totalNum.add(orderItem.getNum());
                    }
                }

                for (WorkerNormStockBean stockBean : stockBeanList) {
                    // 当前订单收费标准扣总数量
                    BigDecimal useTotalQty = totalNum.multiply(stockBean.getQty());
                    if (!workerStockMap.containsKey(stockBean.getWorkerGoodsId())) {
                        WorkerNormStockBean bean = new WorkerNormStockBean();
                        BeanUtils.copyProperties(stockBean, bean);
                        bean.setRealQty(BigDecimal.ZERO);
                        workerStockMap.put(bean.getWorkerGoodsId(), bean);
                    }
                    WorkerNormStockBean stock = workerStockMap.get(stockBean.getWorkerGoodsId());
                    stock.setRealQty(stock.getRealQty().add(useTotalQty));
                }
            }
        }



        workerOrderItem.setTotalAmount(websitNormCharge.getNormAmount().multiply(Convert.toBigDecimal(workerOrderItem.getNum())));
        workerOrderItem.setGoodsAmount(websitNormCharge.getNormAmount());
        workerOrderItem.setGoodsCode(websitNormCharge.getNormCode());
        workerOrderItem.setNormAmount(websitNormCharge.getNormAmount());
        workerOrderItem.setUnit(websitNormCharge.getUnit());
        workerOrderItem.setManualAmount(websitNormCharge.getManualAmount().multiply(workerOrderItem.getNum()));
        if (websitNormCharge.getNormType().equals("M")) {
            workerOrderItem.setChargeType("MCC");
        }else {
            workerOrderItem.setChargeType("SERV");
        }


        workerOrderItem.setWorkerAmount(workerOrderItem.getTotalAmount());


        BigDecimal workerProceAmount = workerOrderItem.getWorkerAmount().multiply(Convert.toBigDecimal("0.006"));


        if (workerProceAmount.doubleValue() > 0.01) {
            workerOrderItem.setWorkerProceAmount(workerProceAmount.setScale(2, BigDecimal.ROUND_HALF_UP));

        }else {
            workerOrderItem.setWorkerProceAmount(Convert.toBigDecimal("0.01"));
        }

        workerOrderItem.setWorkerAmount(workerOrderItem.getWorkerAmount().subtract(workerOrderItem.getWorkerProceAmount()));


        if (workerOrderItem.getWorkerAmount().doubleValue() < 0){
            workerOrderItem.setWorkerProceAmount(Convert.toBigDecimal("0"));
            workerOrderItem.setWorkerAmount(Convert.toBigDecimal("0"));
        }

    }

    public WorkerOrderDetail getOrder(String orderId) {
        WorkerOrder workerOrder = workerOrderService.getById(orderId);
        if(workerOrder == null){
            return null;
        }
        WorkerOrderDetail workerOrderDetail = BeanUtil.toBean(workerOrder, WorkerOrderDetail.class);
        workerOrderDetail.setWorkerOrderItems(workerOrderItemService.lambdaQuery()
        .eq(WorkerOrderItem::getOrderId,orderId).list());
        return workerOrderDetail;
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean paid(String orderId, String authCode,String ip,String payType) throws Exception {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        WorkerOrder workerOrder = workerOrderService.getById(orderId);

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

        if (StringUtil.isEmpty(adminWebsit.getPayWorkerCodeId()))
            throw new RemoteServiceException("网点支付配置未配置");



        if (!workerOrder.getPayStatus().equals("WAIT")){
            throw new RemoteServiceException("订单已取消支付");
        }

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


        workerOrder.setSource(commonLogic.getSource().equals(OrderInfoSourceEnum.A)?OrderInfoSourceEnum.A.getRemark():OrderInfoSourceEnum.B.getRemark() );

        workerOrder.setPayTime(new Date());
        workerOrder.setPayType(payType);
        workerOrder.setPayStatus(PayStatusEnum.PAID.getKey());
        workerOrder.updateById();



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

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

       // this.addSettlementWorker(workerOrder,workerOrderItems);


        // 配件扣库存
        try {
            if (workerOrder.getGoodsType().equals("P")) {
                final PgOrderBase orderBase = pgOrderBaseService.getById(workerOrder.getWorkerOrderId());

                if (Objects.nonNull(orderBase)) {

                    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.setWorkerId(workerOrder.getWorkerId());
                        salesCustomerPartsBean.setWorkerName(workerOrder.getWorkerName());
                        salesCustomerPartsBean.setWorkOrderNo(workerOrder.getWorkerOrderId());
                        salesCustomerPartsBean.setCustomerName(orderBase.getUserName());
                        salesCustomerPartsBean.setCustomerTel(orderBase.getUserMobile());
                        salesCustomerPartsBean.setReceiveWebsitId(adminWebsit.getWebsitId());
                        salesCustomerPartsBean.setReceivePartsWebsitId(adminWebsit.getPartsWebsitId());
                        salesCustomerPartsBean.setRemark(workerOrder.getRemark());


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

                        for (WorkerOrderItem workerOrderItem : inner) {
                            SalesCustomerPartsItemBean salesCustomerPartsItemBean = new SalesCustomerPartsItemBean();

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

                            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.setWorkerId(workerOrder.getWorkerId());
                        salesCustomerPartsBean.setWorkerName(workerOrder.getWorkerName());
                        salesCustomerPartsBean.setWorkOrderNo(workerOrder.getWorkerOrderId());
                        salesCustomerPartsBean.setCustomerName(orderBase.getUserName());
                        salesCustomerPartsBean.setCustomerTel(orderBase.getUserMobile());
                        salesCustomerPartsBean.setReceiveWebsitId(adminWebsit.getWebsitId());
                        salesCustomerPartsBean.setReceivePartsWebsitId(adminWebsit.getPartsWebsitId());
                        salesCustomerPartsBean.setRemark(workerOrder.getRemark());


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

                        for (WorkerOrderItem workerOrderItem : OUTSIDE) {
                            SalesCustomerPartsItemBean salesCustomerPartsItemBean = new SalesCustomerPartsItemBean();

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

                            salesCustomerPartsItemBeans.add(salesCustomerPartsItemBean);

                        }

                        salesCustomerPartsBean.setItems(salesCustomerPartsItemBeans);

                        salesCustomerPartsBeans.add(salesCustomerPartsBean);

                    }



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

                    }
                }

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

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

                if (CollectionUtil.isNotEmpty(workerStockDTOS)) {
                    // 开始处理库存
                    materialGoodsStockLogic.handleWorkerStock(workerStockDTOS);
                }
            }
        } catch (Exception e) {
            log.error(workerOrder.getOrderId() + " 师傅辅材扣库存失败: ", e);
        }


        if (payType.equals(PayTypeEnum.WECHAT.getKey())) {
            String transcationId = wechatLogic.paymentFkm(workerOrder.getOrderId(), workerOrder.getTotalAmount(), authCode, "Y", ip,
                    adminWebsit.getPayWorkerCodeId(),workerOrder.getSource());

            workerOrder.setTranscationId(transcationId);
            workerOrder.setOpenId(currentCompanyWechat.getUser().getOpenId());
            workerOrder.setConfigId(adminWebsit.getPayWorkerCodeId());
            workerOrder.updateById();
        }

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


        return true;
    }

    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("M")) {
                // 获取当前关联师傅库存记录
                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())) {
                            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());
                    }
                }
            }
        }

        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(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 addSettlementManaulWorker(WorkerOrder workerOrder, List<WorkerOrderItem> workerOrderItems) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        WorkerSettlementManual one = workerSettlementManualService.lambdaQuery()
                .eq(WorkerSettlementManual::getCompanyWechatId, currentCompanyWechat.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(currentCompanyWechat.getCompanyWechatId());
            workerSettlement.setCompanyWechatName(currentCompanyWechat.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();
        }

    }

    private void addManualSettlementOrder(WorkerOrder workerOrder, List<WorkerOrderItem> workerOrderItems) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        AdminCompanyWechat adminCompanyWechat = adminCompanyWechatService.getById(currentCompanyWechat.getCurrentCompanyWechatId());

        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 addSettlementWorker(WorkerOrder workerOrder, List<WorkerOrderItem> workerOrderItems) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        WorkerSettlement one = workerSettlementService.lambdaQuery().eq(WorkerSettlement::getCompanyWechatId, currentCompanyWechat.getCompanyWechatId())
                .eq(WorkerSettlement::getWebsitId, workerOrder.getWebsitId())
                .eq(WorkerSettlement::getType, "OTHER")
                .eq(WorkerSettlement::getPayType, workerOrder.getPayType())
                .eq(WorkerSettlement::getWorkerId, workerOrder.getWorkerId()).last("limit 1").one();
        if (one != null){
            one.setCommissionAmount(workerOrder.getCommissionAmount().add(one.getCommissionAmount()));
            one.setWorkerAmount(workerOrder.getWorkerAmount().add(one.getWorkerAmount()));

            one.setTotalAmount(workerOrder.getTotalAmount().add(one.getTotalAmount()));
            one.setTotalNum(one.getTotalNum().add(Convert.toBigDecimal("1")));
            one.updateById();
        }else {
            WorkerSettlement workerSettlement = new WorkerSettlement();
            workerSettlement.setCompanyWechatId(currentCompanyWechat.getCompanyWechatId());
            workerSettlement.setCompanyWechatName(currentCompanyWechat.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.setCommissionAmount(workerOrder.getCommissionAmount());
            workerSettlement.setTotalNum(Convert.toBigDecimal("1"));
            workerSettlement.setWorkerAmount(workerOrder.getWorkerAmount());
            workerSettlement.setWebsitAmount(workerOrder.getWebsitAmount());
            workerSettlement.setPayType(workerOrder.getPayType());
            workerSettlement.setType("OTHER");
            workerSettlement.insert();
        }

    }

    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 addSettlementOrder(WorkerOrder workerOrder, List<WorkerOrderItem> workerOrderItems) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        AdminCompanyWechat adminCompanyWechat = adminCompanyWechatService.getById(currentCompanyWechat.getCurrentCompanyWechatId());

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

    }

    public Page<WorkerOrder> orderPage(String yearMonth,String settlementType,String goodsType, String orderId, String startTime, String endTime, String payStatus, Integer pageNum, Integer pageSize) {

        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        String startMonTime = null;
        String endMonTime = null;
        if (StringUtils.isNotBlank(yearMonth)) {
            String[] monthDateTime = computeMonthDateTime(yearMonth);
            startTime = monthDateTime[0];
            endTime = monthDateTime[1];
        }

        return workerOrderService.lambdaQuery()
                .like(!StringUtil.isEmpty(goodsType),WorkerOrder::getGoodsType,goodsType)
                .like(!StringUtil.isEmpty(settlementType),WorkerOrder::getSettlementType,settlementType)
                .eq(!StringUtil.isEmpty(orderId),WorkerOrder::getOrderId,orderId)
                .and(!StringUtil.isEmpty(payStatus),item -> item
                .eq(!StringUtil.isEmpty(payStatus),WorkerOrder::getPayStatus,payStatus)

                .or(!StringUtil.isEmpty(payStatus) && payStatus.equals(PayStatusEnum.CANCEL.getKey()),
                        iter -> iter.eq(WorkerOrder::getRefundStatus, IsYesNoEnum.YES.getKey()))
                )
                .eq(!StringUtil.isEmpty(payStatus) && payStatus.equals(MaterialExamineStatusEnum.PAID.getKey()),WorkerOrder::getRefundStatus, IsYesNoEnum.NO.getKey())

                .eq(WorkerOrder::getUserId,currentCompanyWechat.getUserId())
                .between(!StringUtil.isEmpty(startTime),WorkerOrder::getCreateTime,startTime,endTime)
                .in(WorkerOrder::getCompanyWechatId,currentCompanyWechat.getCompanyWechatId())
                .orderByDesc(WorkerOrder::getCreateTime)
                .page(new Page<>(pageNum,pageSize));

    }


    public Page<WorkerOrder> orderPageWorker(String workerOrderId,String yearMonth,String settlementType,String goodsType, String orderId, String startTime, String endTime, String payStatus, Integer pageNum, Integer pageSize) {

        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        String startMonTime = null;
        String endMonTime = null;
        if (StringUtils.isNotBlank(yearMonth)) {
            String[] monthDateTime = computeMonthDateTime(yearMonth);
            startTime = monthDateTime[0];
            endTime = monthDateTime[1];
        }

        return workerOrderService.lambdaQuery()
                .like(!StringUtil.isEmpty(goodsType),WorkerOrder::getGoodsType,goodsType)
                .like(!StringUtil.isEmpty(settlementType),WorkerOrder::getSettlementType,settlementType)
                .eq(!StringUtil.isEmpty(orderId),WorkerOrder::getOrderId,orderId)
                .eq(!StringUtil.isEmpty(payStatus),WorkerOrder::getPayStatus,payStatus)
                .eq(WorkerOrder::getWorkerOrderId,workerOrderId)

                .eq(WorkerOrder::getUserId,currentCompanyWechat.getUserId())
                .between(!StringUtil.isEmpty(startTime),WorkerOrder::getCreateTime,startTime,endTime)
                .in(WorkerOrder::getCompanyWechatId,currentCompanyWechat.getCompanyWechatId())
                .orderByDesc(WorkerOrder::getCreateTime)
                .page(new Page<>(pageNum,pageSize));

    }



    private String[] computeMonthDateTime(String month) throws RemoteServiceException {
        try {
            String startDate = String.format("%s-01 00:00:00", month);
            Date date = DateUtils.parseDate(startDate);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
            String endDate = DateUtils.formatDate1(cal.getTime()) + " 23:59:59";
            return new String[] { startDate, endDate };
        } catch (ParseException e) {
            throw new RemoteServiceException("月份转换出错");
        }
    }

    public Page<WebsitGoods> websitGoodsList(String normType,String brand,String name,String orderId, String categoryId, Integer pageNum, Integer pageSize) {

        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();


        Page<WebsitGoods> page = websitGoodsService.lambdaQuery()
                .like(!StringUtil.isEmpty(name), WebsitGoods::getGoodsName, name)
                .eq(!StringUtil.isEmpty(normType), WebsitGoods::getNormType, normType)
                .eq(WebsitGoods::getGoodsType, "P")
                .and(item -> item.like(!StringUtil.isEmpty(categoryId), WebsitGoods::getProductRelaName, categoryId)
                  //      .and(item2 -> item2.like(!StringUtil.isEmpty(brand), WebsitGoods::getBrandRelaName, brand)
                        
                        .or().eq(WebsitGoods::getNormType, "S"))

                .in(WebsitGoods::getCompanyWechatId, currentCompanyWechat.getCompanyWechatId())
                .eq(WebsitGoods::getStatus, "ON")
                .page(new Page<>(pageNum, pageSize));

        if (!StringUtil.isEmpty(orderId)){
            PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderId);
            if (pgOrderBase != null && !StringUtil.isEmpty(pgOrderBase.getRpProjectRepairId())){
                for (WebsitGoods record : page.getRecords()) {
                    BigDecimal bigDecimal = this.normPrice(record.getGoodsId(), pgOrderBase.getRpProjectRepairId());

                    record.setNormAmount(bigDecimal == null?record.getNormAmount():bigDecimal);
                }
            }
        }
        return page;

    }

    public Page<WebsitGoodsCategory> websitCategoryList( Integer pageNum, Integer pageSize) {

        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        List<WebsitNormCharge> on = websitNormChargeService.lambdaQuery()
                .select(WebsitNormCharge::getCategoryId)
                .eq(WebsitNormCharge::getStatus, "ON")
                .list();

        List<String> collect = on.stream().map(WebsitNormCharge::getCategoryId).distinct().collect(Collectors.toList());

        if (CollectionUtil.isEmpty(collect)) {
            throw new RemoteServiceException("收费标准暂无数据");
        }

        return websitGoodsCategoryService.lambdaQuery()
                .eq(WebsitGoodsCategory::getCategoryLevel,2)
                .in(WebsitGoodsCategory::getCompanyWechatId,currentCompanyWechat.getCompanyWechatId())
                .in(WebsitGoodsCategory::getCategoryId,collect)
                .page(new Page<>(pageNum,pageSize));
    }

    public OrderCount orderCount(String settlementType, String goodsType, String orderId, String startTime, String endTime, String payStatus) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        OrderCount orderCount = new OrderCount();

        Integer yqx = workerOrderService.lambdaQuery()
                .like(!StringUtil.isEmpty(goodsType), WorkerOrder::getGoodsType, goodsType)
                .like(!StringUtil.isEmpty(settlementType), WorkerOrder::getSettlementType, settlementType)
                .eq(!StringUtil.isEmpty(orderId), WorkerOrder::getOrderId, orderId)
                .eq(!StringUtil.isEmpty(currentCompanyWechat.getUserId()), WorkerOrder::getUserId, currentCompanyWechat.getUserId())

                .and(item -> item
                        .eq(WorkerOrder::getPayStatus,"CANCEL")

                        .or(iter -> iter.eq(WorkerOrder::getRefundStatus, IsYesNoEnum.YES.getKey()))
                )
                .eq(WorkerOrder::getUserId,currentCompanyWechat.getUserId())
                .between(!StringUtil.isEmpty(startTime), WorkerOrder::getCreateTime, startTime, endTime)
                .in(WorkerOrder::getCompanyWechatId, currentCompanyWechat.getCompanyWechatId()).count();


        Integer wzf = workerOrderService.lambdaQuery()
                .like(!StringUtil.isEmpty(goodsType), WorkerOrder::getGoodsType, goodsType)
                .like(!StringUtil.isEmpty(settlementType), WorkerOrder::getSettlementType, settlementType)
                .eq(!StringUtil.isEmpty(orderId), WorkerOrder::getOrderId, orderId)
                .eq(!StringUtil.isEmpty(currentCompanyWechat.getUserId()), WorkerOrder::getUserId, currentCompanyWechat.getUserId())

                .eq( WorkerOrder::getPayStatus, "WAIT")
                .eq(WorkerOrder::getUserId,currentCompanyWechat.getUserId())
                .between(!StringUtil.isEmpty(startTime), WorkerOrder::getCreateTime, startTime, endTime)
                .in(WorkerOrder::getCompanyWechatId, currentCompanyWechat.getCompanyWechatId()).count();


        Integer yzf = workerOrderService.lambdaQuery()
                .like(!StringUtil.isEmpty(goodsType), WorkerOrder::getGoodsType, goodsType)
                .like(!StringUtil.isEmpty(settlementType), WorkerOrder::getSettlementType, settlementType)
                .eq(!StringUtil.isEmpty(orderId), WorkerOrder::getOrderId, orderId)
                .eq(!StringUtil.isEmpty(currentCompanyWechat.getUserId()), WorkerOrder::getUserId, currentCompanyWechat.getUserId())
                .eq(WorkerOrder::getRefundStatus, IsYesNoEnum.NO.getKey())

                .eq( WorkerOrder::getPayStatus, PayStatusEnum.PAID.getKey())
                .eq(WorkerOrder::getUserId,currentCompanyWechat.getUserId())
                .between(!StringUtil.isEmpty(startTime), WorkerOrder::getCreateTime, startTime, endTime)
                .in(WorkerOrder::getCompanyWechatId, currentCompanyWechat.getCompanyWechatId()).count();


        Integer qb = workerOrderService.lambdaQuery()
                .like(!StringUtil.isEmpty(goodsType), WorkerOrder::getGoodsType, goodsType)
                .like(!StringUtil.isEmpty(settlementType), WorkerOrder::getSettlementType, settlementType)
                .eq(!StringUtil.isEmpty(orderId), WorkerOrder::getOrderId, orderId)
                .eq(!StringUtil.isEmpty(currentCompanyWechat.getUserId()), WorkerOrder::getUserId, currentCompanyWechat.getUserId())
                .between(!StringUtil.isEmpty(startTime), WorkerOrder::getCreateTime, startTime, endTime)
                .in(WorkerOrder::getCompanyWechatId, currentCompanyWechat.getCompanyWechatId()).count();

        orderCount.setDzf(wzf);
        orderCount.setQb(qb);
        orderCount.setYqx(yqx);
        orderCount.setYzf(yzf);
        return orderCount;

    }

    public void cancel(String orderId) {
        if (workerOrderService.lambdaQuery().eq(WorkerOrder::getOrderId,orderId)
                .eq(WorkerOrder::getPayStatus,"WAIT").count() < 1){
            throw new RemoteServiceException("订单不属于未支付不可取消");
        }
        workerOrderService.lambdaUpdate().eq(WorkerOrder::getOrderId,orderId)
                .set(WorkerOrder::getPayStatus,"CANCEL").update();
    }

    public List<SysDictCompany> sysDict(String dictType) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        return sysDictCompanyService.lambdaQuery().eq(SysDictCompany::getDictType,dictType)
                .eq(SysDictCompany::getCompanyWechatId,currentCompanyWechat.getCompanyWechatId()).list();
    }

    public List<GoodsCategory> getCategoryList() {

        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();


        return goodsCategoryService.lambdaQuery()
                .eq(GoodsCategory::getType,2)
                .eq(GoodsCategory::getDel,0)
                .eq(GoodsCategory::getLevel, 1)
                .in(GoodsCategory::getCompanyWechatId,currentCompanyWechat.getCompanyWechatId())
                .orderByAsc(GoodsCategory::getSortNum).list();
    }

    public IPage<SettlementOrder> pageSettlementV2(List<String> status, String startTime, String endTime, Integer pageNum, Integer pageSize) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();


        return settlementOrderService.lambdaQuery()
                .in(!CollectionUtils.isEmpty(status),SettlementOrder::getStatus,status)
                .eq(SettlementOrder::getWorkerId,currentCompanyWechat.getUser().getWorkerNumber())
                .between(!StringUtil.isEmpty(startTime),SettlementOrder::getCreateTime,startTime,endTime)
                .in(SettlementOrder::getCompanyWechatId,currentCompanyWechat.getCompanyWechatId())
                .orderByDesc(SettlementOrder::getCreateTime)
                .page(new Page<>(pageNum,pageSize));
    }

    public SettlementOrderDetail detail(String id) {
        SettlementOrderItem settlementOrderItem = settlementOrderItemService.getById(id);

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

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

    public List<WorkerOrderDetail> getOrderList(String workerOrderId) {

        List<WorkerOrder> list = workerOrderService.lambdaQuery().eq(WorkerOrder::getWorkerOrderId, workerOrderId)
                .eq(WorkerOrder::getPayStatus,PayStatusEnum.PAID.getKey()).list();

        if (CollectionUtils.isEmpty(list))
            return new ArrayList<>();

        List<WorkerOrderDetail> workerOrderDetails1 = BeanUtil.copyToList(list, WorkerOrderDetail.class);
        for (WorkerOrderDetail workerOrder : workerOrderDetails1) {

            workerOrder.setWorkerOrderItems(workerOrderItemService.lambdaQuery()
                    .eq(WorkerOrderItem::getOrderId,workerOrder.getOrderId()).list());

        }


        return workerOrderDetails1;

    }


    public List<Brand> getBrand() {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        return brandService.lambdaQuery()
                .eq(Brand::getStatus,1)
                .eq(Brand::getCompanyWechatId,currentCompanyWechat.getCompanyWechatId())
                .orderByAsc(Brand::getSortNum).list();
    }
}
