import { pageUrl, websiteUrl } from "@/http/configAPI.js"
import { guid } from "@/uilts/help";

export const LANDING_PAGE = {
    name: 'received_log',
    url: pageUrl
}

export const LANDING_PAGE_MID = {
    name: 'mid',
    url: pageUrl
}

export const LANDING_PAGE_JUMP_INFO = {
    name: 'jump_info',
    url: pageUrl
}

export const WEBSITE_USER_INFO = {
    name: 'userInfo',
    url: websiteUrl
}

export function setChromeStorage(params, callback) {
    try {
        if (callback) {
            chrome.storage.local.set(params, callback)
        } else {
            chrome.storage.local.set(params)
        }
    } catch (error) {
        console.error(error)
    }
}

export function getChromeStorage(key = '', callback) {
    let params = {}
    params[key] = ''

    if (!callback) {
        return new Promise((resolve) => {
            chrome.storage.local.get(params, (item) => {
                if (item[key]) {
                    resolve(JSON.parse(item[key]))
                } else {
                    resolve(null)
                }
            });
        })
    }

    chrome.storage.local.get(params, (item) => {
        if (item[key]) {
            callback(JSON.parse(item[key]))
        } else {
            callback(null)
        }
    });
}

// export function chromeSendMessage() {
//     try {
//         // chrome.runtime.sendMessage
//     } catch {
//     }
// }

export function setChromeCookie({
    name,
    url
}, value_obj) {
    chrome.cookies.set({
        expirationDate: new Date().getTime() / 10,
        name: name,
        url: url,
        value: encodeURIComponent(JSON.stringify(value_obj)) || ''
    })
}

export function getChromeCookie({ name = '', url = '' }, callback) {
    try {
        chrome.cookies.getAll({ name, url }, (res = []) => {
            let _str = ''
            if (Array.isArray(res) && res.length) {
                _str = res[0].value
            }
            if (_str) {
                callback(JSON.parse(decodeURIComponent(_str)))
            } else {
                callback(null)
            }
        })
    } catch (error) {
        console.error('catch', error)
    }
}

export function removeChromeCookie(params, cb) {
    let { name, url } = params;
    chrome.cookies.remove({ name, url }, () => {
        cb && cb
    })
}

export function sendChromeTabMessage(params, callback) {
    chrome.tabs.getCurrent((tab) => {
        chrome.tabs.sendMessage(tab.id, params, callback);
    })
}

export function checkIsLogin(callback) {
    return new Promise((resolve) => {
        getChromeStorage('userInfo', (_userInfo) => {
            if (!_userInfo) {
                chrome.runtime.sendMessage(
                    { actionType: "POPUP_LOGIN", data: "" },
                    (response) => {
                        console.log("res", response);
                    }
                )
                callback && callback()
                resolve(_userInfo)
            } else {
                resolve(_userInfo)
            }
        })
    })
}

let callback_arr = []
export function httpContentToBack(data, callback) {
    let callback_id = guid()
    chrome.runtime.sendMessage({ actionType: "HTTP_CONTENT_TO_BACK", data, callback_id }, (res) => {
        if (res && callback) {
            callback_arr.push({
                callback_id,
                callback,
            })
        }
    })
}

// 再找到它执行
export function httpBackToContentCallBack(req) {
    for (let i in callback_arr) {
        if (callback_arr[i].callback_id == req.callback_id) {
            // 执行
            callback_arr[i].callback(req.data)
            // 删除
            callback_arr.splice(i, 1)
            break
        }
    }
}
