// ==UserScript==
// @name         idle
// @version      1.31
// @namespace    ErQi
// @description  挂机无止境的辅助脚本
// @author       beside4ever@outlook.com
// @grant         GM_addStyle
// @run-at       document-start
// @match        https://www.idleinfinity.cn/*
// @require      https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/jquery-url-parser/2.3.1/purl.min.js
// @downloadURL none
// ==/UserScript==
const defaultFilterOptions = ['技能', '凹槽(0/2)', '凹槽(0/4)', '取得魔法装备', '攻击速度', '施法速度', '+20 毒素', '+25 毒素'];
let config = {
    userNumber: 1,
    showRequire: true,
    fastFilter: true,
    fastOptions: defaultFilterOptions.slice(0), // 快速过滤器配置,可自行增删
    showSpellColor: true,
    showSpeedLevel: true,
    showCharDmg: true,
    showAccuracy: true,
    dropNotification: true,
    itemStats: true,
    showBattle: true,
    mapHack: true,
    mapHackType: 'all',
    infiniteMap: false,
    showSetAttr: true,
    showAuctionNote: true,
    auctionWatch: true,
    oneKeyEquip: true,
    oneKeyAgree: true,
    oneKeyRune: true,
    showRuneTip: true,
    showBattleDetail: true,
    d3theme: true,
    minLevel: null,
    // 秘境的石头等级  0 表示普通 1表示魔法 2表示稀有,以此类推 按照下拉列表的排序
    level: '',
};
const configLabel = {
    showRequire: '职业专属显示',
    fastFilter: '快速过滤选项',
    showSpellColor: '法术技能高亮',
    showSpeedLevel: '显示速度档位',
    showCharDmg: '角色均伤显示',
    showAccuracy: '角色命中显示',
    dropNotification: '欧皇暗金通知',
    itemStats: '欧皇收获统计',
    showBattle: '快速秘境战斗',
    mapHack: '秘境自动战斗',
    infiniteMap: '无限秘境模式',
    showSetAttr: '显示套装属性',
    showAuctionNote: '显示拍卖备注',
    auctionWatch: '拍卖特别关注',
    oneKeyEquip: '一键换装功能',
    oneKeyAgree: '一键同意功能',
    oneKeyRune: '一键转移符文',
    showRuneTip: '符文之语提示',
    showBattleDetail: '战斗详细分析',
    d3theme: '暗黑界面皮肤',
    minLevel: '符文序号',
};
const userConfig = ['dropNotification', 'd3theme'];
let localConfig = localStorage.getItem('idle-ui-config');
if (localConfig) {
    localConfig = JSON.parse(localConfig);
    Object.keys(localConfig).map(key => {
        if (config[key] !== undefined) config[key] = localConfig[key];
    });
}
if (config.d3theme) {
    const htmlElement = document.getElementsByTagName('html')[0];
    htmlElement.setAttribute('class', 'd3');
}
function idleInit() {
    config.level = '1';
    var style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = `.eq-weapon { background-color: #700;} .eq-armor {background-color: #007;} .eq-amulet {background-color: #0b0;} .eq-delete {background-color: gray;}
        .eq-jewel {background-color: #808a87;} .selected-b {border: 1px solid #66ccff!important;} .selected-r {border: 1px solid #f00!important;} .selected-d {border: 1px solid #fff!important;}`;
    document.getElementsByTagName('head')[0].appendChild(style);
    // Extend page width
    $('.container:nth(1)').css('width', '70%');
    $('body').css('height', $('body').height() + 500);
    var equips = $(".panel-filter").parent().prev().find(".equip-content");
    for (var ii = 0; ii < equips.length; ii++) {
        var e = equips[ii];
        if ($(e).text().indexOf("璀璨之白热的珠宝") >= 0) {
            $(e).prev().children().first().addClass("eq-jewel");
        }
        /*
                else if ($(e).text().indexOf("戒指") >= 0 | $(e).text().indexOf("项链") >= 0) {
                    $(e).prev().children().first().addClass("eq-amulet");
                }
                else if ($(e).text().indexOf("护符") >= 0) {
                    $(e).prev().children().first().addClass("eq-amulet");
                }
                else if ($(e).text().indexOf("伤害:") >= 0) {
                    $(e).prev().children().first().addClass("eq-weapon");
                }
                else if ($(e).text().indexOf("防御:") >= 0) {
                    $(e).prev().children().first().addClass("eq-armor");
                }
                if ($(e).text().indexOf("阿卡娜的诡计") >= 0
                    | $(e).text().indexOf("依雷撒的精洗炉") >= 0
                    | $(e).text().indexOf("卡珊的陷阱") >= 0
                    | $(e).text().indexOf("狂战士的军火库") >= 0
                    | $(e).text().indexOf("米拉伯佳的雪茄") >= 0
                    | $(e).text().indexOf("依森哈德的武器库") >= 0
                    | $(e).text().indexOf("坦克雷的战斗工具") >= 0
                    | $(e).text().indexOf("维达拉之倒刺") >= 0
                    | $(e).text().indexOf("摆动剃刀") >= 0
                    | $(e).text().indexOf("目盲之刃") >= 0
                    | $(e).text().indexOf("凋谢之戒") >= 0
                    | $(e).text().indexOf("致命轨迹") >= 0
                   ) {
                    $(e).prev().addClass("eq-delete");
                }
                else
        */
        if ($(e).text().indexOf("+3 地心守卫") >= 0) {
            $(e).prev().addClass("selected-r");
        }
        else if ($(e).text().indexOf("施法速度提升 20%") >= 0 && $(e).text().indexOf("技能") >= 0) {
            $(e).prev().addClass("selected");
        }
    }
    var on_gears = $('.equip-container .equip-content');
    var i, gear, ps, hits, key, n_name, eqn;
    for (i = 0; i < on_gears.length; i++) {
        gear = on_gears[i];
        ps = gear.getElementsByTagName('p');
        if (ps.length > 0) {
            hits = gear.innerHTML.match(/彩虹刻面/);
            if (hits != null) {
                eqn = gear.previousElementSibling.getElementsByClassName('equip-name');
                hits = gear.innerHTML.match(/(\d+)陨石/);
                if (hits != null) {
                    eqn[eqn.length - 1].innerHTML += ' 火刻 ' + hits[1] + 'slv';
                }
                hits = gear.innerHTML.match(/(\d+)暴风雪/);
                if (hits != null) {
                    eqn[eqn.length - 1].innerHTML += ' 冰刻 ' + hits[1] + 'slv';
                }
                hits = gear.innerHTML.match(/(\d+)连锁闪电/);
                if (hits != null) {
                    eqn[eqn.length - 1].innerHTML += ' 电刻 ' + hits[1] + 'slv';
                }
                hits = gear.innerHTML.match(/(\d+)剧毒新星/);
                if (hits != null) {
                    eqn[eqn.length - 1].innerHTML += ' 毒刻 ' + hits[1] + 'slv';
                }
                hits = gear.innerHTML.match(/(\d+)虚化/);
                if (hits != null) {
                    eqn[eqn.length - 1].innerHTML += ' 魔刻 ' + hits[1] + 'slv';
                }
                hits = gear.innerHTML.match(/(\d+)伤害加深/);
                if (hits != null) {
                    eqn[eqn.length - 1].innerHTML += ' 物刻';
                }
                hits = gear.innerHTML.match(/(\d+)\% 火焰伤害/);
                if (hits != null) {
                    eqn[eqn.length - 1].innerHTML += ' +' + hits[1] + '';
                }
                hits = gear.innerHTML.match(/(\d+)\% 冰冷伤害/);
                if (hits != null) {
                    eqn[eqn.length - 1].innerHTML += ' +' + hits[1] + '';
                }
                hits = gear.innerHTML.match(/(\d+)\% 闪电伤害/);
                if (hits != null) {
                    eqn[eqn.length - 1].innerHTML += ' +' + hits[1] + '';
                }
                hits = gear.innerHTML.match(/(\d+)\% 毒素伤害/);
                if (hits != null) {
                    eqn[eqn.length - 1].innerHTML += ' +' + hits[1] + '';
                }
                hits = gear.innerHTML.match(/(\d+)\% 魔法伤害/);
                if (hits != null) {
                    eqn[eqn.length - 1].innerHTML += ' +' + hits[1] + '';
                }
                hits = gear.innerHTML.match(/(\d+)\% 物理伤害/);
                if (hits != null) {
                    eqn[eqn.length - 1].innerHTML += ' +' + hits[1] + '';
                }
                hits = gear.innerHTML.match(/(\d+)\% 目标火焰抗性/);
                if (hits != null) {
                    eqn[eqn.length - 1].innerHTML += ' -' + hits[1] + '';
                }
                hits = gear.innerHTML.match(/(\d+)\% 目标冰冷抗性/);
                if (hits != null) {
                    eqn[eqn.length - 1].innerHTML += ' -' + hits[1] + '';
                }
                hits = gear.innerHTML.match(/(\d+)\% 目标闪电抗性/);
                if (hits != null) {
                    eqn[eqn.length - 1].innerHTML += ' -' + hits[1] + '';
                }
                hits = gear.innerHTML.match(/(\d+)\% 目标毒素抗性/);
                if (hits != null) {
                    eqn[eqn.length - 1].innerHTML += ' -' + hits[1] + '';
                }
            }
            hits = gear.innerHTML.match(/攻击速度提升 (\d+)\%/);
            if (hits != null) {
                eqn = gear.previousElementSibling.getElementsByClassName('equip-name');
                eqn[eqn.length - 1].innerHTML += ' ' + hits[1] + 'ias ';
            }
            hits = gear.innerHTML.match(/施法速度提升 (\d+)\%/);
            if (hits != null) {
                eqn = gear.previousElementSibling.getElementsByClassName('equip-name');
                eqn[eqn.length - 1].innerHTML += ' ' + hits[1] + 'fcr ';
            }
            hits = gear.innerHTML.match(/\+(\d+)\% 增强伤害/);
            if (hits != null) {
                eqn = gear.previousElementSibling.getElementsByClassName('equip-name');
                eqn[eqn.length - 1].innerHTML += ' ' + hits[1] + 'ed ';
            }
            hits = gear.innerHTML.match(/\+(\d+)\% 暴击几率/);
            if (hits != null) {
                eqn = gear.previousElementSibling.getElementsByClassName('equip-name');
                eqn[eqn.length - 1].innerHTML += ' ' + hits[1] + 'cri ';
            }
            hits = ps[ps.length - 1].textContent.match(/凹槽(\(\d+\/\d+\))/);
            if (hits != null) {
                eqn = gear.previousElementSibling.getElementsByClassName('equip-name')
                eqn[eqn.length - 1].innerHTML += ' ' + hits[1] + ' ';
            }
            hits = gear.innerHTML.match(/\+(\d+)\% 更佳的机会取得魔法装备/);
            if (hits != null) {
                eqn = gear.previousElementSibling.getElementsByClassName('equip-name');
                eqn[eqn.length - 1].innerHTML += '  ' + hits[1] + 'mf ';
            }
            hits = gear.innerHTML.match(/\+(\d+)\% 额外金币从怪物身上取得/);
            if (hits != null) {
                eqn = gear.previousElementSibling.getElementsByClassName('equip-name');
                eqn[eqn.length - 1].innerHTML += '  ' + hits[1] + 'gf ';
            }
            hits = gear.innerHTML.match(/元素抗性 \+(\d+)\%/);
            if (hits != null) {
                eqn = gear.previousElementSibling.getElementsByClassName('equip-name');
                eqn[eqn.length - 1].innerHTML += ' ' + hits[1] + 'ar ';
            }
            hits = gear.innerHTML.match(/抗火 \+(\d+)\%/);
            if (hits != null) {
                eqn = gear.previousElementSibling.getElementsByClassName('equip-name');
                eqn[eqn.length - 1].innerHTML += ' ' + hits[1] + 'f ';
            }
            hits = gear.innerHTML.match(/抗寒 \+(\d+)\%/);
            if (hits != null) {
                eqn = gear.previousElementSibling.getElementsByClassName('equip-name');
                eqn[eqn.length - 1].innerHTML += ' ' + hits[1] + 'c ';
            }
            hits = gear.innerHTML.match(/抗闪电 \+(\d+)\%/);
            if (hits != null) {
                eqn = gear.previousElementSibling.getElementsByClassName('equip-name');
                eqn[eqn.length - 1].innerHTML += ' ' + hits[1] + 'l ';
            }
            hits = gear.innerHTML.match(/抗毒 \+(\d+)\%/);
            if (hits != null) {
                eqn = gear.previousElementSibling.getElementsByClassName('equip-name');
                eqn[eqn.length - 1].innerHTML += ' ' + hits[1] + 'p ';
            }
        }
    }
    addConfig();
    // 显示限定字符
    switchSkin(config.showRequire);
    Notification.requestPermission();
    $('.navbar-nav > li > a').each(function () {
        if ($(this).text().indexOf('帮助') >= 0) {
            const links = [
                {text: '暗金列表', link: '/Help/Content?url=Unique'},
                {text: '套装列表', link: '/Help/Content?url=Set'},
                {text: '秘境圣衣', link: '/Help/Content?url=Sacred'},
                {text: '神器列表', link: '/Help/Content?url=Artifact'},
                {text: '普通物品', link: '/Help/Content?url=BaseEquip'},
                {text: '前缀属性', link: '/Help/Content?url=Prefix'},
                {text: '后缀属性', link: '/Help/Content?url=Suffix'},
                {text: '固定词缀', link: '/Help/Content?url=SpecialAffix'},
            ].map(item => {
                return `
${item.text}`;
            }).join('');
            $(this).next().append(links);
        }
    });
    function fetchItem(name, callback) {
        if (!name) return;
        if (quickSearchType === 'Set' || quickSearchType === 'Unique') {
            $.get(`/Help/${quickSearchType}`, function (html) {
                const dom = $.parseHTML(html);
                const type = quickSearchType.toLowerCase();
                $(dom).find(`.equip > .${type}`).each(function () {
                    if ($(this).text().indexOf(name) >= 0) {
                        callback($(this).parent());
                        return;
                    }
                });
            });
        } else {
            $.get('/Help/Artifact', function (html) {
                const dom = $.parseHTML(html);
                $(dom).find('tr').each(function (i) {
                    if (i > 0) {
                        const nameLabel = $(this).children().last().find('.artifact');
                        if (nameLabel.text().indexOf(name) >= 0) {
                            const ret = [];
                            ret.push(`${nameLabel.text()}
`);
                            $(this).children().first().children('div').each(function () {
                                ret.push(`${$(this).text()}
`);
                            });
                            ret.push('神器
');
                            nameLabel.parent().children().each(function (index) {
                                if (index > 0) ret.push(`${$(this).text()}
`);
                            });
                            const recipe = [];
                            $(this).children().eq(1).find('.artifact.equip-name').each(function () {
                                const id = $(this).text().match(/\d+/g)[0];
                                recipe.push(`${id}#`);
                            });
                            ret.push(`${recipe.join(' + ')}
`);
                            callback($(`${ret.join('')}
`));
                            return;
                        }
                    }
                });
            });
        }
    }
    let quickSearchType = 'Unique';
    const itemTypes = `
    
      
      
    
  `;
    const input = ``;
    $('.navbar-header').append(input);
    $('.quick-option').click(function (e) {
        e.preventDefault();
        quickSearchType = $(this).data('type');
        $('#idle-quick-type').text($(this).text());
        const val = $('#idle-ui-quicksearch > input').val();
        if (val) {
            const popover = $('#idle-ui-quicksearch > input').next();
            popover.hide();
            fetchItem(val, function (html) {
                popover.children().first().html(html);
                popover.show();
            });
        }
    });
    let quickTimer = null;
    $('#idle-ui-quicksearch > input').keyup(function () {
        if (quickTimer) {
            clearTimeout(quickTimer);
            quickTimer = null;
        }
        const val = $(this).val();
        if (!val) $(this).next().hide();
        quickTimer = setTimeout(() => {
            const popover = $(this).next();
            popover.hide();
            fetchItem(val, function (html) {
                popover.children().first().html(html);
                popover.show();
            });
        }, 500);
    });
    if (config.fastFilter) {
        const fastOptions = (['无'].concat(config.fastOptions)).map(function (item) {
            return `${item}`;
        }).join('');
        const fastFilter = '' +
            ''
            + `
`;
        $(fastFilter).insertAfter('.panel-filter');
        $('.filter-text').click(function () {
            const text = $(this).text() === '无' ? '' : $(this).text();
            const filter = $(this).parent().parent().parent().prev();
            filter.val(text);
            filter.trigger('input');
        });
    }
    if (config.showSpellColor) {
        $('.skill-name').each(function () {
            let desc = '';
            let label = '';
            if ($(this).children().length === 2) {
                desc = $(this).next().text();
                label = $(this).children().last();
            } else {
                desc = $(this).parent().next().text();
                label = $(this);
            }
            if (desc.indexOf('法术技能') >= 0) {
                label.addClass('skill');
            }
        });
    }
    function getSpeedLevel(speed, isAttack) {
        const levels = isAttack ? [0, -25, -50, -80, -120, -160, -200] : [0, -20, -45, -75, -110, -145, -180];
        for (let i = 0; i < levels.length; i++) {
            if (speed > levels[i]) {
                const next = levels[i];
                return [i, next];
            }
        }
        return [levels.length, '已最高'];
    }
    function getAvgDmg(dmgStr) {
        const dmgArray = dmgStr.split('~');
        const avg = (((dmgArray[0] - 0) + (dmgArray[1] - 0)) / 2);
        return avg;
    }
    function getKeySkill() {
        let ret = {name: '', accRate: 0, dmgRate: 0};
        $('span.label.label-danger').each(function () {
            if (!$(this).hasClass('sr-only') && $(this).text().indexOf('K') >= 0) {
                ret.name = $(this).prev().text();
                const skill = $(this).parent().next().text();
                ret.isAttack = skill.indexOf('攻击技能') >= 0;
                if (ret.isAttack) {
                    const accMatch = skill.match(/提升(\d+)%准确率/);
                    const dmgMatch = skill.match(/(\d+)%基础伤害/);
                    if (accMatch) ret.accRate = (accMatch[1] - 0) / 100;
                    if (dmgMatch) ret.dmgRate = (dmgMatch[1] - 0) / 100;
                }
            }
        });
        return ret;
    }
    function renderCharLabel(name, value, id) {
        const idStr = id ? `id="${id}"` : '';
        return `${name}:${value}
`;
    }
    if (location.href.indexOf('Character/Detail') >= 0) {
        const keySkill = getKeySkill();
        let level = 0;
        $('.label.label-default').each(function () {
            const label = $(this).text();
            if (label.indexOf('Lv') >= 0 && level === 0) {
                level = label.replace('Lv', '') - 0;
            }
            if (config.showSpeedLevel) {
                if (label === '攻击') {
                    const attackSpeed = $(this).parent().next().next().next().next().children().last();
                    const level = getSpeedLevel(attackSpeed.text(), true);
                    const levelElement = renderCharLabel('攻速档位', level[0]) + renderCharLabel('下档攻速', level[1]);
                    $(levelElement).insertAfter(attackSpeed.parent());
                } else if (label === '法术') {
                    const spellSpeed = $(this).parent().next().children().last();
                    const level = getSpeedLevel(spellSpeed.text(), false);
                    const levelElement = renderCharLabel('速度档位', level[0]) + renderCharLabel('下档速度', level[1]);
                    $(levelElement).insertAfter(spellSpeed.parent());
                }
            }
            if (config.showCharDmg) {
                if (label === '攻击') {
                    const baseDmg = $(this).parent().next().children().last().text();
                    const critElement = $(this).parent().next().next().next();
                    const crit = critElement.children().last().text().replace('%', '') / 100;
                    const avgDmg = getAvgDmg(baseDmg);
                    const finalDmg = (avgDmg * (1 + (crit - 0))).toFixed(2) - 0;
                    let dmgElement = renderCharLabel('普攻均伤', finalDmg);
                    if (keySkill.isAttack) {
                        const keyDmg = (keySkill.dmgRate * finalDmg).toFixed(2) - 0;
                        dmgElement += renderCharLabel(`${keySkill.name}均伤`, keyDmg);
                    }
                    $(dmgElement).insertAfter(critElement);
                }
            }
            if (config.showAccuracy) {
                if (label === '攻击') {
                    const accuracy = $(this).parent().next().next().children().last().text() - 0;
                    const accuracyElement = $(this).parent().next().next();
                    const accRate = getAccRate(level, level, accuracy);
                    let accElement = `命中怪物等级:
`;
                    accElement += renderCharLabel('普攻命中率', `${accRate}%`, 'idle-ui-acc');
                    if (keySkill.isAttack) {
                        const keyAcc = accuracy * keySkill.accRate;
                        const keyAccRate = getAccRate(level, level, keyAcc);
                        accElement += renderCharLabel(`${keySkill.name}命中率`, `${keyAccRate}%`, 'idle-ui-key-acc');
                    }
                    $(accElement).insertAfter(accuracyElement);
                    $('.hit-input').change(function () {
                        const mlvl = $(this).val();
                        const def = (mlvl - 0 + 1) * 10;
                        const curAccRate = getAccRate(level, mlvl, accuracy);
                        $('#idle-ui-acc').text(`${curAccRate}%`);
                        if (keySkill.isAttack) {
                            const curKeyAccRate = getAccRate(level, mlvl, accuracy * keySkill.accRate);
                            $('#idle-ui-key-acc').text(`${curKeyAccRate}%`);
                        }
                    });
                }
            }
            if (config.itemStats) {
                if (label == '综合') {
                    const uniqueNum = $(this).parent().next().next().next().next().children().last().text();
                    const setNum = $(this).parent().next().next().next().next().next().children().last().text();
                    const statsData = {uniqueNum: uniqueNum, setNum: setNum};
                    saveStats({uniqueNum: uniqueNum, setNum: setNum});
                }
            }
        });
    }
    function getAccRate(clvl, mlvl, acc) {
        clvl = clvl - 0;
        mlvl = mlvl - 0;
        acc = acc - 0;
        const def = (mlvl - 0 + 1) * 10;
        return (2 * (clvl / (clvl + mlvl)) * (acc / (acc + def)) * 100).toFixed(2) - 0;
    }
    function saveStats(statsData) {
        const idMatch = location.href.match(/Character\/Detail\?Id=(\d+)/i);
        if (!idMatch) return;
        const id = idMatch[1];
        let stats = localStorage.getItem('idle-ui-stats');
        stats = stats ? JSON.parse(stats) : {uniqueNum: 0, setNum: 0};
        const lastStatsData = stats[id];
        const time = +new Date();
        if (lastStatsData && lastStatsData.time) {
            const duration = moment.duration(moment(time).diff(moment(lastStatsData.time)));
            const timeSpan = duration.asMinutes() > 60 ? (duration.asHours().toFixed(1) - 0) + '小时前' : Math.round(duration.asMinutes()) + '分钟前';
            const uniqueChange = statsData.uniqueNum - lastStatsData.uniqueNum;
            const setChange = statsData.setNum - lastStatsData.setNum;
            displayStats(id, timeSpan, uniqueChange, setChange);
        }
        statsData.time = time;
        stats[id] = statsData;
        localStorage.setItem('idle-ui-stats', JSON.stringify(stats));
    }
    function displayStats(id, timeSpan, uniqueChange, setChange) {
        const message = `上次访问是${timeSpan},这段时间内你获得了 
${uniqueChange} 件暗金,
${setChange} 件套装。
插件设置| ${date} | ${result} | ${item.turns} | ${enemys} | ${drops} | 
`;
            }).join('');
            $('#idle-ui-log-table').html(rows);
            if (page === 1) {
                $('#page-prev').prop('disabled', true);
            } else {
                $('#page-prev').prop('disabled', false);
            }
            if (page === maxPage) {
                $('#page-next').prop('disabled', true);
            } else {
                $('#page-next').prop('disabled', false);
            }
            $('#idle-ui-log-length').text(logLength);
            $('#idle-ui-max-page').text(maxPage);
            $('#idle-ui-page').text(page);
        }
        $('#page-prev').click(function () {
            page = page - 1;
            renderRows();
        });
        $('#page-next').click(function () {
            page = page + 1;
            renderRows();
        });
        $('#idle-ui-only-boss').change(function () {
            page = 1;
            getLengthAndMaxPage();
            renderRows();
        });
        $('#clear-log').click(function () {
            log[id] = [];
            localStorage.setItem('idle-ui-maplog', JSON.stringify(log));
            location.reload();
        });
        function getLengthAndMaxPage() {
            const checked = $('#idle-ui-only-boss').prop('checked');
            logLength = checked ? dataSource.filter(item => item.boss).length : dataSource.length;
            maxPage = Math.ceil(logLength / pageSize);
        }
        function reloadLog() {
            log = localStorage.getItem('idle-ui-maplog');
            log = log ? JSON.parse(log) : {};
            dataSource = log[id] || [];
            getLengthAndMaxPage();
            const stats = getBattleLogStats(dataSource);
            $('#idle-ui-creepnum').text(stats.creepNum);
            $('#idle-ui-avgcreepturns').text(stats.avgCreepTurns);
            $('#idle-ui-creepwinrate').text(`${stats.creepWinRate}%`);
            $('#idle-ui-bossnum').text(stats.bossNum);
            $('#idle-ui-avgbossturns').text(stats.avgBossTurns);
            $('#idle-ui-bosswinrate').text(`${stats.bossWinRate}%`);
            page = 1;
            renderRows();
        }
        $('#idle-ui-reload').click(function () {
            reloadLog();
        });
        $('#idle-ui-maplog').click(function () {
            reloadLog();
            $('#modalMapLog').modal('show');
        });
    }
    if (config.showSetAttr) {
        loadSetAttr();
        function loadSetAttr() {
            if (!$('.equip-content > .equip > .set').length) return;
            const setDB = localStorage.getItem('idle-ui-set-db');
            const newSetDB = localStorage.getItem('idle-ui-set-db-new');
            if (setDB && newSetDB) {
                const JSONSetDB = JSON.parse(setDB);
                const JSONNewSetDB = JSON.parse(newSetDB);
                $('.equip-content > .equip > .set').each(function () {
                    const content = $(this).parent();
                    const itemName = content.children().first().text().replace(/\(\d+\)/g, '');
                    const singleData = JSONSetDB.singleData[itemName];
                    const existSingLeNum = content.children('.set').length - 1;
                    if (singleData && singleData.length > existSingLeNum) {
                        const singleContent = singleData.slice(existSingLeNum).map(item => {
                            return `${item}
`;
                        }).join('');
                        content.children('.unique').before(singleContent);
                    }
                    const fullContent = content.children('.unique');
                    const existFullNum = fullContent.children('p[class!="set"][class!="require"]').length - 1;
                    const setName = fullContent.children('br').last().next().text().replace(/\(\d+\)/g, '');
                    var fullData = JSONSetDB.setData[setName];
                    if (!fullData) {
                        fullData = JSONNewSetDB.setData[setName];
                    }
                    let setContent = fullData.slice(existFullNum).map(item => {
                        return `${item}
`;
                    }).join('');
                    if (fullContent.children('br').length === 1) setContent = '
' + setContent;
                    fullContent.children('br').last().before(setContent);
                });
            } else {
                $.get('/Help/Set', function (html) {
                    const parsedsetDB = parseSetHtml(html);
                    localStorage.setItem('idle-ui-set-db', JSON.stringify(parsedsetDB));
                    loadSetAttr();
                });
                $.get('/Help/Sacred', function (html) {
                    const parsedsetDB = parseSetHtml(html);
                    localStorage.setItem('idle-ui-set-db-new', JSON.stringify(parsedsetDB));
                    loadSetAttr();
                });
            }
        }
        function parseSetHtml(html) {
            $(".footer").before(`${html}
`);
            const singleData = {};
            const setData = {};
            $('#set-data .masonry-item .panel-body .equip').each(function () {
                const lines = $(this).children();
                const itemName = lines.first().text().replace(/\(\d+\)/, '');
                const singleLines = [];
                lines.each(function (index) {
                    const line = $(this);
                    if (index > 0 && line.hasClass('set')) {
                        singleLines.push(line.text().replace(/\n/g, ''));
                    }
                    if (line.hasClass('unique')) {
                        const setItems = line.children();
                        let stop = false;
                        const setLines = [];
                        let setName = '';
                        setItems.each(function (index) {
                            if (index > 0) {
                                if ($(this).prop('tagName').toLowerCase() === 'br') {
                                    stop = true;
                                    setName = $(this).next().text();
                                }
                                if (!stop) setLines.push($(this).text().replace(/\n/g, ''));
                            }
                        });
                        if (!setData[setName]) setData[setName] = setLines;
                    }
                });
                if (singleLines.length) singleData[itemName] = singleLines;
            });
            return {singleData, setData};
        }
    }
    if (location.href.indexOf('Auction/Query') >= 0 && location.href.indexOf('Auction/QueryBid') === -1) {
        if (config.showAuctionNote) {
            $('.physical.equip-des').each(function () {
                const note = $(this).text();
                const label = $(this).parent().parent().prev().children('.equip-name').last();
                label.after(` ${note}`);
            });
        }
        //   if (config.auctionWatch) {
        //       let watchList = [];
        //
        //       function renderTable(params) {
        //           const list = localStorage.getItem('idle-ui-auction');
        //           watchList = (list ? JSON.parse(list) : []) || [];
        //           const rows = watchList.map((item, index) => {
        //               return `| ${item.category} | ${item.name} | 查看 | 
`;
        //           });
        //           $('#modalAuction .table-body').html(rows);
        //           $('.delete-auction').click(function () {
        //               const index = $(this).data('index');
        //               watchList.splice(index, 1);
        //               localStorage.setItem('idle-ui-auction', JSON.stringify(watchList));
        //               renderTable();
        //           });
        //           renderNewItems();
        //       }
        //
        //       function renderNewItems() {
        //           const ids = purl().param().items;
        //           if (!ids) return;
        //           ids.split(',').map(id => {
        //               $(`span[data-id="${id}"`).parent().addClass('idle-ui-new-item');
        //           });
        //       }
        //
        //       const link = '';
        //       $('.btn-group').eq(1).before(link);
        //       const categorys = [];
        //       $('.panel-heading .btn-group button.dropdown-toggle').each(function () {
        //           categorys.push($(this).text().replace('', '').replace(/\s/g, ''));
        //       });
        //       const category = categorys.join(' - ');
        //
        //       const modal = `
        //   
        // `;
        //       $(document.body).append(modal);
        //       renderTable();
        //       $('#open-auction-modal').click(function () {
        //           if ($('.equip-name').length) {
        //               $('#auction-name').val($('.equip-name').eq(0).text().replace('【', '').replace('】', ''));
        //           }
        //           $('#modalAuction').modal('show');
        //       });
        //
        //       $('#add-auction').click(function () {
        //           if (watchList.length >= 10) {
        //               alert('最多关注10条');
        //               return;
        //           }
        //           const params = purl().param();
        //           const et = params.et || '';
        //           const pt = params.pt || '';
        //           const ei = params.ei || '';
        //           const link = `et=${et}&pt=${pt}&ei=${ei}`;
        //           const name = $('#auction-name').val();
        //           const items = [];
        //           $('.equip-name').each(function () {
        //               const curName = $(this).text().replace('【', '').replace('】', '');
        //               if (curName === name) {
        //                   const id = $(this).parent().children().last().data('id');
        //                   items.push(id);
        //               }
        //           });
        //           const data = {
        //               category: category,
        //               name: $('#auction-name').val(),
        //               link: link,
        //               items: items
        //           };
        //           watchList.push(data);
        //           localStorage.setItem('idle-ui-auction', JSON.stringify(watchList));
        //           renderTable();
        //       });
        //   }1
    }
    if (config.oneKeyEquip && location.href.indexOf('Equipment/Query') >= 0) {
        const btn = '';
        const startMetastasis = '';
        const stopMetastasis = '';
        const start = '';
        const end = '';
        $('.panel-heading .btn').eq(0).before(btn);
        let map = localStorage.getItem('idle-ui-maphack');
        if (map) {
            map = JSON.parse(map);
        }
        const cid = $("#cid").val();
        var mysteryIndex = 5;
        // 是否一键转移
        const metastasis = map[`metastasis${cid}`];
        // 要转移人的姓名
        const name = map[`cname${cid}`];
        if (name) {
            $('.panel-filter.hidden-xs')[1].value = name;
        }
        if ((metastasis) && metastasis === 'start') {
            $('.panel-heading .btn').eq(4).before(stopMetastasis);
            mysteryIndex = 6;
        }
        $('#end-metastasis').click(function (params) {
            map[`metastasis${cid}`] = 'end';
            map[`cname${cid}`] = "";
            localStorage.setItem('idle-ui-maphack', JSON.stringify(map));
            location.reload();
        });
        $('.panel-heading .btn').eq(4).before(startMetastasis);
        $('#start-metastasis').click(function (params) {
            map[`metastasis${cid}`] = 'start';
            map[`cname${cid}`] = $('.panel-filter.hidden-xs')[1].value;
            localStorage.setItem('idle-ui-maphack', JSON.stringify(map));
            moveMystery();
        });
        function moveMystery() {
            const mysteryId = $(".equip-dungeon").data('id');
            if (!mysteryId) {
                map[`metastasis${cid}`] = 'end';
                localStorage.setItem('idle-ui-maphack', JSON.stringify(map));
                location.reload();
                return;
            }
            a = {
                cid: cid,
                eid: mysteryId,
                cname: map[`cname${cid}`],
                __RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
            };
            $.ajax({
                //几个参数需要注意一下
                type: "POST",//方法类型
                dataType: "html",//预期服务器返回的数据类型
                url: 'EquipTrade',//url
                data: a,
                success: function (result) {
                    location.reload()
                },
                error: function (result) {
                    alert(result)
                }
            });
        }
        if (metastasis && metastasis === 'start') {
            setTimeout(() => {
                if ((metastasis) && metastasis === 'start') {
                    moveMystery()
                }
            }, 5000);
        }
        // 开始扫荡秘境了,就显示停止扫荡按钮
        const mystery = map[`mystery${cid}`];
        if ((mystery) && mystery === 'start') {
            $('.panel-heading .btn').eq(mysteryIndex).before(end);
            $('#end-mystery').click(function (params) {
                alert('已停止扫荡秘境');
                map[`mystery${cid}`] = 'end';
                localStorage.setItem('idle-ui-maphack', JSON.stringify(map));
            });
        }
        $('.panel-heading .btn').eq(mysteryIndex).before(start);
        $('#start-mystery').click(function (params) {
            map[`mystery${cid}`] = 'start';
            localStorage.setItem('idle-ui-maphack', JSON.stringify(map));
            startMystery();
        });
        function startMystery() {
            const mysteryId = $(".equip-dungeon").data('id');
            map[cid] = 'start';
            a = {
                id: cid,
                cid: cid,
                eid: mysteryId,
                __RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
            };
            $.ajax({
                //几个参数需要注意一下
                type: "POST",//方法类型
                dataType: "html",//预期服务器返回的数据类型
                url: "EquipDungeon",//url
                data: a,
                success: function (result) {
                    // 请求成功,返回网页,自动跳转到秘境界面
                    location.href = `../Map/DungeonForEquip?id=${userId}`
                },
                error: function (XMLHttpRequest, textStatus) {
                    alert(XMLHttpRequest)
                }
            });
        }
        if (mystery && mystery === 'start') {
            setTimeout(() => {
                if ((mystery) && mystery === 'start') {
                    startMystery()
                }
            }, 15000);
        }
        // 设置点击对应的点击事件
        const equipList = ['主手', '副手', '头盔', '护符', '项链', '戒指', '戒指', '衣服', '腰带', '手套', '靴子'];
        let buildMap = {};
        let buildData = [];
        const userId = purl().param().id;
        const equipItems = getEquipItems();
        function loadEquipBuild() {
            buildMap = JSON.parse(localStorage.getItem('idle-ui-equip-build') || '{}');
            buildData = buildMap[userId] || [];
        }
        function saveEquipBuild(data) {
            localStorage.setItem('idle-ui-equip-build', JSON.stringify(data));
            loadEquipBuild();
            renderEquip();
        }
        function renderEquip(buildIndex) {
            if (!buildIndex && buildData.length) buildIndex = 0;
            const data = buildData[buildIndex] || {};
            const equipContent = equipList.map((item, index) => {
                const equipItem = data.items ? data.items[index] : {};
                return `${item}${equipItem.name || ''}
`;
            });
            const firstCol = equipContent.slice(0, 4).join('');
            const secondCol = equipContent.slice(4, 7).join('');
            const thirdCol = equipContent.slice(7).join('');
            const content = `${firstCol}
${secondCol}
${thirdCol}
`;
            $('#equip-build-content').html(content);
            // 一键换装
            const buildTags = buildData.map((item, index) => {
                return `${item.name}`;
            }).join('');
            $('#equip-build-tags').html(buildTags);
            $('#selected-build-name').text(data.name || '选择方案');
            if (buildIndex !== undefined) {
                $('#use-equip-build').data('index', buildIndex);
                $('#del-equip-build').data('index', buildIndex);
            } else {
                $('#use-equip-build').data('index', -1);
                $('#del-equip-build').data('index', -1);
            }
            $('.equip-build-option').click(function (e) {
                e.preventDefault();
                const index = $(this).data('index');
                renderEquip(index);
            });
        }
        const modal = `
        
      `;
        $(document.body).append(modal);
        loadEquipBuild();
        renderEquip();
        $('#show-one-key-equip').click(function () {
            $('#modalEquipBuild').modal('show');
        });
        let processing = false;
        function doEquip(buildIndex, itemIndex) {
            if (blockData.num >= 9) {
                alert('封号打击次数过多,禁止一键换装');
                location.reload();
            }
            if (itemIndex > equipItems.length - 1) {
                setTimeout(() => {
                    processing = false;
                    $('#processing').hide();
                    location.reload();
                }, 500);
                return;
            }
            const list = $('#form').serializeArray();
            const params = {};
            list.forEach(item => {
                params[item.name] = item.value;
            });
            params.eid = buildData[buildIndex].items[itemIndex].id;
            params.cid = userId;
            // 判断当前要替换的装备是否已经装备
            const itemAlreadyEquiped = equipItems.some(item => item.id === params.eid);
            if (!params.eid || !params.cid) return;
            const name = buildData[buildIndex].items[itemIndex].name;
            if (itemAlreadyEquiped) {
                // 已经装备,进入下一件装备
                doEquip(buildIndex, itemIndex + 1);
            } else {
                // 没有装备,还是进行替换
                $.post('/Equipment/EquipOn', params, function (data) {
                    setTimeout(function () {
                        doEquip(buildIndex, itemIndex + 1);
                    }, 1000);
                }).fail(function (data) {
                    setTimeout(function () {
                        doEquip(buildIndex, itemIndex + 1);
                    }, 1000);
                });
            }
        }
        $('#use-equip-build').click(function () {
            if (processing) return;
            const index = $(this).data('index');
            if (index >= 0) {
                processing = true;
                $('#processing').show();
                doEquip(index, 0);
            } else {
                alert('请先选择一个方案');
            }
        });
        $('#del-equip-build').click(function () {
            const index = $(this).data('index');
            if (index >= 0) {
                buildData.splice(index, 1);
                buildMap[userId] = buildData;
                saveEquipBuild(buildMap);
            } else {
                alert('请先选择一个方案');
            }
        });
        function getEquipItems() {
            const items = [];
            $('.panel-body').eq(0).find('.equip-content').each(function () {
                const label = $(this).prev().children('.equip-name').eq(0);
                if (label.length) {
                    const name = label.text();
                    const type = label.prop('class').replace('equip-name', '').trim();
                    const id = label.parent().children().last().data('id');
                    items.push({name: name, type: type, id: id});
                } else {
                    items.push({name: '', type: '', id: 0});
                }
            });
            return items;
        }
        $('#add-equip-build').click(function () {
            if (buildData.length >= 5) {
                alert('同一角色最多保存5套方案');
                return;
            }
            const name = $('#equip-build-name').val();
            if (!name) {
                alert('方案必须有一个名称');
                return;
            }
            const newBuild = {
                name: name,
                items: equipItems
            };
            buildData.push(newBuild);
            buildMap[userId] = buildData;
            saveEquipBuild(buildMap);
        });
    }
    if (config.oneKeyAgree && location.href.indexOf('Notice/Query') >= 0) {
        let processing = false;
        const agreeList = [];
        $('.notice-yes').each(function () {
            agreeList.push($(this).data('id'));
        });
        function doAgree(index) {
            if (blockData.num >= 9) {
                alert('封号打击次数过多,禁止一键同意');
                location.reload();
            }
            if (index > agreeList.length - 1) {
                $('#processing').hide();
                processing = false;
                location.reload();
                return;
            }
            const id = agreeList[index];
            const list = $('#form').serializeArray();
            const params = {};
            list.forEach(item => {
                params[item.name] = item.value;
            });
            params.nid = id;
            $.post('/Notice/NoticeYes', params, function () {
                setTimeout(function () {
                    doAgree(index + 1);
                }, 300);
            }).fail(function (data) {
                alert("发生异常");
                location.reload();
            });
        }
        let action = renderProcessing();
        action += renderButton('idle-ui-agree', '全部同意');
        $('a.btn.btn-xs.btn-default').eq(0).before(action);
        $('#idle-ui-agree').click(function () {
            if (processing) return;
            if (agreeList.length) {
                $('#processing').show();
                processing = true;
                doAgree(0);
            } else {
                alert('没有可处理的消息');
            }
        });
    }
    if (config.oneKeyRune && location.href.indexOf('Equipment/Material') >= 0) {
        let processing = false;
        const runeList = [];
        $('.artifact.equip-name').each(function () {
            const count = $(this).next().next().text() - 0;
            if (count > 0) {
                const rune = {
                    id: $(this).next().next().next().data('id') - 0,
                    count: count
                };
                runeList.push(rune);
            }
        });
        $('.equip-name').each(function () {
            const count = $(this).next().next().text() - 0;
            if (count > 0) {
                const rune = {
                    id: $(this).next().next().next().data('id') - 0,
                    count: count
                };
                runeList.push(rune);
            }
        });
        function doMoveRune(index, cname) {
            if (blockData.num >= 9) {
                alert('封号打击次数过多,禁止一键符文转移');
                location.reload();
            }
            if (index > runeList.length - 1) {
                $('#processing').hide();
                processing = false;
                location.reload();
                return;
            }
            const rune = runeList[index];
            const list = $('#form').serializeArray();
            const params = {};
            list.forEach(item => {
                params[item.name] = item.value;
            });
            params.cname = cname;
            params.count = rune.count;
            params.rune = rune.id;
            $.post('/Equipment/RuneTrade', params, function () {
                setTimeout(function () {
                    doMoveRune(index + 1, cname);
                }, 300);
            }).fail(function (data) {
                alert("发生异常,请检查角色名是否正确");
                location.reload();
            });
        }
        $('.btn.btn-xs.btn-default').eq(1).before(renderButton('idle-ui-show-rune', '转移全部符文'));
        $('#idle-ui-show-rune').click(function () {
            $('#modalMoveRune').modal('show');
        });
        const spinner = renderProcessing();
        const modal = `
      
    `;
        $(document.body).append(modal);
        $('#idle-ui-move-rune').click(function () {
            if (processing) return;
            if (runeList.length) {
                const cname = $('#idle-ui-cname').val();
                if (!cname) {
                    alert('请输入角色名称');
                } else {
                    processing = true;
                    $('#processing').show();
                    doMoveRune(0, cname);
                }
            } else {
                alert('没有转移的符文');
            }
        });
    }
    if (config.showRuneTip) {
        let runeList = [];
        const runeData = localStorage.getItem('idle-ui-rune-db');
        if (runeData) {
            runeList = JSON.parse(runeData);
        } else {
            fetchRuneTip();
        }
        if (location.href.indexOf('Equipment/Inlay') >= 0) {
            const footer = `
        
      `;
            $('.panel').eq(0).append(footer);
            let timer = null;
            $('#panel-filter-runeword').keyup(function () {
                if (timer) {
                    clearTimeout(timer);
                    timer = null;
                }
                timer = setTimeout(() => {
                    const name = $(this).val();
                    const filtered = name ? runeList.filter(item => item.name.indexOf(name) >= 0) : [];
                    let ret = '';
                    if (filtered.length) {
                        const item = filtered[0];
                        const recipe = item.recipe.map(item => {
                            return `${item}`
                        }).join(' + ');
                        ret = `【${item.name}】:${recipe}`;
                        const requireContent = item.require.map(item => {
                            return `${item}
`;
                        }).join('');
                        const attrContent = item.attr.map(item => {
                            return `${item}
`;
                        }).join('');
                        const tip = `${item.name}
${requireContent}${attrContent}
友方伤害占比 | 详情 | 出手次数 | 出手占比 | 每回合伤害');
        $('.battle-data tbody tr').each(function (index) {
            const id = getCharId(index);
            const actor = $(this).children().first().text();
            const turns = getActorTurns(actor);
            const turnsPercent = (turns / totalTurns * 100).toFixed(1) - 0;
            const damage = $(this).children().eq(2).text() - 0;
            const damagePercent = id > 0 ? `${(damage / partyTotalDamage * 100).toFixed(1) - 0}%` : '-';
            const avgDamage = turns > 0 ? Math.round(damage / turns) : '-';
            const link = battleResult[actor] ? `查看` : '-';
            const content = ` | ${damagePercent} | ${link} | ${turns} | ${turnsPercent}% | ${avgDamage}`;
            $(this).children().eq(2).after(content);
        });
        $('.battle-data').css('overflow', 'auto');
        const modal = ` | 
          
              
                  
                  
                      
                        | 技能 | 总伤害 | 伤害占比 | 出手次数 | 出手占比 | 每回合伤害 | 直接伤害 | 溅射 | 触发技能 | 持续伤害及其他 | 
|---|
                        
                      
                      
                        - 直接伤害:技能造成的实际直接伤害
- 溅射:因溅射,对非主目标造成的溅射伤害之和
- 触发技能:【装备自带技能】或【被击中触发】的技能等被触发后造成的伤害
- 持续伤害及其他:技能造成的持续伤害,以及其他伤害  
 
                  
               
           
       
    `;
        $(document.body).append(modal);
        $('.link-detail').click(function () {
            const id = $(this).data('id');
            const data = battleResult[id];
            const actor = $(this).data('actor');
            $('#idle-ui-char').text(actor);
            let actorTotalTurns = 0;
            let actorTotalDamage = 0;
            Object.keys(data).forEach(skill => {
                actorTotalTurns += data[skill].turn;
                actorTotalDamage += data[skill].damage;
            });
            const content = Object.keys(data).map(skill => {
                const skillData = data[skill];
                const percent = (skillData.turn / actorTotalTurns * 100).toFixed(1) - 0;
                const damagePercent = (skillData.damage / actorTotalDamage * 100).toFixed(1) - 0;
                const avgDamage = skillData.turn > 0 ? Math.round(skillData.damage / skillData.turn) : '-';
                return `| ${skill} | ${skillData.damage} | ${damagePercent}% | ${skillData.turn} | ${percent}% | ${avgDamage} | ${skillData.damageDetail.base} | ${skillData.damageDetail['0'] || 0} | ${skillData.damageDetail['1'] || 0} | ${skillData.damageDetail['2'] || 0} | 
`;
            }).join('');
            $('#idle-ui-battle-rows').html(content);
            $('#modalBattleDetail').modal('show');
        });
        function getCharId(index) {
            const ary = $('.battle-char').eq(index).prop('id').split('_');
            return ary[ary.length - 1];
        }
        function getActorTurns(id) {
            let ret = 0;
            if (battleResult[id]) {
                Object.keys(battleResult[id]).forEach(skill => {
                    ret += battleResult[id][skill].turn;
                });
            }
            return ret;
        }
        function getPlainText(element) {
            return element.clone()    //clone the element
                .children() //select all the children
                .remove()   //remove all the children
                .end()  //again go back to selected element
                .text();
        }
    }
    function switchSkin(showRequire) {
        $('.equip-content > .equip').each(function (item) {
            const type = $(this).children().first().attr('class');
            let classLabel = '';
            const requireIndex = $(this).text().indexOf('限');
            if (requireIndex >= 0) {
                const requireClass = $(this).text().substring(requireIndex + 1, requireIndex + 2);
                classLabel = '' + requireClass + '';
            }
            const label = location.href.indexOf('Auction/QueryBid') >= 0 ? $(this).parent().prev().find('.equip-name').first() : $(this).parent().prev().find('.equip-name').last();
            if (classLabel) {
                showRequire ? label.after(classLabel) : label.next().remove();
            }
        });
    }
    function inBattlePage() {
        const battePages = ['Battle/Simulate', 'Battle/InDungeon', 'Battle/WithChar'];
        return battePages.some(path => location.href.indexOf(path) >= 0);
    }
    function renderProcessing() {
        return ' 处理中...';
    }
    function renderButton(id, text, type) {
        if (!type) type = 'success';
        return ``;
    }
    let uid = purl().param().id || purl().param().Id;
    let blockMap = localStorage.getItem('idle-ui-block');
    if (blockMap) {
        blockMap = JSON.parse(blockMap);
    } else {
        blockMap = {};
    }
    if (!blockMap[uid]) blockMap[uid] = {num: 0, time: +new Date()};
    let blockData = blockMap[uid];
    if (location.href.indexOf('Character/Detail') >= 0) {
        checkBlockNum();
        $('.col-sm-6 .panel-body').eq(0).children().last().append(`封号打击次数(仅供参考):${blockData.num}
`);
    }
    function addBlockNum() {
        checkBlockNum();
        if (!blockData.num) blockData.num = 0;
        blockData.num += 1;
        blockData.time = +new Date();
        localStorage.setItem('idle-ui-block', JSON.stringify(blockMap));
        new Notification(`当前封号打击为${blockData.num}次,请注意`);
    }
    function checkBlockNum() {
        const curTime = +new Date();
        const hours = Math.floor((curTime - blockData.time) / (3600 * 1000));
        if (hours > 0) {
            blockData.num = blockData.num > hours ? blockData.num - hours : 0;
            blockData.time = blockData.time + (hours * 3600 * 1000);
            localStorage.setItem('idle-ui-block', JSON.stringify(blockMap));
        }
    }
};
window.addEventListener('load', idleInit, false);
const borderColor = '#6f5a40';
GM_addStyle(`
      .panel-top {
        margin-bottom: 20px;
        text-align: center;
      }
      .idle-ui-title {
        font-size: 18px;
        color: #fff;
        margin-bottom: 6px;
      }
      .panel-header {
        margin: 8px 0;
      }
      .panel-textarea {
        background-color: rgba(255,255,255,0.1);
        color: #a99877;
        margin-bottom: 8px;
      }
      .block-visited {
        background-color: #3f51b5 !important;
      }
      .hit-input {
        display: inline-block;
        color: #fff;
        width: 60px;
        padding: 0 8px;
        border-radius: 0;
        background-color: transparent;
      }
      .idle-ui-set-single, .idle-ui-set-full {
        opacity: 0.5;
      }
      .idle-ui-new-item {
        border: 1px dashed #888 !important;
      }
      .mr-10 {
        margin-right: 10px;
      }
      .ml-10 {
        margin-left: 10px;
      }
      @-webkit-keyframes rotate {
        from {
          -webkit-transform: rotate(0deg);
          -o-transform: rotate(0deg);
          transform: rotate(0deg);
        }
        to {
          -webkit-transform: rotate(360deg);
          -o-transform: rotate(360deg);
          transform: rotate(360deg);
        }
      }
      #processing i {
        animation: rotate 1s ease-in-out infinite;
      }
      .filter-input {
        width: 150px !important;
      }
      #big-slot {
        font-size: 24px;
        margin-top: 10px !important;
        color: #fff;
      }
      #idle-ui-quicksearch {
        position: relative;
        float: left;
        margin-top: 14px;
      }
      #idle-ui-quicksearch > input {
        width: 150px;
        display: inline-block;
        height: 24px;
        line-height: 24px;
        border-radius: 3px;
      }
      .equip-container > p:hover {
        white-space: nowrap;
      }
      .equip-container > p:hover .sr-only {
        z-index: 1;
        position: relative;
      }
      html.d3 body {
        color: #a99877;
        font-family: "Consolas", Arial, sans-serif;
      }
      html.d3 .panel {
        background-color: #171614;
        border-color: ${borderColor};
      }
      html.d3 .panel-inverse > .panel-heading {
        background-color: #101010;
        border-color: ${borderColor};
        font: normal 16px "Exocet Blizzard Light","Palatino Linotype", "Times", serif;
        color: #F3E6D0;
        line-height: 26px;
      }
      html.d3 .panel-inverse > .panel-heading .label {
        font-size: 12px;
        font-family: "Consolas", Arial, sans-serif;
      }
      html.d3 .btn {
        background-color: transparent;
        border: 1px solid ${borderColor};
        vertical-align: top;
        color: #ad835a;
        font: normal 14px/1.5 Arial, sans-serif;
        line-height: normal;
      }
      html.d3 .btn:hover {
        color: #fff !important;
      }
      html.d3 .btn:active {
        background-color: transparent;
      }
      html.d3 .label {
        line-height: normal;
        font-weight: normal;
        border-radius: 2px;
        padding: 3px 4px 1px;
        border: 1px solid #5f3d11;
        box-shadow: 0 0 2px #000;
        background-color: #000;
        color: #ad835a;
      }
      html.d3 .label.label-info {
        color: #6969ff;
      }
      html.d3 .label.label-warning {
        color: #ffff00;
      }
      html.d3 .label.label-danger {
        color: #e60101;
      }
      html.d3 .label.label-success {
        color: #00c400;
      }
      html.d3 .physical {
        color: #f3e6d0 !important;
      }
      html.d3 .navbar-inverse.navbar-fixed-top {
        border-bottom: 1px solid #322a20;
        background-color: #171614;
      }
      html.d3 .navbar-inverse .navbar-brand {
        color: #f3e6d0;
        font-family: "Exocet Blizzard Light","Palatino Linotype", "Times", serif;
      }
      html.d3 a, html.d3 .navbar-inverse .navbar-nav>li>a {
        color: #ad835a;
      }
      html.d3 .magical, html.d3 .skill, html.d3 .cold {
        color: #6969ff !important;
      }
      html.d3 .hit-input {
        border-color: ${borderColor};
      }
      html.d3 .progress {
        border: 1px solid #513f2e;
        border-radius: 0;
        box-shadow: 0 0 5px #000;
        background-color: #101010;
        color: #f3e6d0;
        height: 22px;
      }
      html.d3 .progress-bar {
        border: 1px solid #101010;
        line-height: 20px;
      }
      html.d3 .progress-bar-exp {
        background-color: rgb(251,131,44);
      }
      html.d3 .progress-bar-life {
        background: rgb(235,21,28);
      }
      html.d3 .footer {
        border-top: 1px solid #322a20;
        background-color: #171614;
      }
      html.d3 .btn.btn-success {
        color: #00c400;
      }
      html.d3 .btn.btn-danger {
        color: #e60101;
      }
      html.d3 .img-thumbnail {
        border-color: #d59c52;
      }
      html.d3 .popover {
        background: #1d180e;
        padding: 1px;
        border: 1px solid #322a20;
        border-radius: 2px;
        box-shadow: 0 0 10px #000;
        max-width: 271px;
        font-family: "Consolas", Arial, sans-serif;
      }
      html.d3 .popover-content .equip p:first-child {
        height: 30px;
        width: 263px;
        padding: 0;
        margin: 0 -10px 10px -10px !important;
        background: url(http://images.targetedu.cn/d3/tooltip-title.jpg) no-repeat;
        text-align: center;
        line-height: 28px;
        font-size: 16px;
        font-family: "Exocet Blizzard Light","Palatino Linotype", "Times", serif;
      }
      html.d3 .popover-content .equip p.unique:first-child {
        background-position: 0 -120px;
      }
      html.d3 .popover-content .equip p.set:first-child {
        background-position: 0 -180px;
      }
      html.d3 .popover-content .equip p.rare:first-child {
        background-position: 0 -90px;
      }
      html.d3 .popover-content .equip p.artifact:first-child {
        background-position: 0 -150px;
      }
      html.d3 .popover-content .equip p.magical:first-child {
        background-position: 0 -60px;
      }
      html.d3 .popover-content .equip p.base:first-child {
        background-position: 0 -30px;
      }
      html.d3 .popover-content .equip p.slot:first-child {
        background-position: 0 -30px;
      }
      html.d3 .popover-content {
        background-color: #000;
        padding: 2px 12px;
      }
      html.d3 hr {
        border-color: ${borderColor};
      }
      html.d3 .panel-inverse > .panel-footer {
        background-color: #101010;
        border-color: ${borderColor};
      }
      html.d3 .modal-dialog {
        box-shadow: 0 0 10px #000;
      }
      html.d3 .modal-content {
        background-color: #171614;
        border-color: ${borderColor};
      }
      html.d3 .model-inverse > .modal-header, html.d3 .model-inverse > .modal-footer {
        background-color: #101010;
        border-color: ${borderColor};
      }
      html.d3 .model-inverse > .modal-header span {
        line-height: normal;
      }
      html.d3 .panel-textarea {
        border-color: ${borderColor};
      }
      html.d3 .panel-footer .panel-filter {
        border-color: #2a241c;
      }
      html.d3 .btn-default:active:focus,
      html.d3 .open>.dropdown-toggle.btn-default:focus,
      html.d3 .btn-default.active, .btn-default:active,
      html.d3 .open>.dropdown-toggle.btn-default {
        background-color: transparent;
        color: #a99877;
      }
      html.d3 .dropdown-menu {
        background-color: #101010;
        border-color: ${borderColor};
        box-shadow: 0 0 10px #000;
        font-family: "Consolas", Arial, sans-serif;
      }
      html.d3 .equip-container .selected {
        border: 1px solid ${borderColor};
        background-color: transparent;
      }
      html.d3 .table > tbody > tr > td,
      html.d3 .table > tbody > tr > th,
      html.d3 .table > tfoot > tr > td,
      html.d3 .table > tfoot > tr > th,
      html.d3 .table > thead > tr > td,
      html.d3 .table > thead > tr > th {
        border-color: ${borderColor};
      }
      html.d3 .equip .divider {
        background-color: ${borderColor};
      }
      html.d3 .panel-heading .btn-group, html.d3 .panel-heading .btn {
        vertical-align: top;
      }
      html.d3 .form-control{
        border-color: ${borderColor};
        background-color: #101010;
        color: #a99877;
      }
      html.d3 .form-validation .form-control {
        width: 198px;
      }
      html.d3 .popover.bottom>.arrow:after {
        border-bottom-color: #322a20;
      }
      html.d3 .super, html.d3 .unique {
        color: rgb(255,128,0) !important;
      }
      html.d3 .artifact {
        color: rgb(182,89,245) !important;
      }
      html.d3 .equip > p {
        color: #6969ff;
      }
    `);