package com.dora.service.impl;

import com.dora.dto.OrderDto;
import com.dora.mapper.OrderMapper;
import com.dora.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;

    @Override
    public OrderDto.OrderListResponse getUserOrders(Long userId, Integer page, Integer size) {
        OrderDto.OrderListResponse response = new OrderDto.OrderListResponse();
        
        try {
            int offset = (page - 1) * size;
            List<OrderDto.OrderListItem> records = new ArrayList<>();
            
            // 获取用户订单列表（包含套餐信息）
            List<OrderMapper.OrderWithPlanInfo> ordersWithPlanInfo = 
                orderMapper.selectByUserIdWithPlanInfo(userId, offset, size);
            
            for (OrderMapper.OrderWithPlanInfo orderWithPlanInfo : ordersWithPlanInfo) {
                OrderDto.OrderListItem record = new OrderDto.OrderListItem();
                record.setId(orderWithPlanInfo.getId());
                record.setOrderNo(orderWithPlanInfo.getOrderNo());
                record.setPlanName(orderWithPlanInfo.getPlanName());
                record.setAmount(orderWithPlanInfo.getAmount());
                record.setStatus(orderWithPlanInfo.getStatus());
                record.setStatusText(getStatusText(orderWithPlanInfo.getStatus()));
                record.setPaymentMethod(orderWithPlanInfo.getPaymentMethod());
                record.setPaymentMethodText(getPaymentMethodText(orderWithPlanInfo.getPaymentMethod()));
                record.setCreateTime(orderWithPlanInfo.getCreateTime());
                record.setPaidAt(orderWithPlanInfo.getPaidAt());
                records.add(record);
            }
            
            int total = orderMapper.countByUserId(userId);
            
            response.setSuccess(true);
            response.setMessage("获取成功");
            response.setRecords(records);
            response.setTotal(total);
            response.setPage(page);
            response.setSize(size);
            
            log.info("获取用户订单列表成功 - userId: {}, 记录数: {}, 总数: {}", 
                    userId, records.size(), total);
            
        } catch (Exception e) {
            log.error("获取用户订单列表失败 - userId: {}", userId, e);
            response.setSuccess(false);
            response.setMessage("获取失败：" + e.getMessage());
        }
        
        return response;
    }

    @Override
    public OrderDto.OrderDetailResponse getOrderDetail(Long userId, Long orderId) {
        OrderDto.OrderDetailResponse response = new OrderDto.OrderDetailResponse();
        
        try {
            // 获取订单详情（包含套餐信息）
            OrderMapper.OrderWithPlanInfo orderWithPlanInfo = 
                orderMapper.selectByIdWithPlanInfo(orderId, userId);
            
            if (orderWithPlanInfo == null) {
                response.setSuccess(false);
                response.setMessage("订单不存在或无权限访问");
                return response;
            }
            
            OrderDto.OrderDetail orderDetail = new OrderDto.OrderDetail();
            orderDetail.setId(orderWithPlanInfo.getId());
            orderDetail.setOrderNo(orderWithPlanInfo.getOrderNo());
            orderDetail.setPlanId(orderWithPlanInfo.getPlanId());
            orderDetail.setPlanName(orderWithPlanInfo.getPlanName());
            orderDetail.setPlanDescription(orderWithPlanInfo.getPlanDescription());
            orderDetail.setPlanPrice(orderWithPlanInfo.getPlanPrice());
            orderDetail.setDurationDays(orderWithPlanInfo.getDurationDays());
            orderDetail.setTargetRole(orderWithPlanInfo.getTargetRole());
            orderDetail.setAmount(orderWithPlanInfo.getAmount());
            orderDetail.setStatus(orderWithPlanInfo.getStatus());
            orderDetail.setStatusText(getStatusText(orderWithPlanInfo.getStatus()));
            orderDetail.setPaymentMethod(orderWithPlanInfo.getPaymentMethod());
            orderDetail.setPaymentMethodText(getPaymentMethodText(orderWithPlanInfo.getPaymentMethod()));
            orderDetail.setCreateTime(orderWithPlanInfo.getCreateTime());
            orderDetail.setPaidAt(orderWithPlanInfo.getPaidAt());
            orderDetail.setUpdateTime(orderWithPlanInfo.getUpdateTime());
            
            response.setSuccess(true);
            response.setMessage("获取成功");
            response.setOrder(orderDetail);
            
            log.info("获取订单详情成功 - userId: {}, orderId: {}", userId, orderId);
            
        } catch (Exception e) {
            log.error("获取订单详情失败 - userId: {}, orderId: {}", userId, orderId, e);
            response.setSuccess(false);
            response.setMessage("获取失败：" + e.getMessage());
        }
        
        return response;
    }

    /**
     * 获取订单状态描述
     * @param status 订单状态
     * @return 状态描述
     */
    private String getStatusText(Integer status) {
        if (status == null) return "未知状态";
        switch (status) {
            case 0: return "待支付";
            case 1: return "已完成";
            case 2: return "已取消";
            case 3: return "支付失败";
            default: return "未知状态";
        }
    }

    /**
     * 获取支付方式描述
     * @param paymentMethod 支付方式
     * @return 支付方式描述
     */
    private String getPaymentMethodText(Integer paymentMethod) {
        if (paymentMethod == null) return "未知";
        switch (paymentMethod) {
            case 1: return "支付宝";
            case 2: return "微信支付";
            default: return "未知";
        }
    }
} 