package org.dromara.zhishu.service.strategy;

import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.zhishu.domain.dto.response.LogisticsMethodResponse;
import org.dromara.zhishu.domain.dto.request.OrderDeliveryKWRequest;
import org.dromara.zhishu.domain.dto.request.OrderDeliveryRequest;
import org.dromara.zhishu.service.client.KfzClient;
import org.dromara.zhishu.util.UrlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrderKWStrategy implements OrderStrategy {

    @Autowired
    private KfzClient kfzClient;

    @Override
    public List<LogisticsMethodResponse> deliveryMethodList(Long shopId) {
        return kfzClient.deliveryMethodList(UrlUtil.getKfzServiceUrl(), shopId);
    }

    @Override
    public Boolean orderDelivery(OrderDeliveryRequest request) {
        String methodId = request.getMethodId();
        OrderDeliveryKWRequest orderDeliveryKWRequest = new OrderDeliveryKWRequest();
        orderDeliveryKWRequest.setShopId(request.getShopId());
        orderDeliveryKWRequest.setOrderId(Long.valueOf(request.getOrderSn()));
        String[] parts = methodId.split("_");
        // 确保分割后的数组有足够的元素
        if (parts.length == 2) {
            String shippingId = parts[0]; // 第一部分是shippingId
            String shippingCom = parts[1]; // 第二部分是shippingCom
            orderDeliveryKWRequest.setShippingId(shippingId);
            orderDeliveryKWRequest.setShippingCom(shippingCom);
            if (shippingId.equals("other")) orderDeliveryKWRequest.setUserDefined(request.getUserDefined());
        } else {
            String shippingId = parts[0]; // 第一部分是shippingId
            orderDeliveryKWRequest.setShippingId(shippingId);
        }
        orderDeliveryKWRequest.setShipmentNum(request.getTrackingNumber());
        orderDeliveryKWRequest.setMoreShipmentNum(request.getMoreShipmentNum());
        R<Boolean> r = kfzClient.orderDelivery(UrlUtil.getKfzServiceUrl(), orderDeliveryKWRequest);
        if (R.isError(r)) throw new ServiceException(r.getMsg());
        return r.getData();
    }

    @Override
    public Boolean syncKfzHistoryOrder(Long shopId, Integer days) {
        String result = kfzClient.fullSynchronizationOrder(UrlUtil.getKfzServiceUrl(), days, "manual", List.of(shopId));
        if (!result.equals("true")) throw new ServiceException("同步历史订单失败：店铺Id-" + shopId);
        return true;
    }
}
