package com.cyl.manager.oms.service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cyl.h5.pojo.dto.ApplyRefundDTO;
import com.cyl.h5.pojo.vo.query.OrderH5Query;
import com.cyl.manager.marketing.domain.WechatMemberCoupon;
import com.cyl.manager.marketing.service.impl.WechatMemberCouponServiceImpl;
import com.cyl.manager.oms.convert.OrderConvert;
import com.cyl.manager.oms.convert.OrderItemConvert;
import com.cyl.manager.oms.convert.OrderOperateHistoryConvert;
import com.cyl.manager.oms.domain.*;
import com.cyl.manager.oms.mapper.*;
import com.cyl.manager.oms.pojo.request.DeliverProductRequest;
import com.cyl.manager.oms.pojo.request.ManagerOrderQueryRequest;
import com.cyl.manager.oms.pojo.vo.*;
import com.cyl.manager.pms.convert.SkuConvert;
import com.cyl.manager.pms.mapper.ProductMapper;
import com.cyl.manager.pms.mapper.SkuMapper;
import com.cyl.manager.ums.domain.Member;
import com.cyl.manager.ums.domain.MemberWechat;
import com.cyl.manager.ums.domain.Pet;
import com.cyl.manager.ums.mapper.MemberAddressMapper;
import com.cyl.manager.ums.mapper.MemberCartMapper;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.cyl.manager.ums.pojo.vo.PetVO;
import com.cyl.manager.ums.service.MemberWechatService;
import com.cyl.manager.ums.service.PetService;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.enums.AftersaleStatus;
import com.ruoyi.common.enums.OrderRefundStatus;
import com.ruoyi.common.enums.OrderStatus;
import com.ruoyi.common.utils.AesCryptoUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.IDGenerator;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单表Service业务层处理
 *
 *
 * @author zcc
 */
@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderConvert orderConvert;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private MemberAddressMapper memberAddressMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private SkuConvert skuConvert;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private OrderOperateHistoryMapper orderOperateHistoryMapper;
    @Autowired
    private MemberCartMapper memberCartMapper;
    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private MemberWechatService memberWechatService;

    @Autowired
    private OmsOrderServiceService omsOrderServiceService;

    @Autowired
    private OrderItemConvert orderItemConvert;

    @Value("${aes.key}")
    private String aesKey;
    @Autowired
    private OrderDeliveryHistoryMapper orderDeliveryHistoryMapper;
    @Autowired
    private OrderOperateHistoryConvert historyConvert;

    @Autowired
    private AftersaleMapper aftersaleMapper;

    @Autowired
    private AftersaleItemMapper aftersaleItemMapper;

    @Autowired
    WechatMemberCouponServiceImpl wechatMemberCouponService;

    @Autowired
    PetService petService;

    /**
     * 查询订单表
     *
     * @param id 订单表主键
     * @return 订单表
     */
    public ManagerOrderDetailVO selectById(Long id) {
        Order order = orderMapper.selectById(id);
        if (order == null){
            throw new RuntimeException("查不到订单信息");
        }
        ManagerOrderDetailVO managerOrderDetailVO = new ManagerOrderDetailVO();
        //封装订单信息
        managerOrderDetailVO.setOrderId(id);
        managerOrderDetailVO.setOrderSn(order.getOrderSn());
        managerOrderDetailVO.setOrderStatus(order.getStatus());
        managerOrderDetailVO.setCreateTime(order.getCreateTime());
        managerOrderDetailVO.setDeliveryTime(order.getDeliveryTime());
        managerOrderDetailVO.setExpressName(order.getDeliveryCompany());
        managerOrderDetailVO.setExpressNo(order.getDeliverySn());
        managerOrderDetailVO.setPayAmount(order.getPayAmount());
        managerOrderDetailVO.setPayTime(order.getPaymentTime());
        managerOrderDetailVO.setPayType(order.getPayType());
        managerOrderDetailVO.setTotalAmount(order.getTotalAmount());
        managerOrderDetailVO.setPayAmount(order.getPayAmount());
        managerOrderDetailVO.setReceiveTime(order.getReceiveTime());

        managerOrderDetailVO.setNeedPreFamiliarize(order.getNeedPreFamiliarize());
        managerOrderDetailVO.setWechatMemberCouponId(order.getWechatMemberCouponId());
        //封装订单地址信息
        ManagerOrderAddressVo managerOrderAddressVo = new ManagerOrderAddressVo();
        managerOrderAddressVo.setUserPhone(order.getReceiverPhone());
        managerOrderAddressVo.setAddress(order.getReceiverDetailAddress());
        managerOrderAddressVo.setArea(
                order.getReceiverCity() +
                order.getReceiverDistrict());
        managerOrderAddressVo.setName(order.getReceiverName());
        managerOrderDetailVO.setAddressInfo(managerOrderAddressVo);
        //查询会员信息
        Member member = memberMapper.selectById(order.getMemberId());
        managerOrderDetailVO.setUserName(member.getNickname());
        managerOrderDetailVO.setUserPhone(member.getPhoneHidden());

        //查询服务信息
        List<OmsOrderService> orderServiceInfoList = omsOrderServiceService.selectListByOrderId(id);
        managerOrderDetailVO.setOrderService(orderServiceInfoList.get(0));
        managerOrderDetailVO.setOrderServiceList(orderServiceInfoList);

        Map<Integer, PetVO> petList = new HashMap<>();
        Map<Long, OmsOrderService> omsOrderServiceList = new HashMap<>();

        orderServiceInfoList.forEach(item -> {
                    if (!omsOrderServiceList.containsKey(item.getId())) {
                        omsOrderServiceList.put(item.getId(), item);
                        if (item.getPetId() != null) {
                            if (!petList.containsKey(item.getPetId())) {
                                PetVO pet = petService.selectPetById(item.getPetId());
                                if (pet != null) {
                                    petList.put(pet.getId(), pet);
                                }
                            }
                        }
                    }
        }
        );

        //查询购买商品信息
        QueryWrapper<OrderItem> qw = new QueryWrapper<>();
        qw.eq("order_id", order.getId());
        List<OrderItem> orderItemList = orderItemMapper.selectList(qw);
        List<ManagerOrderProductVO> productList = new ArrayList<>();
        orderItemList.forEach(item -> {
            ManagerOrderProductVO productVO = new ManagerOrderProductVO();
            productVO.setProductId(item.getProductId());
            productVO.setBuyNum(item.getQuantity());
            productVO.setPic(item.getPic());
            productVO.setProductName(item.getProductName());
            productVO.setSalePrice(item.getSalePrice());
            productVO.setSpData(item.getSpData());

            OmsOrderService oos = omsOrderServiceList.get(item.getOrderServiceId());
            if (oos != null) {
                productVO.setExpectServiceTime(oos.getExpectServiceTime());
                productVO.setServiceDate(oos.getServiceDate());
                productVO.setPetId(oos.getPetId());

                PetVO p = petList.get(oos.getPetId());
                if (p != null) {
                    productVO.setPetType(p.getPetType());
                    productVO.setPetName(p.getName());
                }
            }
            productList.add(productVO);
        });
        managerOrderDetailVO.setProductInfo(productList);



        //优惠券信息
        if (order.getWechatMemberCouponId() != null) {
            WechatMemberCoupon wechatMemberCoupon = wechatMemberCouponService.selectWechatMemberCouponById(order.getWechatMemberCouponId());
            managerOrderDetailVO.setWechatMemberCoupon(wechatMemberCoupon);
        }

        return managerOrderDetailVO;
    }

    /**
     * 查询订单表列表
     *
     * @param query 查询条件
     * @param page 分页条件
     * @return 订单表
     */
    public PageImpl<ManagerOrderVO> selectList(ManagerOrderQueryRequest query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        if (!StringUtils.isEmpty(query.getUserPhone())){
            query.setUserPhone(AesCryptoUtils.encrypt(aesKey, query.getUserPhone()));
        }
        List<ManagerOrderVO> managerOrderVOList = orderMapper.selectManagerOrderPage(query);
        if (CollectionUtil.isEmpty(managerOrderVOList)){
            return new PageImpl<>(managerOrderVOList, page, 0);
        }
        long total = ((com.github.pagehelper.Page) managerOrderVOList).getTotal();
        Map<Long, ManagerOrderVO> orderMap = managerOrderVOList.stream().collect(Collectors.toMap(ManagerOrderVO::getId, it -> it, (v1,v2) -> v2, LinkedHashMap::new));
        //查orderItem
        QueryWrapper<OrderItem> qw = new QueryWrapper<>();
        qw.in("order_id", orderMap.keySet());
        Map<Long, List<OrderItem>> groupedOrderItemMap = orderItemMapper.selectList(qw)
                .stream().collect(Collectors.groupingBy(OrderItem::getOrderId));
        groupedOrderItemMap.keySet().forEach(key -> {
            ManagerOrderVO managerOrderVO = orderMap.get(key);
            managerOrderVO.setBuyNum(0);
            List<OrderItem> orderItemList = groupedOrderItemMap.get(key);
            List<ManagerOrderProductVO> addProductList = new ArrayList<>();
            orderItemList.forEach(item -> {
                ManagerOrderProductVO vo = new ManagerOrderProductVO();
                vo.setProductName(item.getProductName());
                vo.setSalePrice(item.getSalePrice());
                vo.setPic(item.getPic());
                vo.setBuyNum(item.getQuantity());
                vo.setProductId(item.getProductId());
                vo.setSpData(item.getSpData());

                vo.setOrderServiceId(item.getOrderServiceId());
                addProductList.add(vo);
                managerOrderVO.setBuyNum(managerOrderVO.getBuyNum() + item.getQuantity());
            });
            managerOrderVO.setProductList(addProductList);
        });
        return new PageImpl<>(new ArrayList<>(orderMap.values()), page, total);
    }

    /**
     * 新增订单表
     *
     * @param order 订单表
     * @return 结果
     */
    public int insert(Order order) {
        order.setCreateTime(LocalDateTime.now());
        return orderMapper.insert(order);
    }

    /**
     * 修改订单表
     *
     * @param order 订单表
     * @return 结果
     */
    public int update(Order order) {
        return orderMapper.updateById(order);
    }

    /**
     * 删除订单表信息
     *
     * @param id 订单表主键
     * @return 结果
     */
    public int deleteById(Long id) {
        return orderMapper.deleteById(id);
    }

    public Page<OrderVO> queryOrderPage(OrderH5Query query, Pageable pageReq) {
        QueryWrapper<Order> qw = new QueryWrapper<>();
        qw.eq("member_id", SecurityUtils.getUserId());
        IPage<Order> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>();
        page.setCurrent(pageReq.getPageNumber())
                .setSize(pageReq.getPageSize());
        if (CollUtil.isEmpty(pageReq.getSort())) {
            pageReq.getSort().forEach(it -> {
                qw.orderBy(true, it.getDirection().isAscending(), it.getProperty());
            });
        }
        Integer tab = query.getTab();
        if (tab != null) {
            qw.eq("delete_status", 0);
            if (tab == 1) {
                qw.eq("status", 0);
            } else if (tab == 2) {
                qw.eq("status", 1);
                qw.eq("aftersale_status", 1);
            } else if (tab == 3) {
                qw.eq("status", 2);
                qw.eq("confirm_status", 0);
            } else if (tab == 4) {
                qw.eq("status", 2);
                qw.eq("confirm_status", 1);
            }
        }
        orderMapper.selectPage(page, qw);
        List<Order> orders = page.getRecords();
        long total = page.getPages();
        if (CollUtil.isEmpty(orders)) {
            return new PageImpl<>(Collections.emptyList(), pageReq, total);
        }
        LambdaQueryWrapper<OrderItem> qw1 = new LambdaQueryWrapper<>();
        qw1.in(OrderItem::getOrderId, orders.stream().map(Order::getId).collect(Collectors.toList()));
        Map<Long, List<OrderItem>> oid2items = orderItemMapper.selectList(qw1)
                .stream().collect(Collectors.groupingBy(OrderItem::getOrderId));
        List<OrderVO> res = orderConvert.dos2vos(orders);
        res.forEach(it -> {
            it.setItems(oid2items.get(it.getId()));
        });
        return new PageImpl<>(res, pageReq, total);
    }


    public Integer saveMerchantNote(Order order) {
        Order orderInDb = orderMapper.selectById(order.getId());
        if (orderInDb == null){
            throw new RuntimeException("订单不存在");
        }
        UpdateWrapper<Order> qw = new UpdateWrapper<>();
        qw.eq("id", order.getId());
        qw.set("merchant_note", order.getMerchantNote());
        return orderMapper.update(null, qw);
    }

    /**
     * 管理后台发货
     * 目前发货是这样的：待发货、已发货、已完成都能执行发货，每次都会创建一条新的发货记录且修改订单发货信息
     * @param request 发货请求
     * @param userId 操作人
     * @return 结果
     */
    @Transactional
    public String deliverProduct(DeliverProductRequest request, Long userId) {
        //查询订单
        Order order = orderMapper.selectById(request.getOrderId());
        QueryWrapper<OrderItem> qw = new QueryWrapper<>();
        qw.eq("order_id", request.getOrderId());
        List<OrderItem> orderItemList = orderItemMapper.selectList(qw);
        if (order == null || CollectionUtil.isEmpty(orderItemList)){
            throw new RuntimeException("未找到该订单信息");
        }
        // 是否为待发货、已发货 、已完成
        if (!(Constants.OrderStatus.SEND.equals(order.getStatus())
                || Constants.OrderStatus.GET.equals(order.getStatus())
                || Constants.OrderStatus.CONFIRM.equals(order.getStatus()))){
            throw new RuntimeException("订单状态错误");
        }
        Integer orderStatus =
                Constants.OrderStatus.SEND.equals(order.getStatus()) ? Constants.OrderStatus.GET : order.getStatus();
        //更新订单
        LocalDateTime optDate = LocalDateTime.now();
        UpdateWrapper<Order> orderQw = new UpdateWrapper();
        orderQw.eq("id", order.getId())
                .set("status", orderStatus)
                .set("delivery_company", request.getExpressName())
                .set("delivery_sn", request.getExpressSn())
                .set("update_time", optDate)
                .set("update_by", userId)
                .set("delivery_time", optDate);
        int rows = orderMapper.update(null, orderQw);
        if (rows < 1){
            throw new RuntimeException("更新订单发货信息失败");
        }
        //创建新的发货记录
        this.createDeliveryHistory(request, userId, optDate);
        //创建订单操作记录
        this.createOrderOptHistory(order.getId(), order.getOrderSn(), orderStatus, userId, optDate);
        return "发货成功";
    }

    @Transactional
    public String orderComplete(Long orderId, Long userId) {
        LocalDateTime optDate = LocalDateTime.now();
        Order order = orderMapper.selectById(orderId);
        OrderItem queryOrderItem = new OrderItem();
        queryOrderItem.setOrderId(orderId);
        List<OrderItem> orderItemList = orderItemMapper.selectByEntity(queryOrderItem);
        if(order == null || CollectionUtil.isEmpty(orderItemList)){
            throw new RuntimeException("未查询到订单信息");
        }
        // 只有【待收货】状态才能确认
        if(!order.getStatus().equals(Constants.H5OrderStatus.DELIVERED)){
            throw new RuntimeException("订单状态已改变，请刷新");
        }
        //更新订单
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", order.getId());
        updateWrapper.set("status", Constants.H5OrderStatus.COMPLETED);
        updateWrapper.set("confirm_status", 1);
        updateWrapper.set("receive_time", optDate);
        int rows = orderMapper.update(null, updateWrapper);
        if (rows < 1){
            throw new RuntimeException("更新订单状态失败");
        }
        //创建订单操作记录
        OrderOperateHistory optHistory = new OrderOperateHistory();
        optHistory.setOrderId(order.getId());
        optHistory.setOrderSn(order.getOrderSn());
        optHistory.setOperateMan("后台管理员");
        optHistory.setOrderStatus(Constants.H5OrderStatus.COMPLETED);
        optHistory.setCreateTime(optDate);
        optHistory.setCreateBy(userId);
        optHistory.setUpdateBy(userId);
        optHistory.setUpdateTime(optDate);
        rows = orderOperateHistoryMapper.insert(optHistory);
        if (rows < 1){
            throw new RuntimeException("创建订单操作记录失败");
        }

        //TODO 发送短信 订单完成提醒（发给消费者和伴宠师）

        return order.getOrderSn();
    }

    /**
     * 创建发货记录
     * @param request 发货请求
     * @param userId 操作人
     * @param optDate 操作时间
     */
    private void createDeliveryHistory(DeliverProductRequest request, Long userId, LocalDateTime optDate){
        OrderDeliveryHistory orderDeliveryHistory = new OrderDeliveryHistory();
        orderDeliveryHistory.setOrderId(request.getOrderId());
        orderDeliveryHistory.setDeliveryCompany(request.getExpressName());
        orderDeliveryHistory.setDeliverySn(request.getExpressSn());
        orderDeliveryHistory.setCreateTime(optDate);
        orderDeliveryHistory.setCreateBy(userId);
        int rows = orderDeliveryHistoryMapper.insert(orderDeliveryHistory);
        if (rows < 1) {
            throw new RuntimeException("新增订单发货记录失败");
        }
    }

    /**
     * 创建订单操作历史
     * @param orderId 订单id
     * @param orderStatus 订单状态
     * @param userId 操作人
     * @param optDate 操作时间
     */
    private void createOrderOptHistory(Long orderId, String orderSn, Integer orderStatus, Long userId, LocalDateTime optDate){
        OrderOperateHistory optHistory = new OrderOperateHistory();
        optHistory.setOrderId(orderId);
        optHistory.setOrderSn(orderSn);
        optHistory.setOperateMan("后台管理员");
        optHistory.setOrderStatus(orderStatus);
        optHistory.setCreateTime(optDate);
        optHistory.setCreateBy(userId);
        optHistory.setUpdateBy(userId);
        optHistory.setUpdateTime(optDate);
        int rows = orderOperateHistoryMapper.insert(optHistory);
        if (rows < 1) {
            throw new RuntimeException("新增订单操作记录失败");
        }
    }

    /**
     * 根据订单id查询订单操作日志
     * @param orderId 订单id
     * @return 结果
     */
    public List<OrderOperateHistoryVO> log(Long orderId) {
        LambdaQueryWrapper<OrderOperateHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderOperateHistory::getOrderId, orderId);
        wrapper.in(OrderOperateHistory::getOrderStatus, Arrays.asList(0, 1, 2, 3, 4));
        wrapper.orderByDesc(OrderOperateHistory::getCreateTime);
        List<OrderOperateHistory> historyList = orderOperateHistoryMapper.selectList(wrapper);
        return historyConvert.dos2vos(historyList);
    }

    public List<OrderExportVO> selectExportList(ManagerOrderQueryRequest query, Pageable page) {
        PageImpl<ManagerOrderVO> list = this.selectList(query, page);

        List<ManagerOrderVO> orderList = list.getContent();
        if (CollectionUtil.isEmpty(orderList)) {
            return new ArrayList<OrderExportVO>();
        }


        List<OrderExportVO> orderMVOs = new ArrayList<>();
        orderList.stream().forEach(order -> {
            List<ManagerOrderProductVO> orderItemList = order.getProductList();
            if (CollectionUtil.isNotEmpty(orderItemList)){
                //OmsOrderService orderServiceInfo = omsOrderServiceService.selectByOrderId(order.getId());

                //查询所有的服务信息
                List<OmsOrderService> orderServiceInfoList = omsOrderServiceService.selectListByOrderId(order.getId());

                Map<Integer, PetVO> petList = new HashMap<>();
                Map<Long, OmsOrderService> omsOrderServiceList = new HashMap<>();

                orderServiceInfoList.forEach(item -> {
                            if (!omsOrderServiceList.containsKey(item.getId())) {
                                omsOrderServiceList.put(item.getId(), item);
                                if (item.getPetId() != null) {
                                    if (!petList.containsKey(item.getPetId())) {
                                        PetVO pet = petService.selectPetById(item.getPetId());
                                        if (pet != null) {
                                            petList.put(pet.getId(), pet);
                                        }
                                    }
                                }
                            }
                        }
                );


                orderItemList.stream().forEach(orderItem -> {
                    OrderExportVO orderMVO = orderConvert.vo2vo(order);

                    ManagerOrderProductExportVO managerOrderProductExportVO = orderItemConvert.vo2vo(orderItem);


                    OmsOrderService oos = omsOrderServiceList.get(orderItem.getOrderServiceId());
                    if (oos != null) {
                        managerOrderProductExportVO.setExpectServiceTime(oos.getExpectServiceTime());
                        managerOrderProductExportVO.setServiceDate(oos.getServiceDate());
                        managerOrderProductExportVO.setPetId(oos.getPetId());

                        PetVO p = petList.get(oos.getPetId());
                        if (p != null) {
                            managerOrderProductExportVO.setPetType(p.getPetType());
                            managerOrderProductExportVO.setPetName(p.getName());
                        }
                    }

                    orderMVO.setOrderItem(managerOrderProductExportVO);

                    MemberWechat memberWechat = memberWechatService.selectByMemberId(order.getMemberId());
                    orderMVO.setWechatId(memberWechat.getWechatId());

                    orderMVOs.add(orderMVO);
                });
            }
        });

        return orderMVOs;
    }

    /**
     * 申请售后
     * @param applyRefundDTO
     * @return
     */
    @Transactional
    public String applyRefund(ApplyRefundDTO applyRefundDTO) {
        Order order = orderMapper.selectById(applyRefundDTO.getOrderId());
        //是否符合售后条件
        this.checkIfCanApplyRefund(order);
        LocalDateTime optDate = LocalDateTime.now();
        Long memberId = order.getMemberId();

        applyRefundDTO.setApplyRefundType(1);
        applyRefundDTO.setQuantity(1);
//        applyRefundDTO.

        //创建售后单aftersale
        Aftersale addAftersale = new Aftersale();
        addAftersale.setId(IDGenerator.generateId());
        addAftersale.setMemberId(order.getMemberId());
        addAftersale.setOrderId(order.getId());
        addAftersale.setReturnAmount(order.getPayAmount());
        addAftersale.setType(applyRefundDTO.getApplyRefundType());
        addAftersale.setStatus(AftersaleStatus.APPLY.getType());
        addAftersale.setReason(applyRefundDTO.getReason());
        addAftersale.setQuantity(applyRefundDTO.getQuantity());
        addAftersale.setReason(applyRefundDTO.getReason());
        addAftersale.setDescription(applyRefundDTO.getDescription());
        addAftersale.setProofPics(applyRefundDTO.getProofPics());
        addAftersale.setCreateTime(optDate);
        addAftersale.setCreateBy(memberId);
        addAftersale.setUpdateTime(optDate);
        addAftersale.setUpdateBy(memberId);
        int rows = aftersaleMapper.insert(addAftersale);
        if (rows != 1) {
            throw new RuntimeException("插入订单售后失败");
        }
        //创建aftersale item
        QueryWrapper<OrderItem> orderItemQw = new QueryWrapper<>();
        orderItemQw.eq("order_id", order.getId());
        List<OrderItem> orderItemList = orderItemMapper.selectList(orderItemQw);
        List<AftersaleItem> addAftersaleItemList = new ArrayList<>();
        orderItemList.forEach(orderItem -> {
            AftersaleItem aftersaleItem = new AftersaleItem();
            aftersaleItem.setMemberId(memberId);
            aftersaleItem.setAftersaleId(addAftersale.getId());
            aftersaleItem.setOrderId(orderItem.getOrderId());
            aftersaleItem.setOrderItemId(orderItem.getId());
            aftersaleItem.setReturnAmount(orderItem.getSalePrice().multiply(BigDecimal.valueOf(orderItem.getQuantity())));
            aftersaleItem.setQuantity(orderItem.getQuantity());
            aftersaleItem.setCreateTime(optDate);
            aftersaleItem.setCreateBy(memberId);
            aftersaleItem.setUpdateTime(optDate);
            aftersaleItem.setUpdateBy(memberId);
            addAftersaleItemList.add(aftersaleItem);
        });
        rows = aftersaleItemMapper.insertBatch(addAftersaleItemList);
        if (rows < 1){
            throw new RuntimeException("创建售后订单item失败");
        }
        //更新订单
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", order.getId()).set("aftersale_status", OrderRefundStatus.APPLY.getType())
                .set("update_time", optDate)
                .set("update_by", memberId);
        rows = orderMapper.update(null, updateWrapper);
        if (rows < 1){
            throw new RuntimeException("修改订单状态失败");
        }
        //创建订单操作记录
        OrderOperateHistory optHistory = new OrderOperateHistory();
        optHistory.setOrderId(order.getId());
        optHistory.setOrderSn(order.getOrderSn());
        optHistory.setOperateMan("" + memberId);
        optHistory.setOrderStatus(11);
        optHistory.setCreateTime(optDate);
        optHistory.setCreateBy(memberId);
        optHistory.setUpdateBy(memberId);
        optHistory.setUpdateTime(optDate);
        rows = orderOperateHistoryMapper.insert(optHistory);
        if (rows < 1){
            throw new RuntimeException("创建订单操作记录失败");
        }
        return "售后申请成功";
    }

    /**
     * check是否能售后 可售后的状态为：待发货、待收货、已完成
     * @param order 订单
     */
    private void checkIfCanApplyRefund(Order order){
        if (order == null){
            throw new RuntimeException("为查询到订单信息");
        }
        Integer status = order.getStatus();
        boolean flag = OrderStatus.NOT_DELIVERED.getType().equals(status) || OrderStatus.DELIVERED.getType().equals(status)
                || OrderStatus.COMPLETE.getType().equals(status);
        if (!flag){
            throw new RuntimeException("该订单无法申请售后");
        }
        if (OrderStatus.COMPLETE.getType().equals(order.getStatus()) &&
                DateUtils.betweenDay(LocalDateTime.now(), order.getReceiveTime()) > 7){
            throw new RuntimeException("订单确认收货时间已超过7天，无法申请售后");
        }
        if(OrderRefundStatus.APPLY.getType().equals(order.getAftersaleStatus())
                || OrderRefundStatus.WAIT.getType().equals(order.getAftersaleStatus())){
            throw new RuntimeException("售后正在处理中");
        }
    }

    public List<Order> getAllValidOrder() {
         return orderMapper.getAllValidOrder();
    }

    public List<Order> getOrdersByMemberId(Long memberId, Date startDate,Date endDate) {
        return orderMapper.getOrdersByMemberId(memberId,startDate,endDate);
    }
}
