package com.erp.waybill.express;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 模拟快递适配器（用于测试/开发环境）
 * 生产环境请配置具体的快递适配器
 */
@Slf4j
@Component
@ConditionalOnProperty(name = "waybill.express.mock", havingValue = "true", matchIfMissing = true)
public class MockExpressAdapter implements ExpressAdapter {

    @Override
    public String getCode() {
        return "MOCK";
    }

    @Override
    public ExpressAdapter.ApplyResult applyWaybill(ExpressAdapter.ApplyParams params) {
        log.info("【Mock】申请电子面单，订单ID: {}", params.getOrderId());

        String waybillNo = "MOCK" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 6).toUpperCase();
        String printContent = buildPrintContent(waybillNo, params);

        return ExpressAdapter.ApplyResult.builder()
                .expressCode(getCode())
                .waybillNo(waybillNo)
                .printContent(printContent)
                .build();
    }

    @Override
    public boolean cancelWaybill(String waybillNo) {
        log.info("【Mock】取消运单: {}", waybillNo);
        return true;
    }

    @Override
    public ExpressAdapter.TrackResult queryStatus(String waybillNo) {
        log.info("【Mock】查询运单状态: {}", waybillNo);
        return ExpressAdapter.TrackResult.builder()
                .status("in_transit")
                .location("上海市浦东新区")
                .description("快件已发出，正在运输中")
                .build();
    }

    private String buildPrintContent(String waybillNo, ExpressAdapter.ApplyParams params) {
        return String.format("""
            {
                "waybillNo": "%s",
                "sender": {
                    "name": "%s",
                    "phone": "%s",
                    "address": "%s"
                },
                "receiver": {
                    "name": "%s",
                    "phone": "%s",
                    "address": "%s"
                },
                "printTime": "%s"
            }
            """,
                waybillNo,
                params.getSenderName(),
                params.getSenderPhone(),
                params.getSenderAddress(),
                params.getReceiverName(),
                params.getReceiverPhone(),
                params.getReceiverAddress(),
                LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
        );
    }
}
