package com.seer.teach.mall.app.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.seer.teach.common.enums.CommentStatusEnum;
import com.seer.teach.common.enums.OperateTypeEnum;
import com.seer.teach.common.enums.OrderStatusEnum;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.enums.ShippingStatusEnum;
import com.seer.teach.common.enums.UserTypeEnum;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.mall.app.order.service.IAppOrderRefundCallbackService;
import com.seer.teach.mall.entity.OrderChildEntity;
import com.seer.teach.mall.entity.OrderEntity;
import com.seer.teach.mall.entity.OrderLogEntity;
import com.seer.teach.mall.service.IOrderChildService;
import com.seer.teach.mall.service.IOrderLogService;
import com.seer.teach.mall.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 订单退款回调服务实现
 * 处理支付系统退款成功或失败后的订单状态更新
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AppOrderRefundCallbackServiceImpl implements IAppOrderRefundCallbackService {

    private final IOrderService orderService;
    private final IOrderChildService orderChildService;
    private final IOrderLogService orderLogService;

    /**
     * 订单取消退款成功通知
     *
     * @param orderSn 订单编号
     * @return 处理结果
     */
    public boolean cancelOrderRefundAfterSuccessNotify(String orderSn) {
        log.info("开始处理订单 {} 的退款成功回调", orderSn);

        try {
            // 查询订单信息
            OrderEntity order = orderService.getOne(new LambdaUpdateWrapper<OrderEntity>()
                    .eq(OrderEntity::getOrderSn, orderSn));

            AssertUtils.notNull(order, ResultCodeEnum.ORDER_NOT_FOUND);

            // 记录订单操作日志
            OrderLogEntity orderLog = getOrderLogEntity(order,"订单取消退款成功");
            orderLogService.save(orderLog);

            // 查询所有子订单
            List<OrderChildEntity> childOrders = orderChildService.list(new LambdaUpdateWrapper<OrderChildEntity>()
                    .eq(OrderChildEntity::getParentOrderId, order.getId()));

            if (childOrders.isEmpty()) {
                log.warn("未找到子订单，订单号: {}", orderSn);
                return false;
            }

            return true;
        } catch (Exception e) {
            log.error("处理订单 {} 退款成功回调时发生异常", orderSn, e);
            throw e;
        }
    }

    private OrderLogEntity getOrderLogEntity(OrderEntity order, String content) {
        OrderLogEntity orderLog = new OrderLogEntity();
        orderLog.setOrderId(order.getId());
        orderLog.setUserId(order.getUserId());
        orderLog.setUserType(UserTypeEnum.PARENT.getCode());
        orderLog.setOperateType(OperateTypeEnum.UPDATE.getCode());
        orderLog.setAfterStatus(OrderStatusEnum.CANCELED.getCode());
        orderLog.setBeforeStatus(OrderStatusEnum.CANCELED.getCode());
        orderLog.setContent(content);
        orderLog.setCommentStatus(CommentStatusEnum.NON_COMMENTED.getCode());
        orderLog.setShippingStatus(ShippingStatusEnum.NOT_SHIPPED.getCode());
        return orderLog;
    }

    /**
     * 处理退款失败回调
     * @param orderSn 订单编号
     * @return 处理结果
     */
    public boolean cancelOrderRefundAfterFailNotify(String orderSn) {
        log.info("开始处理订单 {} 的退款失败回调", orderSn);

        try {
            // 查询订单信息
            OrderEntity order = orderService.getOne(new LambdaUpdateWrapper<OrderEntity>()
                    .eq(OrderEntity::getOrderSn, orderSn));

            AssertUtils.notNull(order, ResultCodeEnum.ORDER_NOT_FOUND);

            // 记录订单操作日志
            OrderLogEntity orderLog = getOrderLogEntity(order,"订单取消退款失败，需要人工处理");
            orderLogService.save(orderLog);

            // 退款失败时，可以记录日志或发送通知，但不改变订单状态
            log.info("订单 {} 退款失败，需要人工处理", orderSn);

            return true;
        } catch (Exception e) {
            log.error("处理订单 {} 退款失败回调时发生异常", orderSn, e);
            throw e;
        }
    }
}