package com.erp.logistics.controller;

import com.erp.common.core.model.ApiResponse;
import com.erp.logistics.dto.request.LogisticsCallbackRequest;
import com.erp.logistics.dto.request.TraceSyncRequest;
import com.erp.logistics.dto.request.WaybillStatusQueryRequest;
import com.erp.common.core.model.PageResponse;
import com.erp.logistics.dto.response.TraceResponse;
import com.erp.logistics.dto.response.WaybillStatusResponse;
import com.erp.logistics.service.LogisticsService;
import com.erp.logistics.service.TraceSyncService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 物流轨迹控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/logistics")
@RequiredArgsConstructor
@Tag(name = "物流轨迹服务", description = "物流轨迹查询、同步、回调处理")
public class LogisticsController {

    private final LogisticsService logisticsService;
    private final TraceSyncService traceSyncService;

    // ==================== 轨迹查询 ====================

    @GetMapping("/trace/{waybillNo}")
    @Operation(summary = "查询物流轨迹", description = "根据运单号查询物流轨迹记录")
    public ApiResponse<TraceResponse> getTrace(
            @Parameter(description = "运单号") @PathVariable String waybillNo) {
        TraceResponse trace = logisticsService.getTraces(waybillNo);
        if (trace == null) {
            return ApiResponse.notFound("未找到物流轨迹");
        }
        return ApiResponse.success(trace);
    }

    @GetMapping("/trace/timeline/{waybillNo}")
    @Operation(summary = "物流时间轴（增强版）", description = "返回物流轨迹时间轴，包含统计信息、预计送达、分段节点等")
    public ApiResponse<TraceResponse> getTraceTimeline(
            @Parameter(description = "运单号") @PathVariable String waybillNo) {
        TraceResponse trace = logisticsService.getTracesEnhanced(waybillNo);
        if (trace == null) {
            return ApiResponse.notFound("未找到物流轨迹");
        }
        return ApiResponse.success(trace);
    }

    // ==================== 运单状态 ====================

    @GetMapping("/status/{waybillNo}")
    @Operation(summary = "查询运单状态", description = "根据运单号查询当前运单状态")
    public ApiResponse<WaybillStatusResponse> getStatus(
            @Parameter(description = "运单号") @PathVariable String waybillNo) {
        WaybillStatusResponse status = logisticsService.getWaybillStatus(waybillNo);
        if (status == null) {
            return ApiResponse.notFound("未找到运单状态");
        }
        return ApiResponse.success(status);
    }

    @GetMapping("/waybills")
    @Operation(summary = "运单列表查询", description = "分页查询运单列表，支持按物流商、状态筛选")
    public ApiResponse<PageResponse<WaybillStatusResponse>> queryWaybills(
            @Valid WaybillStatusQueryRequest request) {
        return ApiResponse.success(logisticsService.queryWaybills(request));
    }

    // ==================== 轨迹同步 ====================

    @PostMapping("/sync")
    @Operation(summary = "同步物流轨迹", description = "主动同步指定运单的物流轨迹")
    public ApiResponse<Void> syncTraces(@Valid @RequestBody TraceSyncRequest request) {
        logisticsService.syncTraces(request);
        return ApiResponse.<Void>success("同步任务已提交", null);
    }

    @PostMapping("/sync/batch")
    @Operation(summary = "批量同步", description = "触发待同步运单的批量同步任务")
    public ApiResponse<Void> syncPending() {
        traceSyncService.syncPendingAsync();
        return ApiResponse.<Void>success("批量同步任务已触发", null);
    }

    // ==================== 回调处理 ====================

    @PostMapping("/callback/{carrier}")
    @Operation(summary = "物流回调", description = "接收物流商的回调推送")
    public ApiResponse<Void> callback(
            @Parameter(description = "物流商编码") @PathVariable String carrier,
            @RequestBody LogisticsCallbackRequest request) {
        request.setCarrier(carrier);
        boolean success = traceSyncService.processCallback(carrier, request.getData());
        if (success) {
            return ApiResponse.success();
        }
        return ApiResponse.error(500, "回调处理失败");
    }

    // ==================== 运单管理 ====================

    @GetMapping("/carriers")
    @Operation(summary = "支持的物流商列表", description = "获取系统支持的物流商列表")
    public ApiResponse<List<Map<String, String>>> getCarriers() {
        List<Map<String, String>> carriers = List.of(
                Map.of("code", "SF", "name", "顺丰速运"),
                Map.of("code", "YTO", "name", "圆通速递"),
                Map.of("code", "ZTO", "name", "中通快递"),
                Map.of("code", "YUNDA", "name", "韵达快递")
        );
        return ApiResponse.success(carriers);
    }

    @PostMapping("/waybill")
    @Operation(summary = "创建运单", description = "创建或更新运单信息")
    public ApiResponse<WaybillStatusResponse> saveWaybill(
            @RequestBody com.erp.logistics.entity.WaybillStatus waybill) {
        return ApiResponse.success("运单保存成功", logisticsService.saveOrUpdateWaybill(waybill));
    }
}
