document.addEventListener('DOMContentLoaded', () => {
    const encryption = str => window.btoa(unescape(encodeURIComponent(str)));
    const decrypt = str => decodeURIComponent(escape(window.atob(str)));

    /* 当前页的CID */
    const cid = $('.joe_detail').attr('data-cid');

    /* 获取本篇文章百度收录情况 */
    {
        $.ajax({
            url: Joe.BASE_API,
            type: 'POST',
            dataType: 'json',
            data: { routeType: 'baidu_record', site: window.location.href },
            success(res) {
                if (res.data && res.data === '已收录') {
                    $('#Joe_Baidu_Record').css('color', '#67C23A');
                    $('#Joe_Baidu_Record').html('已收录');
                } else {
                    /* 如果填写了Token，则自动推送给百度 */
                    if (Joe.BAIDU_PUSH) {
                        $('#Joe_Baidu_Record').html('<span style="color: #E6A23C">未收录，推送中...</span>');
                        const _timer = setTimeout(function () {
                            $.ajax({
                                url: Joe.BASE_API,
                                type: 'POST',
                                dataType: 'json',
                                data: {
                                    routeType: 'baidu_push',
                                    domain: window.location.protocol + '//' + window.location.hostname,
                                    url: encodeURI(window.location.href)
                                },
                                success(res) {
                                    if (res.data.error) {
                                        $('#Joe_Baidu_Record').html('<span style="color: #F56C6C">推送失败，请检查！</span>');
                                    } else {
                                        $('#Joe_Baidu_Record').html('<span style="color: #67C23A">推送成功！</span>');
                                    }
                                }
                            });
                            clearTimeout(_timer);
                        }, 1000);
                    } else {
                        const url = `https://ziyuan.baidu.com/linksubmit/url?sitename=${encodeURI(window.location.href)}`;
                        $('#Joe_Baidu_Record').html(`<a target="_blank" href="${url}" rel="noopener noreferrer nofollow" style="color: #F56C6C">未收录，提交收录</a>`);
                    }
                }
            }
        });
    }

    /* 激活代码高亮 */
    {
        Prism.highlightAll();
        $("pre[class*='language-']").each(function (index, item) {
            let text = $(item).find("code[class*='language-']").text();
            let span = $(`<span class="copy"><i class="fa fa-clone"></i></span>`);
            new ClipboardJS(span[0], { text: () => text }).on('success', () => Qmsg.success('复制成功！'));
            $(item).append(span);
        });
    }

    /* 激活图片预览功能 */
    {
        $('.joe_detail__article img:not(img.owo_image)').each(function () {
            $(this).wrap($(`<span style="display: block;" data-fancybox="Joe" href="${$(this).attr('src')}"></span>`));
        });
    }

    /* 设置文章内的链接为新窗口打开 */
    {
        $('.joe_detail__article a:not(.joe_detail__article-anote)').each(function () {
            $(this).attr({ target: '_blank', rel: 'noopener noreferrer nofollow' });
        });
    }

    /* 激活浏览功能 */
    {
        let viewsArr = localStorage.getItem(encryption('views')) ? JSON.parse(decrypt(localStorage.getItem(encryption('views')))) : [];
        const flag = viewsArr.includes(cid);
        if (!flag) {
            $.ajax({
                url: Joe.BASE_API,
                type: 'POST',
                dataType: 'json',
                data: { routeType: 'handle_views', cid },
                success(res) {
                    if (res.code !== 1) return;
                    $('#Joe_Article_Views').html(`${res.data.views} 阅读`);
                    viewsArr.push(cid);
                    const name = encryption('views');
                    const val = encryption(JSON.stringify(viewsArr));
                    localStorage.setItem(name, val);
                }
            });
        }
    }

    /* 激活文章点赞功能 */
    {
        let agreeArr = localStorage.getItem(encryption('agree')) ? JSON.parse(decrypt(localStorage.getItem(encryption('agree')))) : [];
        if (agreeArr.includes(cid)) $('.joe_detail__agree .icon-1').addClass('active');
        else $('.joe_detail__agree .icon-2').addClass('active');
        let _loading = false;
        $('.joe_detail__agree .icon').on('click', function () {
            if (_loading) return;
            _loading = true;
            agreeArr = localStorage.getItem(encryption('agree')) ? JSON.parse(decrypt(localStorage.getItem(encryption('agree')))) : [];
            let flag = agreeArr.includes(cid);
            $.ajax({
                url: Joe.BASE_API,
                type: 'POST',
                dataType: 'json',
                data: { routeType: 'handle_agree', cid, type: flag ? 'disagree' : 'agree' },
                success(res) {
                    if (res.code !== 1) return;
                    $('.joe_detail__agree .text').html(res.data.agree);
                    if (flag) {
                        const index = agreeArr.findIndex(_ => _ === cid);
                        agreeArr.splice(index, 1);
                        $('.joe_detail__agree .icon-1').removeClass('active');
                        $('.joe_detail__agree .icon-2').addClass('active');
                        $('.joe_detail__agree .icon').removeClass('active');
                    } else {
                        agreeArr.push(cid);
                        $('.joe_detail__agree .icon-2').removeClass('active');
                        $('.joe_detail__agree .icon-1').addClass('active');
                        $('.joe_detail__agree .icon').addClass('active');
                    }
                    const name = encryption('agree');
                    const val = encryption(JSON.stringify(agreeArr));
                    localStorage.setItem(name, val);
                },
                complete() {
                    _loading = false;
                }
            });
        });
    }

    /* 密码保护文章，输入密码访问 */
    {
        let isSubmit = false;
        $('.joe_detail__article-protected').on('submit', function (e) {
            e.preventDefault();
            const url = $(this).attr('action') + '&time=' + +new Date();
            const protectPassword = $(this).find('input[type="password"]').val();
            if (protectPassword.trim() === '') return Qmsg.info('请输入访问密码！');
            if (isSubmit) return;
            isSubmit = true;
            $.ajax({
                url,
                type: 'POST',
                data: {
                    cid,
                    protectCID: cid,
                    protectPassword
                },
                dataType: 'text',
                success(res) {
                    let arr = [],
                        str = '';
                    arr = $(res).contents();
                    Array.from(arr).forEach(_ => {
                        if (_.parentNode.className === 'container') str = _;
                    });
                    if (!/Joe/.test(res)) {
                        Qmsg.warning(str.textContent.trim() || '');
                        isSubmit = false;
                        $('.joe_comment__respond-form .foot .submit button').html('发表评论');
                    } else {
                        location.reload();
                    }
                }
            });
        });
    }

    /* 激活文章视频模块 */
    {
        if ($('.joe_detail__article-video').length > 0) {
            const player = $('.joe_detail__article-video .play iframe').attr('data-player');
            $('.joe_detail__article-video .episodes .item').on('click', function () {
                $(this).addClass('active').siblings().removeClass('active');
                const url = $(this).attr('data-src');
                $('.joe_detail__article-video .play iframe').attr({ src: player + url });
            });
            $('.joe_detail__article-video .episodes .item').first().click();
        }
    }

    /* 分享 */
    {
        if ($('.joe_detail__operate-share').length) {
            $('.joe_detail__operate-share > svg').on('click', e => {
                e.stopPropagation();
                $('.joe_detail__operate-share').toggleClass('active');
            });
            $(document).on('click', () => $('.joe_detail__operate-share').removeClass('active'));
        }
    }

    /* 导航窗格 */
    {
        // 获取目录列表
        function get_catalogs(article_content) {
            let titles = [];
            let diffLevel = 0;
            let nodeNameSet = new Set();
            const titleTag = ["H1", "H2", "H3", "H4"];
            article_content.childNodes.forEach((e, index) => nodeNameSet.add(e.nodeName));
            for (let ttIndex in titleTag) {
                let item = titleTag[ttIndex];
                if (!nodeNameSet.has(item)) {
                    diffLevel++;
                } else {
                    break;
                }
            }
            article_content.childNodes.forEach((e, index) => {
                const id = "header-" + index;
                if(titleTag.includes(e.nodeName)){
                    titles.push({
                        id: id,
                        text: e.textContent,
                        level: Number(e.nodeName.substring(1, 2) - diffLevel)
                    });
                    e.setAttribute("id", id);
                }
            });
            return titles;
        }
        // 找到目录容器
        article_content = document.querySelector('.joe_detail__article');
        if (article_content) {
            var catalog = get_catalogs(article_content);
            if (catalog.length == 0) {
                // 无目录，隐藏
                $('.catalogue').hide();
            } else {
                // 有目录，将其他侧边栏移除
                let asideArr = ['timelife', 'today', 'hot', 'newreply', 'weather', 'tags', 'flatterer'];
                asideArr.forEach(item => $('.joe_aside__item.' + item).remove());
                // 构建目录
                let catalogue = '';
                for (let i = 0; i < catalog.length; i++) {
                    let node = '<li class="catalogue-item"><a href="javascript:;" id="to-' + catalog[i].id + '" to="' + catalog[i].id + '" title="' + catalog[i].text + '"><span class="dir_name">' + catalog[i].text + '</span></a>';
                    if (i == catalog.length - 1) {
                        catalogue += node + '</li>'
                    } else {
                        if (catalog[i + 1].level == catalog[i].level) {
                            catalogue += node + '</li>';
                        } else if (catalog[i + 1].level > catalog[i].level) {
                            catalogue += (catalog[i + 1].level > 1) ? node + '<ul class="level-' + catalog[i + 1].level + '">' : node + '</li>';
                        } else {
                            if (catalog[i + 1].level - catalog[i].level == -2) {
                                catalogue += i > 1 ? node + '</li></ul></li></ul></li>' : node + '</li></ul></li>';
                            } else {
                                catalogue += i > 1 ? node + '</li></ul></li>' : node + '</li>';
                            }
                        }
                    }
                }
                document.querySelector('.catalogue-items').innerHTML = catalogue;
                $('.catalogue-item > a').on('mouseenter', function () {
                    $(this).parent().addClass('_active');
                });
                $('.catalogue-item > a').on('mouseleave', function () {
                    $(this).parent().removeClass('_active');
                });
                // 根据目录定位到标题
                $('.catalogue-item > a').on('click', function () {
                    document.removeEventListener("scroll", autoActive);
                    $('.catalogue-item').removeClass('active');
                    $(this).parent().addClass('active');
                    let aim = document.querySelector('#' + $(this).attr('to'));
                    let aim_top = aim.offsetTop;
                    let aim_h = aim.clientHeight;
                    let above_h = document.querySelector('.joe_header__above').clientHeight;
                    let below_h = document.querySelector('.joe_header__below').clientHeight;
                    let offset = 0;
                    let case1 = !document.querySelector('.joe_header__above').className.includes('active');
                    let case2 = document.getElementsByTagName("html")[0].scrollTop + above_h > aim_top;
                    if (case1 && case2) {
                        offset = above_h;
                    }
                    window.scrollTo({
                        top: aim_top - offset - below_h - 10,
                        behavior: 'smooth'
                    });
                    setTimeout(() => {
                        document.addEventListener("scroll", autoActive);
                    }, 500);
                });
                if (catalog.length)
                    $('.catalogue-item').eq(0).addClass('active');
                // 目录侧标题自动定位
                let autoActive = function () {
                    let html_top = document.getElementsByTagName("html")[0].scrollTop; // 获得父级卷去的高度
                    let contain = $(".joe_aside__item.catalogue .joe_aside__item-contain"); // 获取带有滚动条的元素的jQuery对象
                    for (let i = 0; i < catalog.length; i++) {
                        let offset = 0;
                        let h_id = '#' + catalog[i].id;
                        let h_offset = document.querySelector(h_id).offsetTop;
                        let above_h = document.querySelector('.joe_header__above').clientHeight;
                        let below_h = document.querySelector('.joe_header__below').clientHeight;

                        if (!document.querySelector('.joe_header').className.includes('active'))
                            offset = above_h;
                        if (h_offset + below_h + offset + 10 >= html_top) {
                            $('.catalogue-item').removeClass('active');
                            if (i > 0 && i < catalog.length - 1 && document.querySelector('#' + catalog[i].id).offsetTop > html_top + window.innerHeight * 0.2) {
                                //还没到下一个标题
                                i--;
                            }
                            $('#to-' + catalog[i].id).parent().addClass('active');
                            break;
                        }
                    }
                };
                document.addEventListener("scroll", autoActive);
            }
        } else {
            // 不是文章，隐藏目录
            $('.catalogue').hide();
        }
    }
    
});

/* 写在load事件里，为了解决图片未加载完成，滚动距离获取会不准确的问题 */
window.addEventListener('load', function () {
    /* 判断地址栏是否有锚点链接，有则跳转到对应位置 */
    {
        const scroll = new URLSearchParams(location.search).get('scroll');
        if (scroll) {
            const height = $('.joe_header').height();
            let elementEL = null;
            if ($('#' + scroll).length > 0) {
                elementEL = $('#' + scroll);
            } else {
                elementEL = $('.' + scroll);
            }
            if (elementEL && elementEL.length > 0) {
                const top = elementEL.offset().top - height - 15;
                window.scrollTo({ top, behavior: 'smooth' });
            }
        }
    }
});

