package com.erp.order.controller;

import com.erp.order.dto.request.*;
import com.erp.order.dto.response.*;
import com.erp.order.service.OrderService;
import com.erp.order.service.OrderService.OperatorInfo;
import com.erp.order.service.OrderService.StatusOption;
import com.erp.order.service.OrderService.ShopOption;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import com.erp.common.core.model.ApiResponse;

@Slf4j
@RestController
@RequestMapping("/api/orders")
@RequiredArgsConstructor
public class OrderController {

    private final OrderService orderService;

    // ============ 订单查询 ============

    @GetMapping
    public ApiResponse<OrderPageResponse> listOrders(OrderQueryRequest request) {
        return ApiResponse.success(orderService.listOrders(request));
    }

    @GetMapping("/{id}")
    public ApiResponse<OrderResponse> getOrder(@PathVariable("id") Long id) {
        return ApiResponse.success(orderService.getOrder(id));
    }

    // ============ 订单拉取 & 创建 ============

    @PostMapping("/pull")
    public ApiResponse<?> pullOrders(@Valid @RequestBody PullOrdersRequest request) {
        OrderService.PullOrdersResult result = orderService.pullOrders(request);
        return ApiResponse.success(String.format("成功拉取 %d 个订单", result.getCount(), result));
    }

    // ============ 待审核 & 待匹配订单查询 ============

    /**
     * 获取待审核订单列表
     * @description 查询 audit_status = 'pending' 的订单
     */
    @GetMapping("/pending-audit")
    public ApiResponse<OrderPageResponse> listPendingAuditOrders(
            @RequestParam(value = "platform", required = false) String platform,
            @RequestParam(value = "shopId", required = false) Long shopId,
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "limit", defaultValue = "10") int limit) {
        return ApiResponse.success(orderService.listPendingAuditOrders(platform, shopId, keyword, page, limit));
    }

    /**
     * 获取待匹配订单列表
     * @description 查询存在订单项但 erp_sku_id 为空的订单（商品尚未匹配到ERP商品）
     */
    @GetMapping("/pending-match")
    public ApiResponse<OrderPageResponse> listPendingMatchOrders(
            @RequestParam(value = "platform", required = false) String platform,
            @RequestParam(value = "shopId", required = false) Long shopId,
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "limit", defaultValue = "10") int limit) {
        return ApiResponse.success(orderService.listPendingMatchOrders(platform, shopId, keyword, page, limit));
    }

    // ============ 订单审核 ============

    @PostMapping("/{id}/audit")
    public ApiResponse<OrderResponse> auditOrder(
            @PathVariable("id") Long id,
            @RequestParam("action") String action,
            @RequestParam(value = "comment", required = false) String comment,
            HttpServletRequest request) {
        OperatorInfo operator = buildOperatorInfo(request);
        OrderResponse result = orderService.auditOrder(id, action, comment, operator);
        String message = "approve".equals(action) ? "订单审核通过" : "订单已驳回";
        return ApiResponse.success(message, result);
    }

    @PostMapping("/batch-audit")
    public ApiResponse<BatchOperationResult> batchAudit(
            @Valid @RequestBody BatchAuditRequest request,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        BatchOperationResult result = orderService.batchAudit(request, operator);
        return ApiResponse.success(String.format("成功审核 %d 个订单", result.getSuccessCount()), result);
    }

    // ============ 仓库 & 发货 ============

    @PutMapping("/{id}/warehouse")
    public ApiResponse<OrderResponse> setWarehouseExpress(
            @PathVariable("id") Long id,
            @RequestBody SetWarehouseExpressRequest request,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("设置成功", orderService.setWarehouseExpress(id, request, operator));
    }

    @PostMapping("/{id}/ship")
    public ApiResponse<OrderResponse> shipOrder(
            @PathVariable("id") Long id,
            @Valid @RequestBody ShipOrderRequest request,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("发货成功", orderService.shipOrder(id, request, operator));
    }

    // ============ 状态流转 ============

    @PostMapping("/{id}/complete")
    public ApiResponse<OrderResponse> completeOrder(
            @PathVariable("id") Long id,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("订单已完成", orderService.completeOrder(id, operator));
    }

    @PostMapping("/{id}/cancel")
    public ApiResponse<OrderResponse> cancelOrder(
            @PathVariable("id") Long id,
            @RequestParam(value = "reason", required = false) String reason,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("订单已取消", orderService.cancelOrder(id, reason, operator));
    }

    // ============ 批量操作 ============

    @PostMapping("/batch-operation")
    public ApiResponse<BatchOperationResult> batchOperation(
            @Valid @RequestBody BatchOperationRequest request,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        BatchOperationResult result = orderService.batchOperation(request, operator);
        return ApiResponse.success(String.format("成功处理 %d 个订单", result.getSuccessCount()), result);
    }

    // ============ 统计 & 导出 ============

    @GetMapping("/statistics")
    public ApiResponse<OrderStatisticsResponse> getStatistics(OrderQueryRequest request) {
        return ApiResponse.success(orderService.getStatistics(request));
    }

    @GetMapping("/dashboard")
    public ApiResponse<DashboardStatsResponse> getDashboardStats() {
        return ApiResponse.success(orderService.getDashboardStats());
    }

    @GetMapping("/export")
    public ApiResponse<OrderService.ExportResult> exportOrders(
            OrderQueryRequest request,
            @RequestParam(value = "exportType", defaultValue = "excel") String exportType) {
        return ApiResponse.success("导出数据准备完成", orderService.exportOrders(request, exportType));
    }

    // ============ 备注 & 日志 ============

    @PutMapping("/{id}/remark")
    public ApiResponse<OrderResponse> updateRemark(
            @PathVariable("id") Long id,
            @RequestParam("remark") String remark,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("备注更新成功", orderService.updateRemark(id, remark, operator));
    }

    @GetMapping("/{id}/logs")
    public ApiResponse<List<OperationLogResponse>> getOrderLogs(@PathVariable("id") Long id) {
        return ApiResponse.success(orderService.getOrderLogs(id));
    }

    @PostMapping("/{id}/sync")
    public ApiResponse<OrderResponse> syncToPlatform(
            @PathVariable("id") Long id,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("订单已同步到平台", orderService.syncToPlatform(id, operator));
    }

    // ============ 选项接口 ============

    @GetMapping("/options/status")
    public ApiResponse<List<StatusOption>> getOrderStatusOptions() {
        return ApiResponse.success(orderService.getOrderStatusOptions());
    }

    @GetMapping("/options/audit-status")
    public ApiResponse<List<StatusOption>> getAuditStatusOptions() {
        return ApiResponse.success(orderService.getAuditStatusOptions());
    }

    @GetMapping("/options/delivery-status")
    public ApiResponse<List<StatusOption>> getDeliveryStatusOptions() {
        return ApiResponse.success(orderService.getDeliveryStatusOptions());
    }

    @GetMapping("/options/platforms")
    public ApiResponse<List<StatusOption>> getPlatformOptions() {
        return ApiResponse.success(orderService.getPlatformOptions());
    }

    @GetMapping("/options/shops")
    public ApiResponse<List<ShopOption>> getShopOptions() {
        return ApiResponse.success(orderService.getShopOptions());
    }

    // ============ Helper ============

    private OperatorInfo buildOperatorInfo(HttpServletRequest request) {
        return OperatorInfo.builder()
                .operatorId(0L) // 从SecurityContext获取
                .operatorName("API")
                .ip(getClientIp(request))
                .userAgent(request.getHeader("User-Agent"))
                .build();
    }

    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty()) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.isEmpty()) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
