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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.ExcelData;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.esOrder.EsOrderAddBean;
import com.gree.mall.manager.bean.esOrder.EsOrderRefundBean;
import com.gree.mall.manager.bean.order.OrderDetailListBean;
import com.gree.mall.manager.enums.*;
import com.gree.mall.manager.enums.es.ESGoodsStatusEnum;
import com.gree.mall.manager.enums.material.PayTypeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.ExpressLogic;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.common.WechatLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.StringUtil;
import com.gree.mall.manager.utils.excel.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class EsOrderLogic {

    @Autowired
    EsOrderInfoService esOrderInfoService;

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    EsOrderPriceService esOrderPriceService;

    @Autowired
    ExpressLogic expressLogic;

    @Autowired
    EsOrderRefundService esOrderRefundService;

    @Autowired
    EsGoodsService esGoodsService;

    @Autowired
    UserService userService;

    @Autowired
    EsGoodsImgService esGoodsImgService;

    @Autowired
    UserAddressService userAddressService;

    @Autowired
    WechatLogic wechatLogic;

    @Autowired
    AdminUserService adminUserService;

    @Autowired
    EsOrderRefundFileService esOrderRefundFileService;

    @Autowired
    CarouselMapService carouselMapService;


    public IPage<EsOrderInfo> list(HttpServletRequest request, String goodsName, String orderId, String sellName, String userName, String userMobile,
                                   String sellMobile, List<String> status, String startCreateTime, String endCreateTime, String startPayTime, String endPayTime,
                                   Integer pageNum, Integer pageSize) {

        AdminUserCom adminUser = commonLogic.getAdminUser();

        return esOrderInfoService.lambdaQuery().eq(!StringUtil.isEmpty(goodsName), EsOrderInfo::getEsGoodsName, goodsName)
                .eq(!StringUtil.isEmpty(orderId), EsOrderInfo::getEsOrderId, orderId)
                .eq(!StringUtil.isEmpty(sellName), EsOrderInfo::getSellName, sellName)
                .eq(!StringUtil.isEmpty(userName), EsOrderInfo::getUserName, userName)
                .eq(!StringUtil.isEmpty(userMobile), EsOrderInfo::getUserMobile, userMobile)
                .eq(!StringUtil.isEmpty(sellMobile), EsOrderInfo::getSellMobile, sellMobile)
                .in(!CollectionUtils.isEmpty(status), EsOrderInfo::getStatus, status)
                .in(!CollectionUtils.isEmpty(adminUser.getCompanyWechatIds()), EsOrderInfo::getCompanyWechatId, adminUser.getCompanyWechatIds())
                .between(!StringUtil.isEmpty(startCreateTime), EsOrderInfo::getCreateTime, startCreateTime, endCreateTime)
                .between(!StringUtil.isEmpty(startPayTime), EsOrderInfo::getPayTime, startPayTime, endPayTime)
                .orderByDesc(EsOrderInfo::getCreateTime)
                .page(new Page<>(pageNum, pageSize));
    }

    public EsOrderInfo detail(String esOrderId) {

        return esOrderInfoService.getById(esOrderId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(EsOrderAddBean esOrderAddBean) {

        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getCompanyWechatId() == null)
            throw new RemoteServiceException("非商户不能下单");

        for (EsOrderInfo esOrderInfo : esOrderAddBean.getEsOrderInfos()) {
            EsGoods esGoods = esGoodsService.getById(esOrderInfo.getEsGoodsId());
            EsGoodsImg esGoodsImg = esGoodsImgService.lambdaQuery().eq(EsGoodsImg::getEsGoodsId, esGoods.getId()).last("limit 1").one();

            if (!esGoods.getStatus().equals(ESGoodsStatusEnum.ON.getKey()) || esGoods.getDel())
                throw new RemoteServiceException("商品已下架");


            if (esOrderInfo.getNum() > esGoods.getQty()) {
                throw new RemoteServiceException(esGoods.getGoodsName()+"大于了上架数量");
            }


            User user = userService.getById(esGoods.getUserId());


            esOrderInfo.setUserName(esOrderAddBean.getUserName());
            esOrderInfo.setEsOrderId("ES"+ IdWorker.getIdStr());
            esOrderInfo.setUserMobile(esOrderAddBean.getUserMobile());
            esOrderInfo.setPayType(esOrderAddBean.getPayType());
            esOrderInfo.setProvince(esOrderAddBean.getProvince());
            esOrderInfo.setCity(esOrderAddBean.getCity());
            esOrderInfo.setArea(esOrderAddBean.getArea());
            esOrderInfo.setStreet(esOrderAddBean.getStreet());
            esOrderInfo.setReceAddress(esOrderAddBean.getReceAddress());
            esOrderInfo.setSellName(user.getNickName());
            esOrderInfo.setSellTime(esGoods.getCreateTime());
            esOrderInfo.setSellMobile(user.getMobile());
            esOrderInfo.setSellId(user.getUserId());

            esOrderInfo.setEsCategoryId(esGoods.getCategoryId());
            esOrderInfo.setEsCategoryName(esGoods.getCategoryName());
            esOrderInfo.setNum(esOrderInfo.getNum());
            esOrderInfo.setBrandName(esGoods.getBrand());
            esOrderInfo.setPower(esGoods.getPower());
            esOrderInfo.setProductionTime(esGoods.getMakeDate());
            esOrderInfo.setEnergyLabel(esGoods.getMark());
            esOrderInfo.setSaleType(esOrderAddBean.getSaleType());
            esOrderInfo.setTotalAmount(esOrderInfo.getGoodsPrice().multiply(Convert.toBigDecimal(esOrderInfo.getNum())));
            esOrderInfo.setGoodsPrice(esOrderInfo.getGoodsPrice());
            esOrderInfo.setEsGoodsId(esGoods.getId());
            esOrderInfo.setEsGoodsName(esGoods.getGoodsName());
            esOrderInfo.setGoodsUrl(esGoodsImg.getImgUrl());
            esOrderInfo.setSellUrl(esGoods.getUserHeadImg());
            esOrderInfo.setGoodsNote(esGoods.getGoodsNote());

            esOrderInfo.setProvinceId(esOrderAddBean.getProvinceId());
            esOrderInfo.setCityId(esOrderAddBean.getCityId());
            esOrderInfo.setAreaId(esOrderAddBean.getAreaId());
            esOrderInfo.setStreetId(esOrderAddBean.getStreetId());

            esOrderInfo.setCompanyName(esOrderAddBean.getStreetId());
            esOrderInfo.setCompanyWechatId(esOrderAddBean.getStreetId());




            esOrderInfo.setSource("公众号");

            esOrderInfo.setCompanyName(esGoods.getCompanyWechatName());
            esOrderInfo.setCompanyWechatId(esGoods.getCompanyWechatId());

            esOrderInfo.setStatus(ExamineStatusEnum.WAIT.getKey());


            esOrderInfo.setSource("公众号");


            esOrderInfo.setTotalAmount(esOrderInfo.getGoodsPrice().multiply(Convert.toBigDecimal(esOrderInfo.getNum())));
            esOrderInfo.setStatus(ExamineStatusEnum.WAIT.getKey());
            esOrderInfo.setPayStatus(PayStatusEnum.PAID.getKey());
            esOrderInfo.insert();

            esGoods.setStatus(ESGoodsStatusEnum.SALE.getKey());
            esGoods.updateById();


            carouselMapService.lambdaUpdate().eq(CarouselMap::getGoodsId,esGoods.getId())
                    .set(CarouselMap::getState,0).update();

            this.sendMaterialExamineEsOrder(esOrderInfo.getEsOrderId());
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void payPrice(String esOrderId, BigDecimal price, String fileUrl, String remark) {
        EsOrderPrice esOrderPrice = new EsOrderPrice();
        esOrderPrice.setEsOrderInfoId(esOrderId);
        esOrderPrice.setPrice(price);
        esOrderPrice.setFileUrl(fileUrl);
        esOrderPrice.setRemark(remark);
        esOrderPrice.insert();

        EsOrderInfo esOrderInfo = esOrderInfoService.getById(esOrderId);

        if (!(esOrderInfo.getStatus().equals("SAVE") && esOrderInfo.getSaleType().equals(1) && esOrderInfo.getPayType().equals(PayTypeEnum.CASH.getKey())))
            throw new RemoteServiceException("不可确认收款");


        esOrderInfoService.lambdaUpdate().eq(EsOrderInfo::getEsOrderId,esOrderId)
                .eq(EsOrderInfo::getStatus,ExamineStatusEnum.SAVE.getKey())
                .set(EsOrderInfo::getStatus,"PAID")
                .set(EsOrderInfo::getPayStatus,"PAID")
                .update();
    }

    public List<EsOrderPrice> payPriceList(String esOrderId) {

        return esOrderPriceService.lambdaQuery().eq(EsOrderPrice::getEsOrderInfoId,esOrderId).list();
    }

    @Transactional(rollbackFor = Exception.class)
    public void send(String esOrderId, String pickType, String logisticsNo, String logisticsCode, String logisticsName) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        EsOrderInfo esOrderInfo = esOrderInfoService.getById(esOrderId);
        if (esOrderInfo.getStatus().equals("SEND") || esOrderInfo.getStatus().equals("OVER"))
            throw new RemoteServiceException("无需发货");

        esOrderInfoService.lambdaUpdate().eq(EsOrderInfo::getEsOrderId,esOrderId)
                .set(EsOrderInfo::getStatus,"SEND")
                .set(EsOrderInfo::getPickType,pickType)
                .set(EsOrderInfo::getSendName,adminUser.getNickName())
                .set(EsOrderInfo::getSendTime,new Date())
                .set(!StringUtil.isEmpty(logisticsNo),EsOrderInfo::getLogisticsNo,logisticsNo)
                .set(!StringUtil.isEmpty(logisticsCode),EsOrderInfo::getLogisticsCode,logisticsCode)
                .set(!StringUtil.isEmpty(logisticsName),EsOrderInfo::getLogisticsName,logisticsName).update();

        //订阅物流
        if (!StringUtil.isEmpty(logisticsNo)) {
            expressLogic.subscribeExpress(logisticsNo, logisticsCode, esOrderInfo.getUserMobile());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void refund(String esOrderId, String refundType, Integer refundNum, String refundRemark, BigDecimal refundPrice) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        EsOrderInfo esOrderInfo = esOrderInfoService.getById(esOrderId);

        EsOrderRefund esOrderRefund = BeanUtil.toBean(esOrderInfo, EsOrderRefund.class);

        if (refundNum != null){
            esOrderInfo.setRefundNum(refundNum+esOrderInfo.getRefundNum());
            if (esOrderInfo.getNum() < esOrderInfo.getRefundNum())
                throw new RemoteServiceException("退货数量大于了商品数量");

        }

        if (refundPrice != null){
            esOrderInfo.setRefundPrice(refundPrice.add(esOrderInfo.getRefundPrice()));
            if (esOrderInfo.getTotalAmount().doubleValue() < esOrderInfo.getRefundPrice().doubleValue())
                throw new RemoteServiceException("退货金额大于了商品金额");

        }

        esOrderInfo.setStatus("CANCEL");

        esOrderInfo.updateById();

        esOrderRefund.setEsOrderId(esOrderId);
        esOrderRefund.setRefundType(refundType);
        esOrderRefund.setRefundNum(refundNum);
        esOrderRefund.setRefundRemark(refundRemark);
        esOrderRefund.setRefundPrice(refundPrice);
        esOrderRefund.setStatus("OVER");
        esOrderRefund.setRefundName(adminUser.getNickName());
        esOrderRefund.setRefundTime(new Date());
        esOrderRefund.insert();


        if (!StringUtil.isEmpty(esOrderInfo.getTransactionId()) && esOrderRefund.getRefundPrice()!= null && esOrderRefund.getRefundPrice().doubleValue() > 0) {

            wechatLogic.refund(esOrderInfo.getTransactionId(), esOrderRefund.getEsOrderRefundId(), esOrderInfo.getTotalAmount().doubleValue()
                    , esOrderRefund.getRefundPrice().doubleValue(), esOrderRefund.getCompanyWechatId(), esOrderInfo.getSource());
        }
    }

    public IPage<EsOrderRefund> listRefund(HttpServletRequest request, String esOrderRefundId,String esGoodsName, String orderId, String sellName, String userName, String userMobile, String sellMobile, List<String> status, String startCreateTime, String endCreateTime, String startPayTime, String endPayTime, Integer pageNum, Integer pageSize) {

        AdminUserCom adminUser = commonLogic.getAdminUser();

        return esOrderRefundService.lambdaQuery().eq(!StringUtil.isEmpty(esGoodsName), EsOrderRefund::getEsGoodsName, esGoodsName)
                .eq(!StringUtil.isEmpty(orderId), EsOrderRefund::getEsOrderId, orderId)
                .eq(!StringUtil.isEmpty(esOrderRefundId), EsOrderRefund::getEsOrderRefundId, esOrderRefundId)
                .eq(!StringUtil.isEmpty(sellName), EsOrderRefund::getSellName, sellName)
                .eq(!StringUtil.isEmpty(userName), EsOrderRefund::getUserName, userName)
                .eq(!StringUtil.isEmpty(userMobile), EsOrderRefund::getUserMobile, userMobile)
                .eq(!StringUtil.isEmpty(sellMobile), EsOrderRefund::getSellMobile, sellMobile)
                .in(!CollectionUtils.isEmpty(status), EsOrderRefund::getStatus, status)
                .in(!CollectionUtils.isEmpty(adminUser.getCompanyWechatIds()), EsOrderRefund::getCompanyWechatId, adminUser.getCompanyWechatIds())
                .between(!StringUtil.isEmpty(startCreateTime), EsOrderRefund::getCreateTime, startCreateTime, endCreateTime)
                .between(!StringUtil.isEmpty(startPayTime), EsOrderRefund::getPayTime, startPayTime, endPayTime)
                .orderByDesc(EsOrderRefund::getCreateTime)

                .page(new Page<>(pageNum, pageSize));
    }

    public EsOrderRefundBean detailRefund(String esOrderRefundId) {
        EsOrderRefund esOrderRefund = esOrderRefundService.getById(esOrderRefundId);
        EsOrderRefundBean esOrderRefundBean = BeanUtil.toBean(esOrderRefund, EsOrderRefundBean.class);
        List<EsOrderRefundFile> esOrderRefundFiles = esOrderRefundFileService.lambdaQuery().eq(EsOrderRefundFile::getEsOrderRefundId, esOrderRefund.getEsOrderRefundId()).list();
        esOrderRefundBean.setEsOrderRefundFiles(esOrderRefundFiles);
        return esOrderRefundBean;
    }

    public void cancel(String esOrderId) {
        EsOrderInfo esOrderInfo = esOrderInfoService.getById(esOrderId);

        if (!(esOrderInfo.getStatus().equals(ExamineStatusEnum.WAIT.getKey()) || esOrderInfo.getStatus().equals(ExamineStatusEnum.SAVE.getKey()))) {
            throw new RemoteServiceException("非待确认无法取消");
        }

        if (esOrderInfo.getPayStatus().equals(PayStatusEnum.PAID.getKey())){
            EsGoods esGoods = esGoodsService.getById(esOrderInfo.getEsGoodsId());
            esGoods.setStatus(ESGoodsStatusEnum.ON.getKey());
            esGoods.updateById();


            carouselMapService.lambdaUpdate().eq(CarouselMap::getGoodsId,esGoods.getId())
                    .set(CarouselMap::getState,1).update();
        }

        esOrderInfoService.lambdaUpdate().eq(EsOrderInfo::getEsOrderId,esOrderId)
                .set(EsOrderInfo::getStatus,"CANCEL")
                .set(EsOrderInfo::getPayStatus,"WAIT")
                .update();
    }

    @Transactional(rollbackFor = Exception.class)
    public void refundPrice(String esOrderRefundId, String refundType, Integer refundNum, String refundRemark, BigDecimal refundPrice) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        EsOrderRefund esOrderRefund = esOrderRefundService.getById(esOrderRefundId);

        EsOrderInfo esOrderInfo = esOrderInfoService.getById(esOrderRefund.getEsOrderId());

        if (refundNum != null){
            esOrderInfo.setRefundNum(refundNum+esOrderInfo.getRefundNum());
            if (esOrderInfo.getNum() < esOrderInfo.getRefundNum())
                throw new RemoteServiceException("退货数量大于了商品数量");

        }

        if (refundPrice != null){
            esOrderInfo.setRefundPrice(refundPrice.add(esOrderInfo.getRefundPrice()));
            if (esOrderInfo.getTotalAmount().doubleValue() < esOrderInfo.getRefundPrice().doubleValue())
                throw new RemoteServiceException("退货金额大于了商品金额");

        }

        esOrderInfo.setStatus(PayStatusEnum.CANCEL.getKey());

        esOrderInfo.updateById();

        esOrderRefund.setEsOrderId(esOrderInfo.getEsOrderId());
        esOrderRefund.setRefundType(refundType);
        esOrderRefund.setRefundNum(refundNum);
        esOrderRefund.setRefundRemark(refundRemark);
        esOrderRefund.setRefundPrice(refundPrice);
        esOrderRefund.setStatus("OVER");
        esOrderRefund.setRefundName(adminUser.getNickName());
        esOrderRefund.setRefundTime(new Date());
        esOrderRefund.updateById();

        if (!StringUtil.isEmpty(esOrderInfo.getTransactionId()) && esOrderRefund.getRefundPrice()!= null && esOrderRefund.getRefundPrice().doubleValue() > 0) {

            wechatLogic.refund(esOrderInfo.getTransactionId(), esOrderRefund.getEsOrderRefundId(), esOrderInfo.getTotalAmount().doubleValue()
                    , esOrderRefund.getRefundPrice().doubleValue(), esOrderRefund.getCompanyWechatId(), esOrderInfo.getSource());
        }
    }

    public void export2(HttpServletRequest request, HttpServletResponse response, String esGoodsName, String orderId, String sellName, String userName,
                        String userMobile, String sellMobile, List<String> status, String startCreateTime, String endCreateTime, String startPayTime,
                        String endPayTime) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        ExcelData excelData = new ExcelData();
        String[] titles = {"订单号", "商品名称", "数量", "单位", "销售单价", "总金额", "订单状态", "收货人姓名",
                "收货手机号", "收货地址", "退款金额", "退款数量", "备注", "下单时间","支付时间",
                "买家名称", "买家电话", "商品分类"};

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

        List<EsOrderInfo> list = esOrderInfoService.lambdaQuery().eq(!StringUtil.isEmpty(esGoodsName), EsOrderInfo::getEsGoodsName, esGoodsName)
                .eq(!StringUtil.isEmpty(orderId), EsOrderInfo::getEsOrderId, orderId)
                .eq(!StringUtil.isEmpty(sellName), EsOrderInfo::getSellName, sellName)
                .eq(!StringUtil.isEmpty(userName), EsOrderInfo::getUserName, userName)
                .eq(!StringUtil.isEmpty(userMobile), EsOrderInfo::getUserMobile, userMobile)
                .eq(!StringUtil.isEmpty(sellMobile), EsOrderInfo::getSellMobile, sellMobile)
                .in(!CollectionUtils.isEmpty(status), EsOrderInfo::getStatus, status)
                .in(!CollectionUtils.isEmpty(adminUser.getCompanyWechatIds()), EsOrderInfo::getCompanyWechatId, adminUser.getCompanyWechatIds())
                .between(!StringUtil.isEmpty(startCreateTime), EsOrderInfo::getCreateTime, startCreateTime, endCreateTime)
                .between(!StringUtil.isEmpty(startPayTime), EsOrderInfo::getPayTime, startPayTime, endPayTime)
                .orderByDesc(EsOrderInfo::getCreateTime)
                .list();
        List<List<Object>> rows =new ArrayList<>();
        for (EsOrderInfo esOrderInfo:list
        ) {
            List<Object> row = new ArrayList<>();
            rows.add(row);

            row.add(esOrderInfo.getEsOrderId());
            row.add(esOrderInfo.getEsGoodsName());
            row.add(esOrderInfo.getNum());
            row.add("台");
            row.add(esOrderInfo.getGoodsPrice());
            row.add(esOrderInfo.getTotalAmount());
            if (esOrderInfo.getStatus().equals(ExamineStatusEnum.SAVE.getKey()))
                row.add("待付款");
            if (esOrderInfo.getStatus().equals(ExamineStatusEnum.WAIT.getKey()))
                row.add("待确认");
            if (esOrderInfo.getStatus().equals(PayStatusEnum.PAID.getKey()))
                row.add("待发货");
            if (esOrderInfo.getStatus().equals("SEND"))
                row.add("已发货");
            if (esOrderInfo.getStatus().equals(OrderShareFlagEnum.OVER.getKey()))
                row.add("已完成");
            if (esOrderInfo.getStatus().equals(PayStatusEnum.CANCEL.getKey()))
                row.add("已退货/取消");
            if (esOrderInfo.getStatus().equals("TIME_OUT"))
                row.add("已超时");

            row.add(esOrderInfo.getUserName());
            row.add(esOrderInfo.getUserMobile());
            row.add(esOrderInfo.getReceAddress());
            row.add(esOrderInfo.getRefundPrice());
            row.add(esOrderInfo.getRefundNum());
            row.add(esOrderInfo.getRemark());
            row.add(DateUtil.format(esOrderInfo.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            row.add(DateUtil.format(esOrderInfo.getPayTime(), "yyyy-MM-dd HH:mm:ss"));
            row.add(esOrderInfo.getWechatUserName());
            row.add(esOrderInfo.getWechatUserMobile());
            row.add(esOrderInfo.getEsCategoryName());

        }

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

    public void downloadFileRefund(HttpServletRequest request, HttpServletResponse response, String esGoodsName, String orderId, String sellName, String userName, String userMobile, String sellMobile, List<String> status, String startCreateTime, String endCreateTime, String startPayTime, String endPayTime) throws Exception {

        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        ExcelData excelData = new ExcelData();
        String[] titles = {"订单号", "商品名称", "数量", "单位", "订单销售单价", "订单总金额", "状态", "收货人姓名",
                "收货手机号", "收货地址", "退款金额", "退款数量", "备注", "下单时间","支付时间",
                "买家名称", "买家电话", "商品分类"};

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


        List<EsOrderRefund> esOrderRefunds = esOrderRefundService.lambdaQuery().eq(!StringUtil.isEmpty(esGoodsName), EsOrderRefund::getEsGoodsName, esGoodsName)
                .eq(!StringUtil.isEmpty(orderId), EsOrderRefund::getEsOrderId, orderId)
                .eq(!StringUtil.isEmpty(sellName), EsOrderRefund::getSellName, sellName)
                .eq(!StringUtil.isEmpty(userName), EsOrderRefund::getUserName, userName)
                .eq(!StringUtil.isEmpty(userMobile), EsOrderRefund::getUserMobile, userMobile)
                .eq(!StringUtil.isEmpty(sellMobile), EsOrderRefund::getSellMobile, sellMobile)
                .in(!CollectionUtils.isEmpty(status), EsOrderRefund::getStatus, status)
                .in(!CollectionUtils.isEmpty(adminUser.getCompanyWechatIds()), EsOrderRefund::getCompanyWechatId, adminUser.getCompanyWechatIds())
                .between(!StringUtil.isEmpty(startCreateTime), EsOrderRefund::getCreateTime, startCreateTime, endCreateTime)
                .between(!StringUtil.isEmpty(startPayTime), EsOrderRefund::getPayTime, startPayTime, endPayTime)
                .orderByDesc(EsOrderRefund::getCreateTime)

                .list();

        List<List<Object>> rows =new ArrayList<>();
        for (EsOrderRefund esOrderRefund:esOrderRefunds
        ) {
            List<Object> row = new ArrayList<>();
            rows.add(row);

            row.add(esOrderRefund.getEsOrderId());
            row.add(esOrderRefund.getEsGoodsName());
            row.add(esOrderRefund.getNum());
            row.add("台");
            row.add(esOrderRefund.getGoodsPrice());
            row.add(esOrderRefund.getTotalAmount());
            if (esOrderRefund.getStatus().equals(ExamineStatusEnum.WAIT.getKey()))
                row.add("待商家处理");
            if (esOrderRefund.getStatus().equals("OVER"))
                row.add("已完成");


            row.add(esOrderRefund.getUserName());
            row.add(esOrderRefund.getUserMobile());
            row.add(esOrderRefund.getReceAddress());
            row.add(esOrderRefund.getRefundPrice());
            row.add(esOrderRefund.getRefundNum());
            row.add(esOrderRefund.getRemark());
            row.add(DateUtil.format(esOrderRefund.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            row.add(DateUtil.format(esOrderRefund.getPayTime(), "yyyy-MM-dd HH:mm:ss"));
            row.add(esOrderRefund.getWechatUserName());
            row.add(esOrderRefund.getWechatUserMobile());
            row.add(esOrderRefund.getEsCategoryName());

        }

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

    @Transactional(rollbackFor = Exception.class)
    public void payOk(String esOrderId) {

        EsOrderInfo esOrderInfo = esOrderInfoService.getById(esOrderId);
        if (!esOrderInfo.getStatus().equals(ExamineStatusEnum.WAIT.getKey()))
            throw new RemoteServiceException("非待确认");


        esOrderInfoService.lambdaUpdate().eq(EsOrderInfo::getEsOrderId,esOrderId)
                .eq(EsOrderInfo::getStatus,ExamineStatusEnum.WAIT.getKey())
                .set(EsOrderInfo::getStatus,"PAID")
                .set(EsOrderInfo::getPayStatus,"PAID")
                .update();
    }



    public void sendMaterialExamineEsOrder(String orderId) {

        EsOrderInfo esOrderInfo = esOrderInfoService.getById(orderId);


        AdminUser one = adminUserService.lambdaQuery().eq(AdminUser::getCompanyWechatId, esOrderInfo.getCompanyWechatId())
                .eq(AdminUser::getType, 1).last("limit 1").one();

        NoticeRecord noticeRecordCom = new NoticeRecord();
        noticeRecordCom.setNoticeId(esOrderInfo.getEsOrderId());
        String format = DateUtil.format(new Date(), "yyyy-MM-dd");
        noticeRecordCom.setTitle(esOrderInfo.getEsGoodsName()+"创建时间"+format+",已支付成功");
        noticeRecordCom.setContent(esOrderInfo.getEsGoodsName()+"创建时间"+format+",已支付成功");
        noticeRecordCom.setType("B");
        noticeRecordCom.setIsNotice("YES");
        noticeRecordCom.setReadFlag("NO");
        noticeRecordCom.setAdminUserId(one.getAdminUserId());
        noticeRecordCom.setAdminNickName(one.getNickName());
        noticeRecordCom.setIssueTime(new Date());
        noticeRecordCom.setAdminCompanyId(one.getCompanyWechatId());
        noticeRecordCom.setAdminCompanyName(one.getCompanyName());
        noticeRecordCom.setAdminNoticeType(AdminNoticTypeEnum.CR_ES_SALES.getKey());
        noticeRecordCom.setOrderId(esOrderInfo.getEsOrderId());
        noticeRecordCom.setPaidType("ES");
        noticeRecordCom.insert();

    }
}
