package com.erp.waybill.controller;

import com.erp.waybill.dto.*;
import com.erp.waybill.entity.LogisticsTrace;
import com.erp.waybill.entity.PrintLog;
import com.erp.waybill.entity.WaybillStatus;
import com.erp.waybill.service.WaybillService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

/**
 * 运单管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/waybills")
@RequiredArgsConstructor
public class WaybillController {

    private final WaybillService waybillService;

    // ==================== 运单申请 ====================

    /**
     * 申请电子面单
     */
    @PostMapping("/apply")
    public ResponseEntity<ApiResponse<WaybillResponse>> applyWaybill(
            @Valid @RequestBody WaybillApplyRequest request,
            @RequestHeader(value = "X-Operator-Id", required = false) Long operatorId) {

        log.info("申请电子面单，订单ID: {}, 快递: {}", request.getOrderId(), request.getExpressCode());
        WaybillResponse response = waybillService.applyWaybill(request, operatorId);
        return ResponseEntity.ok(ApiResponse.success("申请成功", response));
    }

    /**
     * 批量申请电子面单
     */
    @PostMapping("/apply/batch")
    public ResponseEntity<ApiResponse<Map<String, Object>>> batchApplyWaybill(
            @Valid @RequestBody BatchApplyRequest request,
            @RequestHeader(value = "X-Operator-Id", required = false) Long operatorId) {

        log.info("批量申请电子面单，订单数: {}", request.getOrderIds().size());
        WaybillService.BatchApplyResult result = waybillService.batchApplyWaybill(request, operatorId);

        return ResponseEntity.ok(ApiResponse.success("批量申请完成", Map.of(
                "success", result.success(),
                "errors", result.errors()
        )));
    }

    // ==================== 运单查询 ====================

    /**
     * 查询运单详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<WaybillResponse>> getWaybill(@PathVariable Long id) {
        WaybillResponse response = waybillService.getWaybill(id);
        return ResponseEntity.ok(ApiResponse.success(response));
    }

    /**
     * 根据运单号查询
     */
    @GetMapping("/no/{waybillNo}")
    public ResponseEntity<ApiResponse<WaybillResponse>> getWaybillByNo(@PathVariable String waybillNo) {
        WaybillResponse response = waybillService.getWaybillByNo(waybillNo);
        return ResponseEntity.ok(ApiResponse.success(response));
    }

    /**
     * 查询订单的所有运单
     */
    @GetMapping("/order/{orderId}")
    public ResponseEntity<ApiResponse<List<WaybillResponse>>> getWaybillsByOrderId(@PathVariable Long orderId) {
        List<WaybillResponse> responses = waybillService.getWaybillsByOrderId(orderId);
        return ResponseEntity.ok(ApiResponse.success(responses));
    }

    // ==================== 运单取消/作废 ====================

    /**
     * 取消运单
     */
    @PostMapping("/cancel")
    public ResponseEntity<ApiResponse<Void>> cancelWaybill(@Valid @RequestBody WaybillCancelRequest request) {
        log.info("取消运单: {}", request.getWaybillNo());
        waybillService.cancelWaybill(request);
        return ResponseEntity.ok(ApiResponse.success("取消成功", null));
    }

    /**
     * 作废运单
     */
    @PostMapping("/void")
    public ResponseEntity<ApiResponse<WaybillResponse>> voidWaybill(@Valid @RequestBody WaybillVoidRequest request) {
        log.info("作废运单: {}", request.getWaybillId());
        WaybillResponse response = waybillService.voidWaybill(request);
        return ResponseEntity.ok(ApiResponse.success("作废成功", response));
    }

    // ==================== 打印管理 ====================

    /**
     * 打印运单（首次）
     */
    @PostMapping("/{id}/print")
    public ResponseEntity<ApiResponse<Map<String, String>>> printWaybill(
            @PathVariable Long id,
            @RequestHeader(value = "X-Operator-Id", required = false) Long operatorId) {

        log.info("打印运单: {}", id);
        WaybillService.PrintResult result = waybillService.printWaybill(id, operatorId);
        return ResponseEntity.ok(ApiResponse.success("获取成功", Map.of(
                "waybillNo", result.waybillNo(),
                "printContent", result.printContent()
        )));
    }

    /**
     * 补打运单
     */
    @PostMapping("/{id}/reprint")
    public ResponseEntity<ApiResponse<Map<String, String>>> reprintWaybill(
            @PathVariable Long id,
            @RequestHeader(value = "X-Operator-Id", required = false) Long operatorId) {

        log.info("补打运单: {}", id);
        WaybillService.PrintResult result = waybillService.reprintWaybill(id, operatorId);
        return ResponseEntity.ok(ApiResponse.success("获取成功", Map.of(
                "waybillNo", result.waybillNo(),
                "printContent", result.printContent()
        )));
    }

    /**
     * 换单号（面单破损）
     */
    @PostMapping("/{id}/change-no")
    public ResponseEntity<ApiResponse<Map<String, String>>> changeWaybillNo(
            @PathVariable Long id,
            @RequestParam String reason,
            @RequestHeader(value = "X-Operator-Id", required = false) Long operatorId) {

        log.info("换单号: {}", id);
        WaybillService.ChangeWaybillNoResult result = waybillService.changeWaybillNo(id, reason, operatorId);
        return ResponseEntity.ok(ApiResponse.success("换单成功", Map.of(
                "oldWaybillNo", result.oldWaybillNo(),
                "newWaybillNo", result.newWaybillNo()
        )));
    }

    // ==================== 状态跟踪 ====================

    /**
     * 查询运单物流状态
     */
    @GetMapping("/{waybillNo}/tracking")
    public ResponseEntity<ApiResponse<WaybillStatus>> getTrackingStatus(@PathVariable String waybillNo) {
        WaybillStatus status = waybillService.getTrackingStatus(waybillNo);
        if (status == null) {
            return ResponseEntity.ok(ApiResponse.notFound("暂无物流信息"));
        }
        return ResponseEntity.ok(ApiResponse.success(status));
    }

    /**
     * 查询物流轨迹明细
     */
    @GetMapping("/{waybillNo}/traces")
    public ResponseEntity<ApiResponse<List<LogisticsTrace>>> getLogisticsTraces(@PathVariable String waybillNo) {
        List<LogisticsTrace> traces = waybillService.getLogisticsTraces(waybillNo);
        return ResponseEntity.ok(ApiResponse.success(traces));
    }

    /**
     * 同步运单状态
     */
    @PostMapping("/{waybillNo}/sync")
    public ResponseEntity<ApiResponse<WaybillStatus>> syncTrackingStatus(@PathVariable String waybillNo) {
        log.info("同步运单状态: {}", waybillNo);
        WaybillStatus status = waybillService.syncTrackingStatus(waybillNo);
        return ResponseEntity.ok(ApiResponse.success("同步成功", status));
    }

    /**
     * 批量同步运单状态
     */
    @PostMapping("/sync/batch")
    public ResponseEntity<ApiResponse<Map<String, Integer>>> batchSync(
            @RequestParam(defaultValue = "50") int limit) {
        int synced = waybillService.batchSyncTrackingStatus(limit);
        return ResponseEntity.ok(ApiResponse.success("获取同步结果", Map.of("synced", synced)));
    }

    // ==================== 打印日志 ====================

    /**
     * 查询打印日志
     */
    @GetMapping("/order/{orderId}/print-logs")
    public ResponseEntity<ApiResponse<List<PrintLog>>> getPrintLogs(@PathVariable Long orderId) {
        List<PrintLog> logs = waybillService.getPrintLogs(orderId);
        return ResponseEntity.ok(ApiResponse.success(logs));
    }
}
