package com.ruoyi.frequency.mallorder.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.code.DictConstant;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.page.PageResult;
import com.ruoyi.controller.req.*;
import com.ruoyi.controller.resp.MallOrderDetailResp;
import com.ruoyi.controller.resp.MallOrderPageResp;
import com.ruoyi.enums.IntegralDetailEnums;
import com.ruoyi.enums.MallExceptionEnum;
import com.ruoyi.enums.PlatformRecordEnums;
import com.ruoyi.enums.WalletDetailEnums;
import com.ruoyi.enums.mallorder.MallOrderStatusEnums;
import com.ruoyi.enums.mallorder.RefundStatusEnums;
import com.ruoyi.enums.message.OrderMessageEnums;
import com.ruoyi.frequency.customer.service.UserService;
import com.ruoyi.frequency.integralrecord.service.IntegralRecordService;
import com.ruoyi.frequency.mallevaluate.entity.MallEvaluate;
import com.ruoyi.frequency.mallevaluate.service.MallEvaluateService;
import com.ruoyi.frequency.mallgoods.entity.MallGoods;
import com.ruoyi.frequency.mallgoods.mapper.MallGoodsMapper;
import com.ruoyi.frequency.mallgoods.service.MallGoodsService;
import com.ruoyi.frequency.mallorder.entity.MallOrder;
import com.ruoyi.frequency.mallorder.mapper.MallOrderMapper;
import com.ruoyi.frequency.mallorder.model.result.MallOrderCount;
import com.ruoyi.frequency.mallorder.service.MallOrderService;
import com.ruoyi.frequency.mallorderaddress.entity.MallOrderAddress;
import com.ruoyi.frequency.mallorderaddress.service.MallOrderAddressService;
import com.ruoyi.frequency.mallordergoods.entity.MallOrderGoods;
import com.ruoyi.frequency.mallordergoods.service.MallOrderGoodsService;
import com.ruoyi.frequency.mallorderstatus.service.MallOrderStatusService;
import com.ruoyi.frequency.mallrefund.entity.MallRefund;
import com.ruoyi.frequency.mallrefund.service.MallRefundService;
import com.ruoyi.frequency.mallspecifications.entity.MallSpecifications;
import com.ruoyi.frequency.mallspecifications.mapper.MallSpecificationsMapper;
import com.ruoyi.frequency.mallspecifications.service.MallSpecificationsService;
import com.ruoyi.frequency.ordermessage.service.OrderMessageService;
import com.ruoyi.frequency.platformrecord.service.PlatformRecordService;
import com.ruoyi.pay.enums.PayEnums;
import com.ruoyi.pay.enums.PaySourceEnums;
import com.ruoyi.pay.utils.PayUtil;
import com.ruoyi.response.ResponseData;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.utils.BusinessUtil;
import com.ruoyi.vo.PayVo;
import com.ruoyi.vo.UserInfo;
import com.ruoyi.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单主Service业务层处理
 *
 * @author liwenlong
 * @date 2024-01-25
 */
@Service
public class MallOrderServiceImpl extends ServiceImpl<MallOrderMapper, MallOrder> implements MallOrderService {
    @Autowired
    private MallOrderMapper mallOrderMapper;

    @Autowired
    private MallOrderGoodsService orderGoodsService;

    /**
     * 查询订单主
     *
     * @param id 订单主主键
     * @return 订单主
     */
    @Override
    public MallOrder selectMallOrderById(Long id) {

        MallOrder mallOrder = mallOrderMapper.selectMallOrderById(id);

        if (mallOrder != null) {
            List<MallOrderGoods> mallOrderGoods = orderGoodsService.selectMallOrderGoodsList(new MallOrderGoods().setOrderId(id).setDelFlag(PublicCommon.启用));
            mallOrder.setMallOrderGoods(mallOrderGoods);

            Set<UserVo> userVoSet = CollectionUtil.newHashSet(new UserVo(mallOrder.getUserType(), mallOrder.getUserId()));

            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet, null);

            mallOrder.setUserInfo(userMap.get(new UserVo(mallOrder.getUserType(), mallOrder.getUserId())));

            //查询订单地址
            MallOrderAddress orderAddress = orderAddressService.getOne(new QueryWrapper<MallOrderAddress>().lambda()
                    .eq(MallOrderAddress::getOrderId, id)
                    .eq(MallOrderAddress::getDelFlag, PublicCommon.启用));
            mallOrder.setOrderAddress(orderAddress);

            //用户评价
            MallEvaluate evaluate = evaluateService.getOne(new QueryWrapper<MallEvaluate>().lambda()
                    .eq(MallEvaluate::getOrderId, id)
                    .eq(MallEvaluate::getDelFlag, PublicCommon.启用));
            mallOrder.setEvaluate(evaluate);

        }

        return mallOrder;
    }


    @Autowired
    private UserService userService;

    /**
     * 查询订单主列表
     *
     * @param mallOrder 订单主
     * @return 订单主
     */
    @Override
    public List<MallOrder> selectMallOrderList(MallOrder mallOrder) {
        List<MallOrder> mallOrders = mallOrderList(mallOrder);
        if (mallOrders.size() > 0) {

            //获取订单id
            List<Long> orderIdList = mallOrders.stream().map(MallOrder::getId).collect(Collectors.toList());
            //根据订单id 查询订单商品
            List<MallOrderGoods> orderGoodsList = orderGoodsService.orderGoodsList(orderIdList);

            //key 订单id value 订单商品
            Map<Long, List<MallOrderGoods>> orderGoodsVOMap = orderGoodsList.stream().collect(Collectors.groupingBy(MallOrderGoods::getOrderId));

            Set<UserVo> userVoSet = mallOrders.stream().map(s -> new UserVo(s.getUserType(), s.getUserId())).collect(Collectors.toSet());
            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet, null);

            mallOrders.stream().forEach(s -> {
                s.setMallOrderGoods(orderGoodsVOMap.get(s.getId()));
                s.setUserInfo(userMap.get(new UserVo(s.getUserType(), s.getUserId())));
            });

        }

        return mallOrders;
    }

    private List<MallOrder> mallOrderList(MallOrder mallOrder) {
        List<MallOrder> mallOrders = mallOrderMapper.selectMallOrderList(mallOrder);
        return mallOrders;
    }

    @Override
    public MallOrderCount statistics(MallOrder mallOrder) {
        List<MallOrder> mallOrders = mallOrderList(mallOrder);
        List<Long> mallOrderIdList = mallOrders.stream().map(x -> x.getId()).collect(Collectors.toList());
        mallOrderIdList.add(-1L);

        MallOrderCount count = mallOrderMapper.statistics(mallOrderIdList);
        return count;
    }

    /**
     * 新增订单主
     *
     * @param mallOrder 订单主
     * @return 结果
     */
    @Override
    public int insertMallOrder(MallOrder mallOrder) {
        mallOrder.setCreateData();
        return mallOrderMapper.insert(mallOrder);
    }

    /**
     * 修改订单主
     *
     * @param mallOrder 订单主
     * @return 结果
     */
    @Override
    public int updateMallOrder(MallOrder mallOrder) {
        mallOrder.setUpdateData();
        return mallOrderMapper.updateMallOrder(mallOrder);
    }

    /**
     * 批量删除订单主
     *
     * @param ids 需要删除的订单主主键
     * @return 结果
     */
    @Override
    public int deleteMallOrderByIds(Long[] ids, Integer delFlag) {
        this.lambdaUpdate().set(MallOrder::getDelFlag, delFlag).in(MallOrder::getId, ids).update();
        return ids.length;
    }

    @Autowired
    private OrderMessageService orderMessageService;

    @Override
    public AjaxResult send(MallOrder mallOrder) {
        MallOrder order = baseMapper.selectById(mallOrder.getId());

        //判断订单是否是售后状态
        Integer count = refundService.count(new QueryWrapper<MallRefund>().lambda()
                .eq(MallRefund::getOrderId, mallOrder.getId())
                .eq(MallRefund::getDelFlag, PublicCommon.启用)
                .eq(MallRefund::getStatus, 1)
        );
        if (count > 0) {
            return AjaxResult.error("退款申请中,请先处理退款申请");
        }
        if (!order.getOrderStatus().equals(MallOrderStatusEnums.待发货.getCode())) {
            return AjaxResult.error("订单状态错误 请刷新数据");
        }
        order.setOrderStatus(MallOrderStatusEnums.已发货.getCode());
        order.setSendComCourierId(mallOrder.getSendComCourierId());

        SysDictData dict = businessUtil.getDict(mallOrder.getDictCode());
        order.setSendComLogistics(dict.getDictLabel());
        order.setSendComLogisticsCode(dict.getDictValue());
        order.setSendTime(new Date());
        baseMapper.updateById(order);

        //订单流程状态
        orderStatusService.recordOrderStatus(order, MallOrderStatusEnums.已发货);

        //发送消息
        orderMessageService.addOrderMessage(new UserVo(order.getUserType(), order.getUserId()), order.getId(), "", PublicCommon.Order.商城订单, OrderMessageEnums.MALL_ORDER_SEND);

        return AjaxResult.success();
    }

    @Autowired
    private MallSpecificationsService specificationsService;

    @Autowired
    private MallGoodsService mallGoodsService;

    @Autowired
    private BusinessUtil businessUtil;

    @Override
    public PayVo settlement(MallSettlementReq req, UserVo userVo) {

        PayVo payVo = new PayVo();
        //规格
        MallSpecifications specifications = specificationsService.getById(req.getSpecId());

        //限制购买数量
        MallGoods mallGoods = mallGoodsService.getById(specifications.getGoodsId());
        if (mallGoods.getLimitNum() != null && mallGoods.getLimitNum() > 0) {
            //查询用户购买数量
            Integer hasBuyNum = baseMapper.hasBuyNum(mallGoods.getId(), userVo);
            if (hasBuyNum + req.getQuantity() > mallGoods.getLimitNum()) {
                Integer overNum = mallGoods.getLimitNum() - hasBuyNum;
                throw new ServiceException("该商品每人限买" + mallGoods.getLimitNum() + "件,你还可购买" + (overNum < 0 ? 0 : overNum) + "件");
            }
        }

        //支付金额
        BigDecimal price = specifications.getPrice().multiply(new BigDecimal(req.getQuantity()));
        payVo.setPrice(price);

        //支付积分
        BigDecimal integral = specifications.getIntegral().multiply(new BigDecimal(req.getQuantity()));
        payVo.setIntegral(integral);

        //最大使用赠送金额
        BigDecimal maxGivePrice = businessUtil.userMaxGivePrice(userVo, price);
        payVo.setMaxGivePrice(maxGivePrice);

        return payVo;
    }

    @Autowired
    private MallGoodsService goodsService;

    @Autowired
    private MallOrderAddressService orderAddressService;

    @Autowired
    private PayUtil payUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData createOrder(CreateOrderReq req, UserVo userVo) {

        //判断商品是否下架
        MallGoods goods = goodsService.getById(req.getGoodsId());
        MallSpecifications specifications = specificationsService.getById(req.getSpecId());

        if (ObjectUtil.notEqual(PublicCommon.启用, goods.getDelFlag()) || ObjectUtil.notEqual(PublicCommon.启用, specifications.getDelFlag())) {
            return ResponseData.error(MallExceptionEnum.GOODS_DEL_FLAG);
        }

        //限制购买数量
        if (goods.getLimitNum() != null && goods.getLimitNum() > 0) {
            //查询用户购买数量
            Integer hasBuyNum = baseMapper.hasBuyNum(goods.getId(), userVo);
            if (hasBuyNum + req.getQuantity() > goods.getLimitNum()) {
                throw new ServiceException("该商品每人限买" + goods.getLimitNum() + "件,你还可购买" + (goods.getLimitNum() - hasBuyNum) + "件");
            }
        }
        //计算金额
        PayVo payVo = settlement(new MallSettlementReq().setQuantity(req.getQuantity()).setSpecId(req.getSpecId()), userVo);

        //判断余额
        if (ObjectUtil.equal(PayEnums.balance.getCode(), req.getPayType())) {
            businessUtil.judgeBalancePay(userVo, payVo.getPrice(), req.getBalancePayPwd());
        }

        //判断积分余额
        businessUtil.judgeIntegralPay(userVo, payVo.getIntegral(), req.getBalancePayPwd());

        //扣除库存
        List<MallSpecifications> specList = CollectionUtil.toList(new MallSpecifications().setId(req.getSpecId()).setStock(req.getQuantity()));
        Boolean updateStock = specificationsMapper.subStock(specList);
        if (!updateStock) {
            throw new CustomException(MallExceptionEnum.NOT_STOCK);
        }

        //组装订单
        MallOrder order = assembleOrder(userVo, req, payVo);
        this.save(order);

        //关联订单商品中间表
        MallOrderGoods orderGoods = assembleOrderGoods(specifications, goods, req.getQuantity(), order.getId());
        orderGoodsService.save(orderGoods);

        //关联订单地址关联表
        MallOrderAddress orderAddress = orderAddressService.assembleOrderAddress(order.getId(), req.getAddressId());
        orderAddressService.saveOrUpdate(orderAddress);

        //记录订单状态
        orderStatusService.recordOrderStatus(order, MallOrderStatusEnums.待付款);

        //支付
        ResponseData responseData = payUtil.pay(userVo, order.getId(), req.getPayType(), payVo.getPrice().subtract(payVo.getMaxGivePrice()), payVo.getMaxGivePrice(), order.getPayOrderNo(), PaySourceEnums.mall_order_pay, WalletDetailEnums.MALL_ORDER_PAY);

        //支付成功/支付金额为0
        if (responseData.getSuccess() || responseData.getCode().equals(210)) {
            //余额支付/苹果支付
            if (req.getPayType().equals(PayEnums.balance.getCode()) || req.getPayType().equals(PayEnums.apple.getCode())) {
                after(order);
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", order.getId());
        responseData.setData(JSONObject.toJSON(map));
        return responseData;
    }

    /**
     * 组装订单商品
     *
     * @param specifications
     * @param goods
     * @param buyNum
     * @param orderId
     * @return
     */
    private MallOrderGoods assembleOrderGoods(MallSpecifications specifications, MallGoods goods, Integer buyNum, Long orderId) {

        //订单商品
        MallOrderGoods orderGoods = new MallOrderGoods()
                .setGoodsName(goods.getName())
                .setOrderId(orderId)
                .setGoodsImage(goods.getCoverImage())
                .setSpecImage(specifications.getImage())
                .setUnitPrice(specifications.getPrice())
                .setUnitIntegral(specifications.getIntegral())
                .setBuyNum(buyNum)
                .setSpecName(specifications.getName())
                .setGoodsId(specifications.getGoodsId())
                .setSpecId(specifications.getId());

        return orderGoods;
    }

    /**
     * 组装订单
     *
     * @param userVo
     * @param req
     * @param payVo
     * @return
     */
    private MallOrder assembleOrder(UserVo userVo, CreateOrderReq req, PayVo payVo) {

        MallOrder order = new MallOrder()
                .setOrderNo(generateOrderNo(1))
                .setUserId(userVo.getUserId())
                .setUserType(userVo.getUserType())
                .setGoodsPrice(payVo.getPrice())
                .setPayType(req.getPayType())
                .setRemark(req.getRemark())
                .setPayOrderNo(generateOrderNo(2))
                .setPayPrice(payVo.getPrice())
                .setOrderStatus(MallOrderStatusEnums.待付款.getCode())
                .setIntegralPrice(payVo.getIntegral())
                .setGivePrice(payVo.getMaxGivePrice());

        //售后时间
        SysDictData dictOne = businessUtil.getDict(DictConstant.MallOrderDict.售后天数);
        order.setAfterSalesDays(dictOne == null ? 7 : Integer.valueOf(dictOne.getDictValue()));

        return order;
    }


    /**
     * 生成订单号
     *
     * @param type 1订单号 2 支付单号
     * @return
     */
    @Override
    public String generateOrderNo(Integer type) {
        String orderNo;
        String prefix = type == 1 ? "JF" : "JFP";

        while (true) {
            orderNo = prefix + DateUtil.format(new Date(), "MMdd" + RandomUtil.randomNumbers(6));
            MallOrder old = this.getBaseMapper().selectOne(new QueryWrapper<MallOrder>().lambda()
                    .eq(type == 1, MallOrder::getOrderNo, orderNo)
                    .eq(type == 2, MallOrder::getPayOrderNo, orderNo)

            );
            if (old == null) {
                break;
            }
        }
        return orderNo;
    }

    @Autowired
    private MallSpecificationsMapper specificationsMapper;

    @Autowired
    private MallOrderStatusService orderStatusService;

    @Autowired
    private IntegralRecordService integralRecordService;

    @Autowired
    private MallGoodsMapper mallGoodsMapper;

    @Override
    public void after(MallOrder order) {

        //扣除积分
        integralRecordService.updateIntegral(new UserVo(order.getUserType(), order.getUserId()), order.getId(), order.getIntegralPrice().negate(), IntegralDetailEnums.ORDER_PAY,null);

        //修改订单状态
        boolean update = this.lambdaUpdate().set(MallOrder::getOrderStatus, MallOrderStatusEnums.待发货.getCode())
                .set(MallOrder::getPayStatus, PublicCommon.Pay.已支付)
                .set(MallOrder::getPayTime, new Date())
                .eq(MallOrder::getId, order.getId())
                .eq(MallOrder::getOrderStatus, MallOrderStatusEnums.待付款.getCode())
                .update();

        if (update) {
            //查询订单商品
            List<MallOrderGoods> orderGoods = orderGoodsService.list(new QueryWrapper<MallOrderGoods>().lambda()
                    .eq(MallOrderGoods::getOrderId, order.getId())
                    .eq(MallOrderGoods::getDelFlag, PublicCommon.启用));

            //增加销量
            List<MallSpecifications> specList = orderGoods.stream().map(s -> new MallSpecifications().setId(s.getSpecId()).setSales(s.getBuyNum())).collect(Collectors.toList());
            specificationsMapper.addSales(specList);

            List<MallGoods> mallGoodsList = orderGoods.stream().map(s -> new MallGoods().setId(s.getGoodsId()).setSales(s.getBuyNum())).collect(Collectors.toList());
            mallGoodsMapper.addSales(mallGoodsList);


            //记录订单状态
            orderStatusService.recordOrderStatus(order, MallOrderStatusEnums.待发货);
        }

        //订单消息
        orderMessageService.addOrderMessage(new UserVo(order.getUserType(), order.getUserId()), order.getId(), "", PublicCommon.Order.商城订单, OrderMessageEnums.MALL_PAY_ORDER);

    }

    @Override
    public ResponseData orderPage(MallOrderPageReq req, UserVo userVo) {
        Page<MallOrderPageResp> page = this.baseMapper.orderPage(new Page<>(req.getPageNo(), req.getPageSize()), req, userVo);

        if (page.getRecords().size() > 0) {

            //获取订单id
            List<Long> orderIdList = page.getRecords().stream().map(MallOrderPageResp::getOrderId).collect(Collectors.toList());
            //根据订单id 查询订单商品
            List<MallOrderGoods> orderGoodsList = orderGoodsService.orderGoodsList(orderIdList);

            //key 订单id value 订单商品
            Map<Long, List<MallOrderGoods>> orderGoodsVOMap = orderGoodsList.stream().collect(Collectors.groupingBy(MallOrderGoods::getOrderId));

            page.getRecords().stream().forEach(s -> {
                s.setOrderGoodsList(orderGoodsVOMap.get(s.getOrderId()));
            });

        }

        return ResponseData.success(new PageResult<>(page));
    }

    @Override
    public List<MallOrderPageResp> orderList(List<Long> mallOrderIds, UserVo userVo) {

        if (mallOrderIds.size() == 0) {
            return new ArrayList<>();
        }

        List<MallOrderPageResp> list = this.baseMapper.orderList(mallOrderIds, userVo);

        if (list.size() > 0) {

            //获取订单id
            List<Long> orderIdList = list.stream().map(MallOrderPageResp::getOrderId).collect(Collectors.toList());
            //根据订单id 查询订单商品
            List<MallOrderGoods> orderGoodsList = orderGoodsService.orderGoodsList(orderIdList);

            //key 订单id value 订单商品
            Map<Long, List<MallOrderGoods>> orderGoodsVOMap = orderGoodsList.stream().collect(Collectors.groupingBy(MallOrderGoods::getOrderId));

            list.stream().forEach(s -> {
                s.setOrderGoodsList(orderGoodsVOMap.get(s.getOrderId()));
            });

        }

        return list;
    }

    @Autowired
    private MallEvaluateService evaluateService;

    @Override
    public ResponseData orderDetail(Long orderId, UserVo userVo) {
        MallOrderDetailResp orderDetailResp = this.baseMapper.orderDetail(orderId);

        if (orderDetailResp != null) {
            List<Long> orderIdList = new ArrayList<>();
            orderIdList.add(orderId);
            //根据订单id 查询订单商品
            List<MallOrderGoods> orderGoodsList = orderGoodsService.orderGoodsList(orderIdList);
            orderDetailResp.setOrderGoodsList(orderGoodsList);

            //查询订单地址
            MallOrderAddress orderAddress = orderAddressService.getOne(new QueryWrapper<MallOrderAddress>().lambda()
                    .eq(MallOrderAddress::getOrderId, orderId)
                    .eq(MallOrderAddress::getDelFlag, PublicCommon.启用));
            orderDetailResp.setOrderAddress(orderAddress);

            //用户评价
            MallEvaluate evaluate = evaluateService.getOne(new QueryWrapper<MallEvaluate>().lambda()
                    .eq(MallEvaluate::getOrderId, orderId)
                    .eq(MallEvaluate::getDelFlag, PublicCommon.启用));
            orderDetailResp.setEvaluate(evaluate);
        }

        return ResponseData.success(orderDetailResp);
    }

    @Override
    public ResponseData orderPay(MallOrderPayReq req, UserVo userVo) {
        return null;
    }

    @Override
    public ResponseData orderCancel(Long orderId, UserVo userVo) {

        MallOrder order = this.getById(orderId);

        //判断订单状态
        if (!order.getOrderStatus().equals(MallOrderStatusEnums.待付款.getCode())) {
            return ResponseData.error(MallExceptionEnum.ORDER_STATUS_ERROR);
        }

        //修改订单状态
        boolean update = this.lambdaUpdate().set(MallOrder::getOrderStatus, MallOrderStatusEnums.已取消.getCode())
                .eq(MallOrder::getOrderStatus, MallOrderStatusEnums.待付款.getCode())
                .eq(MallOrder::getId, orderId)
                .update();
        if (update) {
            //查询订单商品
            List<MallOrderGoods> orderGoods = orderGoodsService.list(new QueryWrapper<MallOrderGoods>().lambda()
                    .eq(MallOrderGoods::getOrderId, order.getId())
                    .eq(MallOrderGoods::getDelFlag, PublicCommon.启用));

            //添加库存
            List<MallSpecifications> specList = orderGoods.stream().map(s -> new MallSpecifications().setId(s.getSpecId()).setStock(s.getBuyNum())).collect(Collectors.toList());
            specificationsMapper.subStock(specList);

            //记录订单状态
            orderStatusService.recordOrderStatus(order, MallOrderStatusEnums.已取消);

        }

        return ResponseData.success();
    }

    @Override
    public ResponseData orderRefund(Long orderId, UserVo userVo) {
        MallOrder order = this.getById(orderId);

        //判断订单状态
        if (!order.getOrderStatus().equals(MallOrderStatusEnums.待发货.getCode())) {
            return ResponseData.error(MallExceptionEnum.ORDER_STATUS_ERROR);
        }

        //修改订单状态
        boolean update = this.lambdaUpdate().set(MallOrder::getOrderStatus, MallOrderStatusEnums.已取消.getCode())
                .eq(MallOrder::getOrderStatus, MallOrderStatusEnums.待发货.getCode())
                .eq(MallOrder::getId, orderId)
                .update();
        if (update) {
            //查询订单商品
            List<MallOrderGoods> orderGoods = orderGoodsService.list(new QueryWrapper<MallOrderGoods>().lambda()
                    .eq(MallOrderGoods::getOrderId, order.getId())
                    .eq(MallOrderGoods::getDelFlag, PublicCommon.启用));

            //添加库存
            List<MallSpecifications> specList = orderGoods.stream().map(s -> new MallSpecifications().setId(s.getSpecId()).setStock(s.getBuyNum()).setSales(s.getBuyNum())).collect(Collectors.toList());
            specificationsMapper.addStock(specList);

            //扣除销量
            specificationsMapper.subSales(specList);

            List<MallGoods> mallGoodsList = orderGoods.stream().map(s -> new MallGoods().setId(s.getGoodsId()).setSales(s.getBuyNum())).collect(Collectors.toList());
            mallGoodsMapper.addSales(mallGoodsList);

            //退款
            ResponseData responseData = payUtil.refund(new UserVo(order.getUserType(), order.getUserId()), order.getId(), order.getPayType(), order.getPayPrice().subtract(order.getGivePrice()), order.getPayPrice().subtract(order.getGivePrice()), order.getPayOrderNo(), order.getAliReturnPayId(), order.getGivePrice());
            if (!responseData.getSuccess()) {
                log.error("退款失败：" + order.getOrderNo());
                return responseData;
            }

            //记录订单状态
            orderStatusService.recordOrderStatus(order, MallOrderStatusEnums.已取消);

        }

        return ResponseData.success();
    }

    @Override
    public ResponseData orderConfirm(MallOrderConfirmReq req, UserVo userVo) {

        MallOrder order = baseMapper.selectById(req.getOrderId());

        //判断该订单状态
        if (ObjectUtil.notEqual(MallOrderStatusEnums.已发货.getCode(), order.getOrderStatus())) {
            return ResponseData.error(MallExceptionEnum.ORDER_STATUS_ERROR);
        }

        //是否直接分佣（1用户确认收货直接到账，直接分佣 2 售后时间过后分佣）
        Integer isDirect = 2;

        //是否允许退货
        if (isDirect == 2) {

            boolean update = this.lambdaUpdate().set(MallOrder::getOrderStatus, MallOrderStatusEnums.已完成.getCode())
                    .set(MallOrder::getReceiveTime, new Date())
                    .eq(MallOrder::getId, order.getId()).update();
            if (update) {
                orderStatusService.recordOrderStatus(order, MallOrderStatusEnums.已完成);
            }
        } else {
            boolean update = this.lambdaUpdate().set(MallOrder::getOrderStatus, MallOrderStatusEnums.已到账.getCode())
                    .set(MallOrder::getReceiveTime, new Date())
                    .set(MallOrder::getArrivalTime, new Date())
                    .set(MallOrder::getCompleteTime, new Date())
                    .eq(MallOrder::getId, order.getId()).update();

            //记录订单状态
            if (update) {
                orderStatusService.recordOrderStatus(order, MallOrderStatusEnums.已到账);

                //分佣
                distributeCommission(order);
            }
        }

        return ResponseData.success();
    }

    @Autowired
    private PlatformRecordService platformRecordService;

    /**
     * 分佣
     *
     * @param order
     */

    public ResponseData distributeCommission(MallOrder order) {

        //平台收益
        BigDecimal platCommission = order.getPayPrice();

        //平台流水
        platformRecordService.addPlatformRecord(new UserVo(order.getUserType(), order.getUserId()), order.getId(), platCommission, PlatformRecordEnums.MALL_ORDER_PAY);

        return ResponseData.success();
    }

    @Autowired
    private MallRefundService refundService;

    @Override
    public ResponseData orderAfterApply(ApplyAfterSalesReq req, UserVo userVo) {

        MallOrder order = baseMapper.selectById(req.getOrderId());

        if (ObjectUtil.notEqual(MallOrderStatusEnums.已完成.getCode(), order.getOrderStatus())) {
            return ResponseData.error(MallExceptionEnum.ORDER_STATUS_ERROR);
        }

        MallRefund refund = null;
        if (ObjectUtil.isNotEmpty(req.getRefundId())) {
            refund = refundService.getById(req.getRefundId());
            if (!refund.getStatus().equals(RefundStatusEnums.待审核.getCode())) {
                return ResponseData.error(MallExceptionEnum.ORDER_REPEAT_APPLY);
            }
        } else {
            refundService.getOne(new QueryWrapper<MallRefund>().lambda().eq(MallRefund::getOrderId, req.getOrderId())
                    .eq(MallRefund::getDelFlag, PublicCommon.启用)
                    .orderByDesc(MallRefund::getCreateTime).last(" limit 1"));
            if (refund != null) {
                if (refund.getStatus() != 5) {
                    return ResponseData.error(MallExceptionEnum.ORDER_REPEAT_APPLY);
                }
            } else {
                refund = new MallRefund();
            }
        }

        refund.setOrderId(req.getOrderId());
        refund.setRefundImages(req.getRefundImages());
        refund.setRefundReason(req.getRefundReason());
        refund.setRefundExplain(req.getRefundExplain());
        refund.setRefundType(2);
        refund.setStatus(1);
        refund.setRefundPrice(order.getPayPrice());
        refundService.saveOrUpdate(refund);

        //订单消息
        orderMessageService.addOrderMessage(new UserVo(order.getUserType(), order.getUserId()), order.getId(), "", PublicCommon.Order.商城订单, OrderMessageEnums.MALL_ORDER_REFUND);

        return ResponseData.success();
    }

    @Override
    public ResponseData orderAfterDetail(Long orderId, UserVo userVo) {
        MallRefund refund = refundService.getOne(new QueryWrapper<MallRefund>().lambda().eq(MallRefund::getOrderId, orderId)
                .orderByDesc(MallRefund::getCreateTime).last(" limit 1"));

        if (refund != null) {
            List<Long> orderIdList = new ArrayList<>();
            orderIdList.add(orderId);
            //根据订单id 查询订单商品
            List<MallOrderGoods> orderGoodsList = orderGoodsService.orderGoodsList(orderIdList);
            refund.setOrderGoodsList(orderGoodsList);
        }

        return ResponseData.success(refund);
    }

    @Override
    public ResponseData orderAfterRevokeApply(Long refundId, UserVo userVo) {

        boolean update = refundService.lambdaUpdate().set(MallRefund::getDelFlag, PublicCommon.删除)
                .eq(MallRefund::getStatus, RefundStatusEnums.待审核.getCode())
                .eq(MallRefund::getId, refundId).update();
        if (!update) {
            return ResponseData.error(MallExceptionEnum.ORDER_STATUS_ERROR);
        }

        return ResponseData.success();
    }

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Override
    public ResponseData customerDeliverGoods(CustomerDeliverGoodsReq req) {
        MallRefund refund = new MallRefund();
        if (ObjectUtil.isNotEmpty(req.getRefundId())) {
            refund = refundService.getById(req.getRefundId());
        } else {
            refund = refundService.getOne(new QueryWrapper<MallRefund>().lambda().eq(MallRefund::getOrderId, req.getOrderId())
                    .eq(MallRefund::getOrderType, req.getOrderType())
                    .eq(MallRefund::getDelFlag, PublicCommon.启用)
                    .orderByDesc(MallRefund::getCreateTime).last(" limit 1"));
        }

        //只有退款退货类型才需要判断状态，只退款类型不需要判断状态，随时可退
        if (refund.getRefundType() != 2 || ObjectUtil.notEqual(RefundStatusEnums.商家同意退款退货.getCode(), refund.getStatus())) {
            return ResponseData.error("订单状态错误 请刷新数据");
        }
        //如果是退货，需要修改退货状态
        if (refund.getRefundType() == 2) {
            refund.setStatus(RefundStatusEnums.用户发货.getCode());
        }
        refund.setComCourierId(req.getComCourierId());
        SysDictData dict = sysDictDataMapper.selectDictDataById(req.getDictId());
        refund.setComLogistics(dict.getDictLabel());
        refund.setComLogisticsCode(dict.getDictValue());
        refundService.updateById(refund);
        return ResponseData.success();
    }


    @Override
    public ResponseData evaluate(MallEvaluateReq req, UserVo userVo) {

        MallOrder order = this.getById(req.getOrderId());

        //判断订单状态
        if (ObjectUtil.notEqual(MallOrderStatusEnums.已完成.getCode(), order.getOrderStatus())
                && ObjectUtil.notEqual(MallOrderStatusEnums.已到账.getCode(), order.getOrderStatus())
        ) {
            return ResponseData.error(MallExceptionEnum.ORDER_STATUS_ERROR);
        }

        MallEvaluate evaluate = new MallEvaluate();
        BeanUtil.copyProperties(req, evaluate);
        evaluate.setUserId(userVo.getUserId())
                .setUserType(userVo.getUserType());
        evaluateService.save(evaluate);

        return ResponseData.success();
    }

    @Override
    public ResponseData onceAgainCreateOrder(OnceAgainCreateOrderReq req, UserVo userVo) {
        return null;
    }


}
