package com.sckw.report.service;

import com.sckw.core.exception.SystemException;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.response.BaseResult;
import com.sckw.transport.api.feign.TransportApi;
import com.sckw.transport.api.model.vo.CurrentCapacityAnalysisVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 库位容量分析服务类
 * 提供获取当前库位容量分析数据的相关业务逻辑
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class KwCapacityAnalysisService {

    private final TransportApi transportApi;

    /**
     * 获取当前库位容量分析数据
     *
     * @return 当前库位容量分析视图对象
     * @throws SystemException 当远程调用失败或返回异常时抛出系统异常
     */
    public CurrentCapacityAnalysisVo currentCapacityAnalysis() {
        BaseResult<CurrentCapacityAnalysisVo> remote;
        try {
            // 调用远程接口获取当前库位容量分析数据
            remote = transportApi.currentCapacityAnalysis();
        } catch (Exception e) {
            // 记录远程调用失败的错误日志
            log.error("调用当前库位容量分析接口失败", e);
            throw new SystemException("获取当前库位容量分析失败: " + e.getMessage());
        }
        
        // 检查远程响应是否为空
        if (remote == null) {
            log.error("获取当前库位容量分析失败: 远程响应为空");
            throw new SystemException("获取当前库位容量分析失败: 远程响应为空");
        }
        
        // 检查远程调用是否成功
        if (remote.getCode() != HttpStatus.SUCCESS_CODE) {
            String errorMsg = remote.getMessage() != null ? remote.getMessage() : "远程调用失败";
            log.error("获取当前库位容量分析失败, 错误码: {}, 错误信息: {}", remote.getCode(), errorMsg);
            throw new SystemException(remote.getCode(), errorMsg);
        }
        
        return remote.getData();
    }

    /**
     * 按子任务获取当前库位容量分析数据
     *
     * @return 当前库位容量分析视图对象
     * @throws SystemException 当远程调用失败或返回异常时抛出系统异常
     */
    public CurrentCapacityAnalysisVo currentCapacityAnalysisBySubtask() {
        BaseResult<CurrentCapacityAnalysisVo> remote;
        try {
            // 调用远程接口按子任务获取当前库位容量分析数据
            remote = transportApi.currentCapacityAnalysisBySubtask();
        } catch (Exception e) {
            // 记录远程调用失败的错误日志
            log.error("调用按子任务获取当前库位容量分析接口失败", e);
            throw new SystemException("按子任务获取当前库位容量分析失败: " + e.getMessage());
        }
        
        // 检查远程响应是否为空
        if (remote == null) {
            log.error("按子任务获取当前库位容量分析失败: 远程响应为空");
            throw new SystemException("按子任务获取当前库位容量分析失败: 远程响应为空");
        }
        
        // 检查远程调用是否成功
        if (remote.getCode() != HttpStatus.SUCCESS_CODE) {
            String errorMsg = remote.getMessage() != null ? remote.getMessage() : "远程调用失败";
            log.error("按子任务获取当前库位容量分析失败, 错误码: {}, 错误信息: {}", remote.getCode(), errorMsg);
            throw new SystemException(remote.getCode(), errorMsg);
        }
        
        return remote.getData();
    }
}