package com.erp.platformsync.service.pdd.impl;

import com.erp.platformsync.adapter.PlatformAdapter;
import com.erp.platformsync.adapter.PlatformAdapterFactory;
import com.erp.platformsync.dto.pdd.PddGoodsDTO;
import com.erp.platformsync.dto.pdd.PddOrderDTO;
import com.erp.platformsync.dto.pdd.PddWaybillDTO;
import com.erp.platformsync.service.pdd.PddOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 拼多多订单服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PddOrderServiceImpl implements PddOrderService {

    private final PlatformAdapterFactory adapterFactory;

    private static final DateTimeFormatter DT_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

    @Override
    public List<PddOrderDTO> getOrders(Long shopId, String status, String startTime, String endTime, Integer page, Integer pageSize) {
        PlatformAdapter adapter = adapterFactory.getAdapter("pinduoduo");
        if (adapter == null || !adapter.isConfigured()) {
            log.warn("[pdd订单] 拼多多平台未配置");
            return Collections.emptyList();
        }

        try {
            LocalDateTime start = parseTime(startTime);
            LocalDateTime end = parseTime(endTime);
            if (start == null) start = LocalDateTime.now().minusDays(7);
            if (end == null) end = LocalDateTime.now();
            if (page == null || page < 1) page = 1;
            if (pageSize == null || pageSize < 1) pageSize = 20;

            // 使用适配器拉取订单
            var orders = adapter.pullOrders(shopId, "all", null, start, end);
            if (orders == null || orders.isEmpty()) {
                return Collections.emptyList();
            }

            // 转换为PddOrderDTO
            List<PddOrderDTO> result = new ArrayList<>();
            for (var order : orders) {
                PddOrderDTO dto = PddOrderDTO.builder()
                        .orderSn(order.getOrderSn())
                        .platformOrderSn(order.getPlatformOrderSn())
                        .orderStatus(order.getStatus())
                        .receiverName(order.getReceiverName())
                        .receiverPhone(order.getReceiverPhone())
                        .receiverProvince(order.getReceiverProvince())
                        .receiverCity(order.getReceiverCity())
                        .receiverDistrict(order.getReceiverDistrict())
                        .receiverAddress(order.getReceiverAddress())
                        .fullAddress(buildFullAddress(order))
                        .totalAmount(order.getTotalAmount())
                        .createTime(order.getCreatedTime())
                        .payTime(order.getPayTime())
                        .shopId(shopId)
                        .items(convertItems(order.getItems()))
                        .build();
                result.add(dto);
            }

            log.info("[pdd订单] 获取订单列表成功: count={}", result.size());
            return result;

        } catch (Exception e) {
            log.error("[pdd订单] 获取订单列表异常: {}", e.getMessage());
            return Collections.emptyList();
        }
    }

    @Override
    public PddOrderDTO getOrderDetail(String orderSn) {
        PlatformAdapter adapter = adapterFactory.getAdapter("pinduoduo");
        if (adapter == null || !adapter.isConfigured()) {
            log.warn("[pdd订单] 拼多多平台未配置");
            return null;
        }

        try {
            // 使用适配器拉取单个订单
            var orders = adapter.pullOrders(null, "all", orderSn, null, null);
            if (orders == null || orders.isEmpty()) {
                log.warn("[pdd订单] 订单不存在: orderSn={}", orderSn);
                return null;
            }

            var order = orders.get(0);
            PddOrderDTO dto = PddOrderDTO.builder()
                    .orderSn(order.getOrderSn())
                    .platformOrderSn(order.getPlatformOrderSn())
                    .orderStatus(order.getStatus())
                    .receiverName(order.getReceiverName())
                    .receiverPhone(order.getReceiverPhone())
                    .receiverProvince(order.getReceiverProvince())
                    .receiverCity(order.getReceiverCity())
                    .receiverDistrict(order.getReceiverDistrict())
                    .receiverAddress(order.getReceiverAddress())
                    .fullAddress(buildFullAddress(order))
                    .totalAmount(order.getTotalAmount())
                    .createTime(order.getCreatedTime())
                    .payTime(order.getPayTime())
                    .items(convertItems(order.getItems()))
                    .build();

            log.info("[pdd订单] 获取订单详情成功: orderSn={}", orderSn);
            return dto;

        } catch (Exception e) {
            log.error("[pdd订单] 获取订单详情异常: orderSn={}, error={}", orderSn, e.getMessage());
            return null;
        }
    }

    @Override
    public List<PddGoodsDTO> getGoods(Long shopId, String goodsName, Integer page, Integer pageSize) {
        // 拼多多商品列表查询（需要调用拼多多API）
        // 这里暂时返回空列表，实际需要实现拼多多商品API调用
        log.info("[pdd订单] 获取商品列表: shopId={}, goodsName={}", shopId, goodsName);
        return Collections.emptyList();
    }

    @Override
    public PddGoodsDTO getGoodsDetail(Long goodsId) {
        // 拼多多商品详情查询
        log.info("[pdd订单] 获取商品详情: goodsId={}", goodsId);
        return null;
    }

    @Override
    public PddWaybillDTO applyWaybill(String orderSn, String logisticsCode, String senderName, String senderPhone, String senderAddress) {
        PlatformAdapter adapter = adapterFactory.getAdapter("pinduoduo");
        if (adapter == null || !adapter.isConfigured()) {
            log.warn("[pdd运单] 拼多多平台未配置");
            return PddWaybillDTO.builder()
                    .waybillCode("")
                    .orderSn(orderSn)
                    .success(false)
                    .errorMsg("平台未配置")
                    .build();
        }

        try {
            // 调用拼多多申请运单接口
            log.info("[pdd运单] 申请运单: orderSn={}, logisticsCode={}", orderSn, logisticsCode);

            // 实际实现需要调用拼多多API: pdd.logistics.csb.waybill.apply
            // 这里返回模拟结果
            return PddWaybillDTO.builder()
                    .waybillCode("PPD" + System.currentTimeMillis())
                    .orderSn(orderSn)
                    .logisticsCode(logisticsCode)
                    .senderName(senderName)
                    .senderPhone(senderPhone)
                    .senderAddress(senderAddress)
                    .success(true)
                    .build();

        } catch (Exception e) {
            log.error("[pdd运单] 申请运单异常: orderSn={}, error={}", orderSn, e.getMessage());
            return PddWaybillDTO.builder()
                    .waybillCode("")
                    .orderSn(orderSn)
                    .success(false)
                    .errorMsg(e.getMessage())
                    .build();
        }
    }

    @Override
    public String getWaybillTracking(String waybillCode) {
        PlatformAdapter adapter = adapterFactory.getAdapter("pinduoduo");
        if (adapter == null || !adapter.isConfigured()) {
            log.warn("[pdd运单] 拼多多平台未配置");
            return "";
        }

        try {
            // 调用拼多多运单轨迹查询接口
            log.info("[pdd运单] 查询轨迹: waybillCode={}", waybillCode);

            // 实际实现需要调用拼多多API: pdd.logistics.trace.search
            // 这里返回模拟轨迹
            return "[{\"status\":\"已发货\",\"time\":\"2024-01-01 10:00:00\",\"desc\":\"商品已从仓库发出\"},"
                    + "{\"status\":\"运输中\",\"time\":\"2024-01-01 14:00:00\",\"desc\":\"快件已到达杭州中转站\"},"
                    + "{\"status\":\"派送中\",\"time\":\"2024-01-02 09:00:00\",\"desc\":\"快递员正在派送\"}]";

        } catch (Exception e) {
            log.error("[pdd运单] 查询轨迹异常: waybillCode={}, error={}", waybillCode, e.getMessage());
            return "";
        }
    }

    private LocalDateTime parseTime(String timeStr) {
        if (timeStr == null || timeStr.isEmpty()) {
            return null;
        }
        try {
            return LocalDateTime.parse(timeStr, DT_FORMATTER);
        } catch (Exception e) {
            try {
                return LocalDateTime.parse(timeStr + "T00:00:00");
            } catch (Exception e2) {
                log.warn("[pdd订单] 无法解析时间: {}", timeStr);
                return null;
            }
        }
    }

    private String buildFullAddress(com.erp.platformsync.dto.PullOrdersResponse.PullOrderItem order) {
        StringBuilder sb = new StringBuilder();
        if (order.getReceiverProvince() != null) sb.append(order.getReceiverProvince());
        if (order.getReceiverCity() != null) sb.append(order.getReceiverCity());
        if (order.getReceiverDistrict() != null) sb.append(order.getReceiverDistrict());
        if (order.getReceiverAddress() != null) sb.append(order.getReceiverAddress());
        return sb.toString();
    }

    private List<PddOrderDTO.PddOrderItemDTO> convertItems(List<com.erp.platformsync.dto.PullOrdersResponse.PullOrderItem.OrderItem> items) {
        if (items == null || items.isEmpty()) {
            return Collections.emptyList();
        }
        List<PddOrderDTO.PddOrderItemDTO> result = new ArrayList<>();
        for (var item : items) {
            result.add(PddOrderDTO.PddOrderItemDTO.builder()
                    .skuId(item.getSkuCode())
                    .skuName(item.getSkuName())
                    .quantity(item.getQuantity())
                    .price(item.getPrice())
                    .build());
        }
        return result;
    }
}
