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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.gree.mall.manager.bean.ExcelData;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.order.*;
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.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.UMSLogic;
import com.gree.mall.manager.logic.common.WechatLogic;
import com.gree.mall.manager.logic.common.kuaidi100.response.SubscribePushParamResp;
import com.gree.mall.manager.logic.user.MsgSubscriptLogic;
import com.gree.mall.manager.logic.user.UserLogic;
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.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
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 org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
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
    RedisLockRegistry redisLockRegistry;
    @Autowired
    CommentTagLogic commentTagLogic;
    @Autowired
    CommonLogic commonLogic;
    @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
    UMSLogic umsLogic;
    @Autowired
    AdminCompanyWechatService adminCompanyWechatService;


    /**
     * 订单列表
     *
     * @return
     */
    public IPage<OrderDetailBean> list(HttpServletRequest request, 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, String workerOrderNo, String goodsId
    ) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        //派工异常订单
        if (StringUtils.isNotEmpty(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.isNotEmpty(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.getAdminCompanyIds()), OrderInfo::getCompanyId, adminUser.getAdminCompanyIds())
                .in(CollectionUtils.isNotEmpty(adminUser.getAdminWebsitIds()), OrderInfo::getWebsitId, adminUser.getAdminWebsitIds())
                .eq(StringUtils.isNotEmpty(userId), OrderInfo::getUserId, userId)
                .eq(StringUtils.isNotEmpty(goodsId), OrderInfo::getPromotionPackageGoodsId, goodsId)
                .like(StringUtils.isNotEmpty(exchangeCode), OrderInfo::getExchangeCode, exchangeCode)
                .like(StringUtils.isNotEmpty(orderId), OrderInfo::getOrderId, orderId)
                .like(StringUtils.isNotEmpty(productName), OrderInfo::getOrderTitle, productName)
                .in(CollectionUtils.isNotEmpty(orderIds), OrderInfo::getOrderId, orderIds)
                .eq(StringUtils.isNotEmpty(websitId), OrderInfo::getWebsitId, websitId)
                .and(StringUtils.isNotEmpty(userName), v -> v.like(OrderInfo::getUserName, userName).or().like(OrderInfo::getReceUserName, userName))
                .and(StringUtils.isNotEmpty(phone), v -> v.like(OrderInfo::getPhone, phone).or().like(OrderInfo::getRecePhone, phone).or().like(OrderInfo::getWorkerPhone, phone))
                .eq(StringUtils.isNotEmpty(orderStatus), OrderInfo::getOrderStatus, orderStatus)
                .between(StringUtils.isNotEmpty(startCreateTime) && StringUtils.isNotEmpty(endCreateTime), OrderInfo::getCreateTime, startCreateTime, endCreateTime + " 23:59:59")
                .between(StringUtils.isNotEmpty(startPayTime) && StringUtils.isNotEmpty(endPayTime), OrderInfo::getPayTime, startPayTime, endPayTime + " 23:59:59")
                .and(StringUtils.isNotEmpty(isNegative) && isNegative.trim().equals("2"),
                        v -> v.gt(OrderInfo::getCommentExpress, 2).gt(OrderInfo::getCommentService, 2).gt(OrderInfo::getCommentGoods, 2))
                .and(StringUtils.isNotEmpty(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.isNotEmpty(isNegative) && isNegative.trim().equals("0"),
                        v -> v.eq(OrderInfo::getCommentExpress, 0).eq(OrderInfo::getCommentService, 0).eq(OrderInfo::getCommentGoods, 0))
                .and(StringUtils.isNotEmpty(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();

            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);
        }
        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.getAdminCompanyIds(), 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.isNotEmpty(userId), OrderInfo::getUserId, userId)
                .like(StringUtils.isNotEmpty(orderId), OrderInfo::getOrderId, orderId)
                .like(StringUtils.isNotEmpty(productName), OrderInfo::getOrderTitle, productName)
                .like(StringUtils.isNotEmpty(userName), OrderInfo::getUserName, userName)
                .like(StringUtils.isNotEmpty(phone), OrderInfo::getPhone, phone)
                .eq(StringUtils.isNotEmpty(orderStatus), OrderInfo::getOrderStatus, orderStatus)
                .between(StringUtils.isNotEmpty(startCreateTime) && StringUtils.isNotEmpty(endCreateTime), OrderInfo::getCreateTime, startCreateTime, endCreateTime + " 23:59:59")
                .between(StringUtils.isNotEmpty(startPayTime) && StringUtils.isNotEmpty(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())) {
            throw new RemoteServiceException("订单已支付，不可取消");
        }
//        if(!orderInfo.getOrderStatus().equals(OrderStatusEnum.NOPAY.toString())) {
//
//            log.info("【退款开始：】退款金额{}", orderInfo.getPayAmount().doubleValue());
//            wechatLogic.refund(orderInfo.getOrderId(), orderInfo.getOrderId()+"T", orderInfo.getPayAmount().doubleValue()
//                    , orderInfo.getPayAmount().doubleValue());
//
//            orderShareLogic.reloadAmount(orderId, null);
//        }
        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, String refundPassword) throws Exception {
        if (num < 1) {
            throw new RemoteServiceException("退款数量不能小于1");
        }
        OrderDetail orderDetail = orderDetailService.getById(orderDetailId);
        //1=非团购商品  2=团购商品
        int flag = StringUtils.isNotEmpty(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));
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        if (orderInfo.getOrderStatus().equals(OrderStatusEnum.DFH.toString()) ||
                (orderInfo.getOrderStatus().equals(OrderStatusEnum.REFUND.toString()) &&
                        org.apache.commons.lang3.StringUtils.isEmpty(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.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.isNotEmpty(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(), orderInfo.getCouponMerchantContribute().doubleValue());
        orderShareLogic.reloadAmount(orderId, totalShareAmount, flag);
        log.info("【退款开始：】退款金额{}", refundAmount);
        if (!orderInfo.getPayType().equals("云闪付")) {
            wechatLogic.refund(orderId, orderId + StringUtil.getUUID(), orderInfo.getPayAmount().doubleValue()
                    , refundAmount.doubleValue(), orderInfo.getPayWorkerCodeId());
        } else {
            umsLogic.refund(orderId, orderInfo.getPayAmount().doubleValue()
                    , refundAmount.doubleValue(), orderInfo.getWebsitId());
        }
        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, String refundPassword) throws Exception {

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

        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.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.isNotEmpty(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.isNotEmpty(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());
        if (!orderInfo.getPayType().equals("云闪付")) {
            wechatLogic.refund(orderId, orderId + StringUtil.getUUID(), orderInfo.getPayAmount().doubleValue()
                    , refundAmount.doubleValue(), orderInfo.getPayWorkerCodeId());
        } else {
            umsLogic.refund(orderId, orderInfo.getPayAmount().doubleValue()
                    , refundAmount.doubleValue(), orderInfo.getWebsitId());
        }
        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.isEmpty(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 {
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        final AdminCompanyWechat companyWechat = adminCompanyWechatService.getById(orderInfo.getCompanyId());
        User user = userLogic.getById(orderInfo.getUserId());
        if (!orderInfo.getOrderStatus().equals(OrderStatusEnum.DFH.toString())) {
            throw new RemoteServiceException("非待发货订单不可发货");
        }
        //发货商
        Storage detail = storageLogic.detail(storageId);
        String companyName = expressLogic.expressCompanyName(companyCode);
        orderInfo.setLogisticsNo(logisticsNo);
        orderInfo.setCompanyCode(companyCode);
        orderInfo.setPickCompanyName(companyName);
        orderInfo.setOrderStatus(OrderStatusEnum.YFH.toString());
        orderInfo.setStorageName(detail.getStorageName());
        orderInfo.setStorageAddress(detail.getStorageAddress());
        orderInfo.setStoragePhone(detail.getStorageMobile());
        orderInfo.setDeliverTime(new Date());
        orderInfo.setWorkOrder(workOrder);
        orderInfo.setExchangeOrder(exchange);
        orderInfo.updateById();

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

        //订阅物流
        expressLogic.subscribeExpress(logisticsNo, companyCode, orderInfo.getRecePhone());
        //发货通知
        if (user != null) {
            msgSubscriptLogic.sendFhNotice(user.getUserId(), user.getOpenId(), orderInfo.getOrderId(), orderInfo.getPayAmount()
                    , companyName, orderInfo.getLogisticsNo());
        }
    }


    //@Transactional
    public void deliverBatchGoods(HttpServletRequest request, MultipartFile file) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        List<Object> datas = ExcelUtils.importExcel(file);
        List<DeliverGoodsBean> deliverGoodsBeanList = new ArrayList<>();
        for (Object object : datas) {
            List<String> row = (List<String>) object;
            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)));
            deliverGoodsBeanList.add(deliverGoodsBean);
        }
        //预检查
        String check = preCheck(adminUser, deliverGoodsBeanList);
        if (StringUtils.isNotEmpty(check)) {
            throw new RemoteServiceException(check);
        }
        for (DeliverGoodsBean deliverGoodsBean : deliverGoodsBeanList) {
            Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_ORDER + ":" + deliverGoodsBean.getOrderId());
            try {
                if (!obtain.tryLock(30, TimeUnit.SECONDS)) {
                    throw new RemoteServiceException("请勿重复操作发货，请稍后再试");
                }
                updateDeliverItem(adminUser, deliverGoodsBean);
            } finally {
                obtain.unlock();
            }
        }

    }

    private String preCheck(AdminUserCom adminUser, List<DeliverGoodsBean> deliverGoodsBeanList) {

        StringBuffer sb = new StringBuffer();
        int index = 0;
        for (DeliverGoodsBean deliverGoodsBean : deliverGoodsBeanList) {
            ++index;
            String orderId = deliverGoodsBean.getOrderId();
            if (org.apache.commons.lang3.StringUtils.isEmpty(orderId)) {
                sb.append(String.format("第%d条数据订单号不能为空\n", index));
                continue;
            }
            OrderInfo orderInfo = orderInfoService.lambdaQuery()
                    .eq(OrderInfo::getOrderId, orderId)
                    .eq(OrderInfo::getOrderStatus, OrderStatusEnum.DFH.toString())
                    .one();

            if (orderInfo == null) {
                sb.append(String.format("第%d条数据订单号不正确或已发货,请检查\n", index));
            }

            Storage detail = storageLogic.detailByName(null, deliverGoodsBean.getWarehouse().trim());
            if (detail == null) {
                sb.append(String.format("第%d条数据仓库出错,请检查\n", index));
            }
            ExpressCompany company = expressLogic.expressCompany(deliverGoodsBean.getExpressCorp().trim());
            if (company == null) {
                sb.append(String.format("第%d条数据物流公司出错,请检查\n", index));
            }

        }
        return sb.toString();
    }

    public void updateDeliverItem(AdminUserCom adminUserCom, 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.isEmpty(orderId)) {
            throw new RemoteServiceException("订单号不能为空");
        }
        final AdminCompanyWechat companyWechat = adminCompanyWechatService.getById(orderInfo.getCompanyId());

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

        Storage detail = storageLogic.detailByName(null, deliverGoodsBean.getWarehouse().trim());
        if (detail == null) {
            throw new RemoteServiceException(String.format("订单号:%s仓库出错,请检查", deliverGoodsBean.getOrderId()));
        }
        ExpressCompany company = expressLogic.expressCompany(deliverGoodsBean.getExpressCorp().trim());
        if (company == null) {
            throw new RemoteServiceException(String.format("订单号:%s物流公司出错,请检查", deliverGoodsBean.getOrderId()));
        }
        orderInfo.setLogisticsNo(deliverGoodsBean.getLogisticsNo());
        orderInfo.setCompanyCode(company.getCode());
        orderInfo.setCompanyName(company.getName());
        orderInfo.setOrderStatus(OrderStatusEnum.YFH.toString());
        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.updateById();

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

        expressLogic.subscribeExpress(deliverGoodsBean.getLogisticsNo(), company.getCode(), orderInfo.getRecePhone());
        if (orderInfo != null) {
            User user = userLogic.getById(orderInfo.getUserId());
            if (user != null) {
                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 OrderDetailBean detail(String orderId) {
        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();
        //组装数据
        OrderDetailBean orderDetailBean = new OrderDetailBean();
        BeanUtils.copyProperties(orderInfo, orderDetailBean);
        orderDetailBean.setOrderDetails(orderDetails);
        Boolean refundFlag = false;
        if (count == 0) {
            refundFlag = true;
        }
        orderDetailBean.setRefundAble(refundFlag);
        //团长信息
        if (StringUtils.isNotEmpty(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));
        return orderDetailBean;
    }

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


    /**
     * 修改订单状态,修改结算的订单状态
     */
    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.isNotEmpty(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.isNotEmpty(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 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, websitId, goodsId, adminUser.getAdminCompanyIds(), adminUser.getAdminWebsitIds());

        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.isNotEmpty(orderDetailListBean.getOrderStatus())) {
                row.add(OrderStatusEnum.valueOf(orderDetailListBean.getOrderStatus()).getName());
            } else {
                row.add("");
            }
            if (StringUtils.isNotEmpty(orderDetailListBean.getRefundFlag())) {
                row.add(RefundFlagEnum.valueOf(orderDetailListBean.getRefundFlag()).getName());
            } else {
                row.add("");
            }
            row.add(orderDetailListBean.getRefundAmount());
            row.add(orderDetailListBean.getRefundNum());
            row.add(org.apache.commons.lang3.StringUtils.isBlank(orderDetailListBean.getRemark()) ? "" : orderDetailListBean.getRemark());
            row.add(orderDetailListBean.getCreateTime() == null ? "" : simpleDateFormat.format(orderDetailListBean.getCreateTime()));
            row.add(orderDetailListBean.getPayTime() == null ? "" : simpleDateFormat.format(orderDetailListBean.getPayTime()));
            row.add(org.apache.commons.lang3.StringUtils.isBlank(orderDetailListBean.getUserName()) ? "" : orderDetailListBean.getUserName());
            row.add(org.apache.commons.lang3.StringUtils.isBlank(orderDetailListBean.getWorkerName()) ? "" : orderDetailListBean.getWorkerName());
            row.add(org.apache.commons.lang3.StringUtils.isBlank(orderDetailListBean.getBuyerMsg()) ? "" : orderDetailListBean.getBuyerMsg());
            row.add(org.apache.commons.lang3.StringUtils.isBlank(orderDetailListBean.getRemark()) ? "" : orderDetailListBean.getRemark());
            row.add(org.apache.commons.lang3.StringUtils.isBlank(orderDetailListBean.getWebsitName()) ? "" : orderDetailListBean.getWebsitName());
            row.add(org.apache.commons.lang3.StringUtils.isBlank(orderDetailListBean.getWorkerNameWithWebsitName()) ? "" : orderDetailListBean.getWorkerNameWithWebsitName());
            row.add(org.apache.commons.lang3.StringUtils.isBlank(orderDetailListBean.getWorkerPhone()) ? "" : orderDetailListBean.getWorkerPhone());
            row.add(orderDetailListBean.getShareAmount());
            row.add(org.apache.commons.lang3.StringUtils.isBlank(orderDetailListBean.getNickName()) ? "" : orderDetailListBean.getNickName());
            row.add(org.apache.commons.lang3.StringUtils.isBlank(orderDetailListBean.getMobile()) ? "" : orderDetailListBean.getMobile());
            row.add(org.apache.commons.lang3.StringUtils.isBlank(orderDetailListBean.getPromotionGroupId()) ? "" : orderDetailListBean.getPromotionGroupId());
            row.add(orderDetailListBean.getCommentGoods());
            row.add(orderDetailListBean.getCommentService());
            row.add(orderDetailListBean.getCommentExpress());
            row.add(org.apache.commons.lang3.StringUtils.isBlank(orderDetailListBean.getWorkerOrderNo()) ? "" : orderDetailListBean.getWorkerOrderNo());
            row.add(org.apache.commons.lang3.StringUtils.equals(orderDetailListBean.getWorkOrderType(), "INSTALL") ? "安装" : "维修");
            row.add("");
            row.add(orderDetailListBean.getIsAddCorp() != null && orderDetailListBean.getIsAddCorp() ? "是" : "否");
            row.add(org.apache.commons.lang3.StringUtils.isBlank(orderDetailListBean.getGoodsCode()) ? "" : orderDetailListBean.getGoodsCode());
            row.add(org.apache.commons.lang3.StringUtils.isBlank(orderDetailListBean.getBuyerName()) ? "" : orderDetailListBean.getBuyerName());
            row.add(org.apache.commons.lang3.StringUtils.isBlank(orderDetailListBean.getBuyerIdCard()) ? "" : orderDetailListBean.getBuyerIdCard());
            row.add(Objects.nonNull(orderDetailListBean.getCouponMerchantContribute()) ? BigDecimal.ZERO : orderDetailListBean.getCouponMerchantContribute());
            row.add(org.apache.commons.lang3.StringUtils.isBlank(orderDetailListBean.getBarCode()) ? "" : orderDetailListBean.getBarCode());
            row.add(org.apache.commons.lang3.StringUtils.isBlank(orderDetailListBean.getTransactionId()) ? "" : orderDetailListBean.getTransactionId());
        }

        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;
            }
            final AdminCompanyWechat companyWechat = adminCompanyWechatService.getById(orderInfo.getPayWorkerCodeId());
            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();

        }
    }

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


    public void testQueryShareResult(String orderShareId) throws Exception {
        final OrderShare orderShare = orderShareService.getById(orderShareId);
        orderShareLogic.queryShareResult(orderShare);
    }
}
