import { getChromeStorage, setChromeStorage } from '@/uilts/chromeExtension.js'
import { throttle, getQueryString, getCookie, nextTick } from '@/uilts/help'
import { discordAuthRedirectUri } from '@/http/configAPI'
import { reportSrcPublishEvent } from '@/http/publishApi'
import Report from "@/log-center/log"
import { fetchAddFinishEvent } from '@/logic/background/fetch/facebook';
import { showNFTGroupIcon, hideNFTGroupList, checkUserJoinGroup, addJoinedGroupList } from '@/logic/content/nft';

let dom = {};

function twitterPinLogin() {
    if (window.location.href == 'https://api.twitter.com/oauth/authorize') {
        let code = document.querySelector('code')

        if (code) {
            chrome.runtime.sendMessage({ actionType: "CONTENT_SEND_CODE", code: code.innerText }, () => { })
            // port.postMessage({ state: 'CONTENT_SEND_CODE', code: code.innerText })
        }
    }
}

function getDiscordAuthCode() {
    if (window.location.href.indexOf(discordAuthRedirectUri) > -1) {
        const urlParams = new URLSearchParams(window.location.search);
        const code = urlParams.get('code');
        if (code) {
            chrome.runtime.sendMessage({ actionType: "CONTENT_SEND_DISCORD_AUTH_CODE", code }, () => { })
        }
    }
};



/**
 * 渲染要插入的dom,初始化逻辑
 * @param port
 */
function renderDom() {
    if (window.location.href.indexOf('https://twitter.com') > -1) {
        _createBtnDom();
        onWindowResize();
        checkHasDeBtn();
        setTimeout(() => {
            _addIframe();
            _addDeNetBtn();
            _getSliderTwitterBtn();
        }, 800)
    }
}

/**
 * 展示give弹窗
 */
export function showGiveDialogHandler(userInfo) {
    let iframe = document.getElementById('iframe-content');
    if (iframe) {
        iframe.contentWindow.postMessage({ actionType: 'CONTENT_SHOW_GIVE_DIALOG', userInfo }, '*');
    } else {
        _addIframe();
        let iframe = document.getElementById('iframe-content');
        iframe.contentWindow.postMessage({ actionType: 'CONTENT_SHOW_GIVE_DIALOG', userInfo }, '*');
    }
}

export function showIframeHandler() {
    document.getElementById('iframe-content').style.display = 'block';
}

export function hideIframeHandler() {
    document.getElementById('iframe-content').style.display = 'none';
}

/**
 * 展示twitter原生发布框
 */
let tweetPublishStore = {
    showPublishDialog: false
}
export function showTwitterPublishDialogHandler(publishRes) {
    let bigBtn = document.querySelector('a[data-testid="SideNav_NewTweet_Button"]');
    if (bigBtn) {
        bigBtn.click();
        tweetPublishStore.showPublishDialog = true;
    } else {
        let smallBtn = document.querySelector('a[href="/compose/tweet"]')
        smallBtn && smallBtn.click();
        tweetPublishStore.showPublishDialog = true;
    }

    setChromeStorage({ publishData: JSON.stringify(publishRes) })

    addPublishTipsIframe({
        srcContent: publishRes.copyContent
    })
    _setPublishContent(publishRes.srcContent);
    _publishTweetEvent(publishRes, bindTwitterArtMethod);
}

export function twitterPublishHandler(res) {
    let bigBtn = document.querySelector('a[data-testid="SideNav_NewTweet_Button"]');
    if (bigBtn) {
        bigBtn.click();
    } else {
        let smallBtn = document.querySelector('a[href="/compose/tweet"]')
        smallBtn && smallBtn.click();
    }

    nextTick(() => {
        document.execCommand('selectAll');
    }, 100).then(() => {
        _setPublishContent(res.srcContent, 500);
    })
}

export function showPinTips() {
    hidePopupPage();
    hideNoticeBindTweet();
    getChromeStorage('pinData', (res) => {
        if (!res || res.show) {
            let domPop = document.getElementById('de-pin-pop');
            domPop.style.display = 'block';
        }
    })
}

export function hidePinTips() {
    let pop = document.querySelector('#de-pin-pop');
    if (pop) {
        pop.style.display = 'none';
    }
}

function addPinedPop() {
    let domPop = document.getElementById('de-pin-pop');

    if (domPop) {
        return;
    }

    let popWrapper = document.createElement('div');
    popWrapper.style.cssText = 'position: fixed; height: 400px;width: 300px;top: 12px;right: 20px;border-radius: 12px;border: 0.5px solid #919191;box-sizing: border-box;padding: 20px;background: #fff;display:none';
    popWrapper.id = 'de-pin-pop'

    let img = document.createElement('img');
    img.src = require("@/assets/img/img-pined-guide.png");
    img.width = 253;

    let contentDom = document.createElement('div');
    contentDom.innerHTML = "<div style='font-weight: 500;font-size: 18px;margin-top: 20px;margin-bottom: 20px'>📌 Pin an Extension is more convenient to open😄</div><div style='display: flex; align-items: center; justify-content: space-between;'><div style='display: flex; align-items: center; font-size: 14px; color: #899099; cursor: pointer;' id='de-remind'><input id='de-check' type='checkbox'/> Don't remind</div><div class='de-pin-skip' style='font-weight: 500; font-size: 16px; color: #1D9BF0;cursor: pointer;'>Skip</div></div>"

    popWrapper.appendChild(img);
    popWrapper.appendChild(contentDom);

    document.querySelector('body').appendChild(popWrapper);

    let deCheck = document.querySelector('#de-check');
    let deRemind = document.querySelector('#de-remind');

    deCheck.onclick = function (e) {
        e && e.stopPropagation && e.stopPropagation();
        setChromeStorage({ pinData: JSON.stringify({ show: !this.checked }) })
    }

    deRemind.onclick = function () {
        deCheck.checked = !deCheck.checked;
        setChromeStorage({ pinData: JSON.stringify({ show: !deCheck.checked }) })
    }

    document.querySelector('.de-pin-skip').onclick = function () {
        document.querySelector('#de-pin-pop').style.display = 'none';
    }
}

function getUserInfo(cb) {
    getChromeStorage('userInfo', (res) => {
        cb && cb(res);
    })
}

// 绑定推文id所需参数
let bindTwitterArt = {
    needBind: false,
    postId: '',
    isBindIng: false
};
/**
 * 监听dialog内点击原生发布按钮事件
 * @private
 */
function _publishTweetEvent(params, cb) {
    setTimeout(() => {
        let publishTweetBtn;
        let dialog = document.querySelector('div[role="dialog"]');
        if (dialog) {
            publishTweetBtn = dialog.querySelector('div[data-testid="tweetButton"]');
            onClosePublishDialogHandle(dialog, params)
        } else {
            let domMain = document.querySelector('main[role="main"]');
            publishTweetBtn = domMain && domMain.querySelector('div[data-testid="tweetButton"]');
        }

        publishTweetBtn && publishTweetBtn.addEventListener('click', function () {
            bindTwitterArt.needBind = true;
            bindTwitterArt.postId = params.postId;
            tweetPublishStore.showPublishDialog = false;
            // checkIsShowReSend(dialog, params);
            cb && cb()
        });
    }, 800)
}

function onClosePublishDialogHandle(dom, params) {
    dom.querySelector('div[role="group"]').addEventListener('click', function () {
        setTimeout(() => {
            let parent = document.querySelector('div[data-testid="confirmationSheetDialog"]');
            if (parent) {
                let btnArr = parent.querySelectorAll('div[role=button]')
                for (let i = 0; i < btnArr.length; i++) {
                    let btn = btnArr[i];
                    btn.addEventListener('click', function () {
                        tweetPublishStore.showPublishDialog = false;
                        let taskLuckdropId = JSON.parse(params.postBizData).taskLuckdropId;
                        noticeBindTweet({ postId: params.postId, taskLuckdropId });
                    })
                }
            } else {
                setTimeout(() => {
                    let dialog = document.querySelector('div[role="dialog"]');
                    if (!dialog) {
                        tweetPublishStore.showPublishDialog = false;
                    }
                }, 800)
            }
        }, 1000)
    })
}

function checkIsShowReSend(dom, params) {
    let str = dom.querySelector('div[data-contents="true"]').innerHTML;
    if (str.indexOf(params.postId) < 0) {
        let taskLuckdropId = JSON.parse(params.postBizData).taskLuckdropId;
        noticeBindTweet({ postId: params.postId, taskLuckdropId });
    }
}

/**
 * 在输入推文区插入deNet按钮
 * @param parent
 * @param dom
 * @param isClick
 * @private
 */
function _addDeNetEditBtn(parent, dom, isClick = false) {
    setTimeout(() => {
        if (parent && parent.parentNode) {
            Report.reportLog({
                pageSource: Report.pageSource.mainPage,
                businessType: Report.businessType.buttonView,
                objectType: Report.objectType.buttonSecond
            });
            let innerDeIcon = document.getElementById('de-btn1');
            if (!innerDeIcon) {
                parent.parentNode.insertBefore(dom, parent.nextElementSibling);
            }
        } else {
            setTimeout(() => {
                parent = _getScheduleDom(isClick);
                if (parent && parent.parentNode) {
                    Report.reportLog({
                        pageSource: Report.pageSource.mainPage,
                        businessType: Report.businessType.buttonView,
                        objectType: Report.objectType.buttonSecond
                    });
                    let innerDeIcon = document.getElementById('de-btn1');
                    if (!innerDeIcon) {
                        parent.parentNode.insertBefore(dom, parent.nextElementSibling);
                    }
                }
            }, 1000)
        }
    })
}

/**
 * 在dialog插入deNet按钮
 * @private
 */
// function _addDeNetBtnToDialog() {
//     setTimeout(() => {
//         let dialogScheduleBtn = _getScheduleDom(true);
//         _addDeNetEditBtn(dialogScheduleBtn, dom.deBtn2);
//     }, 800)
// }

/**
 * 获取左侧twitter按钮
 * @private
 */
function _getSliderTwitterBtn() {
    dom.tweetBtn = document.querySelector('a[data-testid="SideNav_NewTweet_Button"]');
    dom.tweetBtn.addEventListener('click', function () {
        // _addDeNetBtnToDialog();
    })
}

/**
 * 添加deNet按钮
 * @private
 */
function _addDeNetBtn() {
    setTimeout(() => {
        let navWidth = document.querySelector('nav[role="navigation"]').offsetWidth;
        addSliderNavDeBtn(navWidth < 245);
        let innerDeIcon = document.getElementById('de-btn1');
        if (!innerDeIcon) {
            let dialogScheduleBtn = _getScheduleDom(false);
            dom && dom.deBtn1 && _addDeNetEditBtn(dialogScheduleBtn, dom.deBtn1);
        }
    }, 800)
}

/**
 * 获取推文输入框内dom,用于插入deNet
 * @param isDialogInner
 * @returns {Element}
 * @private
 */
function _getScheduleDom(isDialogInner = false) {
    let scheduleBtn;
    if (isDialogInner) {
        scheduleBtn = document.querySelector('div[role="dialog"]').querySelector('[data-testid="createPollButton"]');
    } else {
        let toolBar = document.querySelector('div[data-testid="toolBar"]');
        if (toolBar) {
            scheduleBtn = toolBar.querySelector('div[data-testid="geoButton"]');
        }
    }
    return scheduleBtn;
}

/**
 * 插入iframe到页面
 * @private
 */
function _addIframe() {
    // let span = document.createElement('span');
    // const shadowRoot = span.attachShadow({mode: 'closed'})
    let iframe = document.createElement('iframe');
    iframe.src = chrome.runtime.getURL('/iframe/publish.html')
    iframe.id = 'iframe-content'
    iframe.style.cssText = 'position:fixed;top:0px;right:0;display:block; width:100%;height:100%;z-index:10000; border: medium none;display:none';
    // shadowRoot.appendChild(iframe);
    // document.body.appendChild(span)
    dom.iframe = iframe;
    let iframeContent = document.getElementById('iframe-content');
    if (!iframeContent) {
        document.querySelector('body').appendChild(iframe);
    }
}

function addPublishTipsIframe(params = {}) {
    let { time = 1000 } = params;
    setTimeout(() => {
        let dialog = document.querySelector('div[role="dialog"]').querySelector('div[role="dialog"]')

        if (dialog) {
            let right = dialog.offsetLeft - 15 - 266;

            let iframe = document.createElement('iframe');
            iframe.id = 'de-publish-tips'
            iframe.src = chrome.runtime.getURL('/iframe/publish-tips.html');
            iframe.style.cssText = `border: medium none; width:270px;height:500px;position: fixed; right: ${right}px; top: 5%;z-index: -1`
            let iframeContent = document.getElementById('de-publish-tips');
            if (!iframeContent) {
                dialog.appendChild(iframe)
            }
        }
    }, time)
}

export function noticeBindTweet(params) {
    hidePinTips();
    hidePopupPage();
    let iframe = document.createElement('iframe');
    iframe.id = 'de-notice-bind-tweet';
    iframe.src = chrome.runtime.getURL('/iframe/bind-tweet.html') + `?params=${JSON.stringify(params)}`;
    iframe.style.cssText = `border: medium none; width:400px;min-height:313px;position: fixed; right: 16px; top: 16px;`
    let iframeContent = document.getElementById('de-notice-bind-tweet');
    if (!iframeContent) {
        document.querySelector('body').appendChild(iframe)
    }
}

export function hideNoticeBindTweet() {
    let iframeContent = document.getElementById('de-notice-bind-tweet');
    if (iframeContent) {
        document.querySelector('body').removeChild(iframeContent)
    }
}

/**
 * 点击deNet按钮处理
 * @private
 */
function _deNetBtnClick() {
    getUserInfo((res) => {
        if (res) {
            if (window.location.pathname != '/home') {
                if (!dom.homeBtn) {
                    dom.homeBtn = document.querySelector('a[data-testid="AppTabBar_Home_Link"]');
                }
                dom.homeBtn.click();
            }
            showGiveDialogHandler(res);
        } else {
            let loadIcon = document.getElementById('de-btn-loading');
            if (loadIcon) {
                return;
            }
            dom && dom.deBtn && dom.deBtn.insertBefore(dom.loadingImg, dom.deBtn.querySelector('span'));
            setTimeout(() => {
                dom.loadingImg.style.transform = 'rotate(1080deg)'
            });
            setTimeout(() => {
                dom.loadingImg.style.transform = 'rotate(0deg)'
                dom.deBtn.innerHTML = '<span>DeNet<span>';
            }, 2000)

            chrome.runtime.sendMessage({ actionType: "CONTENT_TWITTER_LOGIN", data: '1' }, (res) => { console.log(res) })
        }
    })
}

/**
 * 设置发布内容
 * @param content
 * @private
 */
let isSetContent = false;
export const _setPublishContent = throttle(function (content, time = 1000) {
    if (!isSetContent) {
        isSetContent = true;
        let inputEle = document.querySelector('div[contenteditable="true"]');
        if (inputEle) {
            inputEle.focus();
        }
        setTimeout(() => {
            document.execCommand("insertText", false, content);
            setTimeout(() => {
                isSetContent = false;
            }, 2000)
        }, time);
    }
}, 800);

/**
 * 创建deNet按钮 添加到页面
 * @returns {{deBtn2: HTMLDivElement, deBtn1: HTMLDivElement, deBtn: HTMLSpanElement}}
 * @private
 */
function _createBtnDom() {
    let loadingImg = document.createElement('img');
    loadingImg.id = 'de-btn-loading'
    loadingImg.src = require("@/assets/img/icon-btn-loading.png");
    loadingImg.style.cssText = 'width:20px;height: 20px;margin-right:3px;transition-duration: 3s;';

    let style = document.createElement('style');
    style.innerHTML = "#de-btn:hover{opacity: .9;};@-webkit-keyframes load{from{ transform: rotate(0deg);} to{transform: rotate(360deg);}}";
    document.getElementsByTagName('head').item(0).appendChild(style);

    // 左侧大屏按钮
    let deBtn = document.createElement('span');
    // const shadowDiv = document.createElement('div');
    deBtn.innerHTML = '<span>DeNet</span>';
    deBtn.id = 'de-btn';
    deBtn.style.cssText = 'width:90%;height: 52px;text-align:center;line-height:52px;margin-bottom: 4px;margin-top: 4px;background: linear-gradient(274.8deg, #FF9900 -3.69%, #BD00FF 69.71%, #00F0FF 122.65%);color:#fff;font-size:17px;font-weight:700;border-radius:100px;cursor: pointer;display: flex;align-items: center;justify-content: center;';

    // 编辑框内按钮
    const deBtn1 = document.createElement('img');
    let src = require("@/assets/img/icon-gift-pack.png");
    const smallDeBtnStyle = 'width:20px;height: 20px;cursor: pointer;padding: 0px 8px';
    deBtn1.id = 'de-btn1';
    deBtn1.style.cssText = smallDeBtnStyle;
    deBtn1.src = src

    const deBtn2 = document.createElement('div');
    deBtn2.id = 'de-btn2';
    deBtn2.style.cssText = smallDeBtnStyle;
    deBtn2.src = "@/assets/img/icon-gift-pack.png"

    // 小屏按钮
    const deBtn3 = document.createElement('img');
    deBtn3.id = 'de-btn3'
    deBtn3.src = require("@/assets/logo/128.png");
    deBtn3.style.cssText = 'width:52px;height: 52px;margin-top:20px;cursor: pointer;';

    deBtn.addEventListener('click', () => {
        // chrome.runtime.sendMessage({
        //     actionType: 'CONTENT_SET_BADGE',
        //     data: {
        //         text: '2'
        //     }
        // }, res => {
        //     console.log(res);
        // })

        Report.reportLog({
            pageSource: Report.pageSource.mainPage,
            businessType: Report.businessType.buttonClick,
            objectType: Report.objectType.buttonMain
        });
        _deNetBtnClick();
    })
    deBtn1.addEventListener('click', () => {
        Report.reportLog({
            pageSource: Report.pageSource.mainPage,
            businessType: Report.businessType.buttonClick,
            objectType: Report.objectType.buttonSecond
        });
        _deNetBtnClick();
    })
    deBtn2.addEventListener('click', () => {
        _deNetBtnClick();
    })
    deBtn3.addEventListener('click', () => {
        Report.reportLog({
            pageSource: Report.pageSource.mainPage,
            businessType: Report.businessType.buttonClick,
            objectType: Report.objectType.buttonMain
        });
        _deNetBtnClick();
    })
    dom.deBtn = deBtn;
    dom.deBtn1 = deBtn1;
    dom.deBtn2 = deBtn2;
    dom.deBtn3 = deBtn3;
    dom.loadingImg = loadingImg;
}

function addSliderNavDeBtn(isSmall = false) {
    if (!isSmall) {
        let bigDom = document.querySelector('a[href="/compose/tweet"]').parentNode.parentNode;
        let deBtn = document.getElementById('de-btn');
        if (bigDom && !deBtn) {
            dom && dom.deBtn && bigDom.appendChild(dom.deBtn);
            Report.reportLog({
                pageSource: Report.pageSource.mainPage,
                businessType: Report.businessType.buttonView,
                objectType: Report.objectType.buttonMain
            });
        }
    } else {
        let smallDom = document.querySelector('a[href="/compose/tweet"]').parentNode.parentNode;
        let deBtn3 = document.getElementById('de-btn3');
        if (smallDom && !deBtn3) {
            dom && dom.deBtn3 && smallDom.appendChild(dom.deBtn3);
            Report.reportLog({
                pageSource: Report.pageSource.mainPage,
                businessType: Report.businessType.buttonView,
                objectType: Report.objectType.buttonMain
            });
        }
    }
}

function onWindowResize() {
    window.onresize = throttle(function () {
        try {
            if (tweetPublishStore.showPublishDialog) {
                let dialog = document.querySelector('div[role="dialog"]');
                let dePublishTips = document.getElementById('de-publish-tips');
                if (dialog && !dePublishTips) {
                    addPublishTipsIframe({ time: 0 });
                } else if (dialog && dePublishTips) {
                    let dialogContent = dialog.querySelector('div[role=dialog]')
                    if (dialogContent) {
                        let right = dialogContent.offsetLeft - 15 - 266;
                        dePublishTips.style.right = right + 'px';
                    }
                }
            }

            if (window.innerWidth < 1273) {
                let bigBtn = document.querySelector('#de-btn');
                bigBtn && bigBtn.remove();
                setTimeout(() => {
                    addSliderNavDeBtn(true);
                })
            } else {
                let smallBtn = document.querySelector('#de-btn3');
                smallBtn && smallBtn.remove();
                setTimeout(() => {
                    addSliderNavDeBtn()
                })
            }
        } catch (e) {
            console.log(e)
        }
    }, 800)
}

function checkHasDeBtn() {
    try {
        let toolBar = document.querySelector('div[data-testid="toolBar"]');
        let innerDeIcon = document.getElementById('de-btn1');
        if (toolBar && !innerDeIcon) {
            let dialogScheduleBtn = _getScheduleDom(false);
            dom && dom.deBtn1 && _addDeNetEditBtn(dialogScheduleBtn, dom.deBtn1);
        }
    } catch (e) {
        console.log(e)
    }
}

/**
 * 点击发推，后端绑定推特id
 */
function bindTwitterArtMethod() {
    if (!bindTwitterArt.postId) {
        return
    }
    if (bindTwitterArt.needBind && !bindTwitterArt.isBindIng) {
        bindTwitterArt.isBindIng = true;
        reportSrcPublishEvent({
            params: {
                postId: bindTwitterArt.postId,
            }
        }).then((res) => {
            if (res.code == 0) {
                Report.reportLog({
                    objectType: Report.objectType.tweetPostBinded
                });
                bindTwitterArt.needBind = false;
                bindTwitterArt.postId = '';
                bindTwitterArt.isBindIng = false;
            }
        })
    }
}


import parseCard from './ParseCard'

// 检测dom改变 
// 获取短链接 
// 查看本地是否有postid 
// 如果有 修改dom 返回 
// 如果没有 网络请求 
// 获取postid 
// 获取twitterid 
// 检测当前所有dom 如果没有 



let queue_num = 1

export const changeQueueNum = (num = 0) => {
    queue_num = queue_num + num
    if (queue_num > 5) {
        queue_num = 5
    }
}

let main_observer = null
function onChangePageMain(targetNode) {
    try {
        const config = { attributes: false, childList: true, subtree: true };
        const callback = (mutationsList, observer) => {
            changeQueueNum(1)
        }
        main_observer = new MutationObserver(callback);
        main_observer.observe(targetNode, config);
    } catch (error) {
        main_observer = null
    }
}

// 1.监听main改变
// 2.监听卡片是否可见
// 3.如果可见了 去找

function setIframeRedPacket(type = 'twitter') {
    // 获取所有卡片参数
    let card_json_data
    switch (type) {
        case 'facebook':
            card_json_data = parseCard.parseFacebookCardParmas()
            for (let i in card_json_data) {
                parseCard.replaceFacebookPacket(card_json_data[i])
            }
            break;
        default:
            card_json_data = parseCard.parseAllDeNetCardParmas()
            // 过滤出可以请求的短链接
            parseCard.getCardParmas(card_json_data).then((res) => {
                for (let i in res.has_post_Id_card_data) {
                    let item = res.has_post_Id_card_data[i];
                    if (item && item.post_Id && item.post_Id.indexOf('nft/') >= 0) {
                        parseCard.replaceNftDomRedPacket(item)
                    } else {
                        parseCard.replaceDOMRedPacket(item)
                    }
                }
                if (res.need_net_short_url.length > 0) {
                    // 请求短链接
                    chrome.runtime.sendMessage({ actionType: "CONTENT_TWITTER_SHORT_LINK", data: "", arr_url: res.need_net_short_url }, () => { })
                }
            })
            break;
    }
}

// 监听点击发推 按钮绑定事件
// document.addEventListener('click', (e) => {
//     try {
//         if (e.target.dataset && e.target.dataset.testid && e.target.dataset.testid == 'tweetButton') {
//             bindTwitterArtMethod()
//         } else if (e.target.closest('div[data-testid=tweetButton]')) {
//             bindTwitterArtMethod()
//         }
//     } catch (error) {
//         console.error('error', error)
//     }
// })


export function initExecuteScript(changes) {
    if (changes.executeScript) {
        let item = JSON.parse(changes.executeScript.newValue)
        if (item.executeScript) {
            init()
        }
    }
}

const createNFTIframe = ({ url, id }, callback) => {
    let iframe = document.createElement('iframe')
    iframe.id = id
    iframe.src = url
    iframe.style.cssText = 'border:medium none; width:100%; height:100%; z-index:100; position: fixed; top:0;left:0; display:none;';
    iframe.onload = () => {
        callback && callback()
    }
    document.body.appendChild(iframe);
}


function initParseCard() {
    let timer = setInterval(() => {
        let inTwitter = window.location.href.includes('twitter.com');
        let inTwitterNode = document.querySelector('main');
        let inFacebook = window.location.href.includes('facebook.com');
        let inFacebookNode = document.querySelector('#facebook');
        if (inTwitter && inTwitterNode) {
            clearInterval(timer)
            setInterval(() => {
                if (!main_observer) {
                    onChangePageMain(inTwitterNode)
                    changeQueueNum(1)
                }
                if (queue_num <= 0) {
                    return
                }
                showNFTGroupIcon()
                setIframeRedPacket()
                checkHasDeBtn()
                checkHasSliderDeBtn();
                changeQueueNum(-1)
                showNFTCard()
                addGroupTab();
                addJoinedGroupList();
            }, 1000)
        } else if (inFacebook && inFacebookNode) {
            clearInterval(timer)
            setInterval(() => {
                if (!main_observer) {
                    onChangePageMain(inFacebookNode)
                    changeQueueNum(1)
                }
                if (queue_num <= 0) {
                    return
                }
                setIframeRedPacket('facebook')
                changeQueueNum(-1)
            }, 1000)
        }
    }, 1000);
}
let inited = false
// 初始化
export function init() {
    if (inited) {
        return
    }
    inited = true
    console.log('init')

    getDiscordAuthCode();
    appendPopupPage();

    chrome.runtime.sendMessage({ 
        actionType: "CONTENT_SET_POPUP_CONFIG", 
        data: {
            popup: 'popup.html'
        } 
    }, () => { });

    let where = window.location.href.indexOf('twitter.com') < 0 && window.location.href.indexOf('facebook.com') < 0;
    if (where) {
        return
    }
    twitterPinLogin();
    // 渲染dom
    initParseCard()
    showNFTCard()
    showNFTGroupIcon()
    addEventAction();
    checkUserJoinGroup();
    renderDom();
    checkTwitterTaskState();
    initBuyNFT();
    addGroupTab();
    addJoinedGroupList();

    getChromeStorage("popupShowPublishDialog", (res) => {
        console.log("popupShowPublishDialog", res);
        if (res && res.show) {
            setTimeout(() => {
                showTwitterPublishDialogHandler({
                    srcContent: res.srcContent,
                    postId: res.postId,
                    copyContent: res.copyContent || ''
                });
            }, 1500);
            chrome.storage.local.remove("popupShowPublishDialog");
        }
    });
    getChromeStorage("userSettings", (res) => {
        setTimeout(() => {
            addPinedPop();
            if (res && !res.isOnToolbar) {
                setTimeout(() => {
                    showPinTips();
                    chrome.storage.local.remove("userSettings");
                }, 800);
            }
        }, 800);
    });
}

function checkHasSliderDeBtn() {
    let deBtn = document.getElementById('de-btn');
    let deBtn3 = document.getElementById('de-btn3');
    if (!deBtn && !deBtn3) {
        addSliderNavDeBtn();
    }
}

export function facebookReplyTweet(params) {
    if (window.location.origin.indexOf('twitter.com')) {
        const urlParams = new URLSearchParams(window.location.search);
        const actionType = urlParams.get('actionType');
        let deReplyParams = urlParams.get('deReplyParams') || '{}';
        deReplyParams = JSON.parse(deReplyParams);
        if (actionType == 'denetFacebookToTwitterReply') {
            if (params.postId == deReplyParams.postId) {
                let iframe = document.getElementById(params.postId);
                iframe.contentWindow.postMessage({ actionType: 'CONTENT_RED_PACKET_FACEBOOK_REPLY', data: deReplyParams }, '*');
            }
        }
    }
}

export function replyHandle(params) {
    let iframe = window.parent.document.getElementById(params.postId);
    let replyBtn = iframe.parentNode.parentNode.querySelector('div[data-testid="reply"]') ||
        iframe.parentNode.parentNode.parentNode.querySelector('div[data-testid="reply"]');
    if (replyBtn) {
        replyBtn.click();
    }
    onReplyDialogOpen(params, iframe);

    // 详情页推文底部评论处理
    let pathNameArr = window.location.pathname.split('/');
    if (pathNameArr.length >= 2 && pathNameArr[pathNameArr.length - 2] == 'status') {
        let tweetReply = document.querySelector('div[data-testid="tweetButtonInline"]');
        if (tweetReply) {
            tweetReply.addEventListener('click', function () {
                // 详情页回复按钮点击
                Report.reportLog({
                    pageSource: Report.pageSource.mainPage,
                    businessType: Report.businessType.buttonClick,
                    objectType: Report.objectType.replyClickByDetailPage
                });

                let eleList = tweetReply.parentNode.parentNode.parentNode.parentNode.parentNode.querySelectorAll('span[data-text="true"]');
                reportReplyResult(eleList, params, () => {
                    // iframe.contentWindow.postMessage({ actionType: 'CONTENT_RED_PACKET_REPLY_RASK_FINSH', data: {} }, '*');
                    chrome.runtime.sendMessage({ actionType: "CONTENT_RED_PACKET_REPLY_RASK_FINSH", data: { postId: params.postId } }, () => { })
                });
            })
        }
    }
}

export function onTweetReplyClick(params) {
    let iframe = window.parent.document.getElementById(params.postId);
    let replyBtn = iframe.parentNode.parentNode.querySelector('div[data-testid="reply"]') ||
        iframe.parentNode.parentNode.parentNode.querySelector('div[data-testid="reply"]');
    if (replyBtn) {
        replyBtn.addEventListener('click', () => {
            onReplyDialogOpen(params, iframe);
        })
    }
}

function onReplyDialogOpen(params, iframe) {
    setTimeout(() => {
        let dialog = document.querySelector('div[role="dialog"]');
        let replyBtn;

        if (dialog) {
            let dialogContent = dialog.querySelector('div[role="dialog"]');
            replyBtn = dialog.querySelector('div[data-testid="toolBar"]').querySelector('div[data-testid="tweetButton"]');
            if (dialogContent) {
                let width = dialogContent.offsetWidth;
                let ele = document.createElement('div');
                ele.innerText = 'Tag 3 friends to complete the task';
                ele.style.cssText = `width: ${width}px; height: 38px; color: #fff; font-weight: 600;
                font-size: 16px; display: flex; align-items: center; justify-content: center; background: #1D9BF0;
                opacity: 0.8; position: absolute; top: 18px; left: 50%; transform: translateX(-50%); z-index: 1000`;

                dialogContent.style.top = '80px';
                dialogContent.parentNode.appendChild(ele);
            }
        } else {
            dialog = document.querySelector('main[role="main"]');
            if (dialog) {
                replyBtn = dialog.querySelector('div[data-testid="tweetButton"]');
            }
        }

        if (dialog && replyBtn) {
            replyBtn.addEventListener('click', function () {
                // 推文页回复按钮点击
                Report.reportLog({
                    pageSource: Report.pageSource.mainPage,
                    businessType: Report.businessType.buttonClick,
                    objectType: Report.objectType.replyClickByTwitterList
                });

                let eleList = dialog.querySelector('div[contenteditable="true"]').querySelectorAll('span[data-text="true"]');
                reportReplyResult(eleList, params, () => {
                    // 上報完成
                    // iframe.contentWindow.postMessage({ actionType: 'CONTENT_RED_PACKET_REPLY_RASK_FINSH', data: {} }, '*');
                    chrome.runtime.sendMessage({ actionType: "CONTENT_RED_PACKET_REPLY_RASK_FINSH", data: { postId: params.postId } }, () => { })
                })
            });
        }
    }, 1000);
}

const reportReplyResult = throttle(function (eleList, params, cb) {
    //未过滤的回复文本
    Report.reportLog({
        pageSource: Report.pageSource.mainPage,
        businessType: Report.businessType.buttonClick,
        objectType: Report.objectType.replyInputTextGet
    }, {
        replyStr: eleList
    });

    if (eleList && eleList.length) {
        let atList = [];
        for (let i = 0; i < eleList.length; i++) {
            let item = eleList[i];
            // 是否有中文
            let reg = /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/g;

            if (item && item.innerText.startsWith('@') && !reg.test(item.innerText)) {
                atList.push(item.innerText);
            }
        }

        // 去重过滤文本
        atList = Array.from(new Set(atList));

        Report.reportLog({
            pageSource: Report.pageSource.mainPage,
            businessType: Report.businessType.buttonClick,
            objectType: Report.objectType.replyFilterTextGet
        }, {
            replyStr: atList
        });

        if (atList.length >= 3) {
            //真实上报
            Report.reportLog({
                pageSource: Report.pageSource.mainPage,
                businessType: Report.businessType.buttonClick,
                objectType: Report.objectType.replyReport
            }, {
                replyStr: atList
            });

            fetchAddFinishEvent({
                eventType: params.type,
                luckdropId: params.taskLuckdropId
            }).then(res => {
                if (res.code == 0) {
                    cb && cb();
                }
            })
        }
    }
}, 800);



// 根据推特id找到dom，完成任务
export function findTweetByIdDoTask({ tweet_Id = '', follow_names = [] }, task_type = 'like') {
    // 1.根据推特ID寻找推文，获取卡片
    // 获取所有卡片参数
    let card_json_data = parseCard.parseAllDeNetCardParmas()
    let result = card_json_data.filter((item) => { return item.tweet_Id == tweet_Id }) || []
    if (result.length < 1) {
        return
    }
    result = result[0]

    switch (task_type) {
        case 'like':
            // https://twitter.com/intent/retweet?tweet_id=1525900221628223491
            if (result.dom_card) {
                result.dom_card.querySelector('div[data-testid=like]').click()
                result.dom_card.querySelector('iframe').contentWindow.postMessage({ actionType: 'CONTENT_DONE_TASK', task_type, }, '*');
            }
            break;
        case 'retweet':
            if (result.dom_card) {
                result.dom_card.querySelector('div[data-testid=retweet]').click()
                result.dom_card.querySelector('div[data-testid=retweetConfirm]').click()
            }
            break
        case 'follow':
            follow_names.forEach((item) => {
                window.open(`https://twitter.com/intent/follow?screen_name=${item}&tweet_Id=${tweet_Id}`)
            })
            break
    }
}

function clickByDataTestId(e, id, callback) {
    if (e.target.dataset && e.target.dataset.testid && e.target.dataset.testid == id) {
        callback()
    } else if (e.target.closest('div[data-testid=' + id + ']')) {
        callback()
    }
}

// 校验关注推特状态 
export function checkTwitterTaskState() {
    let task_type = ''
    let url = window.location.href
    let tweet_Id
    let task_data = {
        follow_name: ''
    }
    // 校验当前链接
    if (url.includes('https://twitter.com/intent/retweet')) {
        task_type = 'retweet'
    } else if (url.includes('https://twitter.com/intent/follow')) {
        task_type = 'follow'
        task_data.follow_name = getQueryString('screen_name')
    } else if (url.includes('https://twitter.com/intent/like')) {
        task_type = 'like'
    } else {
        return
    }
    tweet_Id = getQueryString('tweet_id')

    // let root_status
    document.body.addEventListener('click', (e) => {
        // 点击 确认
        clickByDataTestId(e, 'confirmationSheetConfirm', () => {
            chrome.runtime.sendMessage({ actionType: "DO_TASK", tweet_Id, task_type, task_data, task_done: true }, () => { })
        })
        // 点击取消
        clickByDataTestId(e, 'confirmationSheetCancel', () => {
            chrome.runtime.sendMessage({ actionType: "DO_TASK", tweet_Id, task_type, task_data, task_done: false }, () => { })
        })
        // 点击 蒙层
        if (e.target && e.target.nextSibling && e.target.nextSibling.dataset && e.target.nextSibling.dataset.testid == 'confirmationSheetDialog') {
            chrome.runtime.sendMessage({ actionType: "DO_TASK", tweet_Id, task_type, task_data, task_done: false }, () => { })
        }
    }, true)

    let timer = setInterval(() => {
        // 喜欢
        if (document.querySelector('div[data-testid=unlike]') && task_type == 'like') {
            clearInterval(timer)
            chrome.runtime.sendMessage({ actionType: "DO_TASK", tweet_Id, task_type, task_data, task_done: true }, () => { })
        }
        // 转推
        if (document.querySelector('div[data-testid=unretweet]') && task_type == 'retweet') {
            clearInterval(timer)
            chrome.runtime.sendMessage({ actionType: "DO_TASK", tweet_Id, task_type, task_data, task_done: true }, () => { })
        }
        // 关注
        if (task_type == 'follow') {
            let follow_area = document.querySelector('div[data-testid=placementTracking]')
            if (follow_area && follow_area.querySelectorAll('div')) {
                follow_area = follow_area.querySelectorAll('div')
                clearInterval(timer)
                for (let i in follow_area) {
                    if (follow_area[i] && follow_area[i].dataset && follow_area[i].dataset.testid && follow_area[i].dataset.testid.indexOf('unfollow') > 0) {
                        chrome.runtime.sendMessage({ actionType: "DO_TASK", tweet_Id, task_type, task_data, task_done: true }, () => { })
                        break
                    }
                }
            }
        }
    }, 1000)
}

export function getTweetAuthorByDom(params) {
    let iframe = document.getElementById(params.postId);
    if (!iframe) {
        return;
    }
    let fullNameDom;
    let pathNameArr = window.location.pathname.split('/');
    if (pathNameArr.length >= 2 && pathNameArr[pathNameArr.length - 2] == 'status') {
        fullNameDom = iframe.parentNode.parentNode.parentNode.parentNode.querySelector('a[role=link]');
    } else {
        fullNameDom = iframe.parentNode.parentNode.parentNode.querySelector('a[role=link]');
    }
    if (fullNameDom) {
        let arr = fullNameDom.href.split('/');
        if (arr.length) {
            let fullName = arr[arr.length - 1];
            if (fullName) {
                iframe.contentWindow.postMessage({ actionType: 'CONTENT_RED_PACKET_GET_TWEET_AUTHOR', data: { fullName } }, '*');
            }
        }
    }
}
export function doTaskTwitterAPI({ task_data, task_type }) {
    switch (task_type) {
        case 'like':
            TwitterLikeAPI(task_data.tweet_Id)
            break
        case 'retweet':
            TwitterRetweetAPI(task_data.tweet_Id)
            break
        case 'follow':
            task_data.follow_data.forEach((item) => {
                if (item.name && item.twitterUserId) {
                    TwitterFollowAPI(item, task_data.tweet_Id)
                }
            })
            break
    }
}

const TwitterFollowAPI = (item, tweet_Id) => {
    fetch("https://twitter.com/i/api/1.1/friendships/create.json", {
        "headers": {
            "authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA",
            "content-type": "application/x-www-form-urlencoded",
            "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"102\", \"Google Chrome\";v=\"102\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"macOS\"",
            "x-csrf-token": getCookie('ct0'),
            "x-twitter-active-user": "yes",
            "x-twitter-auth-type": "OAuth2Session",
            "x-twitter-client-language": "zh-cn"
        },
        "referrer": "https://twitter.com/home",
        "referrerPolicy": "strict-origin-when-cross-origin",
        "body": "include_profile_interstitial_type=1&include_blocking=1&include_blocked_by=1&include_followed_by=1&include_want_retweets=1&include_mute_edge=1&include_can_dm=1&include_can_media_tag=1&include_ext_has_nft_avatar=1&skip_status=1&user_id=" + item.twitterUserId + "",
        "method": "POST",
        "mode": "cors",
        "credentials": "include"
    }).then(() => {
        let task_data = {
            follow_name: item.name
        }
        chrome.runtime.sendMessage({ actionType: "DO_TASK", do_type: 'api', tweet_Id, task_type: 'follow', task_data, task_done: true }, () => { })
    }).catch(() => {
        chrome.runtime.sendMessage({ actionType: "DO_TASK", do_type: 'api', tweet_Id, task_type: 'follow', task_data, task_done: false }, () => { })
    })
}


const TwitterRetweetAPI = (tweet_Id) => {
    fetch("https://twitter.com/i/api/graphql/ojPdsZsimiJrUGLR1sjUtA/CreateRetweet", {
        "headers": {
            "accept": "*/*",
            "accept-language": "zh,en;q=0.9,zh-CN;q=0.8",
            "authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA",
            "content-type": "application/json",
            "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"102\", \"Google Chrome\";v=\"102\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"macOS\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "x-csrf-token": getCookie('ct0'),
            "x-twitter-active-user": "yes",
            "x-twitter-auth-type": "OAuth2Session",
            "x-twitter-client-language": "zh-cn"
        },
        "referrer": "https://twitter.com/home",
        "referrerPolicy": "strict-origin-when-cross-origin",
        "body": "{\"variables\":{\"tweet_id\":\"" + tweet_Id + "\",\"dark_request\":false},\"queryId\":\"ojPdsZsimiJrUGLR1sjUtA\"}",
        "method": "POST",
        "mode": "cors",
        "credentials": "include"
    }).then(() => {
        chrome.runtime.sendMessage({ actionType: "DO_TASK", do_type: 'api', tweet_Id, task_type: 'retweet', task_data: '', task_done: true }, () => { })
    }).catch(() => {
        chrome.runtime.sendMessage({ actionType: "DO_TASK", do_type: 'api', tweet_Id, task_type: 'retweet', task_data: '', task_done: false }, () => { })
    })
}

const TwitterLikeAPI = (tweet_Id) => {
    fetch("https://twitter.com/i/api/graphql/lI07N6Otwv1PhnEgXILM7A/FavoriteTweet", {
        "headers": {
            "accept": "*/*",
            "accept-language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
            "authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA",
            "content-type": "application/json",
            "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"101\", \"Google Chrome\";v=\"101\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "x-csrf-token": getCookie('ct0'),
            "x-twitter-active-user": "yes",
            "x-twitter-auth-type": "OAuth2Session",
            "x-twitter-client-language": "en"
        },
        "referrer": "https://twitter.com/home",
        "referrerPolicy": "strict-origin-when-cross-origin",
        "body": "{\"variables\":{\"tweet_id\":\"" + tweet_Id + "\"},\"queryId\":\"lI07N6Otwv1PhnEgXILM7A\"}",
        "method": "POST",
        "mode": "cors",
        "credentials": "include"
    }).then(() => {
        chrome.runtime.sendMessage({ actionType: "DO_TASK", do_type: 'api', tweet_Id, task_type: 'like', task_data: '', task_done: true }, () => { })
    }).catch(() => {
        chrome.runtime.sendMessage({ actionType: "DO_TASK", do_type: 'api', tweet_Id, task_type: 'like', task_data: '', task_done: false }, () => { })
    })
}

export const hideBuyNFT = () => {
    let iframe = document.querySelector('#nftProjectId')
    iframe.style.display = 'none'
    iframe.src = ''
}

export const showBuyNFT = ({ nft_project_Id }) => {
    if (!nft_project_Id) {
        return
    }
    let iframe = document.querySelector('#nftProjectId')
    iframe.style.display = 'block'
    iframe.src = chrome.runtime.getURL(`/iframe/buy-nft.html?nftProjectId=${nft_project_Id}`)
}

const initBuyNFT = () => {
    let url = chrome.runtime.getURL(`/iframe/buy-nft.html`)
    let id = `nftProjectId`
    createNFTIframe({ url, id })
}

export const showNFTCard = () => {
    let urlInfo = new URL(window.location.href)
    let isTwitter = urlInfo.hostname === 'twitter.com'
    let userElem = document.querySelector('div[data-testid="UserName"]');
    let sideElem = document.querySelector('div[data-testid="sidebarColumn"]')
    let tabIndex = sideElem && sideElem.querySelector('div[tabindex="0"]');
    let isAppend = document.querySelector('div[id="de-nft-node"]');
    let where = isTwitter && userElem && tabIndex;
    if (where) {
        let iframe = document.createElement('iframe');
        iframe.src = chrome.runtime.getURL(`/iframe/nft-card.html`)
        iframe.style.cssText = 'border:medium none; width:100%; height:290px;';
        let nftElement = document.createElement('div');
        nftElement.id = 'de-nft-node';
        nftElement.innerHTML = `
                ${iframe.outerHTML}
                <style>
                    #de-nft-node {height:290px; margin-bottom:17px; display:none;}
                </style>
            `;

        if (tabIndex && tabIndex.firstChild && tabIndex.firstChild.childNodes && !isAppend) {
            tabIndex.firstChild.insertBefore(nftElement, tabIndex.firstChild.childNodes[2]);
        }
    }
}

export const showNFTSale = () => {
    document.querySelector('div[id="de-nft-node"]').style.display = 'block';
}

export const addEventAction = () => {
    let urlInfo = new URL(window.location.href)
    let isTwitter = urlInfo.hostname === 'twitter.com'
    // 监听发推按钮
    let btn = document.querySelector('a[data-testid="SideNav_NewTweet_Button"]');
    btn && btn.addEventListener('click', () => {
        // 重置监听次数
        queue_num = 3;
    })

    // 页面滚动
    if (isTwitter) {
        // 首页
        if (urlInfo.pathname === '/home') {
            window.addEventListener('scroll', () => {
                hideNFTGroupList()
            })
        }
    }
}

export const appendPopupPage = (params = {}) => {
    let { path = '' } = params;

    let iframe = document.createElement('iframe');
        iframe.id = 'de-popup-page';
        iframe.src = chrome.runtime.getURL('/iframe/popup-page.html') + `#${path}`;
        iframe.style.cssText = `border: medium none; width: 375px;
        height: 650px;position: fixed; right: 16px; top: 16px;background: #FFFFFF;border: 0.5px solid #919191;box-shadow: 0px 4px 20px rgba(0, 0, 0, 0.2);box-sizing: border-box;z-index: 90000;
        animation-duration: 0.5s !important;
        animation-timing-function: ease-in-out !important;
        animation-fill-mode: forwards !important;
        transition: all 1s ease 0s !important;right: -385px;transform: translateX(385px);`
    let iframeContent = document.getElementById('de-popup-page');

    let overlayDom = document.createElement('div');
        overlayDom.id = 'de-popup-overlay';
        overlayDom.style.cssText = `position: fixed;z-index: 88888;top: 0;
        left: 0;width: 100%;height: 100%;opacity: 0;display: none`;

    let overlay = document.getElementById('de-popup-overlay');
    let body = document.querySelector('body');

    if (!iframeContent && body) {
        document.querySelector('body').appendChild(iframe);
        if(!overlay) {
            document.querySelector('body').appendChild(overlayDom);

            overlayDom.addEventListener('click', function() {
                hidePopupPage();
            })
        } else {
            overlay.addEventListener('click', function() {
                hidePopupPage();
            })
        }
    }
}

let showPopupPageFrom = '';
export const showPopupPage = (params = {}) => {
    let { path = '', from, showJoinGroupFinish = false } = params;
    showPopupPageFrom = from;
    hidePinTips();
    hideNoticeBindTweet();

    let iframe = document.getElementById('de-popup-page');
    if (!iframe) {
        appendPopupPage();
        iframe = document.getElementById('de-popup-page');
    }
    if(iframe) {
        if(path) {
            iframe.src = chrome.runtime.getURL('/iframe/popup-page.html') + `#${path}`;
        }
        iframe.style.transform = 'translateX(-' + 395 + 'px)';
    
        chrome.runtime.sendMessage({ 
            actionType: "CONTENT_POPUP_PAGE_SHOW", 
            data: {
                path,
                showJoinGroupFinish,
            }
        }, () => { });

        chrome.runtime.sendMessage({ 
            actionType: "CONTENT_SET_POPUP_CONFIG", 
            data: {
                popup: ''
            } 
        }, () => { });
    
        let overlay = document.getElementById('de-popup-overlay');
        overlay.style.display = 'block';
    
        let htmlDom = document.querySelector('html');
        if(htmlDom) {
            htmlDom.style.overflowY = 'hidden';
        }
    }
}

export const hidePopupPage = () => {
    let iframe = document.getElementById('de-popup-page');
    if (iframe) {
        iframe.style.transform = 'translateX(' + 385 + 'px)';

        let overlay = document.getElementById('de-popup-overlay');
        overlay.style.display = 'none';

        let htmlDom = document.querySelector('html');
        if(htmlDom) {
            htmlDom.style.overflowY = 'auto';
        }

        chrome.runtime.sendMessage({ 
            actionType: "CONTENT_SET_POPUP_CONFIG", 
            data: {
                popup: 'popup.html'
            } 
        }, () => { });

        if(showPopupPageFrom == 'BUY_NFT_FINISH') {
            chrome.runtime.sendMessage({ 
                actionType: "CONTENT_GET_PINED", 
                data: {} 
            }, () => { });
            showPopupPageFrom = '';
        }
    }
}

export const tiggerInjectPopupPage = () => {
    let iframeContent = document.getElementById('de-popup-page');
    if (iframeContent) {
        hidePinTips();
        hideNoticeBindTweet();
        let {transform = ''} = iframeContent.style;
        if(transform == 'translateX(385px)' || !transform) {
            showPopupPage();
        } else {
            hidePopupPage();
        }
    } else {
        appendPopupPage();
        setTimeout(() => {
            let iframe = document.getElementById('de-popup-page');
            let {transform = ''} = iframe.style;
            if(transform == 'translateX(385px)' || !transform) {
                showPopupPage();
            } else {
                hidePopupPage();
            }
        }, 300)
    }
}

export const setPopupConfByPopupPage = () => {
    let iframe = document.getElementById('de-popup-page');
    if (iframe) {
        let {transform = ''} = iframe.style;

        if(transform && transform == 'translateX(-395px)') {
            chrome.runtime.sendMessage({ 
                actionType: "CONTENT_SET_POPUP_CONFIG", 
                data: {
                    popup: ''
                } 
            }, () => { });
        } else {
            chrome.runtime.sendMessage({ 
                actionType: "CONTENT_SET_POPUP_CONFIG", 
                data: {
                    popup: 'popup.html'
                } 
            }, () => { });
        }
    } else {
        chrome.runtime.sendMessage({ 
            actionType: "CONTENT_SET_POPUP_CONFIG", 
            data: {
                popup: 'popup.html'
            } 
        }, () => { });
    }
}


/** 
 * 
 * Group Tab List Start 
 */

const addGroupTab = () => {
    let tabListDom = document.querySelector('div[role="tablist"]');
    let groupItemTab = document.querySelector('#de-nav-tab-group');

    let groupIcon = document.createElement('img');
    groupIcon.id = 'de-group-tab-icon'
    groupIcon.src = require("@/assets/img/icon-group-tab-item.png");
    groupIcon.style.cssText = 'width:20px;height: 20px;margin-right:4px;';

    let divNode = document.createElement('div');
    divNode.style.cssText = 'display: flex; align-items: center';
    divNode.appendChild(groupIcon);
    divNode.appendChild(document.createTextNode('Group'));

    if(tabListDom && !groupItemTab) {
        let lineDom = document.createElement('div');
        lineDom.id = 'de-tab-line';
        lineDom.style.cssText = `border-radius: 9999px;
            position: absolute;
            bottom: 0px;
            min-width: 56px;
            align-self: center;
            height: 4px;
            background-color: rgb(29, 155, 240);
            display: none`;

        let groupTab = document.createElement('div');
        groupTab.id = 'de-nav-tab-group';
        groupTab.style.cssText = `z-index: 1;
            position: relative;
            display: flex;
            min-width: 56px;
            -webkit-box-pack: center;
            justify-content: center;
            -webkit-box-align: center;
            align-items: center;
            text-align: center;
            padding: 0px 16px;
            color: rgb(83, 100, 113);
            font-weight: 700;
            height: 53px;
            cursor: pointer;
            font: 500 15px / 20px TwitterChirp, -apple-system, "system-ui", "Segoe UI", Roboto, Helvetica, Arial, sans-serif;`;

        groupTab.appendChild(divNode);
        groupTab.appendChild(lineDom);
        tabListDom.appendChild(groupTab);

        groupTab.addEventListener('mouseenter', function() {
            groupTab.style.background = 'rgba(15, 20, 25, 0.1)'
        });
        groupTab.addEventListener('mouseleave', function() {
            groupTab.style.background = 'none'
        });

        addGroupTabEventListener({groupTab});
    }
    
    addTweetTabEventListener({
        tabListDom
    });

    addTabGroupContent();
    checkNeedSelectGroupTab();
}

/**
 * 跳转到个人主页 检查是否需要选中 Group tab
 */
const checkNeedSelectGroupTab = () => {
    if(window.location.pathname != '/home') {
        setTimeout(() => {
            const urlParams = new URLSearchParams(window.location.search);
            const deTabVal = urlParams.get('deTabVal');
            if (deTabVal == 'deGroupTab') {
                selectGroupTab();
            }
        }, 500)
    }
}

/** 选中 Group tab */
const selectGroupTab = () => {
    let groupTab = document.querySelector('#de-nav-tab-group');
    if(groupTab) {
        groupTab.click();
    }
};

/**
 * 
 * Group tab点击事件监听
 */
const addGroupTabEventListener = (params) => {
    let {groupTab} = params;
    groupTab.addEventListener('click', function() {
        setGroupTabSelfStyle({groupColor: 'rgb(15, 20, 25)', 
            groupFontWeight: '700', 
            lineDisplay: 'block'});
        
        setTweetActiveTabStyle({
            color: 'rgb(83, 100, 113)', 
            display: 'none'});

        setTabContentStyle({
            tweetTabContentDisply: 'none', 
            iframeContentDisplay: 'block'});

        refreshTabGroup();

        window.addEventListener('scroll', addPageScrollEvent) 
    })
}

const addPageScrollEvent = () => {
    let wrapperDom = document.querySelector('html');
    let contentDom = document.querySelector('main[role="main"]');
    let data = {
        wrapperHeight: wrapperDom.offsetHeight,
        wrapperScrollTop: wrapperDom.scrollTop,
        contentHeight: contentDom.offsetHeight
    }

    chrome.runtime.sendMessage({ actionType: "CONTENT_GROUP_LIST_SCROLL", 
        data: data}, () => {});
};

/**
 * 
 * twitter tab点击事件监听
 */
const addTweetTabEventListener = (params) => {
    let {tabListDom} = params;
    let  groupItemTab = document.querySelector('#de-nav-tab-group');

    if(tabListDom && groupItemTab) {
        // 监听twitter tab点击事件
        let tweetTabItem = tabListDom.querySelectorAll('div[role="presentation"]');
        if(tweetTabItem.length) {
            for(let i = 0; i < tweetTabItem.length; i++) {
                let item = tweetTabItem[i];
                item.addEventListener('click', function() {
                    window.removeEventListener('scroll', addPageScrollEvent);

                    setGroupTabSelfStyle({groupColor: 'rgb(83, 100, 113)', 
                        groupFontWeight: '500', 
                        lineDisplay: 'none'});

                    setTabContentStyle({
                        tweetTabContentDisply: 'block', 
                        iframeContentDisplay: 'none'});

                    setTweetActiveTabStyle({
                        color: 'rgb(15, 20, 25)', 
                        display: 'block'});
                })
            }
        }
    }
}

/**
 * 设置 Group Tab 样式
 */
const setGroupTabSelfStyle = (params = {}) => {
    let {groupColor, groupFontWeight, lineDisplay} = params;
    let  groupTab = document.querySelector('#de-nav-tab-group');
    groupTab.style.color = groupColor;
    groupTab.style.fontWeight = groupFontWeight;

    let lineDom = groupTab.querySelector('#de-tab-line');
    if(lineDom) {
        lineDom.style.display = lineDisplay;
    }
};

/**
 * 切换到 Group tab时 刷新列表
 */
const refreshTabGroup = () => {
    chrome.runtime.sendMessage({ actionType: "CONTENT_REFRESH_TAB_GROUP_LIST", 
        data:{}}, () => { });
}

/**
 * 
 * tab选中时设置 激活 的字体样式和选中条
 */
const setTweetActiveTabStyle = (params) => {
    let {color, display} = params || {};
    let tweetActiveTab = document.querySelector('a[aria-selected="true"]').querySelector('div');
    tweetActiveTab.style.color = color;
    
    let tweetTabLine = tweetActiveTab.querySelector('div');
    if(tweetTabLine) {
        tweetTabLine.style.display = display;
    }
}

/**
 * 
 * 设置 tab 切换时 tab内容的样式（显示隐藏）
 */
const setTabContentStyle = (params) => {
    let {tweetTabContentDisply, iframeContentDisplay} = params;
    let tweetTabContent = getTweetTabContent();
    if(tweetTabContent) {
        if(tweetTabContentDisply == 'block') {
            let {display} = tweetTabContent.style;
            if(display == 'none') {
                tweetTabContent.style.display = 'block';
            } 
        } else {
            tweetTabContent.style.display = tweetTabContentDisply;
        }
    }

    let iframeContent = document.getElementById('de-tab-group-content');

    if(!iframeContent) {
        addTabGroupContent();
    }
    setTimeout(() => {
        iframeContent = document.getElementById('de-tab-group-content');
        if(iframeContent) {
            iframeContent.style.display = iframeContentDisplay;
        }
    })
};

/**
 * 
 * 获取 twitter tab 下的内容
 */
const getTweetTabContent = () => {
    let tweetTabContent = document.querySelector('[data-testid="primaryColumn"] [role="navigation"] + * > div[aria-label]:not([role="progressbar"])') || document.querySelector('div[data-testid="emptyState"]');
    return tweetTabContent;
}

/**
 * 注入 Group List 内容
 */
const addTabGroupContent = () => {
    let params = {
        windowLocation: window.location
    }
    let iframe = document.createElement('iframe');
        iframe.id = 'de-tab-group-content';
        iframe.src = chrome.runtime.getURL('/iframe/tab-group.html') + `?params=${JSON.stringify(params)}`;
        iframe.style.cssText = `border: medium none; height: 500px;display: none`

    let iframeContent = document.getElementById('de-tab-group-content');

    let tweetTabContent = getTweetTabContent();
    if (!iframeContent) {
        if(tweetTabContent && tweetTabContent.parentElement) {
            tweetTabContent.parentElement.appendChild(iframe);
        }
    }
};

/**
 * 
 * 设置Tab Group Iframe 样式
 */
export const setTabGroupIframeStyle = (params) => {
    let iframeContent = document.getElementById('de-tab-group-content');
    iframeContent.style.height =  document.querySelector('html').offsetHeight + 'px';
}

export const pageJumpHandler = (params) => {
    let {url, name = '_self'} = params
    window.open(url, name)
}

export const getTweetProfileNavTop = (params) => {
    let top = document.querySelector('div[role="tablist"]').closest('nav').getBoundingClientRect().top;

    chrome.runtime.sendMessage({ actionType: "CONTENT_SEND_GROUP_NAV_TOP", data: {
        top,
        scrollTop: params.scrollTop
    } }, () => { })
} 

/** 
 * 
 * Group Tab List End 
 * 
 */


export const loginSuccessHandle = () => {
    // 检查是否漏出group图标
    checkUserJoinGroup(() => {
        showNFTGroupIcon()
        addEventAction()
        addJoinedGroupList();
    })
}