package com.erp.logistics.service.adapter;

import com.erp.logistics.entity.LogisticsTrace;
import com.erp.logistics.entity.WaybillStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 圆通速递适配器
 */
@Slf4j
@Component
public class YtoCarrierAdapter extends AbstractCarrierAdapter {

    public static final String CARRIER_CODE = "YTO";
    public static final String CARRIER_NAME = "圆通速递";

    @Value("${logistics.callback.secret-keys.yto:}")
    private String secretKey;

    @Value("${logistics.carriers.yto.api-url:}")
    private String apiUrl;

    @Value("${logistics.carriers.yto.customer-code:}")
    private String customerCode;

    @Value("${logistics.carriers.yto.api-key:}")
    private String apiKey;

    @Override
    public String getCarrierCode() {
        return CARRIER_CODE;
    }

    @Override
    public String getCarrierName() {
        return CARRIER_NAME;
    }

    @Override
    public boolean match(String waybillNo) {
        // 圆通运单号通常以YT开头，10-15位数字
        return waybillNo != null && waybillNo.matches("^YT\\d{10,15}$");
    }

    @Override
    protected String getSecretKey() {
        return secretKey;
    }

    @Override
    protected boolean doVerifySign(Map<String, Object> data, String sign) {
        // 圆通签名验证
        return verifyMd5Sign(data, sign, "sign", "timestamp");
    }

    @Override
    public List<LogisticsTrace> queryTraces(String waybillNo) {
        log.info("[圆通] 查询轨迹, 运单号: {}", waybillNo);
        List<LogisticsTrace> traces = new ArrayList<>();

        try {
            // TODO: 调用圆通API
            log.warn("[圆通] API对接待实现，当前返回空轨迹");
        } catch (Exception e) {
            log.error("[圆通] 查询轨迹异常: {}", waybillNo, e);
        }

        return traces;
    }

    @Override
    @SuppressWarnings("unchecked")
    public CallbackResult parseCallback(Map<String, Object> rawData) {
        log.info("[圆通] 解析回调数据: {}", rawData);

        String waybillNo = String.valueOf(rawData.getOrDefault("mailNo", rawData.getOrDefault("waybillNo", "")));
        String statusCode = String.valueOf(rawData.getOrDefault("statusCode", rawData.getOrDefault("status", "")));
        String statusName = String.valueOf(rawData.getOrDefault("statusName", rawData.getOrDefault("statusCN", "")));
        String location = String.valueOf(rawData.getOrDefault("city", rawData.getOrDefault("location", "")));
        String description = String.valueOf(rawData.getOrDefault("remark", rawData.getOrDefault("description", "")));
        String scanTime = String.valueOf(rawData.getOrDefault("scanTime", rawData.getOrDefault("acceptTime", "")));

        // 状态映射
        String status = mapYtoStatus(statusCode);
        String statusLabel = statusName;

        // 构建运单状态
        WaybillStatus waybillStatus = new WaybillStatus()
                .setWaybillNo(waybillNo)
                .setCarrier(CARRIER_CODE)
                .setStatus(status)
                .setStatusLabel(statusLabel)
                .setLocation(location)
                .setDescription(description)
                .setLastTraceTime(parseTime(scanTime))
                .setSyncStatus(2)
                .setSyncRetryCount(0);

        if ("SIGNED".equals(status)) {
            waybillStatus.setSignedTime(parseTime(scanTime));
        }

        // 构建轨迹
        LogisticsTrace trace = new LogisticsTrace()
                .setWaybillNo(waybillNo)
                .setCarrier(CARRIER_CODE)
                .setStatus(status)
                .setStatusLabel(statusLabel)
                .setLocation(location)
                .setDescription(description)
                .setTraceTime(parseTime(scanTime))
                .setRawStatusCode(statusCode)
                .setRawData(toJson(rawData))
                .setCreatedAt(LocalDateTime.now());

        List<LogisticsTrace> traces = List.of(trace);

        return new CallbackResult(waybillNo, waybillStatus, traces);
    }

    /**
     * 圆通状态码映射
     */
    private String mapYtoStatus(String statusCode) {
        return switch (statusCode) {
            case "COLLECTED", "ARRIVED", "DEPARTED", "IN_TRANSIT" -> "IN_TRANSIT";
            case "OUT_FOR_DELIVERY", "DELIVERING" -> "DELIVERING";
            case "SIGNED", "RECEIVED" -> "SIGNED";
            case "RETURN", "RETURNING" -> "RETURNING";
            case "RETURNED" -> "RETURNED";
            case "EXCEPTION", "EXCEPTION_RETURN" -> "EXCEPTION";
            default -> "IN_TRANSIT";
        };
    }
}
