import { pageUrl } from "@/http/configAPI.js"
import { guid, iframeId } from "@/uilts/help";
import messageCenter from '@/uilts/messageCenter';
import MESSAGE_ENUM from "@/uilts/messageCenter/messageEnum";

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 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 getSessionStorge(key) {
    const value = sessionStorage.getItem(key);
    return value && JSON.parse(value);
}

export function setSessionStorge(key, value) {
    return sessionStorage.setItem(key, JSON.stringify(value));
}

export function setChromeStoragetoExtension(data) {
    messageCenter.send({
        info: {
            actionType: MESSAGE_ENUM.IFRAME_SET_EXTENSION_STORGE_DATA,
        },
        data
    })
}

export async function getChromeStorageFromExtension(key = '') {
    let params = {}
    params[key] = ''
    // const value = getSessionStorge(key);
    // if (value) {
    //     return Promise.resolve(value);
    // } else { 
        return new Promise((res, rej) => {
            messageCenter.send({
                info: {
                    iframeId,//用于告诉父窗口会传消息给哪个iframe
                    actionType: MESSAGE_ENUM.IFRAME_GET_EXTENSION_STORGE_DATA,
                },
                data: {
                    key,// storage key
                },
                callback: (data) => {
                    setSessionStorge(key, data);
                    res(data);
                },
                failback: (e) => {
                    console.log('getChromeStorageFromExtension fail', e)
                    rej(null)
                }
            })
        })
    // }
    // console.log(window.parent.window.atest)
    // window.postMessage({actionType: 'iframe_test', data: key})
}

export const openUrlInNewWindow = (data) => { 
    messageCenter.send({
        info: {
            iframeId,//用于告诉父窗口会传消息给哪个iframe
            actionType: 'OPEN_URL_IN_NEW_WINDOW',
        },
        data
    })
}

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
        }
    }
}
