import { appVersionCode, baseAPIUrl } from '@/http/configAPI.js'
import { getChromeStorageFromExtension } from '@/uilts/chromeExtension.js'

export async function commonFetch({ url = '', method = 'POST' , params = {}, baseInfo = {}}) {

    let storage_mid = await getChromeStorageFromExtension('mid') || ''
    const { mid } = storage_mid || {}
    if (!baseInfo.token || !baseInfo.uid) {
        const { accessToken: token = '', uid = '' } = await getChromeStorageFromExtension('userInfo') || {}
        baseInfo.token = token
        baseInfo.uid = uid
    }
    baseInfo.mid = mid
    baseInfo.appVersionCode = appVersionCode
    baseInfo.machineCode = mid
    baseInfo.appType = 1
    baseInfo.loginUid = baseInfo.uid

    return new Promise(function (resolve, reject) {
        let _url = baseAPIUrl + url
        if(url.includes('http')){
            _url = url
        }
        let bodyObj = {
            "baseInfo": baseInfo,
            "params": params
        };
        fetch(_url, {
            method: method, // or 'PUT'
            cache: 'no-cache',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(bodyObj),
        })
            .then(response => response.json())
            .then(data => {
                switch (data.code.toString()) {
                    // twitter授权失效
                    case '1003':
                        chrome.storage.local.remove("userInfo");
                        chrome.runtime.sendMessage(
                            { actionType: "POPUP_LOGIN", data: "" },
                            (response) => {
                                console.log("res", response);
                            }
                        )
                        break;
                    // 登陆token失效
                    case '-107':
                        chrome.storage.local.remove("userInfo");
                        chrome.runtime.sendMessage(
                            { actionType: "POPUP_LOGIN", data: "" },
                            (response) => {
                                console.log("res", response);
                            }
                        )
                        break;
                }

                resolve(data);
            })
            .catch((error) => {
                reject({url: _url, error: error, requestParams: bodyObj});
            });
    })
}