import { getOffsetRect, nextTick } from '@/uilts/help'
import { listJoinNftGroup } from '@/http/nft';
import { getChromeStorage } from '@/uilts/chromeExtension.js'
import { _setPublishContent, publishNFTTweetPost, bindTwitterArt, bindTwitterArtMethod } from './twitter';
import { jumpTwitterDetailByAlert } from '@/logic/content/help/twitter.js'

var ifShowNftGroup = false;
var tempNftGroupPost = null;
var groupImgNoSelect = require("@/assets/img/icon-nft-group-entry.png");
var groupImgSelect = require("@/assets/img/icon-nft-group-select.png");

export const showNFTGroupIcon = () => {
    let urlInfo = new URL(window.location.href)
    let isTwitter = urlInfo.hostname === 'twitter.com'
    let toolElem = document.querySelector('div[data-testid="toolBar"]');
    let isAppend = toolElem && toolElem.querySelector('#de-nft-group-enter');
    let where = isTwitter && toolElem && !isAppend && ifShowNftGroup;
    if (where) {
        let oDiv = document.createElement(`div`);
            oDiv.id = 'de-nft-group-enter';
        let oImg = document.createElement('img');
            oImg.src = groupImgNoSelect;
            oImg.className = 'addGroup';
            oDiv.innerHTML = `
                ${oImg.outerHTML}
                <style>
                    #de-nft-group-enter {position:relative; display:flex; padding:0 8px;}
                    #de-nft-group-enter .addGroup {cursor:pointer; height:32px;}
                </style>
            `;
            oDiv.addEventListener('click', (e) => {
                showNFTGroupList(e);
                e.stopPropagation();
            })
        toolElem.firstChild.appendChild(oDiv)
    }
}

export const showNFTGroupList = (e) => {
    let rectObject = e.target.getBoundingClientRect();
    let { top, left, height } = rectObject;
    let oTop = top + height + 10;
    // 居底判断
    let wHeight = document.body.offsetHeight || document.body.clientHeight;
    if ((top + height + 290) > wHeight) oTop = top - 290;
    let iframe = document.createElement('iframe');
        iframe.src = chrome.runtime.getURL(`/iframe/nft-group.html`)
        iframe.style.cssText = 'border:medium none; width:315px; height:260px;';
    let html = document.createElement('div');
        html.id = 'de-nft-group-list';
        html.innerHTML = `
            <div class="de-nft-group-div">
                ${iframe.outerHTML}
            </div>
            <div class="de-nft-group-mask"></div>
            <style>
                .de-nft-group-div {position:fixed; display:flex; align-items:center; justify-content:center; z-index:100; width:350px; height:280px; left:${left}px; top:${oTop}px; background:#fff; border-radius:20px; box-shadow:0px 4px 20px 0px rgba(0, 0, 0, 0.26);}
                .de-nft-group-mask {position:fixed; z-index:99; width:100%; height:100%; left:0; top:0;}
            </style>`;

    document.body.appendChild(html);
    document.querySelector('.de-nft-group-mask').addEventListener('click', () => {
        hideNFTGroupList();
    })
}

export const hideNFTGroupList = () => {
    let dom = document.querySelector('#de-nft-group-list');
    dom && document.body.removeChild(dom);
}

export const checkUserJoinGroup = (fn) => {
    getChromeStorage('userInfo', (res) => {
        // 如果登录
        if (res) {
            listJoinNftGroup({
                params: {
                    pageNum: 1,
                    pageSize: 1
                }
            }).then(res => {
                let { data = [] } = res;
                if (data !== null && data.length > 0) {
                    ifShowNftGroup = true;
                    if (fn) fn()
                }
            })
        }
    })
}

export const clearPostContent = (fn) => {
    let edit = document.querySelector('div[contenteditable="true"]')
    let where = (edit.innerText === '\n') || (edit.innerText === '')
    if (where) {
        fn()
    } else {
        nextTick(() => {
            let inputEle = document.querySelector('div[contenteditable="true"]');
            if (inputEle) {
                inputEle.focus();
            }
        }, 20).then(() => {
            document.execCommand('selectAll');
            document.execCommand('delete');
            clearPostContent(fn)
        })
    }
}

export const setPostContent = (res) => {
    nextTick(() => {
        let inputEle = document.querySelector('div[contenteditable="true"]');
        if (inputEle) {
            inputEle.focus();
        }
        setGroupIconStatus();
    }, 100).then(() => {
        _setPublishContent(res.srcContent + ' ');
    })
}

export const endPostContent = () => {
    return new Promise((resolve) => {
        let inputEle = document.querySelector('div[contenteditable="true"]');
        let range = document.createRange();
            range.selectNodeContents(inputEle);
            range.collapse(false);
        let sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        resolve()
    })
}

export const setNFTGroupContent = (res) => {
    tempNftGroupPost = res;

    let dialogDiv = document.querySelectorAll('div[role="dialog"]');
    if (dialogDiv.length === 0) {
        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();
        }
    }

    let edit = document.querySelector('div[contenteditable="true"]')
    let where = (edit.innerText === '\n') || (edit.innerText === '')
    if (where) {
        setPostContent(res)
        nextTick(() => {
            _addTweetButtonListen()
        }, 100)
        
    } else {
        endPostContent().then(() => {
            let inputEle = document.querySelector('div[contenteditable="true"]');
            if (inputEle) {
                inputEle.focus();
            }
            setPostContent(res)
            nextTick(() => {
                _addTweetButtonListen()
            }, 100)
        })
    }
}

export const elemAddEventListener = (elem, action, fn) => {
    if (elem) {
        elem.removeEventListener(action, fn)
        elem.addEventListener(action, fn)
    }
}


export const addJoinedGroupList = () => {
    if(ifShowNftGroup) {
        let {pathname} = window.location;

        let iframe = document.createElement('iframe');
            iframe.id = 'de-joined-group-list';
            iframe.src = chrome.runtime.getURL('/iframe/joined-group-list.html');
            iframe.style.cssText = `border: medium none;height: 120px;border-radius: 16px;margin-bottom: 16px`

        let iframeContent = document.getElementById('de-joined-group-list');

        if (!iframeContent && pathname == '/home') {
            let sidebarColumn = document.querySelector('div[data-testid="sidebarColumn"]');
            if(sidebarColumn) {
                let searchDom = sidebarColumn.querySelector('form[role="search"]');
                if(searchDom) {
                    let listWrapperDom = searchDom.parentElement.parentElement.parentElement.parentElement;
                    if(listWrapperDom) {
                        let listParent = listWrapperDom.parentElement;
                        if(listParent) {
                            listParent.insertBefore(iframe, listWrapperDom.nextElementSibling.nextElementSibling);
                        }
                    }
                }
            } 
        }
    }
};

export const setJoinedGroupIframeStyle = (params) => {
    let {height = '321px'} = params;
    let iframeContent = document.getElementById('de-joined-group-list');
    if(iframeContent) {
        iframeContent.style.height = height;
    }
}

export function setGroupIconStatus() {
    let editElem = document.querySelector('div[contenteditable="true"]');
    let main_observer = new MutationObserver(() => {
        let groupImg = document.querySelector('#de-nft-group-enter');
        let innerText = editElem.innerText || '';
        if (groupImg && innerText) {
            let where = innerText.indexOf('#DNFT') !== -1 && innerText.indexOf('nft_group') !== -1;
            if (where) {
                groupImg.querySelector('.addGroup').src = groupImgSelect;
            } else {
                groupImg.querySelector('.addGroup').src = groupImgNoSelect;
            }
        }
    });
    main_observer.observe(editElem, { attributes: false, childList: true, subtree: true })
}
function _addTweetButtonListen() {
    let btn = document.querySelector('div[data-testid="tweetButton"]');

    btn.removeEventListener('click', _postTweetContent);
    btn.addEventListener('click', _postTweetContent)
}
function _postTweetContent() {
    if (tempNftGroupPost && tempNftGroupPost.groupId) {
        publishNFTTweetPost(tempNftGroupPost)
        bindTwitterArt.needBind = true;
        bindTwitterArt.postId = tempNftGroupPost.postId;
        bindTwitterArtMethod();
        // 非首页处理
        let homeTag = document.querySelectorAll('div[data-testid="toolBar"]');
        if (homeTag.length === 1) {
            jumpTwitterDetailByAlert()
        }
    }
}