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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.google.common.collect.Lists;
import com.gree.mall.manager.bean.ExcelData;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.material.manage.PartsApplyBean;
import com.gree.mall.manager.bean.order.*;
import com.gree.mall.manager.bean.workorder.OrderAddBean2DTO;
import com.gree.mall.manager.commonmapper.CoustomUserCouponMapper;
import com.gree.mall.manager.commonmapper.CustomWebsitMapper;
import com.gree.mall.manager.commonmapper.OrderMapper;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.enums.*;
import com.gree.mall.manager.enums.material.DirectFlagEnum;
import com.gree.mall.manager.enums.material.GoodsMaterialStockAccBillTypeEnum;
import com.gree.mall.manager.enums.material.PartsApplyStatusEnum;
import com.gree.mall.manager.enums.material.PayTypeEnum;
import com.gree.mall.manager.enums.workorder.OrderFlagEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.ExpressLogic;
import com.gree.mall.manager.logic.StorageLogic;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.common.WechatLogic;
import com.gree.mall.manager.logic.common.WxPubNoticeLogic;
import com.gree.mall.manager.logic.common.kuaidi100.response.SubscribePushParamResp;
import com.gree.mall.manager.logic.goods.GoodsMaterialStockAccLogic;
import com.gree.mall.manager.logic.goods.JxGoodsLogic;
import com.gree.mall.manager.logic.user.MsgSubscriptLogic;
import com.gree.mall.manager.logic.user.UserLogic;
import com.gree.mall.manager.logic.workorder.OrderBaseLogic;
import com.gree.mall.manager.logic.workorder.OrderFlagLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.ArithUtils;
import com.gree.mall.manager.utils.StringUtil;
import com.gree.mall.manager.utils.excel.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderLogic {

    @Autowired
    OrderShareLogic orderShareLogic;
    @Autowired
    StorageLogic storageLogic;
    @Autowired
    MsgSubscriptLogic msgSubscriptLogic;
    @Autowired
    UserLogic userLogic;
    @Autowired
    ExpressLogic expressLogic;
    @Autowired
    WechatLogic wechatLogic;
//    @Autowired
//    GongdanLogic gongdanLogic;
    @Autowired
    RedisLockRegistry redisLockRegistry;
    @Autowired
    CommentTagLogic commentTagLogic;
    @Autowired
    CommonLogic commonLogic;
    @Autowired
    OrderBaseLogic orderBaseLogic;
    @Autowired
    GoodsService goodsService;
    @Autowired
    OrderInfoService orderInfoService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    AdminUserService adminUserService;
    @Autowired
    OrderRefundCliaimsService orderRefundCliaimsService;
    @Autowired
    private OrderShareService orderShareService;
    @Autowired
    private OrderRefundService orderRefundService;
    @Autowired
    private UserCouponService userCouponService;
    @Autowired
    private CoustomUserCouponMapper coustomUserCouponMapper;
    @Autowired
    private CustomWebsitMapper customWebsitMapper;
    @Autowired
    ExpressInfoService expressInfoService;
    @Autowired
    OrderRequestService orderRequestService;
    @Autowired
    UserService userService;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    GoodsCategoryService goodsCategoryService;
    @Autowired
    GoodsMaterialService goodsMaterialService;

    @Autowired
    GoodsMaterialItemService goodsMaterialItemService;

    @Autowired
    OrderDetailCodeService orderDetailCodeService;

    @Autowired
    JxGoodsLogic jxGoodsLogic;

    @Autowired
    GoodsMaterialStockAccLogic goodsMaterialStockAccLogic;

    @Autowired
    OrderPrintRecordService orderPrintRecordService;
    @Autowired
    OrderOfflineRefundService orderOfflineRefundService;

    @Autowired
    OrderOldProductService orderOldProductService;

    @Autowired
    OrderOldProductItemService orderOldProductItemService;

    @Autowired
    WebsitPartsApplyService websitPartsApplyService;
    @Autowired
    WebsitPartsApplyItemService websitPartsApplyItemService;
    @Autowired
    WxPubNoticeLogic wxPubNoticeLogic;
    @Autowired
    AdminWebsitService adminWebsitService;
    @Autowired
    OrderFlagLogic orderFlagLogic;

    @Autowired
    GoodsSpecService goodsSpecService;

    @Autowired
    GoodsMaterialStorageService goodsMaterialStorageService;
    /**
     * 订单列表
     *
     * @return
     */
    public IPage<OrderDetailBean> list(HttpServletRequest request, String userId, String orderId, String productName, String userName, String phone,
                                       String exchangeCode, List<String> orderStatus, String startCreateTime, String endCreateTime, String startPayTime,
                                       String endPayTime, String websitId,
                                       Integer pageNum, Integer pageSize,
                                       String isNegative,String abnormalDispatch,String workerOrderNo,String goodsId
    ) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        //派工异常订单
//        if(StringUtils.isNotBlank(abnormalDispatch) && abnormalDispatch.trim().equals("true")){
//            return abnormalDispatchOrder( adminUser,  userId,  orderId,  productName,  userName,  phone,
//                    exchangeCode,  orderStatus,  startCreateTime,  endCreateTime,  startPayTime,
//                    endPayTime,  websitId, pageNum,  pageSize,
//                    isNegative, abnormalDispatch);
//        }

        List<String> orderIds = new ArrayList<>();
        if(StringUtils.isNotBlank(workerOrderNo)) {
            List<OrderRequest> orderRequests = orderRequestService.lambdaQuery().eq(OrderRequest::getWorkerOrderNo, workerOrderNo).list();
            orderIds = orderRequests.stream().map(OrderRequest::getOrderId).collect(Collectors.toList());
        }

        IPage page = orderInfoService.lambdaQuery()
                .in(CollectionUtils.isNotEmpty(adminUser.getCompanyWechatIds()),OrderInfo::getCompanyWechatId,adminUser.getCompanyWechatIds())
                ////.//in(CollectionUtils.isNotEmpty(adminUser.getAdminWebsitIds()),OrderInfo::getWebsitId,adminUser.getAdminWebsitIds())
                .eq(StringUtils.isNotBlank(userId), OrderInfo::getUserId, userId)
                .eq(StringUtils.isNotBlank(goodsId),OrderInfo::getPromotionPackageGoodsId,goodsId)
                .like(StringUtils.isNotBlank(exchangeCode),OrderInfo::getExchangeCode,exchangeCode)
                .like(StringUtils.isNotBlank(orderId), OrderInfo::getOrderId, orderId)
                .like(StringUtils.isNotBlank(productName), OrderInfo::getOrderTitle, productName)
                .in(CollectionUtils.isNotEmpty(orderIds),OrderInfo::getOrderId,orderIds)
                .eq(StringUtils.isNotBlank(websitId),OrderInfo::getWebsitId,websitId)
                .and(StringUtils.isNotBlank(userName), v -> v.like(OrderInfo::getUserName,userName).or().like(OrderInfo::getReceUserName,userName))
                .and(StringUtils.isNotBlank(phone), v -> v.like(OrderInfo::getPhone, phone).or().like(OrderInfo::getRecePhone,phone).or().like(OrderInfo::getWorkerPhone,phone))
          //      .in(!(adminWebsitBean.getType() && org.apache.commons.lang3.StringUtils.isBlank(websitId)), OrderInfo::getWebsitNumber, websitNoList)
                .in(CollectionUtils.isNotEmpty(orderStatus), OrderInfo::getOrderStatus, orderStatus)
                .between(StringUtils.isNotBlank(startCreateTime) && StringUtils.isNotBlank(endCreateTime), OrderInfo::getCreateTime, startCreateTime, endCreateTime + " 23:59:59")
                .between(StringUtils.isNotBlank(startPayTime) && StringUtils.isNotBlank(endPayTime), OrderInfo::getPayTime, startPayTime, endPayTime + " 23:59:59")
                .and(StringUtils.isNotBlank(isNegative)&&isNegative.trim().equals("2"),
                        v -> v.gt(OrderInfo::getCommentExpress,2).gt(OrderInfo::getCommentService,2).gt(OrderInfo::getCommentGoods,2))
                .and(StringUtils.isNotBlank(isNegative)&&isNegative.trim().equals("1"),v -> v
                        .gt(OrderInfo::getCommentExpress,0)
                        .gt(OrderInfo::getCommentService,0)
                        .gt(OrderInfo::getCommentGoods,0)
                        .and(vv -> vv
                                .lt(OrderInfo::getCommentExpress,3)
                                .or().lt(OrderInfo::getCommentService,3)
                                .or().lt(OrderInfo::getCommentGoods,3)
                        )
                )
                .and(StringUtils.isNotBlank(isNegative)&&isNegative.trim().equals("0"),
                        v -> v.eq(OrderInfo::getCommentExpress,0).eq(OrderInfo::getCommentService,0).eq(OrderInfo::getCommentGoods,0))
                .and(StringUtils.isNotBlank(isNegative)&&isNegative.trim().equals("3"),
                        v -> v.gt(OrderInfo::getCommentExpress,0).gt(OrderInfo::getCommentService,0).gt(OrderInfo::getCommentGoods,0))
                .orderByDesc(OrderInfo::getCreateTime)
                .page(new Page<>(pageNum, pageSize));

        List<OrderDetailBean> list = new ArrayList<>();
        for (Object o : page.getRecords()) {
            OrderInfo orderInfo = (OrderInfo) o;
            OrderDetailBean orderDetailBean = new OrderDetailBean();
            BeanUtils.copyProperties(orderInfo, orderDetailBean);
            //查询订单详情
            List<OrderDetail> orderDetails = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, orderInfo.getOrderId()).list();
            OrderRefund orderRefund = orderRefundService.lambdaQuery()
                    .eq(OrderRefund::getOrderId, orderInfo.getOrderId())
                    .ne(OrderRefund::getRemark,"").last("limit 1").one();

            long count = orderDetails.stream().filter(v -> StringUtils.isNotBlank(v.getWorkerOrderNo())).count();

            Integer printCount = orderPrintRecordService.lambdaQuery()
                    .eq(OrderPrintRecord::getOrderId, orderInfo.getOrderId())
                    .count();

            orderDetailBean.setToWorkOrder(count > 0);
            orderDetailBean.setOrderDetails(orderDetails);
            orderDetailBean.setMerchantRemark(orderRefund == null ? "" : orderRefund.getRemark());
            orderDetailBean.setPrintRecordCount(printCount);
            list.add(orderDetailBean);
        }
        page.setRecords(list);
        return page;
    }

    //派工异常订单
    public IPage<OrderDetailBean> abnormalDispatchOrder(AdminUserCom adminUserCom, String userId, String orderId, String productName, String userName, String phone,
                                       String exchangeCode, String orderStatus, String startCreateTime, String endCreateTime, String startPayTime,
                                       String endPayTime, String websitId,
                                       Integer pageNum, Integer pageSize,
                                       String isNegative,String abnormalDispatch){

        IPage<OrderInfo> orderInfoIPage = orderMapper.abnormalDispatchOrder(new Page<>(pageNum, pageSize), userId, orderId, productName, userName, phone,
                exchangeCode, orderStatus, startCreateTime, endCreateTime, startPayTime,
                endPayTime, websitId,
                isNegative, abnormalDispatch,adminUserCom.getCompanyWechatIds(),adminUserCom.getAdminWebsitIds());

        IPage<OrderDetailBean> orderDetailBeanIPage=new Page<>();
        BeanUtils.copyProperties(orderInfoIPage,orderDetailBeanIPage);

        List<OrderDetailBean> list = new ArrayList<>();
        for (OrderInfo orderInfo : orderInfoIPage.getRecords()) {

            OrderDetailBean orderDetailBean = new OrderDetailBean();
            BeanUtils.copyProperties(orderInfo, orderDetailBean);
            //查询订单详情
            List<OrderDetail> orderDetails = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, orderInfo.getOrderId()).list();
            OrderRefund orderRefund = orderRefundService.lambdaQuery().eq(OrderRefund::getOrderId, orderInfo.getOrderId()).one();
            Integer count = orderRequestService.lambdaQuery().eq(OrderRequest::getOrderId, orderInfo.getOrderId()).count();
            orderDetailBean.setToWorkOrder(count > 0);
            orderDetailBean.setOrderDetails(orderDetails);
            orderDetailBean.setMerchantRemark(orderRefund == null ? "" : orderRefund.getRemark());
            list.add(orderDetailBean);
        }


        orderDetailBeanIPage.setRecords(list);
        return orderDetailBeanIPage;
    }

    public List<OrderDetailBean> list(HttpServletRequest request,String userId, String orderId, String productName, String userName, String phone, String orderStatus,
                                      String startCreateTime, String endCreateTime, String startPayTime, String endPayTime, String websitId) {

        List<OrderInfo> orderList = orderInfoService.lambdaQuery()
                .eq(StringUtils.isNotBlank(userId), OrderInfo::getUserId, userId)
                .like(StringUtils.isNotBlank(orderId), OrderInfo::getOrderId, orderId)
                .like(StringUtils.isNotBlank(productName), OrderInfo::getOrderTitle, productName)
                .like(StringUtils.isNotBlank(userName), OrderInfo::getUserName, userName)
                .like(StringUtils.isNotBlank(phone), OrderInfo::getPhone, phone)
                .eq(StringUtils.isNotBlank(orderStatus), OrderInfo::getOrderStatus, orderStatus)
                .between(StringUtils.isNotBlank(startCreateTime) && StringUtils.isNotBlank(endCreateTime), OrderInfo::getCreateTime, startCreateTime, endCreateTime + " 23:59:59")
                .between(StringUtils.isNotBlank(startPayTime) && StringUtils.isNotBlank(endPayTime), OrderInfo::getPayTime, startPayTime, endPayTime + " 23:59:59")
                .orderByDesc(OrderInfo::getCreateTime)
                .list();

        List<OrderDetailBean> list = new ArrayList<>();
        for (Object o : orderList) {
            OrderInfo orderInfo = (OrderInfo) o;
            OrderDetailBean orderDetailBean = new OrderDetailBean();
            BeanUtils.copyProperties(orderInfo, orderDetailBean);
            //查询订单详情
            List<OrderDetail> orderDetails = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, orderInfo.getOrderId()).list();
            orderDetailBean.setOrderDetails(orderDetails);
            list.add(orderDetailBean);
        }
        return list;
    }

    /**
     * 订单备注
     */
    public void remark(String orderId, String remark) {
        orderInfoService.lambdaUpdate()
                .set(OrderInfo::getRemark, remark)
                .eq(OrderInfo::getOrderId, orderId).update();
    }

    /**
     * 修改物流单号
     */
    public void updateExpress(String orderId,String logisticsNo,String companyCode) throws RemoteServiceException {
        //查询物流公司
        String company = expressLogic.expressCompanyName(companyCode);
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        if(!orderInfo.getOrderStatus().equals(OrderStatusEnum.YFH.toString())){
            throw new RemoteServiceException("非已发货订单不可修改物流单号");
        }
        orderInfo.setCompanyCode(companyCode);
        orderInfo.setCompanyName(company);
        orderInfo.setLogisticsNo(logisticsNo);
        orderInfo.updateById();
        //订阅快递
        expressLogic.subscribeExpress(logisticsNo,null,orderInfo.getRecePhone());
    }

    /**
     * 查看物流
     */
    public List<ExpressInfo> queryExpressInfo(String logisticsNo){
        List<ExpressInfo> list = expressInfoService.lambdaQuery().eq(ExpressInfo::getLogisticsNo, logisticsNo).list();
        if (CollectionUtils.isNotEmpty(list)){
            return list;
        }
        return null;

    }


    /**
     * 取消订单
     */
    public void cancel(String orderId) throws RemoteServiceException, WxPayException {
        OrderInfo orderInfo = orderInfoService.getById(orderId);

        if(!orderInfo.getOrderStatus().equals(OrderStatusEnum.NOPAY.toString()) && !orderInfo.getOrderStatus().equals(OrderStatusEnum.DFH.toString())) {
            throw new RemoteServiceException("订单当前状态不可取消");
        }
        if(StringUtils.equals(orderInfo.getOrderStatus(),OrderStatusEnum.DFH.toString())) {
            log.info("【退款开始：】退款金额{}", orderInfo.getPayAmount().doubleValue());
            if(orderInfo.getPayTypeId().equals(PayTypeEnum.WECHAT.getKey())) {
                wechatLogic.refund(orderInfo.getTransactionId(), orderInfo.getOrderId() + "T", orderInfo.getPayAmount().doubleValue()
                        , orderInfo.getPayAmount().doubleValue(), orderInfo.getCompanyWechatId(), orderInfo.getSource());

                orderShareLogic.reloadAmount(orderId, null, 1);
            }
        }
        this.updateOrderStatus(orderId, OrderStatusEnum.CLOSE.toString());
    }

    /**
     * 确定收款
     */
    public void ackPay(String orderId) {
        return;
//        this.updateOrderStatus(orderId, OrderStatusEnum.DFH.toString());
    }

    /**
     * 主动退款
     */
    @Transactional
    public BigDecimal refund(String orderDetailId, int num) throws RemoteServiceException, WxPayException {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (num < 1) {
            throw new RemoteServiceException("退款数量不能小于1");
        }
        OrderDetail orderDetail = orderDetailService.getById(orderDetailId);
        OrderInfo orderInfo = orderInfoService.getById(orderDetail.getOrderId());
        //1=非团购商品  2=团购商品
        int flag = StringUtils.isNotBlank(orderDetail.getPromotionGroupId()) ? 2 : 1;

        String orderId = orderDetail.getOrderId();

        int count = orderShareService.lambdaQuery()
                .eq(OrderShare::getOrderId, orderId)
                .eq(OrderShare::getStatus, OrderShareStatusEnum.OVER.toString())
                .count();

        if (count > 0) {
            throw new RemoteServiceException("已结算订单,不能退款");
        }
        if (num + orderDetail.getRefundNum() > orderDetail.getNum()) {
            throw new RemoteServiceException("退款数量异常");
        }
        //退款的数量占比
        double div = ArithUtils.div(num, orderDetail.getNum(), 4);
        double mul = ArithUtils.mul(orderDetail.getShareAmount().doubleValue(), div, 2);
        //退款的金额
        BigDecimal totalShareAmount = BigDecimal.valueOf(mul);
        //计算需要退款的金额
        BigDecimal refundAmount = BigDecimal.valueOf(ArithUtils.mul(orderDetail.getPayAmount().doubleValue(), div, 2));

        if (orderInfo.getOrderStatus().equals(OrderStatusEnum.DFH.toString()) ||
                (orderInfo.getOrderStatus().equals(OrderStatusEnum.REFUND.toString()) &&
                        org.apache.commons.lang3.StringUtils.isBlank(orderInfo.getLogisticsNo()))) {//待发货状态退运费
            BigDecimal refundFreight = BigDecimal.valueOf(ArithUtils.mul(orderDetail.getFreight().doubleValue(), div, 2));
            if (refundFreight == null) {
                refundFreight = new BigDecimal("0.00");
            }
            refundAmount = refundAmount.add(refundFreight);
        }

        orderDetail.setRefundNum(orderDetail.getRefundNum() + num);
        orderDetail.setRefundAmount(orderDetail.getRefundAmount().add(refundAmount));
        orderDetail.setRefundTime(new Date());
        orderDetail.setRefundBy(adminUser.getNickName());
        orderDetail.setRefund(orderDetail.getNum() - orderDetail.getRefundNum() == 0);
        orderDetail.updateById();


        int totalNum = orderInfo.getTotalNum();
        List<OrderDetail> orderDetails = orderDetailService.lambdaQuery()
                .eq(OrderDetail::getOrderId, orderId)
                .list();
        int refundNum = orderDetails.stream().filter(OrderDetail::getRefund).collect(Collectors.reducing(0, OrderDetail::getRefundNum, (i, j) -> i + j));
        if (totalNum - refundNum == 0) {
            String userCouponId = orderInfo.getUserCouponId();
            orderInfoService.lambdaUpdate()
                    .eq(OrderInfo::getOrderId, orderId)
                    .set(OrderInfo::getOrderStatus, OrderStatusEnum.CLOSE.toString())
                    .set(OrderInfo::getRefundFlag, RefundFlagEnum.ALL.toString())
                    .update();
            if(StringUtils.isNotBlank(userCouponId)){
                UserCoupon userCoupon = userCouponService.getById(orderInfo.getUserCouponId());
                if (userCoupon.getSelfUse() != null && userCoupon.getSelfUse()) {
                    //todo sql处理,数量加一,删除指定记录
                    //coustomUserCouponMapper.increaseLeftTimes(userCoupon.getTransferor());
                    userCouponService.removeById(userCouponId);
                }else{
                    userCouponService.lambdaUpdate()
                            .eq(UserCoupon::getId,userCouponId)
                            .set(UserCoupon::getStatus,false)
                            .update();
                }
            }

        } else {
            orderInfoService.lambdaUpdate()
                    .eq(OrderInfo::getOrderId, orderId)
                    .set(OrderInfo::getRefundFlag, RefundFlagEnum.PARTLY.toString())
                    .update();
        }
        log.info("【退款开始：】重置flag={}的结算金额，需要减掉的金额{}", flag,totalShareAmount.doubleValue());
        orderShareLogic.reloadAmount(orderId, totalShareAmount,flag);
        log.info("【退款开始：】退款金额{}", refundAmount);
        wechatLogic.refund(orderInfo.getTransactionId(), orderId + StringUtil.getUUID(), orderInfo.getPayAmount().doubleValue()
                , refundAmount.doubleValue(),orderInfo.getCompanyWechatId(),orderInfo.getSource());
        return refundAmount;
    }


    /**
     * 理赔列表
     */
    public List<OrderRefundCliaims> cliaimsList(String orderId) {
        List<OrderRefundCliaims> list = orderRefundCliaimsService.lambdaQuery()
                .eq(OrderRefundCliaims::getOrderId, orderId).orderByDesc(OrderRefundCliaims::getCreateTime).list();
        return list;
    }

    /**
     * 理赔
     */
    @Transactional
    public BigDecimal refundCliaims(String orderDetailId, int num, BigDecimal refundAmount, String adminUserId, String remark) throws RemoteServiceException, WxPayException {
//        if (num < 1) {
//            throw new RemoteServiceException("数量错误");
//        }
        if (refundAmount.compareTo(new BigDecimal("0.00")) < 1) {
            throw new RemoteServiceException("金额错误");
        }
        if(StringUtils.isBlank(remark)){
            throw new RemoteServiceException("请填写理赔原因");
        }
        AdminUser adminUser = adminUserService.getById(adminUserId);
        OrderDetail orderDetail = orderDetailService.getById(orderDetailId);
        String orderId = orderDetail.getOrderId();

        //判断是否存在线下退货单待审核的状态，如果存在，需要先处理
        Integer count = orderOfflineRefundService.lambdaQuery()
                .eq(OrderOfflineRefund::getOrderId, orderId)
                .eq(OrderOfflineRefund::getExamineStatus, ExamineStatusEnum.WAIT.getKey()).count();
        if(count > 0){
            throw new RemoteServiceException("存在待处理的线下退货单，请优先处理");
        }

        if (orderDetail.getNum() < orderDetail.getRefundNum() + num) {
            throw new RemoteServiceException("可理赔商品数量不足");
        }
        if (orderDetail.getPayAmount().add(orderDetail.getFreight()).doubleValue() < (orderDetail.getRefundAmount().add(refundAmount).doubleValue())) {
            throw new RemoteServiceException("可理赔金额不足");
        }

        //退款的数量占比
        double div = ArithUtils.div(num, orderDetail.getNum(), 4);
        double mul = ArithUtils.mul(orderDetail.getShareAmount().doubleValue(), div, 2);
        //退款的金额
        BigDecimal totalShareAmount = BigDecimal.valueOf(mul);
        //计算需要退款的金额
        orderDetail.setRefundNum(orderDetail.getRefundNum() + num);
        orderDetail.setRefundAmount(orderDetail.getRefundAmount().add(refundAmount));
        orderDetail.setRefundTime(new Date());
        orderDetail.setRefundBy(adminUser.getNickName());
        orderDetail.setRefund(orderDetail.getNum() - orderDetail.getRefundNum() == 0);
        orderDetail.updateById();

        //记录理赔数据
        OrderRefundCliaims orderRefundCliaims = new OrderRefundCliaims();
        orderRefundCliaims.setCreateTime(new Date());
        orderRefundCliaims.setRefundAmount(refundAmount);
        orderRefundCliaims.setNum(num);
        orderRefundCliaims.setOrderId(orderId);
        orderRefundCliaims.setOrderDetailId(orderDetailId);
        orderRefundCliaims.setGoodsId(orderDetail.getGoodsId());
        orderRefundCliaims.setGoodsName(orderDetail.getGoodsName());
        orderRefundCliaims.setGoodsSpecId(orderDetail.getGoodsSpecId());
        orderRefundCliaims.setGoodsSpecName(orderDetail.getGoodsSpecName());
        orderRefundCliaims.setGoodsSpecValue(orderDetail.getGoodsSpecValue());
        orderRefundCliaims.setOperatorUser(adminUser.getUserName());
        orderRefundCliaims.setRemark(remark);
        orderRefundCliaims.insert();

        OrderInfo orderInfo = orderInfoService.getById(orderDetail.getOrderId());
        int totalNum = orderInfo.getTotalNum();
        List<OrderDetail> orderDetails = orderDetailService
                .lambdaQuery()
                .eq(OrderDetail::getOrderId, orderId)
                .list();
        int refundNum = orderDetails.stream().filter(OrderDetail::getRefund).collect(Collectors.reducing(0, OrderDetail::getRefundNum, (i, j) -> i + j));
        if (totalNum - refundNum == 0) {
            String userCouponId = orderInfo.getUserCouponId();
            orderInfoService.lambdaUpdate()
                    .eq(OrderInfo::getOrderId, orderId)
                    .set(OrderInfo::getOrderStatus, OrderStatusEnum.CLOSE.toString())
                    .set(OrderInfo::getUserCouponId, "")
                    .set(OrderInfo::getRefundFlag, RefundFlagEnum.ALL.toString())
                    .update();
            if(org.apache.commons.lang3.StringUtils.isNotBlank(userCouponId)){
                UserCoupon userCoupon = userCouponService.getById(orderInfo.getUserCouponId());
                if (userCoupon.getSelfUse() != null && userCoupon.getSelfUse()) {
                    //todo sql处理,数量加一,删除指定记录
                    coustomUserCouponMapper.increaseLeftTimes(userCoupon.getTransferor());
                    userCouponService.removeById(userCouponId);
                }else{
                    userCouponService.lambdaUpdate()
                            .eq(UserCoupon::getId,userCouponId)
                            .set(UserCoupon::getStatus,false)
                            .update();
                }
            }
        } else {
            orderInfoService.lambdaUpdate()
                    .eq(OrderInfo::getOrderId, orderId)
                    .set(OrderInfo::getRefundFlag, RefundFlagEnum.PARTLY.toString())
                    .update();
        }

        //1=非团购商品 2=团购商品
        if(totalShareAmount.doubleValue() > 0) {
            int flag = StringUtils.isNotBlank(orderDetail.getPromotionGroupId()) ? 2 : 1;
            log.info("【退款开始：】重置结算,order_id={},flag={}金额，需要减掉的金额{}", orderInfo.getOrderId(),flag, totalShareAmount.doubleValue());
            orderShareLogic.reloadAmount(orderId, totalShareAmount, flag);
        }
        log.info("【退款开始：】退款金额{},order_id={}", refundAmount,orderInfo.getOrderId());
        wechatLogic.refund(orderInfo.getTransactionId(), orderId + StringUtil.getUUID(), orderInfo.getPayAmount().doubleValue()
                , refundAmount.doubleValue(), orderInfo.getCompanyWechatId(),orderInfo.getSource());
        return refundAmount;
    }


    /**
     * 修改价格
     */
    public void updatePrice(String orderId, BigDecimal price) throws RemoteServiceException {
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        if (!orderInfo.getOrderStatus().equals(OrderStatusEnum.NOPAY.toString())) {
            throw new RemoteServiceException("非待付款订单不可修改");
        }
        if (orderInfo.getPayAmount().doubleValue() < price.doubleValue()) {
            throw new RemoteServiceException("不可将价格修改的更贵");
        }
        if (orderInfo.getPayAmount().doubleValue() < orderInfo.getFreight().doubleValue()) {
            throw new RemoteServiceException("不可将价格修改的比运费小");
        }
        orderInfo.setPayAmount(price);
        orderInfo.updateById();
    }

    /**
     * 修改收货人信息
     */
    public void updateReceInfo(OrderInfo orderInfo) throws RemoteServiceException {
        if (orderInfo.getOrderStatus().equals(OrderStatusEnum.OVER.toString())
                || orderInfo.getOrderStatus().equals(OrderStatusEnum.OVER.toString())) {
            throw new RemoteServiceException("已发货、已完成订单不可修改");
        }
        orderInfo.updateById();
    }

    /**
     * 批量设置备注
     */
    public void batchRemark(BatchRemarkBean batchRemarkBean) throws RemoteServiceException {
        if (CollectionUtils.isEmpty(batchRemarkBean.getOrderIds())) {
            throw new RemoteServiceException("订单号不能为空");
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(batchRemarkBean.getRemark())) {
            return;
        }
        orderInfoService.lambdaUpdate()
                .set(OrderInfo::getRemark, batchRemarkBean.getRemark())
                .in(OrderInfo::getOrderId, batchRemarkBean.getOrderIds())
                .update();
    }

    /**
     * 发货
     */
    @Transactional
    public void deliverGoods(String orderId, String logisticsNo, String companyCode, String storageId, Boolean workOrder, Boolean exchange) throws Exception {
        this.deliverGoods(orderId,logisticsNo,companyCode,storageId,workOrder,exchange,"","","");
    }

    /**
     * 发货
     */
    @Transactional
    public void deliverGoods(String orderId, String logisticsNo, String companyCode, String storageId, Boolean workOrder, Boolean exchange,String pickName,String pickPhone ,String pickType) throws Exception {
        //仓库
        Storage detail = storageLogic.detail(storageId);
        //快递公司
        DeliverGoodsBean deliverGoodsBean = new DeliverGoodsBean();
        deliverGoodsBean.setOrderId(orderId);
        if (!StringUtil.isEmpty(deliverGoodsBean.getLogisticsNo())) {
            String companyName = expressLogic.expressCompanyName(companyCode);
            deliverGoodsBean.setExpressCorp(companyName);
            deliverGoodsBean.setLogisticsNo(logisticsNo);
        }
        if(detail != null) {
            deliverGoodsBean.setWarehouse(detail.getStorageName());
        }
        deliverGoodsBean.setSend(workOrder);
        deliverGoodsBean.setExchangeOrder(exchange);
        deliverGoodsBean.setPickName(pickName);
        deliverGoodsBean.setPickPhone(pickPhone);
        deliverGoodsBean.setPickType(pickType);
        //预检查
        preCheck(deliverGoodsBean);
        //发货
        updateDeliverItem(deliverGoodsBean);
    }





    @Transactional
    public void deliverBatchGoods(List<String> row) throws Exception {
        DeliverGoodsBean deliverGoodsBean = new DeliverGoodsBean();
        deliverGoodsBean.setOrderId(row.get(0));
        deliverGoodsBean.setExpressCorp(row.get(1));
        deliverGoodsBean.setLogisticsNo(row.get(2));
        deliverGoodsBean.setWarehouse(row.get(3));
        deliverGoodsBean.setSend("是".equals(row.get(4)));
        deliverGoodsBean.setExchangeOrder("是".equals(row.get(5)));
        //预检查
        preCheck(deliverGoodsBean);
        updateDeliverItem(deliverGoodsBean);
    }

    private void preCheck(DeliverGoodsBean deliverGoodsBean) {
        String orderId = deliverGoodsBean.getOrderId();
        if (org.apache.commons.lang3.StringUtils.isBlank(orderId)) {
            throw new RemoteServiceException("订单号不能为空");
        }
        OrderInfo orderInfo = orderInfoService.lambdaQuery()
                .eq(OrderInfo::getOrderId, orderId)
                .eq(OrderInfo::getOrderStatus, OrderStatusEnum.DFH.toString())
                .one();

        if (orderInfo == null) {
            throw new RemoteServiceException("订单号不正确或已发货："+orderId);
        }
        if (StringUtils.isNotBlank(deliverGoodsBean.getWarehouse())) {
            Storage detail = storageLogic.detailByName(orderInfo.getCompanyWechatId(), deliverGoodsBean.getWarehouse().trim());
            if (detail == null) {
                throw new RemoteServiceException("仓库不正确，订单号："+orderId);
            }
        }
        if (!StringUtil.isEmpty(deliverGoodsBean.getLogisticsNo())) {
            ExpressCompany company = expressLogic.expressCompany(deliverGoodsBean.getExpressCorp().trim());
            if (company == null) {
                throw new RemoteServiceException("物流公司出错，订单号：" + orderId);
            }
        }
    }

    public void updateDeliverItem(DeliverGoodsBean deliverGoodsBean) throws Exception {
        String orderId = deliverGoodsBean.getOrderId();
        OrderInfo orderInfo = orderInfoService.lambdaQuery()
                .eq(OrderInfo::getOrderId, orderId)
                .eq(OrderInfo::getOrderStatus, OrderStatusEnum.DFH.toString())
                .one();
        if (org.apache.commons.lang3.StringUtils.isBlank(orderId)) {
            throw new RemoteServiceException("订单号不能为空");
        }

        if (orderInfo == null) {
            throw new RemoteServiceException(String.format("订单号:%s不正确或已发货,请检查", deliverGoodsBean.getOrderId()));
        }
        Storage detail = storageLogic.detailByName(orderInfo.getCompanyWechatId(), deliverGoodsBean.getWarehouse());

        if (!StringUtil.isEmpty(deliverGoodsBean.getLogisticsNo())) {
            ExpressCompany company = expressLogic.expressCompany(deliverGoodsBean.getExpressCorp());
            if (company == null) {
                throw new RemoteServiceException(String.format("订单号:%s物流公司出错,请检查", deliverGoodsBean.getOrderId()));
            }
            orderInfo.setCompanyCode(company.getCode());
            orderInfo.setCompanyName(company.getName());
        }
        orderInfo.setLogisticsNo(deliverGoodsBean.getLogisticsNo());

        orderInfo.setOrderStatus(OrderStatusEnum.YFH.toString());
        if(detail != null) {
            orderInfo.setStorageName(detail.getStorageName());
            orderInfo.setStorageAddress(detail.getStorageAddress());
            orderInfo.setStoragePhone(detail.getStorageMobile());
        }
        orderInfo.setDeliverTime(new Date());
        orderInfo.setWorkOrder(deliverGoodsBean.getSend());
        orderInfo.setExchangeOrder(deliverGoodsBean.getExchangeOrder());
        orderInfo.setPickName(deliverGoodsBean.getPickName());
        orderInfo.setPickPhone(deliverGoodsBean.getPickPhone());
        orderInfo.setPickType(deliverGoodsBean.getPickType());
        orderInfo.updateById();

        orderShareLogic.updateOrderStatus(orderId, OrderStatusEnum.YFH.toString());

        //对接工单
        this.orderToWorkorder(orderInfo);
        //订阅物流
        if (!StringUtil.isEmpty(deliverGoodsBean.getLogisticsNo())) {
            expressLogic.subscribeExpress(deliverGoodsBean.getLogisticsNo(), orderInfo.getCompanyCode(), orderInfo.getRecePhone());
        }

//        User user = userLogic.getById(orderInfo.getUserId());
//        if (user != null) {
//            //对接微信发货 //自动发货对接微信(立即发货，腾讯那边会有延迟问题找不到订单，所以交给定时器处理)
//            //wechatLogic.deliver(orderInfo,user.getMiniOpenId());
//            //对接小程序发货通知
//            msgSubscriptLogic.sendFhNotice(user.getUserId(), user.getOpenId(), orderInfo.getOrderId(), orderInfo.getPayAmount()
//                    , orderInfo.getCompanyName(), orderInfo.getLogisticsNo());
//        }

    }





    private String getStringValue(Cell cell) {
        if (cell == null) {
            return null;
        }
        CellType cellType = cell.getCellTypeEnum();
        switch (cellType) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                double value = cell.getNumericCellValue();
                return String.valueOf(Math.round(value));
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            default:
                return null;
        }
    }

    /**
     * 订单详情
     */
    public OrderDetailBeanVO detail(String orderId,String storageId) {
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        //查询订单详情
        List<OrderDetail> orderDetails = orderDetailService.lambdaQuery()
                .eq(OrderDetail::getOrderId, orderInfo.getOrderId())
                .list();
        //已结算数量
        int count = orderShareService.lambdaQuery()
                .eq(OrderShare::getOrderId, orderId)
                .eq(OrderShare::getStatus, OrderShareStatusEnum.OVER.toString())
                .count();
        //组装数据

        List<OrderDetailSon> orderDetailSons = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(orderDetails)) {
            List<GoodsMaterial> materialList = goodsMaterialService.lambdaQuery()
                    .eq(GoodsMaterial::getCompanyWechatId, orderInfo.getCompanyWechatId())
                    .isNotNull(GoodsMaterial::getFactoryNo)
                    .in(GoodsMaterial::getId, orderDetails.stream()
                            .map(OrderDetail::getGoodsMaterialId)
                            .collect(Collectors.toList()))
                    .list();

            Map<String, String> stringMap = materialList.stream()
                    .collect(Collectors.toMap(GoodsMaterial::getId, GoodsMaterial::getFactoryNo));

            List<GoodsMaterialStorage> list = goodsMaterialStorageService.lambdaQuery().eq(GoodsMaterialStorage::getCompanyWechatId, orderInfo.getCompanyWechatId()).list();

            for (OrderDetail orderDetail : orderDetails) {
                String factoryNo = stringMap.get(orderDetail.getGoodsMaterialId());
                if (StringUtils.isNotBlank(factoryNo)) {
                    orderDetail.setGoodsMaterialName(orderDetail.getGoodsMaterialName() + "(" + factoryNo + ")");
                    orderDetail.setGoodsName(orderDetail.getGoodsName() + "(" + factoryNo + ")");
                }
                OrderDetailSon orderDetailSon = BeanUtil.toBean(orderDetail, OrderDetailSon.class);

                Integer integer = list.stream().filter(item -> item.getGoodsMaterialId().equals(orderDetail.getGoodsMaterialId()))
                        .map(GoodsMaterialStorage::getStockQty).reduce(Integer::sum).orElse(0);
                orderDetailSon.setAllStockQty(integer);
                if (!StringUtil.isEmpty(storageId)){
                    Integer integerQty = list.stream().filter(item -> item.getGoodsMaterialId().equals(orderDetail.getGoodsMaterialId())
                    && item.getStorageId().equals(storageId)
                    )
                            .map(GoodsMaterialStorage::getStockQty).reduce(Integer::sum).orElse(0);
                    orderDetailSon.setStockOnQty(integerQty);
                }

                orderDetailSons.add(orderDetailSon);
            }
        }

        OrderDetailBeanVO orderDetailBean = new OrderDetailBeanVO();
        BeanUtils.copyProperties(orderInfo, orderDetailBean);
        orderDetailBean.setOrderDetails(orderDetailSons);

        Boolean refundFlag = false;
        if (count == 0) {
            refundFlag = true;
        }
        orderDetailBean.setRefundAble(refundFlag);
        //团长信息
        if(StringUtils.isNotBlank(orderInfo.getPromotionGroupUserId())){
            User user = userService.getById(orderInfo.getPromotionGroupUserId());
            if(user != null){
                orderDetailBean.setPromotionGroupUserName(user.getNickName());
                orderDetailBean.setPromotionGroupMobile(user.getMobile());
            }
        }
        //查询订单评价
        orderDetailBean.setOrderComment(commentTagLogic.getOrderComment(orderId));
        orderDetailBean.setOrderCommentTags(commentTagLogic.getCommentTags(orderId));
        orderDetailBean.setOrderCommentImgs(commonLogic.queryFileUrlsByObjId(orderId, Constant.Img.ORDER_COMMENT));

        Integer printCount = orderPrintRecordService.lambdaQuery()
                .eq(OrderPrintRecord::getOrderId, orderDetailBean.getOrderId())
                .count();

        orderDetailBean.setPrintRecordCount(printCount);


        List<OrderOldProduct> list = orderOldProductService.lambdaQuery()
                .eq(OrderOldProduct::getOrderId, orderId).list();

        List<OrderOldProductDTO> orderOldProductDTOS = new ArrayList<>();

        for (OrderOldProduct orderOldProduct : list) {
            OrderOldProductDTO orderOldProductDTO = BeanUtil.toBean(orderOldProduct, OrderOldProductDTO.class);
            List<OrderOldProductItem> orderOldProductItemList = orderOldProductItemService.lambdaQuery().eq(OrderOldProductItem::getOrderOldProductId, orderOldProduct.getId()).list();
            orderOldProductDTO.setItemList(orderOldProductItemList);

            orderOldProductDTOS.add(orderOldProductDTO);
        }

        orderDetailBean.setOrderOldProductDTOList(orderOldProductDTOS);

        return orderDetailBean;
    }

    /**
     * 是否显示评价
     */
    public void updateShowComment(String orderId,Boolean isShow){
        commentTagLogic.updateShow(orderId,isShow);
    }


    public void ack(String orderBaseId){
        OrderInfo orderInfo = orderInfoService.getById(orderBaseId);
        if(!StringUtils.equals(orderInfo.getOrderStatus(),OrderStatusEnum.DQR.toString())){
            throw new RemoteServiceException("非待确认订单不可操作");
        }
        orderInfo.setOrderStatus(OrderStatusEnum.DFH.toString());
        orderInfo.updateById();
    }


    /**
     * 修改订单状态,修改结算的订单状态
     */
    public void updateOrderStatus(String orderId, String orderStatus) {
        orderInfoService.lambdaUpdate()
                .set(OrderInfo::getOrderStatus, orderStatus)
                .eq(OrderInfo::getOrderId, orderId).update();

        orderShareLogic.updateOrderStatus(orderId, orderStatus);
    }

    /**
     * 查询订单详情
     */
    public List<OrderDetail> queryOrderDetails(String orderId){
        List<OrderDetail> list = orderDetailService.lambdaQuery().in(OrderDetail::getOrderId, orderId).list();
        return list;
    }



    /**
     * 导出excel
     *
     * @param orderId
     * @param orderStatus
     */
    public void export(HttpServletRequest request, HttpServletResponse response, String userId, String orderId, String productName, String userName, String phone, String orderStatus,
                       String startCreateTime, String endCreateTime, String startPayTime, String endPayTime, String websitId) throws Exception {
        List<OrderDetailBean> list = list(request,userId, orderId, productName, userName, phone, orderStatus, startCreateTime, endCreateTime, startPayTime, endPayTime, websitId);
//        OrderDetailBean
        String[] titles = {"订单号", "商品名称", "规格型号", "数量", "单位", "销售单价", "优惠后单价", "实际收款", "收货人姓名",
                "手机号", "收货地址","订单状态", "售后状态", "退款金额(小项)", "退款数量(小项)", "备注", "下单时间", "买家昵称", "购买渠道", "买家备注", "卖家备注", "网点", "业务员/网点","分佣金额","团长名称","团长手机号"};
        ExcelData excelData = new ExcelData();
        List<List<Object>> rows = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (OrderDetailBean orderDetailBean : list) {

            User user = null;
            //查询团长
            String promotionGroupUserId = orderDetailBean.getPromotionGroupUserId();
            if(StringUtils.isNotBlank(promotionGroupUserId)){
                user = userService.getById(promotionGroupUserId);
            }

            for (OrderDetail orderDetail : orderDetailBean.getOrderDetails()) {
                List<Object> row = new ArrayList<>();
                row.add(orderDetail.getOrderId());
                row.add(orderDetail.getGoodsName());

                row.add(trimStr(orderDetail.getGoodsSpecName(), "(", orderDetail.getGoodsSpecValue(), ")"));
                row.add(orderDetail.getNum());
                row.add("台");
                row.add(orderDetail.getPrice());
                row.add(orderDetail.getPayAmount().divide(new BigDecimal(orderDetail.getNum()), 2, BigDecimal.ROUND_HALF_UP));
                row.add(orderDetail.getPayAmount());
                row.add(orderDetailBean.getReceUserName());
                row.add(orderDetailBean.getRecePhone());
                row.add(trimStr(orderDetailBean.getProvince(), orderDetailBean.getCity(),
                        orderDetailBean.getArea(), orderDetailBean.getStreet(), orderDetailBean.getReceAddress(),orderDetailBean.getHouseNo()));
                String orderStatusName = Enum.valueOf(OrderStatusEnum.class, orderDetailBean.getOrderStatus().trim().toUpperCase()).getName();
                if (orderDetailBean.getOrderStatus().equals(OrderStatusEnum.REFUND.toString())) {
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(orderDetailBean.getLogisticsNo())) {
                        orderStatusName = OrderStatusEnum.YFH.getName();
                    } else {
                        orderStatusName = OrderStatusEnum.DFH.getName();
                    }
                }
                if(orderDetailBean.getRefundFlag().equals(RefundFlagEnum.ALL.toString())){
                    orderStatusName = OrderStatusEnum.CLOSE.getName();
                }
                row.add(orderStatusName);
                String refundFlag = "";
                if (orderDetailBean.getRefundFlag().equals(RefundFlagEnum.PARTLY.toString()) ||
                        orderDetailBean.getRefundFlag().equals(RefundFlagEnum.ING.toString())
                ) {
                    if (orderDetail.getRefundNum() == 0) {
                        refundFlag = RefundFlagEnum.COMMONLY.getName();
                    } else {
                        refundFlag = orderDetail.getNum() - orderDetail.getRefundNum() > 0?
                                RefundFlagEnum.PARTLY.getName() : RefundFlagEnum.ALL.getName();
                        if (orderDetailBean.getRefundFlag().equals(RefundFlagEnum.ING.toString())) {
                            refundFlag = RefundFlagEnum.ING.getName();
                        }
                    }
                } else {
                    refundFlag = Enum.valueOf(RefundFlagEnum.class, orderDetailBean.getRefundFlag().trim().toUpperCase()).getName();
                }
                row.add(refundFlag);
                row.add(orderDetail.getRefundAmount());
                row.add(orderDetail.getRefundNum());
//                row.add(orderDetailBean.getRefundTotal());
                row.add(orderDetailBean.getRemark());
                row.add(simpleDateFormat.format(orderDetailBean.getCreateTime()));
                row.add(orderDetailBean.getUserName());
                row.add(orderDetailBean.getWorkerName());
                row.add(orderDetailBean.getBuyerMsg());
                row.add(orderDetailBean.getRemark());
                row.add(orderDetailBean.getWebsitName());
                row.add(trimStr(orderDetailBean.getWorkerName(), "\r\n", orderDetailBean.getWebsitName()));
                row.add(orderDetail.getShareAmount());
                row.add(orderDetailBean.getPromotionGroupUserId());
                if(user != null) {
                    row.add(user.getNickName());
                    row.add(user.getMobile());
                }else{
                    row.add("");
                    row.add("");
                }
                rows.add(row);
            }
        }


        String fileName = String.format("订单导出%s.xlsx", simpleDateFormat.format(new Date()));
        excelData.setTitles(Arrays.asList(titles));
        excelData.setName("订单");
        excelData.setRows(rows);
        ExcelUtils.exportExcel(request, response, fileName, excelData, -1, null);
    }

    /**
     * 导出excel
     *
     */
    public void export2(HttpServletRequest request, HttpServletResponse response,
                        String userId, String orderId, String productName, String userName,
                        String phone, String exchangeCode, String orderStatus,
                        String startCreateTime, String endCreateTime,
                        String startPayTime, String endPayTime, String promotionGroupUserName,String promotionGroupId,
                        String promotionGroupUserId,String promotionFullPieceId,String websitId,String goodsId) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        ExcelData excelData = new ExcelData();
        String[] titles = {"订单号", "商品名称", "规格型号", "数量", "单位", "销售单价", "优惠后单价", "实际收款", "收货人姓名",
                "手机号", "收货地址","订单状态", "售后状态", "退款金额(小项)", "退款数量(小项)", "备注", "下单时间","支付时间", "买家昵称", "购买渠道",
                "买家备注", "卖家备注", "网点", "业务员/网点","业务员手机号","分佣金额","团长名称","团长手机号","团购活动id",
                "评价商品的星数(0未评价)","评价服务的星数(0未评价)","评价物流的星数(0未评价)","信息编号","商品类型","商户名称"};

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String fileName = String.format("订单导出%s.xlsx", simpleDateFormat.format(new Date()));

        List<OrderDetailListBean> orderDetailListBeanList = orderMapper.selectByQueryMsg(userId, orderId, productName, userName,
                phone, exchangeCode, orderStatus,
                startCreateTime, endCreateTime,
                startPayTime, endPayTime, promotionGroupUserName,promotionGroupId,promotionGroupUserId,promotionFullPieceId,websitId,goodsId,adminUser.getCompanyWechatIds(),null);

        List<List<Object>> rows =new ArrayList<>();
        for (OrderDetailListBean orderDetailListBean:orderDetailListBeanList
             ) {
            List<Object> row=new ArrayList<>();
            rows.add(row);

            String goodsName = orderDetailListBean.getGoodsName();
            if(orderDetailListBean.getPromotionPackageGoods() != null && orderDetailListBean.getPromotionPackageGoods()){
                goodsName = "套购："+goodsName;
            }

            row.add(orderDetailListBean.getOrderId());
            row.add(goodsName);
            row.add(orderDetailListBean.getGoodsSpecValue());
            row.add(orderDetailListBean.getNum());
            row.add("台");
            row.add(orderDetailListBean.getPrice());
            row.add(orderDetailListBean.getPayAmount().divide(new BigDecimal(orderDetailListBean.getNum()), 2, BigDecimal.ROUND_HALF_UP));
            row.add(orderDetailListBean.getPayAmount());
            row.add(orderDetailListBean.getReceUserName());
            row.add(orderDetailListBean.getRecePhone());
            row.add(orderDetailListBean.getAddress());

            if (StringUtils.isNotBlank(orderDetailListBean.getOrderStatus())) {
                row.add(OrderStatusEnum.valueOf(orderDetailListBean.getOrderStatus()).getName());
            }else{
                row.add("");
            }
            if (StringUtils.isNotBlank(orderDetailListBean.getRefundFlag())) {
                row.add(RefundFlagEnum.valueOf(orderDetailListBean.getRefundFlag()).getName());
            }else{
                row.add("");
            }
            row.add(orderDetailListBean.getRefundAmount());
            row.add(orderDetailListBean.getRefundNum());
            row.add(orderDetailListBean.getRemark());
            row.add(orderDetailListBean.getCreateTime()==null?"":simpleDateFormat.format(orderDetailListBean.getCreateTime()));
            row.add(orderDetailListBean.getPayTime()==null?"":simpleDateFormat.format(orderDetailListBean.getPayTime()));
            row.add(orderDetailListBean.getUserName());
            row.add(orderDetailListBean.getWorkerName());
            row.add(orderDetailListBean.getBuyerMsg());
            row.add(orderDetailListBean.getRemark());
            row.add(orderDetailListBean.getWebsitName());
            row.add(orderDetailListBean.getWorkerNameWithWebsitName());
            row.add(orderDetailListBean.getWorkerPhone());
            row.add(orderDetailListBean.getShareAmount());
            row.add(orderDetailListBean.getNickName());
            row.add(orderDetailListBean.getMobile());
            row.add(orderDetailListBean.getPromotionGroupId());
            row.add(orderDetailListBean.getCommentGoods());
            row.add(orderDetailListBean.getCommentService());
            row.add(orderDetailListBean.getCommentExpress());
            row.add(orderDetailListBean.getWorkerOrderNo());
            row.add(orderDetailListBean.getCompanyWechatName());
//            row.add(org.apache.commons.lang3.StringUtils.equals(orderDetailListBean.getWorkOrderType(),"INSTALL")?"安装":"维修");
//            row.add(orderDetailListBean.getIsAddCorp() != null && orderDetailListBean.getIsAddCorp() ?"是":"否");
//            row.add(orderDetailListBean.getGoodsCode());
        }

        excelData.setTitles(Arrays.asList(titles));
        excelData.setName("订单");
        excelData.setRows(rows);
        ExcelUtils.exportExcel(request, response, fileName, excelData, -1, null);

    }



    @Transactional
    public void overOrder(SubscribePushParamResp subscribePushParamResp) throws Exception {
        if ("3".equals(subscribePushParamResp.getLastResult().getState())) {
            OrderInfo orderInfo = orderInfoService.lambdaQuery()
                    .eq(OrderInfo::getLogisticsNo,subscribePushParamResp.getLastResult().getNu())
                    .eq(OrderInfo::getCompanyCode,subscribePushParamResp.getLastResult().getCom())
                    .one();
            if(orderInfo == null || !orderInfo.getOrderStatus().equals(OrderStatusEnum.YFH.toString())){
                return;
            }
            orderInfo.setOrderStatus(OrderStatusEnum.OVER.toString());
            orderInfo.setOverTime(new Date());
            orderInfo.updateById();

            orderShareService.lambdaUpdate()
                    .eq(OrderShare::getOrderId, orderInfo.getOrderId())
                    .set(OrderShare::getOrderStatus, orderInfo.getOrderStatus())
                    .set(OrderShare::getOrderFinishTime, new Date())
                    .update();

            //生成工单到工单系统
            //this.orderToPhp(orderInfo,WorkOrderTypeEnum.INSTALL.toString());
        }
    }

    //生成工单到工单系统
    public void orderToWorkorder(OrderInfo orderInfo) throws Exception {
        if (orderInfo.getWorkOrder() == null || !orderInfo.getWorkOrder()) {
            return;
        }
        //订单明细
        List<OrderDetail> orderDetails = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, orderInfo.getOrderId()).list();
        Map<String, List<OrderDetail>> orderDetailMap = orderDetails.stream().collect(Collectors.groupingBy(OrderDetail::getOrderSmallType));
        for(String orderSmallType : orderDetailMap.keySet()){
            List<OrderDetail> orderDetailList = orderDetailMap.get(orderSmallType);
            OrderAddBean2DTO orderAddBeanDTO = new OrderAddBean2DTO();
            orderAddBeanDTO.setUserAddressId(orderInfo.getUserAddressId());
            orderAddBeanDTO.setOrderSmallType(orderSmallType);
            //orderAddBeanDTO.setAppointmentTime(orderInfo.getappo);
            List<PgOrderProduct> pgOrderProductList = new ArrayList<>();
            for(OrderDetail orderDetail : orderDetailList) {
                if(orderDetail.getNum() - orderDetail.getRefundNum() <= 0){
                    continue;
                }
                PgOrderProduct bean = new PgOrderProduct();
                bean.setBrandId(orderDetail.getBrandId());
                bean.setBrandName(orderDetail.getBrandName());
                bean.setImgUrl(orderDetail.getImgUrl());
                if(StringUtils.isNotBlank(orderDetail.getMainNumber())) {
                    bean.setMainId(orderDetail.getMainNumber());
                    bean.setMainName(orderDetail.getMainName());
                    bean.setSmallId(orderDetail.getSmallNumber());
                    bean.setSmallName(orderDetail.getSmallName());
                }else{
                    GoodsCategory goodsCategory = goodsCategoryService.getById(orderDetail.getGoodsCategoryId());
                    if(goodsCategory != null){
                        bean.setMainId(goodsCategory.getMainNumber());
                        bean.setMainName(goodsCategory.getMainName());
                        bean.setSmallId(goodsCategory.getSmallNumber());
                        bean.setSmallName(goodsCategory.getSmallName());
                    }
                }
                bean.setProductName(orderDetail.getGoodsMaterialSpecsName());
                bean.setNum(orderDetail.getNum() - orderDetail.getRefundNum());
                pgOrderProductList.add(bean);
            }
            orderAddBeanDTO.setOrderProducts(pgOrderProductList);
            orderAddBeanDTO.setRemark(orderInfo.getRemark());
            //orderAddBeanDTO.setUserId(orderInfo.getWorkerId());
            orderAddBeanDTO.setCompanyWechatId(orderInfo.getCompanyWechatId());
            orderAddBeanDTO.setCompanyWechatName(orderInfo.getCompanyWechatName());
            orderAddBeanDTO.setSaleOrderId(orderInfo.getOrderId());
            orderAddBeanDTO.setUserName(orderInfo.getReceUserName());
            orderAddBeanDTO.setPhone(orderInfo.getRecePhone());
            orderAddBeanDTO.setAddress(orderInfo.getProvince()+orderInfo.getCity()+orderInfo.getArea()+orderInfo.getStreet()+orderInfo.getReceAddress());
            String orderBaseId = orderBaseLogic.add(orderAddBeanDTO);

            for (OrderDetail orderDetail : orderDetailList) {
                orderDetail.setWorkerOrderNo(orderBaseId);
            }
            List<String> orderDetailIds = orderDetailList.stream().map(OrderDetail::getOrderDetailId).collect(Collectors.toList());
            orderDetailService.lambdaUpdate().set(OrderDetail::getWorkerOrderNo,orderBaseId).in(OrderDetail::getOrderDetailId,orderDetailIds).update();

            //以旧换新的订单，生成拆机单
            if(orderInfo.getYjhxDkFlag() != null && orderInfo.getYjhxDkFlag() != 0){
                OrderOldProduct orderOldProduct = orderOldProductService.lambdaQuery()
                        .eq(OrderOldProduct::getOrderId, orderInfo.getOrderId())
                        .last("limit 1").one();
                if(orderOldProduct == null){
                    return;
                }
                //以旧换新拆机属性
                List<OrderOldProductItem> oldProductItems = orderOldProductItemService.lambdaQuery().eq(OrderOldProductItem::getOrderOldProductId, orderOldProduct.getId()).list();
                String cjRemark = "";
                if(CollectionUtils.isNotEmpty(oldProductItems)) {
                    cjRemark = "以旧换新：";
                    for (OrderOldProductItem item : oldProductItems) {
                        cjRemark += item.getDictName() + "(" + item.getPrice() + "),";
                    }
                }
                if(StringUtils.isNotBlank(cjRemark)){
                    cjRemark = cjRemark.substring(0,cjRemark.length() - 1);
                }

                OrderAddBean2DTO bean2DTO = new OrderAddBean2DTO();
                bean2DTO.setUserAddressId(orderInfo.getUserAddressId());
                //bean2DTO.setOrderSmallType(orderSmallType);
                //bean2DTO.setOrderProducts(pgOrderProductList);
                bean2DTO.setRemark(orderInfo.getRemark());
                bean2DTO.setCompanyWechatId(orderInfo.getCompanyWechatId());
                bean2DTO.setCompanyWechatName(orderInfo.getCompanyWechatName());
                bean2DTO.setSaleOrderId(orderInfo.getOrderId());
                bean2DTO.setUserName(orderInfo.getReceUserName());
                bean2DTO.setPhone(orderInfo.getRecePhone());
                bean2DTO.setAddress(orderInfo.getProvince()+orderInfo.getCity()+orderInfo.getArea()+orderInfo.getStreet()+orderInfo.getReceAddress());
                //拆机的产品信息
                if(orderOldProduct.getNum() - orderOldProduct.getRefundNum() <= 0){
                    continue;
                }
                List<PgOrderProduct> pgOrderProducts2 = new ArrayList<>();
                PgOrderProduct bean = new PgOrderProduct();
                bean.setBrandId("");
                bean.setBrandName("");
                bean.setImgUrl(orderOldProduct.getMainImg());
                bean.setMainId(orderOldProduct.getMainId());
                bean.setMainName(orderOldProduct.getMainName());
                bean.setSmallId(orderOldProduct.getSmallId());
                bean.setSmallName(orderOldProduct.getSmallName());
                bean.setProductName(orderOldProduct.getSpecName());
                bean.setNum(orderOldProduct.getNum() - orderOldProduct.getRefundNum());
                pgOrderProducts2.add(bean);
                bean2DTO.setOrderProducts(pgOrderProducts2);
                bean2DTO.setIsCj(true);
                bean2DTO.setRemark(cjRemark);
                orderBaseLogic.add(bean2DTO);
            }

        }

    }




    private String trimStr(String... str) {
        StringBuffer sb = new StringBuffer("");
        for (String s : str) {
            if (s != null) {
                sb.append(s);
            }
        }
        return sb.toString();
    }


    @Transactional(rollbackFor = Exception.class)
    public void deliverV2(SendOrderBody sendOrderBody) throws Exception {
        //判断导入条码是否符合数量
        List<OrderDetail> list = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, sendOrderBody.getOrderId()).list();
        List<OrderDetailCode> orderDetailCodes = orderDetailCodeService.lambdaQuery().
                eq(OrderDetailCode::getOrderId, sendOrderBody.getOrderId()).list();

        sendOrderBody.setOrderDetailCodes(orderDetailCodes);



        //减少库存+减去条码
        this.subStock(sendOrderBody);


        //最后调用发货
        this.deliverGoods(sendOrderBody.getOrderId(), sendOrderBody.getLogisticsNo(), sendOrderBody.getCompanyCode(), sendOrderBody.getStorageId(), sendOrderBody.getWorkOrder(), sendOrderBody.getExchange()
        ,sendOrderBody.getPickName(),sendOrderBody.getPickPhone(),sendOrderBody.getPickType());
    }

    private void subStock(SendOrderBody sendOrderBody) throws InterruptedException {

        AdminUserCom adminUser = commonLogic.getAdminUser();

        log.info("发货"+adminUser.toString());

        //库存扣除 // 库存变更台账
        List<OrderDetail> orderDetails = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, sendOrderBody.getOrderId()).list();
        for (OrderDetail orderDetail : orderDetails) {
            if (orderDetail.getIsVr() || StringUtil.isEmpty(orderDetail.getGoodsMaterialId()))
                continue;



            if (StringUtil.isEmpty(orderDetail.getGoodsSpecId())){

            }else {
                GoodsSpec goodsSpec = goodsSpecService.getById(orderDetail.getGoodsSpecId());

                if (goodsSpec == null)
                    throw new RemoteServiceException("未找到对应商品规格");

                orderDetail.setGoodsMaterialId(goodsSpec.getGoodsCode());
            }


            jxGoodsLogic.subMaterialStock(orderDetail.getGoodsMaterialId(), orderDetail.getNum(), null,sendOrderBody.getStorageId());
            goodsMaterialStockAccLogic.add(orderDetail.getGoodsMaterialId(), orderDetail.getPrice(), orderDetail.getNum(), DirectFlagEnum.SUB,
                    sendOrderBody.getOrderId(), GoodsMaterialStockAccBillTypeEnum.A,sendOrderBody.getStorageId(),sendOrderBody.getStorageName());
        }

        OrderInfo orderInfo = orderInfoService.getById(sendOrderBody.getOrderId());

        log.info("发货"+adminUser.getJoinCode().toString());
        log.info("发货"+sendOrderBody.getOrderDetailCodes().toString());

        if (adminUser.getJoinCode().equals("CODE")){

            this.checkCode(orderDetails,sendOrderBody);
            //条码变更台账  条码减去批次库存
          //  jxGoodsLogic.subCodeAcc(sendOrderBody.getOrderDetailCodes(), orderInfo);
        }

        //添加销售台账
        //jxGoodsLogic.addGoodsSaleLedger(sendOrderBody.getOrderId());

    }

    private void checkCode(List<OrderDetail> list,SendOrderBody sendOrderBody) {
        for (OrderDetail orderDetail : list) {
            if (orderDetail.getIsVr() || StringUtil.isEmpty(orderDetail.getGoodsMaterialId()))
                continue;
            List<GoodsMaterialItem> goodsMaterialItems = goodsMaterialItemService.lambdaQuery()
                    .eq(GoodsMaterialItem::getGoodsMaterialId, orderDetail.getGoodsMaterialId()).list();
            for (GoodsMaterialItem goodsMaterialItem : goodsMaterialItems) {
                //需要条码数量
                Integer num = goodsMaterialItem.getQty()* orderDetail.getNum();

                if (num == 0)
                    return;
                if (goodsMaterialItem.getUniqueCode().equals(IsYesNoEnum.YES.getKey())){
                    List<OrderDetailCode> collect = sendOrderBody.getOrderDetailCodes().stream()
                            .filter(item -> item.getGoodsMaterialItemId().equals(goodsMaterialItem.getId())
                             && item.getOrderDetailId().equals(orderDetail.getOrderDetailId())
                            )
                            .collect(Collectors.toList());

                    if (collect.size() != num)
                        throw new RemoteServiceException(goodsMaterialItem.getName()+"此条码名称数量不对，条码数量"+collect.size()+"需要数量"+num);

                }else {
                    List<OrderDetailCode> collect = sendOrderBody.getOrderDetailCodes().stream()
                            .filter(item -> item.getGoodsMaterialItemId().equals(goodsMaterialItem.getId())
                                    && item.getOrderDetailId().equals(orderDetail.getOrderDetailId())
                            )
                            .collect(Collectors.toList());

                    if (!collect.get(0).getStockQty().equals(num))
                        throw new RemoteServiceException(goodsMaterialItem.getName() + "此条码名称数量不对，条码数量" + collect.get(0).getStockQty() + "需要数量" + num);
                }
            }
        }
    }

    public void printCount(String orderId) {
        OrderPrintRecord record = new OrderPrintRecord();
        record.setOrderId(orderId)
                .insert();
    }

    public List<OrderPrintRecord> queryPrintRecord(String orderId) {
        return orderPrintRecordService.lambdaQuery()
                .eq(OrderPrintRecord::getOrderId, orderId)
                .list();
    }

    public List<PartsApplyBean> partsApplyRecord(String orderId) {
        final List<WebsitPartsApply> applyList = websitPartsApplyService.lambdaQuery()
                .eq(WebsitPartsApply::getOrderBaseId, orderId)
                .list();
        List<PartsApplyBean> beanList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(applyList)) {
            for (WebsitPartsApply websitPartsApply : applyList) {
                PartsApplyBean bean = new PartsApplyBean();
                BeanUtils.copyProperties(websitPartsApply, bean);
                final List<WebsitPartsApplyItem> items = websitPartsApplyItemService.lambdaQuery()
                        .eq(WebsitPartsApplyItem::getWebsitPartsApplyId, websitPartsApply.getId())
                        .list();
                bean.setItems(items);
                beanList.add(bean);
            }
        }
        return beanList;
    }

    @Transactional
    public void partsApplyRecordCancel(String id) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        final WebsitPartsApply apply = websitPartsApplyService.getById(id);
        websitPartsApplyService.lambdaUpdate()
                .set(WebsitPartsApply::getStatus, PartsApplyStatusEnum.CANCEL.getKey())
                .set(WebsitPartsApply::getCancelBy, adminUser.getNickName())
                .set(WebsitPartsApply::getCancelTime, DateUtil.date())
                .eq(WebsitPartsApply::getId, id)
                .eq(WebsitPartsApply::getStatus, PartsApplyStatusEnum.ING.getKey())
                .update();

        final Integer count = websitPartsApplyService.lambdaQuery()
                .eq(WebsitPartsApply::getOrderBaseId, apply.getOrderBaseId())
                .eq(WebsitPartsApply::getStatus, PartsApplyStatusEnum.ING.getKey())
                .count();
        if (count == 0) {
            orderFlagLogic.deleteOrderFlag(apply.getOrderBaseId(), OrderFlagEnum.PARTS_ING);
        }

        orderFlagLogic.saveOrderFlag(Lists.newArrayList(apply.getOrderBaseId()), OrderFlagEnum.PARTS_CANCEL);
    }

    public void partsApplyItemModify(WebsitPartsApplyItem item) {
        if (StringUtils.isBlank(item.getName())) {
            throw new RemoteServiceException("配件名称不能为空");
        }
        if (Objects.isNull(item.getQty()) || item.getQty() <= 0) {
            throw new RemoteServiceException("配件数量格式异常");
        }
        item.updateById();
        WebsitPartsApply apply = websitPartsApplyService.getById(item.getWebsitPartsApplyId());
        final List<WebsitPartsApplyItem> items = websitPartsApplyItemService.lambdaQuery()
                .eq(WebsitPartsApplyItem::getWebsitPartsApplyId, apply.getId())
                .list();
        if (CollectionUtil.isNotEmpty(items)) {
            final int sum = items.stream().mapToInt(WebsitPartsApplyItem::getQty).sum();
            apply.setTotalQty(sum);
        }
        apply.updateById();
    }

    @Transactional
    public void partsApplyRecordEnd(String id) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        final WebsitPartsApply apply = websitPartsApplyService.getById(id);

        if (Objects.isNull(apply)) {
            throw new RemoteServiceException("申请单号不存在");
        }

        final User user = userService.getById(apply.getCreateById());
        final AdminWebsit websit = adminWebsitService.getById(apply.getWebsitId());

        StringBuilder goodsName = new StringBuilder();
        List<WebsitPartsApplyItem> items = websitPartsApplyItemService.lambdaQuery()
                .eq(WebsitPartsApplyItem::getWebsitPartsApplyId, id)
                .list();

        for (WebsitPartsApplyItem item : items) {
            goodsName.append(item.getName()).append("x").append(item.getQty());
        }

        wxPubNoticeLogic.takePartsNotice(user.getMobile(), apply.getCompanyWechatId(), apply.getOrderBaseId(), goodsName.toString(),
                adminUser.getLinkPhone(), apply.getWebsitName(), websit.getAddress());

        websitPartsApplyService.lambdaUpdate()
                .set(WebsitPartsApply::getStatus, PartsApplyStatusEnum.END.getKey())
                .set(WebsitPartsApply::getConfirmBy, adminUser.getNickName())
                .set(WebsitPartsApply::getConfirmTime, DateUtil.date())
                .set(WebsitPartsApply::getConfirmMobile, adminUser.getLinkPhone())
                .eq(WebsitPartsApply::getId, id)
                .eq(WebsitPartsApply::getStatus, PartsApplyStatusEnum.ING.getKey())
                .update();

        final Integer count = websitPartsApplyService.lambdaQuery()
                .eq(WebsitPartsApply::getOrderBaseId, apply.getOrderBaseId())
                .eq(WebsitPartsApply::getStatus, PartsApplyStatusEnum.ING.getKey())
                .count();

        if (count <= 0) {
            orderFlagLogic.deleteOrderFlag(apply.getOrderBaseId(), OrderFlagEnum.PARTS_ING);
        }
        orderFlagLogic.saveOrderFlag(Lists.newArrayList(apply.getOrderBaseId()), OrderFlagEnum.PARTS_END);
    }

    @Transactional
    public void partsApplyItemDel(String id) {
        final WebsitPartsApplyItem item = websitPartsApplyItemService.getById(id);
        if (Objects.isNull(item)) {
            throw new RemoteServiceException("记录不存在");
        }
        websitPartsApplyItemService.removeById(id);

        WebsitPartsApply apply = websitPartsApplyService.getById(item.getWebsitPartsApplyId());
        final List<WebsitPartsApplyItem> items = websitPartsApplyItemService.lambdaQuery()
                .eq(WebsitPartsApplyItem::getWebsitPartsApplyId, apply.getId())
                .list();
        if (CollectionUtil.isNotEmpty(items)) {
            final int sum = items.stream().mapToInt(WebsitPartsApplyItem::getQty).sum();
            apply.setTotalQty(sum);
        } else {
            apply.setTotalQty(0);
        }
        apply.updateById();
    }
}
