/**
 * SKU定价API请求文件
 * 负责获取外部数据的API请求
 */

class SkuPricingApi {
    constructor() {
        this.baseUrl = 'resource/logistics/';
        this.api = window.api;
        this.logisticList = [];
    }


    async getLogisticList(){

        const res = await this.api.get('/ali/logisticRoutes/list');

        console.log('getLogistics res', res);

        if(res && res.data){
            return res.data;
        }
    }

    /**
     * 获取物流数据
     * @param {Object} data.value - 物流数据名称
     */
    async getLogisticsData(data){
        const url = chrome.runtime.getURL(`${this.baseUrl}${data.value}.json`); 
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`获取物流数据失败: ${response.status}`);
        }

        return await response.json();
    }
    /**
     * 获取物流信息
     * @returns {Promise<Array>} 物流信息列表
     */
    async getLogistics() {

        const res = await this.api.getURL('ali/logisticRoutes/list');

        console.log('getLogistics res', res);

        if(res && res.data){
            return res.data;
        }
    }

    /**
     * 获取汇率信息
     * @param {string} baseCurrency - 基准货币
     * @param {string} targetCurrency - 目标货币
     * @returns {Promise<number>} 汇率
     */
    async getExchangeRate(baseCurrency, targetCurrency) {
        try {
            const response = await fetch(`https://api.frankfurter.app/latest?base=${baseCurrency}&symbols=${targetCurrency}`);
            if (!response.ok) {
                throw new Error(`汇率获取失败: ${response.status}`);
            }
            const data = await response.json();
            return data.rates[targetCurrency];
        } catch (error) {
            console.error('获取汇率失败:', error);
            return 7.0; // 默认汇率
        }
    }

    /**
     * 计算物流费用
     * @param {Object} params - 计算参数
     * @returns {Promise<Object>} 物流费用结果
     */
    async calculateShipping(params) {
        try {
            const response = await fetch(`${this.baseUrl}/shipping/calculate`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(params)
            });
            
            if (!response.ok) {
                throw new Error(`物流费用计算失败: ${response.status}`);
            }
            return await response.json();
        } catch (error) {
            console.error('计算物流费用失败:', error);
            // 返回默认计算结果
            return {
                baseFee: 10,
                weightFee: 5,
                totalFee: 15
            };
        }
    }
}

// 创建全局实例
window.skuPricingApi = new SkuPricingApi();

// 导出类
if (typeof module !== 'undefined' && module.exports) {
    module.exports = SkuPricingApi;
}