import { getChromeStorage, setChromeStorage } from '@/uilts/chromeExtension.js'
import { throttle, getQueryString } from '@/uilts/help'
import { discordAuthRedirectUri } from '@/http/configAPI'
import { reportSrcPublishEvent } from '@/http/publishApi'
import Report from "@/log-center/log"


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原生发布框
 */
export function showTwitterPublishDialogHandler(publishRes) {
    dom.tweetBtn.click();
    _setPublishContent(publishRes.srcContent);
    _publishTweetEvent(publishRes.postId, bindTwitterArtMethod);
}

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

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");

    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(contentStr, cb) {
    setTimeout(() => {
        let publishTweetBtn;
        let dialog = document.querySelector('div[role="dialog"]');
        if (dialog) {
            publishTweetBtn = dialog.querySelector('div[data-testid="tweetButton"]');
        } 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 = contentStr;
            cb && cb()
        });
    }, 800)
}

/**
 * 在输入推文区插入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
            });
            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);
            _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.getElementById('layers').appendChild(iframe);
    }
}

/**
 * 点击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.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;
const _setPublishContent = throttle(function (content) {
    if (!isSetContent) {
        isSetContent = true;
        setTimeout(() => {
            document.execCommand("insertText", false, content);
            setTimeout(() => {
                isSetContent = false;
            }, 2000)
        }, 1000);
    }
}, 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) {
            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) {
            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 (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);
            _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() {
    // 获取所有卡片参数
    let card_json_data = parseCard.parseAllDeNetCardParmas()
    // 过滤出可以请求的短链接
    parseCard.getCardParmas(card_json_data).then((res) => {
        for (let i in res.has_post_Id_card_data) {
            parseCard.replaceDOMRedPacket(res.has_post_Id_card_data[i])
        }
        if (res.need_net_short_url.length > 0) {
            // 请求短链接
            chrome.runtime.sendMessage({ actionType: "CONTENT_TWITTER_SHORT_LINK", data: "", arr_url: res.need_net_short_url }, () => { })
        }
    })
}

// 监听点击发推 按钮绑定事件
// 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 createIframe = ({ url, tweet_Id }, callback) => {
    let iframe = document.createElement('iframe')
    iframe.id = `tweetId${tweet_Id}`
    iframe.src = url
    iframe.onload = () => {
        callback()
    }
}

// 初始化
export function init() {
    getDiscordAuthCode();
    if (window.location.href.indexOf('twitter.com') < 0) {
        return
    }
    twitterPinLogin();
    // 渲染dom
    let targetNode = null
    let timer = setInterval(() => {
        targetNode = document.querySelector('main')
        if (targetNode) {
            clearInterval(timer)
            setInterval(() => {
                if (window.location.href.includes('twitter.com)')) {
                    return
                }
                if (!main_observer) {
                    onChangePageMain(targetNode)
                    changeQueueNum(1)
                }
                if (queue_num <= 0) {
                    return
                }
                setIframeRedPacket()
                checkHasDeBtn()
                changeQueueNum(-1)
            }, 1000)
        }
    }, 1000);
    renderDom();
    checkTwitterTaskState()
    getChromeStorage("popupShowPublishDialog", (res) => {
        console.log("popupShowPublishDialog", res);
        if (res && res.show) {
            setTimeout(() => {
                showTwitterPublishDialogHandler({
                    srcContent: res.srcContent,
                    postId: res.postId
                });
            }, 1500);
            chrome.storage.local.remove("popupShowPublishDialog");
        }
    });
    getChromeStorage("userSettings", (res) => {
        addPinedPop();
        if (res && !res.isOnToolbar) {
            setTimeout(() => {
                showPinTips();
                chrome.storage.local.remove("userSettings");
            }, 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)
}