import { fetchTtwitterRequestToken, fetchTwitterLogin, fetchTwitterShortUrl, fetchAllMessageInfo, fetchReadTaskAllMsg, getDiscordUserInfo } from '@/logic/background/fetch/twitter.js'
import { LANDING_PAGE, LANDING_PAGE_MID, setChromeStorage, setChromeCookie, getChromeCookie, getChromeStorage, removeChromeCookie } from '@/uilts/chromeExtension.js'
import { guid } from '@/uilts/help.js'
import { pageUrl, discordAuthRedirectUri } from '@/http/configAPI'

let authToken = ''
let consumerKey = ''
let tab_flag = true

const isHasTabByUrl = (url, callback) => {
    let item
    chrome.tabs.query({}, (tab) => {
        for (let i in tab) {
            if (tab[i].url.indexOf(url) >= 0) {
                item = tab[i]
                break
            }
        }
        callback(item)
    })
}

export function twitterPinLoginToken() {
    // 1.判断是否登陆了
    getChromeStorage('userInfo', (res) => {
        // 没有登陆
        if (!res) {
            if (tab_flag == false) {
                return
            }
            tab_flag = false
            fetchTtwitterRequestToken().then((res) => {
                tab_flag = true
                if (res.code == 0) {
                    authToken = res.data.authToken
                    consumerKey = res.data.consumerKey
                    isHasTabByUrl('https://api.twitter.com/oauth/authorize?oauth_token', (tab) => {
                        if (!tab) {
                            chrome.tabs.create({
                                url: `https://api.twitter.com/oauth/authorize?oauth_token=${res.data.authToken}`
                            })
                        } else {
                            chrome.tabs.highlight({ windowId: tab.windowId, tabs: tab.index })
                        }
                    })
                }
            }).catch(() => {
                tab_flag = true
            })
        }
    })
}

export function twitterPinLoginCode(sender, code) {
    // actionType:{}

    // port.postMessage({
    //     state: "BACK_TWITTER_LOGIN_SUCCESS",
    // });
    // 关闭code页面
    // chrome.tabs.query({}, (tab) => {
    //     for (let i in tab) {
    //         console.log(tab[i])
    //         if (tab[i].url == 'https://api.twitter.com/oauth/authorize') {
    //             chrome.tabs.remove(tab[i].id)
    //         }
    //     }
    // })
    chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_TWITTER_LOGIN_SUCCESS' }, (res) => { console.log(res) });
    chrome.tabs.remove(sender.tab.id)


    chrome.cookies.getAll(LANDING_PAGE, (e = []) => {
        let _str = '[]'
        if (e.length > 0) {
            _str = e[0].value
        }
        let _arr = JSON.parse(decodeURIComponent(_str))
        let receivedIds = []
        if (_arr.length > 0) {
            for (let i in _arr) {
                receivedIds.push(_arr[i].receivedId)
            }
        }
        // 发送请求
        // token,code
        fetchTwitterLogin(authToken, consumerKey, code, receivedIds).then(res => {
            if (res.code == 0) {
                setChromeStorage({ userInfo: JSON.stringify(res.data) })

                sendActivetabMessage({
                    actionType: 'BG_LOGIN_SET_USERINFO_CB'
                });

                // 获取全局消息数据
                setMessageCount()
                chrome.cookies.remove(LANDING_PAGE)
            }
        })
    })
}

let discordAuthWindowId = '';
export function saveDiscordAuthWindowId(params) {
    let { windowId = '' } = params.data || {};
    discordAuthWindowId = windowId;
}

export function discordLoginCode({ code }, sender) {
    console.log('sender', sender)
    let { windowId, id } = sender.tab || {};
    chrome.tabs.remove(id);

    // 发送请求
    getDiscordUserInfo({
        authCode: code,
        redirectUrl: discordAuthRedirectUri
    }).then(res => {
        if (res.code == 0) {
            setTimeout(() => {
                sendActivetabMessage({
                    actionType: 'BACK_DISCORD_LOGIN_SUCCESS'
                });
            })
        }
    })

    // if(windowId) {
    //     chrome.windows.remove(
    //         windowId,
    //         function () {

    //         }
    //     )
    // }
}

export function twitterShortUrl(sender, url) {
    fetchTwitterShortUrl(url).then(res => {
        let str_arr = res.match(/denetme.net\/([\s\S]*?)"/) || []
        let post_Id = str_arr[1] || ''
        if (!post_Id) {
            return
        }
        // 解析
        let _obj = {
            short_url: url,
            post_Id
        }
        getChromeStorage('cardData', item => {
            if (item) {
                let has = false
                for (let i in item) {
                    if (item[i].short_url == _obj.short_url) {
                        item[i].short_url = _obj.short_url
                        item[i].post_Id = _obj.post_Id
                        setChromeStorage({ cardData: JSON.stringify(item) })
                        has = true
                        break
                    }
                }
                if (!has) {
                    item.push(_obj)
                    setChromeStorage({ cardData: JSON.stringify(item) })
                }

            } else {
                setChromeStorage({ cardData: JSON.stringify([_obj]) })
            }

            chrome.tabs.sendMessage(sender.tab.id, { actionType: 'BACK_TWITTER_SHORT_URL' }, (response) => { });
            // port.postMessage({
            //     state: "BACK_TWITTER_SHORT_URL"
            // });
        })
    })
}


// 安装插件后获取mid
export function onInstalledMid() {
    getChromeCookie(LANDING_PAGE_MID, (res_arr) => {
        // 没有cookie
        if (res_arr && res_arr.length) {
            setChromeStorage({ mid: JSON.stringify(res_arr[0]) })
        } else {
            let _params = {
                mid: guid()
            }
            setChromeCookie(LANDING_PAGE, { 'mid': _params.mid })
            setChromeStorage({ mid: JSON.stringify(_params) })
        }
    })
}

export function onInstalledUserSet() {
    chrome.action.getUserSettings().then(res => {
        setChromeStorage({ userSettings: JSON.stringify({ res }) })
        // 无刷新插入js
        chrome.tabs.query({}, (tab) => {
            for (let i in tab) {
                chrome.scripting.executeScript({
                    target: { tabId: tab[i].id },
                    files: ['js/content_help.js']
                }, () => { })
                if (tab[i].url.indexOf('twitter.com') >= 0 || tab[i].url.indexOf('facebook.com') >= 0) {
                    chrome.scripting.executeScript({
                        target: { tabId: tab[i].id },
                        files: ['js/content.js'],
                    }, () => {
                        setTimeout(() => {
                            setChromeStorage({ executeScript: JSON.stringify({ executeScript: 1 }) })
                        }, 2000);
                    })
                }
            }
        })
    })
}

/**
 * 检查是否pined 显示tips
 */
export function checkPined() {
    chrome.action.getUserSettings(res => {
        let { isOnToolbar } = res;
        if (!isOnToolbar) {
            sendActivetabMessage({
                actionType: 'BG_SHOW_PIN_TIPS'
            });
        }
    })
}

function sendActivetabMessage(message = {}) {
    chrome.tabs.query({
        active: true,
        currentWindow: true
    }, (tabs) => {
        chrome.tabs.sendMessage(tabs[0].id, message, res => {
            console.log(res)
        })
    })
}


/**
 * 安装后打开新标签页
 */
export function onInstalledCreateTab() {
    let cookiesParams = {
        name: 'pickup_info',
        url: pageUrl
    }
    getChromeCookie(cookiesParams, (res) => {
        let { postNickName, srcContentId } = res;
        if (res && postNickName && srcContentId) {
            let url = `https://twitter.com/${postNickName}/status/${srcContentId}`
            chrome.tabs.create({
                url
            });
            removeChromeCookie(cookiesParams)
        } else {
            let nftParams = {
                name: 'nft_info',
                url: pageUrl
            }
            getChromeCookie(nftParams, (res) => {
                let { twitterAccount, nftProjectId } = res;
                if (res && twitterAccount && nftProjectId) {
                    let url = `https://twitter.com/${twitterAccount}`
                    chrome.tabs.create({
                        url
                    });
                    removeChromeCookie(nftParams)
                } else {
                    chrome.tabs.create({
                        url: "https://twitter.com",
                    });
                }
            })
        }
    })
}

/**
 * 在popop重新发送
 * @param {*} req 
 */
export function popupRePublish(req) {
    setChromeStorage({
        popupShowPublishDialog: JSON.stringify({
            ...req.data,
            show: true
        }),
    });
    chrome.tabs.create({
        url: "https://twitter.com",
    });
}

export function setBadgeInfo(params) {
    let { text = '', color = '#DF3535' } = params.data || {};
    chrome.action.setBadgeText({ text: text });
    chrome.action.setBadgeBackgroundColor({ color: color });
}

export function hideBadge() {
    chrome.action.setBadgeText({ text: '' });
    chrome.action.setBadgeBackgroundColor({ color: [0, 0, 0, 0] });
}

export async function setMessageCount() {
    const { accessToken: token = '', uid = '' } = await getChromeStorage('userInfo') || {}
    if (token) {
        getMessageInfo();
        createAlarm();
    }
}

function createAlarm() {
    let alarmInfo = {
        //1分鐘之後開始(該值不能小於1) 
        delayInMinutes: 1,
        //與上方等同的寫法是 
        // when : Date.now() + n,
        //開始後每一分鐘執行一次(該值不能小于1) 
        periodInMinutes: 1
    };

    //每次加載就清空定時器
    chrome.alarms.clear('denetChromeAlarm');
    //創造定時器
    chrome.alarms.create('denetChromeAlarm', alarmInfo);
}

export function getMessageInfo() {
    fetchAllMessageInfo().then(res => {
        if (res.code == 0) {
            let { unReadCountTotal = 0 } = res.data;
            if (unReadCountTotal > 0) {
                let text = unReadCountTotal > 99 ? '99+' : unReadCountTotal + '';
                setBadgeInfo({ data: { text } });
            } else {
                hideBadge();
            }
        }
    })
}

export function readTaskAllMsg({ msgType }, cb) {
    fetchReadTaskAllMsg({
        msgType // 1:任务红包 2:钱包明细
    }).then(res => {
        if (res.code == 0) {
            cb && cb();
        }
    });
}

export const onDisconnectHandler = (port) => {
    if (port.name === "popup" || port.name === "popup_transactions") {
        let msgType = port.name === "popup" ? 1 : 2;
        readTaskAllMsg({ msgType }, () => {
            getMessageInfo();
        })
    }
}

export const injectExtensionPopup = (tab) => {
    sendActivetabMessage({
        actionType: 'BG_INJECT_EXTENSION_POPUP'
    });
}

export const setPopupConfig = (activeInfo) => {
    chrome.tabs.query({
        active: true,
        currentWindow: true
    }, (tabs) => {
        if(tabs.length) {
            let {pendingUrl = '', url = ''} = tabs[0];
            if(pendingUrl.startsWith('https://twitter.com') || url.startsWith('https://twitter.com')) {
                sendActivetabMessage({
                    actionType: 'BG_SET_POPUP_CONFIG'
                });
            } else {
                chrome.action.setPopup({
                    popup: 'popup.html',
                },function() {
                });
            }

            // if(pendingUrl.startsWith('chrome://') || url.startsWith('chrome://') || pendingUrl.startsWith('https://chrome.google.com') || url.startsWith('https://chrome.google.com')) {
            //     chrome.action.setPopup({
            //         popup: 'popup.html',
            //     },function() {
            //     });
            // } else {
            //     chrome.action.setPopup({
            //         popup: '',
            //     },function() {
            //     });
            // }
        }
    })
}

export const windwoLoadSetPopupPage = (data, sender) => {
    let {url = ''} = sender.tab;
    if(url.startsWith('chrome://')) {
        chrome.action.setPopup({
            popup: 'popup.html',
        },function() {
        });
    } else {
        chrome.action.setPopup({
            popup: '',
        },function() {
        });
    }
}

export const setActionPopup = (data) => {
    let {popup} = data.data || {};
    if(popup) {
        chrome.action.getPopup(
            {},
            function(result){
                if(!result) {
                    chrome.action.setPopup({
                        popup,
                    },function() {
                    });
                }
        });
    } else {
        chrome.action.setPopup({
            popup: '',
        },function() {
        });
    }
}