package org.springblade.thirdparty.track.service.impl;

import cn.hutool.json.JSONUtil;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.core.tool.utils.StringPool;
import org.springblade.thirdparty.track.config.TrackProperties;
import org.springblade.thirdparty.track.constant.TrackConstant;
import org.springblade.thirdparty.track.exception.TrackException;
import org.springblade.thirdparty.track.feign.ITrackClient;
import org.springblade.thirdparty.track.pojo.dto.TrackWaybillSendDTO;
import org.springblade.thirdparty.track.pojo.vo.TrackResultVO;
import org.springblade.thirdparty.track.service.ITrackService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author bfhuange
 * @since 2024/12/16
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class TrackServiceImpl implements ITrackService {

    private final TrackProperties trackProperties;
    private final ITrackClient client;

    @Override
    public void sendWaybills(List<Long> ids) {
        if (!trackProperties.isEnabled()) {
            log.warn("未启用轨迹系统");
            return;
        }
        log.info("推送运单到轨迹，参数：{}", JSONUtil.toJsonStr(ids));
        if (CollectionUtil.isEmpty(ids)) {
            log.warn("推送运单到轨迹 参数为空");
            return;
        }
        List<String> list = ids.stream()
                .filter(Objects::nonNull)
                .distinct()
                .map(String::valueOf)
                .toList();
        if (CollectionUtil.isEmpty(ids)) {
            log.warn("推送运单到轨迹 参数为空");
            return;
        }
        TrackResultVO result = null;
        try {
            for (List<String> subList : Lists.partition(list, 100)) {
                result = client.sendWaybills(new TrackWaybillSendDTO(subList, trackProperties.getBpsType()));
                if (result == null || !TrackConstant.SUCCESS_CODE.equals(result.getCode())) {
                    // 结果为空，或不是成功，抛出异常
                    log.error("推送运单到轨迹异常 响应参数：{}", JSONUtil.toJsonStr(result));
                    String message = Optional.ofNullable(result)
                            .map(TrackResultVO::getMsg)
                            .orElse(StringPool.EMPTY);
                    throw new TrackException("推送运单到轨迹异常 " + message);
                }
            }
        } catch (TrackException e) {
            throw e;
        } catch (Exception e) {
            log.error("推送运单到轨迹 异常", e);
            throw new TrackException("推送运单到轨迹异常");
        }
    }

    @Override
    public String getTrackUrl(String id) {
        return trackProperties.getBaseUrl() + trackProperties.getTrackUrlFormat().formatted(id);
    }

    @Override
    public String getTrackUrlPrefix() {
        return  trackProperties.getBaseUrl() + trackProperties.getTrackUrlFormat().replace("%s", "");
    }
}
