package com.ycwl.basic.order.controller;

import com.github.pagehelper.PageInfo;
import com.ycwl.basic.order.dto.*;
import com.ycwl.basic.order.service.IOrderService;
import com.ycwl.basic.utils.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 订单管理控制器V2 - 管理端
 */
@Slf4j
@RestController
@RequestMapping("/api/order/v2")
@RequiredArgsConstructor
public class OrderV2Controller {
    
    private final IOrderService orderService;
    
    /**
     * 分页查询订单列表
     */
    @PostMapping("/page")
    public ApiResponse<PageInfo<OrderV2ListResponse>> pageOrders(@RequestBody OrderV2PageRequest request) {
        log.info("分页查询订单列表: {}", request);
        try {
            PageInfo<OrderV2ListResponse> pageInfo = orderService.pageOrders(request);
            return ApiResponse.success(pageInfo);
        } catch (Exception e) {
            log.error("分页查询订单列表失败", e);
            return ApiResponse.fail("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询订单详情
     */
    @GetMapping("/detail/{orderId}")
    public ApiResponse<OrderV2DetailResponse> getOrderDetail(@PathVariable("orderId") Long orderId) {
        log.info("查询订单详情: orderId={}", orderId);
        try {
            OrderV2DetailResponse detail = orderService.getOrderDetail(orderId);
            if (detail == null) {
                return ApiResponse.fail("订单不存在");
            }
            return ApiResponse.success(detail);
        } catch (Exception e) {
            log.error("查询订单详情失败: orderId={}", orderId, e);
            return ApiResponse.fail("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新订单备注
     */
    @PutMapping("/remark/{orderId}")
    public ApiResponse<String> updateOrderRemarks(@PathVariable("orderId") Long orderId, 
                                                @RequestBody OrderRemarkRequest request) {
        log.info("更新订单备注: orderId={}, remarks={}", orderId, request.getRemarks());
        try {
            boolean success = orderService.updateOrderRemarks(orderId, request.getRemarks());
            if (success) {
                return ApiResponse.success("备注更新成功");
            } else {
                return ApiResponse.fail("备注更新失败");
            }
        } catch (Exception e) {
            log.error("更新订单备注失败: orderId={}", orderId, e);
            return ApiResponse.fail("更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 申请退款
     */
    @PostMapping("/refund")
    public ApiResponse<String> createRefund(@RequestBody RefundRequest request) {
        log.info("申请退款: {}", request);
        try {
            Long refundId = orderService.createRefundRecord(request);
            return ApiResponse.success("退款申请已提交，退款ID：" + refundId);
        } catch (Exception e) {
            log.error("申请退款失败: {}", request, e);
            return ApiResponse.fail("退款申请失败：" + e.getMessage());
        }
    }
}