package com.yami.shop.platform.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yami.shop.bean.dto.OrderRefundDto;
import com.yami.shop.bean.enums.OrderStatus;
import com.yami.shop.bean.enums.RefundStatusEnum;
import com.yami.shop.bean.enums.ReturnMoneyStsType;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.bean.model.OrderRefund;
import com.yami.shop.bean.param.OrderRefundParam;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.enums.YamiHttpStatus;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.delivery.comment.model.DeliveryOrder;
import com.yami.shop.delivery.comment.service.DeliveryOrderService;
import com.yami.shop.platform.controller.OrderRefundController;
import com.yami.shop.service.OrderItemService;
import com.yami.shop.service.OrderRefundService;
import com.yami.shop.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component("orderRefundTask")
public class OrderRefundTask {

    @Autowired
    private OrderRefundService orderRefundService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private DeliveryOrderService deliveryOrderService;

    @Autowired
    private OrderService orderService;


    /**
     * 取消申请超时的订单，无论该超时订单处于任何状态
     */
    public void cancelWhenTimeOut() {
        log.info("==============订单退款超时处理开始===================");
        // 设定时间值
        Date date = DateUtil.offsetDay(new Date(), -Constant.MAX_REFUND_APPLY_TIME);
        // 获取待处理的退款订单
        List<OrderRefund> orderRefundList = orderRefundService.list(new LambdaQueryWrapper<OrderRefund>()
                .in(OrderRefund::getReturnMoneySts, Arrays.asList(ReturnMoneyStsType.APPLY.value(), ReturnMoneyStsType.PROCESSING.value(), ReturnMoneyStsType.CONSIGNMENT.value(), ReturnMoneyStsType.RECEIVE.value()))
                .lt(OrderRefund::getApplyTime, date));
        if (CollectionUtils.isNotEmpty(orderRefundList)) {
            orderRefundService.cancelWhenTimeOut(orderRefundList);
        }
        log.info("==============订单退款超时处理结束===================");
    }

    /**
     * 获取买家发起配送给后24小时后未关闭的订单
     */
    public void confirmOrderRefund() {
        log.info("==============买家发货后24小时后订单处理===================");
        // 设定时间值
        //获取用户已发货的订单，一天后商家取消订单
        Date date = DateUtil.offsetDay(new Date(), -1);
        // 获取待处理的退款订单
        List<OrderRefund> orderRefundList = orderRefundService.list(new LambdaQueryWrapper<OrderRefund>()
                .eq(OrderRefund::getReturnMoneySts, ReturnMoneyStsType.CONSIGNMENT)
                .lt(OrderRefund::getShipTime, date));
        if (CollectionUtils.isNotEmpty(orderRefundList)) {

            for (OrderRefund orderRefund : orderRefundList) {
                // 获取退款信息
                OrderRefundDto orderRefundDto = orderRefundService.getOrderRefundByRefundSn(orderRefund.getRefundSn());
                if (orderRefundDto == null) {
                    throw new GlobalException("退款单不存在");
                }
                if (orderRefundDto.getDecisionTime() == null) {
                    throw new GlobalException("请先确定退款，才能发起退款操作");
                }

                if (orderRefundDto.getRefundTime() != null) {
                    throw new GlobalException("已退款成功，无法再申请退款操作");
                }
                if (Objects.equals(-1, orderRefundDto.getReturnMoneySts())) {
                    throw new GlobalException("买家已取消申请");
                }
                // 提交退款请求
                orderRefundService.submitWxRefund(orderRefundDto);
            }
        }
        log.info("==============买家发货后24小时后订单处理===================");
    }


    // 自动审核退款
    public void agreeRefund() {
        // 设定时间值
        //获取用户已发货的订单，一天后商家取消订单
        Date date1 = DateUtil.offsetDay(new Date(), -1);
        // 获取待处理的退款订单
        List<OrderRefund> orderRefundList = orderRefundService.list(new LambdaQueryWrapper<OrderRefund>()
                .eq(OrderRefund::getReturnMoneySts, 1)
                .lt(OrderRefund::getApplyTime, date1));
        if (CollectionUtils.isNotEmpty(orderRefundList)) {

            for (OrderRefund orderRefund : orderRefundList) {
                OrderRefundParam orderRefundParam = new OrderRefundParam();
                orderRefundParam.setRefundId(orderRefund.getRefundId());
                orderRefundParam.setRefundSn(orderRefund.getRefundSn());
                orderRefundParam.setRefundSts(2);
                orderRefundParam.setPayer("1");

                // 处理退款操作
                OrderRefundDto orderRefundDto = orderRefundService.processRefundOrder(orderRefundParam, orderRefund.getShopId());

                // 仅退款，执行退款操作
                if (Objects.equals(orderRefundDto.getApplyType(), 1)) {
                    orderRefundService.submitWxRefund(orderRefundDto);
                }
                if (orderRefundDto.getReturnMoneySts() == 5) {
                    // 将orderItem.status改成 0 表示可以发货
                    OrderItem orderItem = orderItemService.getOne(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderItemId, orderRefundDto.getOrderItemId()));
                    if (Objects.isNull(orderItem)) {
                        return;
                    }
                    String orderNumber = orderItem.getOrderNumber();
                    List<OrderItem> orderItems1 = orderItemService.list(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderNumber, orderNumber));
                    if (orderItems1.size() <= 1) {
                        return;
                    }
                    orderItemService.update(new LambdaUpdateWrapper<OrderItem>()
                            .set(OrderItem::getStatus, 0)
                            .eq(OrderItem::getOrderItemId, orderItem.getOrderItemId()));
                    // 如果该单是商品项目的所有订单都是已发货，其他的都是退款成功，则可以改成订单项发货状态
                    List<OrderItem> orderItems = orderItemService.list(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderNumber, orderNumber));
                    // 如果所有的订单都是申请退款，并且退款成功，则不改变
                    int total = 0;
                    for (OrderItem item : orderItems) {
                        int count = orderRefundService.count(new LambdaQueryWrapper<OrderRefund>()
                                .eq(OrderRefund::getOrderItemId, item.getOrderItemId())
                                .eq(OrderRefund::getReturnMoneySts, 5));
                        if (count > 0) {
                            total++;
                        }
                    }
                    // 所有订单都是退款成功
                    if (total == orderItems.size()) {
                        return;
                    }
                    boolean isOk = true;
                    for (OrderItem item : orderItems) {
                        if (item.getStatus() != 0) {
                            isOk = false;
                            break;
                        }
                    }
                    // 所有的订单，有已发货的订单

                    if (isOk) {
                        Order order = new Order();
                        order.setOrderId(orderRefundDto.getOrderId());
                        // 更新到发货状态
                        Date date = new Date();
                        order.setHbOrderStatus(OrderStatus.CONSIGNMENT.value());
                        order.setUpdateTime(date);
                        order.setDvyTime(date);
                        Integer type = null;
                        for (OrderItem item : orderItems) {
                            if (Objects.nonNull(item.getDvyType())) {
                                type = item.getDvyType();
                            }
                        }
                        List<DeliveryOrder> deliveryOrders = deliveryOrderService.list(new LambdaQueryWrapper<DeliveryOrder>().eq(DeliveryOrder::getOrderNumber, orderNumber));
                        if (!CollectionUtils.isEmpty(deliveryOrders)) {
                            order.setDvyType(1);
                        } else {
                            order.setDvyType(type);
                        }
                        orderService.updateById(order);
                    }

                }

            }
        }
        log.info("==============买家发货后24小时后订单处理===================");
    }


    public void closeRefund() {
        // 设定时间值
        //获取用户已发货的订单，一天后商家取消订单
        Date date1 = DateUtil.offsetDay(new Date(), -2);
        // 获取待处理的退款订单
        List<OrderRefund> orderRefundList = orderRefundService.list(new LambdaQueryWrapper<OrderRefund>()
                .eq(OrderRefund::getReturnMoneySts, 2)
                .lt(OrderRefund::getApplyTime, date1));
        orderRefundService.cancelWhenTimeOut(orderRefundList);
    }
}
