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.PddDeliveryDTO;
import com.erp.platformsync.dto.pdd.PddLogisticsDTO;
import com.erp.platformsync.service.pdd.PddDeliveryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 拼多多发货服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PddDeliveryServiceImpl implements PddDeliveryService {

    private final PlatformAdapterFactory adapterFactory;

    @Override
    public List<PddLogisticsDTO> getLogisticsCompanies(Long shopId) {
        // 拼多多物流公司列表（常用物流）
        log.info("[pdd发货] 获取物流公司列表: shopId={}", shopId);

        return Arrays.asList(
                PddLogisticsDTO.builder().logisticsCode("YTO").logisticsName("圆通速递").shortName("圆通").supportElectric("Y").sort(1).build(),
                PddLogisticsDTO.builder().logisticsCode("ZTO").logisticsName("中通快递").shortName("中通").supportElectric("Y").sort(2).build(),
                PddLogisticsDTO.builder().logisticsCode("ZJS").logisticsName("宅急送").shortName("宅急送").supportElectric("Y").sort(3).build(),
                PddLogisticsDTO.builder().logisticsCode("YUNDA").logisticsName("韵达快递").shortName("韵达").supportElectric("Y").sort(4).build(),
                PddLogisticsDTO.builder().logisticsCode("STO").logisticsName("申通快递").shortName("申通").supportElectric("Y").sort(5).build(),
                PddLogisticsDTO.builder().logisticsCode("SF").logisticsName("顺丰速运").shortName("顺丰").supportElectric("N").sort(6).build(),
                PddLogisticsDTO.builder().logisticsCode("EMS").logisticsName("邮政EMS").shortName("EMS").supportElectric("Y").sort(7).build(),
                PddLogisticsDTO.builder().logisticsCode("JD").logisticsName("京东物流").shortName("京东").supportElectric("Y").sort(8).build(),
                PddLogisticsDTO.builder().logisticsCode("DBL").logisticsName("德邦快递").shortName("德邦").supportElectric("Y").sort(9).build(),
                PddLogisticsDTO.builder().logisticsCode("SY").logisticsName("顺友物流").shortName("顺友").supportElectric("Y").sort(10).build(),
                PddLogisticsDTO.builder().logisticsCode("YZBK").logisticsName("邮政小包").shortName("小包").supportElectric("N").sort(11).build(),
                PddLogisticsDTO.builder().logisticsCode("LB").logisticsName("龙邦速递").shortName("龙邦").supportElectric("N").sort(12).build(),
                PddLogisticsDTO.builder().logisticsCode("GTO").logisticsName("国通快递").shortName("国通").supportElectric("N").sort(13).build(),
                PddLogisticsDTO.builder().logisticsCode("JDWL").logisticsName("京东物流").shortName("京东").supportElectric("Y").sort(14).build(),
                PddLogisticsDTO.builder().logisticsCode("UCT").logisticsName("优速快递").shortName("优速").supportElectric("Y").sort(15).build()
        );
    }

    @Override
    public PddDeliveryDTO deliver(String orderSn, String logisticsCode, String waybillNo, String remark, Long shopId) {
        PlatformAdapter adapter = adapterFactory.getAdapter("pinduoduo");
        if (adapter == null || !adapter.isConfigured()) {
            log.warn("[pdd发货] 拼多多平台未配置");
            return PddDeliveryDTO.builder()
                    .orderSn(orderSn)
                    .success(false)
                    .errorCode("NOT_CONFIGURED")
                    .errorMsg("拼多多平台未配置API凭证")
                    .build();
        }

        try {
            log.info("[pdd发货] 开始发货: orderSn={}, logisticsCode={}, waybillNo={}", orderSn, logisticsCode, waybillNo);

            // 使用适配器同步发货状态
            boolean success = adapter.syncOrderToPlatform(orderSn, "SHIP", logisticsCode, waybillNo);

            if (success) {
                log.info("[pdd发货] 发货成功: orderSn={}", orderSn);
                return PddDeliveryDTO.builder()
                        .orderSn(orderSn)
                        .logisticsCode(logisticsCode)
                        .waybillNo(waybillNo)
                        .success(true)
                        .build();
            } else {
                log.error("[pdd发货] 发货失败: orderSn={}", orderSn);
                return PddDeliveryDTO.builder()
                        .orderSn(orderSn)
                        .logisticsCode(logisticsCode)
                        .waybillNo(waybillNo)
                        .success(false)
                        .errorCode("SYNC_FAILED")
                        .errorMsg("同步到拼多多平台失败")
                        .build();
            }

        } catch (Exception e) {
            log.error("[pdd发货] 发货异常: orderSn={}, error={}", orderSn, e.getMessage());
            return PddDeliveryDTO.builder()
                    .orderSn(orderSn)
                    .logisticsCode(logisticsCode)
                    .waybillNo(waybillNo)
                    .success(false)
                    .errorCode("EXCEPTION")
                    .errorMsg(e.getMessage())
                    .build();
        }
    }

    @Override
    public List<PddDeliveryDTO> batchDeliver(List<PddDeliveryDTO> deliveries) {
        if (deliveries == null || deliveries.isEmpty()) {
            return Collections.emptyList();
        }

        List<PddDeliveryDTO> results = new ArrayList<>();
        for (PddDeliveryDTO delivery : deliveries) {
            PddDeliveryDTO result = deliver(
                    delivery.getOrderSn(),
                    delivery.getLogisticsCode(),
                    delivery.getWaybillNo(),
                    delivery.getRemark(),
                    delivery.getShopId()
            );
            results.add(result);
        }

        log.info("[pdd发货] 批量发货完成: total={}, success={}", deliveries.size(),
                results.stream().filter(PddDeliveryDTO::getSuccess).count());

        return results;
    }
}
