Greasy Fork

云班课🆕答题小能手🥇(MeTo题库)

【😎蓝墨云考试,测试全自动答题,题目答案搜索功能由MeTo团队提供,一键完成所有资源学习(视频挨个刷时长不存在滴)😎】、【基于生成式AI(ChatGPT)的答案生成】【💙新增AI搜题、AI问答,模版定制化服务💙】,【🌛无须繁琐的注册流程,无须key,直接与AI对话!🌛】,【🔥一键导入题目🔥】、【🧡新增背题模式(遮挡答案,更好的进行考试复习)🧡】、【🌹特别感谢MeTo题库提供题目搜索与AI问答功能🌹】。【💚作者在此保证,脚本无任何诸如(手机号,学校信息)隐私信息收集💚】如果需要纯净版的chatgpt划词可以看一下这个项目https://greasyfork.org/zh-CN/scripts/473522-metogpt%E5%88%92%E8%AF%8D%E5%99%A8

目前为 2023-08-25 提交的版本。查看 最新版本

// ==UserScript==
// @run-at       document-body
// @name         云班课🆕答题小能手🥇(MeTo题库)
// @namespace    http://tampermonkey.net/
// @version      4.0
// @description  【😎蓝墨云考试,测试全自动答题,题目答案搜索功能由MeTo团队提供,一键完成所有资源学习(视频挨个刷时长不存在滴)😎】、【基于生成式AI(ChatGPT)的答案生成】【💙新增AI搜题、AI问答,模版定制化服务💙】,【🌛无须繁琐的注册流程,无须key,直接与AI对话!🌛】,【🔥一键导入题目🔥】、【🧡新增背题模式(遮挡答案,更好的进行考试复习)🧡】、【🌹特别感谢MeTo题库提供题目搜索与AI问答功能🌹】。【💚作者在此保证,脚本无任何诸如(手机号,学校信息)隐私信息收集💚】如果需要纯净版的chatgpt划词可以看一下这个项目https://greasyfork.org/zh-CN/scripts/473522-metogpt%E5%88%92%E8%AF%8D%E5%99%A8
// @author       阿绿
// @note         致谢表:@M_、@吃土豆长大的马铃薯、@悟虚、@台灯没电了、@Pumpkin、@小陈陈陈陈啊、@Sli、@无心人、@29827*0049、@热心解答(以上均是对此脚本做出过有效BUG提交OR提供账户帮助修复OR提供好的idea)
// @match        https://www.mosoteach.cn/web/index.php?*
// @icon         https://bkimg.cdn.bcebos.com/pic/4ec2d5628535e5dde7114110e88eb0efce1b9c16c4e1
// @require      https://cdn.bootcss.com/crypto-js/3.1.9-1/crypto-js.min.js
// @require      https://greasyfork.org/scripts/463249-%E4%BA%91%E7%8F%AD%E7%8F%AD%E4%BE%9D%E8%B5%96/code/%E4%BA%91%E7%8F%AD%E7%8F%AD%E4%BE%9D%E8%B5%96.js?version=1202671
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_addStyle
// @grant        GM_getResourceText
// @grant        GM_info
// @grant        GM_xmlhttpRequest
// @grant        GM_registerMenuCommand
// @connect      m.met0.top
// @connect      c.met0.top
// @connect      d.met0.top
// @connect      127.0.0.1
// @connect      gitee.com
// @connect      *

// @resource     JQ361JS https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.min.js
// @resource     Vue http://lib.baomitu.com/vue/2.6.0/vue.min.js
// @resource     jqueryweui https://cdn.bootcdn.net/ajax/libs/jquery-weui/1.2.1/js/jquery-weui.min.js
// @resource     weuiCss https://cdn.bootcdn.net/ajax/libs/weui/2.5.12/style/weui.min.css
// @require      https://lib.baomitu.com/jquery/3.6.0/jquery.min.js

// @license      MIT
// ==/UserScript==


(function () {
    (function($) {
        var tips = [];
        function handleWindowResize() {
            $.each(tips, function() {
                this.refresh(true);
            });
        }
        $(window).resize(handleWindowResize);

        $.JPopBox = function(elm, options) {
            this.$elm = $(elm);
            this.opts = this.getOptions(options);
            var popBoxHtml=[];
            popBoxHtml.push('<div class="'+this.opts.className+'">');
            if(this.opts.title!=""){
                popBoxHtml.push('<div class="JPopBox-tip-title">'+this.opts.title+'</div>');
            }
            if(this.opts.isShowArrow){
                popBoxHtml.push('<div class="JPopBox-tip-arrow JPopBox-tip-arrow-top JPopBox-tip-arrow-right JPopBox-tip-arrow-bottom JPopBox-tip-arrow-left" style="visibility:inherit"></div>');
            }
            popBoxHtml.push('<div class="JPopBox-tip-content"></div>'),
                popBoxHtml.push('</div>');
            this.$tip = $(popBoxHtml.join('')).appendTo(document.body);
            this.$arrow = this.$tip.find('div.JPopBox-tip-arrow');
            this.$inner = this.$tip.find('div.JPopBox-tip-content');
            this.disabled = false;
            this.content = null;
            this.init();
        };

        $.JPopBox.hideAll = function() {
            $.each(tips, function() {
                this.hide();
            });
        };

        $.JPopBox.prototype = {
            getOptions:function(options){
                options = $.extend({}, $.fn.jPopBox.defaults, options);
                if (options.delay && typeof options.delay == 'number') {
                    options.delay = {
                        show: options.delay,
                        hide: options.delay
                    };
                }
                if (typeof options.offset == 'number') {
                    options.offset = {
                        X: options.offset,
                        Y: options.offset
                    };
                }
                return options
            },
            init: function() {
                tips.push(this);
                this.$elm.data('jPopBox', this);
                if (this.opts.trigger != 'none') {
                    this.opts.trigger!="click" && this.$elm.on({
                        'mouseenter.jPopBox': $.proxy(this.mouseenter, this),
                        'mouseleave.jPopBox': $.proxy(this.mouseleave, this)
                    });
                    switch (this.opts.trigger) {
                        case 'click':
                            this.$elm.on('click.jPopBox', $.proxy(this.toggle, this));
                            break;
                        case 'hover':
                            if (this.opts.isTipHover)
                                this.$tip.hover($.proxy(this.clearTimeouts, this), $.proxy(this.mouseleave, this));
                            break;
                        case 'focus':
                            this.$elm.on({
                                'focus.jPopBox': $.proxy(this.showDelayed, this),
                                'blur.jPopBox': $.proxy(this.hideDelayed, this)
                            });
                            break;
                    }
                }
            },
            toggle:function(){
                var active=this.$tip.data('active');
                if(!active)
                    this.showDelayed();
                else
                    this.hideDelayed();
            },
            mouseenter: function(e) {
                if (this.disabled)
                    return true;
                this.updateCursorPos(e);
                this.$elm.attr('title', '');
                if (this.opts.trigger == 'focus')
                    return true;
                this.showDelayed();
            },
            mouseleave: function(e) {
                if (this.disabled || this.asyncAnimating && (this.$tip[0] === e.relatedTarget || jQuery.contains(this.$tip[0], e.relatedTarget)))
                    return true;
                if (this.opts.trigger == 'focus')
                    return true;
                this.hideDelayed();
            },
            mousemove: function(e) {
                if (this.disabled)
                    return true;
                this.updateCursorPos(e);
                if (this.opts.isFollowCursor && this.$tip.data('active')) {
                    this.calcPos();
                    this.$tip.css({left: this.pos.l, top: this.pos.t});
                }
            },
            show: function() {
                this.$elm.trigger($.Event('show.jPopBox'));
                if (this.disabled || this.$tip.data('active'))
                    return;
                this.reset();
                this.update();
                if (!this.content)
                    return;
                this.display();
                this.$elm.trigger($.Event('shown.jPopBox'));
            },
            showDelayed: function(timeout) {
                this.clearTimeouts();
                this.showTimeout = setTimeout($.proxy(this.show, this), typeof timeout == 'number' ? timeout:this.opts.delay.show);
            },
            hide: function() {
                this.$elm.trigger($.Event('hide.jPopBox'));
                if (this.disabled || !this.$tip.data('active'))
                    return;
                this.display(true);
                this.$elm.trigger($.Event('hidden.jPopBox'));
            },
            hideDelayed: function(timeout) {
                this.clearTimeouts();
                this.hideTimeout = setTimeout($.proxy(this.hide, this),typeof timeout == 'number' ? timeout :this.opts.delay.hide);
            },
            reset: function() {
                this.$tip.queue([]).detach().css('visibility', 'hidden').data('active', false);
                this.$inner.find('*').jPopBox('hide');
                this.$arrow.length && (this.$arrow[0].className = 'JPopBox-tip-arrow JPopBox-tip-arrow-top JPopBox-tip-arrow-right JPopBox-tip-arrow-bottom JPopBox-tip-arrow-left');
                this.asyncAnimating = false;
            },
            update: function(content, dontOverwriteOption) {
                if (this.disabled)
                    return;

                var async = content !== undefined;
                if (async) {
                    if (!dontOverwriteOption)
                        this.opts.content = content;
                    if (!this.$tip.data('active'))
                        return;
                } else {
                    content = this.opts.content;
                }

                // update content only if it has been changed since last time
                var self = this,
                    newContent = typeof content == 'function' ?
                        content.call(this.$elm[0], function(newContent) {
                            self.update(newContent);
                        }) : content;
                if (this.content !== newContent) {
                    this.$inner.empty().append(newContent);
                    this.content = newContent;
                }
                this.refresh(async);
            },
            refresh: function(async) {
                if (this.disabled)
                    return;
                if (async) {
                    if (!this.$tip.data('active'))
                        return;
                }
                this.$tip.css({left: 0, top: 0}).appendTo(document.body);
                if (this.opacity === undefined)
                    this.opacity = this.$tip.css('opacity');
                this.calcPos();
                this.$tip.css({left: this.pos.l, top: this.pos.t});
            },
            display: function(hide) {
                var active = this.$tip.data('active');
                if (active && !hide || !active && hide)
                    return;

                this.$tip.stop();
                var from = {}, to = {};
                from.opacity = hide ? this.$tip.css('opacity') : 0;
                to.opacity = hide ? 0 : this.opacity;
                this.$tip.css(from).animate(to, 300);

                hide ? this.$tip.queue($.proxy(this.reset, this)) : this.$tip.css('visibility', 'inherit');
                this.$tip.data('active', !active);
            },
            disable: function() {
                this.reset();
                this.disabled = true;
            },
            enable: function() {
                this.disabled = false;
            },
            destroy: function() {
                this.reset();
                this.$tip.remove();
                delete this.$tip;
                this.content = null;
                this.$elm.off('.jPopBox').removeData('jPopBox');
                tips.splice($.inArray(this, tips), 1);
            },
            clearTimeouts: function() {
                if (this.showTimeout) {
                    clearTimeout(this.showTimeout);
                    this.showTimeout = 0;
                }
                if (this.hideTimeout) {
                    clearTimeout(this.hideTimeout);
                    this.hideTimeout = 0;
                }
            },
            updateCursorPos: function(e) {
                this.eventX = e.pageX;
                this.eventY = e.pageY;
            },
            calcPos: function() {
                this.tipOuterW = this.$tip.outerWidth();
                this.tipOuterH = this.$tip.outerHeight();
                var pos = {l: 0, t: 0, arrow: ''},
                    $win = $(window),
                    win = {
                        l: $win.scrollLeft(),
                        t: $win.scrollTop(),
                        w: $win.width(),
                        h: $win.height()
                    }, xL, xC, xR, yT, yC, yB,arrowOuterWH,placement,isAuto=false;
                var elmOffset = this.$elm.offset(),
                    elm = {
                        l: elmOffset.left,
                        t: elmOffset.top,
                        w: this.$elm.outerWidth(),
                        h: this.$elm.outerHeight()
                    };
                xL = elm.l;	        // left
                xC = xL + Math.floor(elm.w / 2);    // h center
                xR = xL + elm.w;    // right
                yT = elm.t;	        // top
                yC = yT + Math.floor(elm.h / 2);    // v center
                yB = yT +elm.h;	    // bottom
                placement=this.opts.placement;
                var autoReg=/\s?auto?\s?/i;
                isAuto=autoReg.test(placement);
                if (isAuto) placement = placement.replace(autoReg, '') || 'top';
                //calc left position
                switch (placement) {
                    case "top":
                    case "bottom":
                        pos.l = xC - Math.floor(this.tipOuterW / 2)-this.opts.offset.X;
                        {
                            if (pos.l + this.tipOuterW > win.l + win.w)
                                pos.l = win.l + win.w - this.tipOuterW;
                            else if (pos.l < win.l)
                                pos.l = win.l;
                        }
                        break;
                    case "right":
                        arrowOuterWH=this.setArrowAndGetWH(placement);
                        pos.l = xR + this.opts.offset.X+arrowOuterWH.W;
                        if (isAuto && pos.l + this.tipOuterW > win.l + win.w){
                            arrowOuterWH=this.setArrowAndGetWH("left");
                            pos.l =xL - this.tipOuterW - this.opts.offset.X-arrowOuterWH.W;
                        }
                        break;
                    case "left":
                        arrowOuterWH=this.setArrowAndGetWH(placement);
                        pos.l = xL - this.tipOuterW- this.opts.offset.X-arrowOuterWH.W;
                        if (isAuto && pos.l < win.l){
                            arrowOuterWH=this.setArrowAndGetWH("right");
                            pos.l =xR + this.opts.offset.X+arrowOuterWH.W;
                        }
                        break;
                }
                //calc top position
                switch (placement) {
                    case "top":
                        arrowOuterWH=this.setArrowAndGetWH(placement);
                        pos.t = yT - this.tipOuterH - this.opts.offset.Y-arrowOuterWH.H;
                        if (isAuto && pos.t < win.t) {
                            arrowOuterWH=this.setArrowAndGetWH("bottom");
                            pos.t = yB + this.opts.offset.Y+arrowOuterWH.H;
                        }
                        break;
                    case "bottom":
                        arrowOuterWH=this.setArrowAndGetWH(placement);
                        pos.t = yB+ this.opts.offset.Y +arrowOuterWH.H;
                        if (isAuto && pos.t + this.tipOuterH > win.t + win.h) {
                            arrowOuterWH=this.setArrowAndGetWH("top");
                            pos.t = yT - this.tipOuterH - this.opts.offset.Y-arrowOuterWH.H;
                        }
                        break;
                    case "right":
                    case "left":
                        pos.t = yC - Math.floor(this.tipOuterH / 2)-this.opts.offset.Y;
                        {
                            if (pos.t + this.tipOuterH > win.t + win.h){
                                pos.t = win.t + win.h - this.tipOuterH;
                            }
                            else if (pos.t < win.t)
                                pos.t = win.t;
                        }
                        break;
                }
                this.pos = pos;
            },
            setArrowAndGetWH:function(placement){
                var arrowOuteWH={};
                var W=0,H=0;
                if(this.$arrow.length){
                    this.$arrow.attr("class", "JPopBox-tip-arrow JPopBox-tip-arrow-" + placement);
                    W = this.$arrow.outerWidth();
                    H = this.$arrow.outerHeight();
                }
                arrowOuteWH.W=W;
                arrowOuteWH.H=H;
                return arrowOuteWH;
            }
        };
        $.fn.jPopBox = function(options) {
            if (typeof options == 'string') {
                var args = arguments,
                    method = options;
                Array.prototype.shift.call(args);
                if (method == 'destroy') {
                    this.die ?
                        this.die('mouseenter.jPopBox').die('focus.jPopBox') :
                        $(document).undelegate(this.selector, 'mouseenter.jPopBox').undelegate(this.selector, 'focus.jPopBox');
                }
                return this.each(function() {
                    var jPopBox = $(this).data('jPopBox');
                    if (jPopBox && jPopBox[method])
                        jPopBox[method].apply(jPopBox, args);
                });
            }

            var opts = $.extend({}, $.fn.jPopBox.defaults, options);
            if (!$('#jPopBox-css-' + opts.className)[0])
                $(['<style id="jPopBox-css-',opts.className,'" type="text/css">',
                    'div.',opts.className,'{visibility:hidden;position:absolute;top:0;left:0;}',
                    'div.',opts.className,' div.JPopBox-tip-arrow{visibility:hidden;position:absolute;font:1px/1px sans-serif;}',
                    '</style>'].join('')).appendTo('head');

            return this.each(function() {
                new $.JPopBox(this, opts);
            });
        };

        // default settings
        $.fn.jPopBox.defaults = {
            title:'',                   // 标题
            content:'',	                // 弹出框内容 ('string', element, function(updateCallback){...})
            className:'JPopBox-tip-white',	    // class名称
            placement:'top',            // 如何定位弹出框 (top|bottom|left|right|auto)。当指定为 auto 时,会动态调整弹出框。例如,如果 placement 是 "auto left",弹出框将会尽可能显示在左边,在情况不允许的情况下它才会显示在右边
            delay:100,                  // 延迟显示和隐藏弹出框的毫秒数,对 trigger:none 手动触发类型不适用。如果提供的是一个数字,那么延迟将会应用于显示和隐藏。如果提供的是一个对象{ show: 500, hide: 100 },那么延迟将会分别应用于显示和隐藏
            trigger:'hover',	        // 如何触发弹出框 ('click',hover', 'focus', 'none'),none为手动触发
            offset:0,                   // 方向偏移量,值为负数时,将会反向偏移。如果提供的是一个数字,那么偏移量将会应用于X轴和Y轴。如果提供的是一个对象{ X:200, Y: 100 },那么偏移量将会分别应用于X轴和Y轴
            isShowArrow:true,           // 是否显示指向箭头
            isTipHover:true             // 是否允许在弹出框上移动,而不自动隐藏。只对trigger:hover有效。
        };
    })(jQuery);


    /**
     * 借鉴 网页限制解除(改)
     * 原作者 qxin i
     * 开源地址 https://greasyfork.org/zh-CN/scripts/28497-%E7%BD%91%E9%A1%B5%E9%99%90%E5%88%B6%E8%A7%A3%E9%99%A4-%E6%94%B9/code
     */

    var settingData = {
        "status": 1,
        "version": 0.1,
        "message": "借鉴 网页限制解除(改)",
        "positionTop": "0",
        "positionLeft": "0",
        "positionRight": "auto",
        "addBtn": true,
        "connectToTheServer": false,
        "waitUpload": [],
        "currentURL": "null",
        "shortcut": 3,
        // 域名规则列表
        "rules": {
            "rule_def": {
                "name": "default",
                "hook_eventNames": "contextmenu|select|selectstart|copy|cut|dragstart|mousemove|beforeunload",
                "unhook_eventNames": "mousedown|mouseup|keydown|keyup",
                "dom0": true,
                "hook_addEventListener": true,
                "hook_preventDefault": true,
                "hook_set_returnValue": true,
                "add_css": true
            },
            "rule_plus": {
                "name": "default",
                "hook_eventNames": "contextmenu|select|selectstart|copy|cut|dragstart|mousedown|mouseup|mousemove|beforeunload",
                "unhook_eventNames": "keydown|keyup",
                "dom0": true,
                "hook_addEventListener": true,
                "hook_preventDefault": true,
                "hook_set_returnValue": true,
                "add_css": true
            },
            "rule_zhihu": {
                "name": "default",
                "hook_eventNames": "contextmenu|select|selectstart|copy|cut|dragstart|mousemove",
                "unhook_eventNames": "keydown|keyup",
                "dom0": true,
                "hook_addEventListener": true,
                "hook_preventDefault": true,
                "hook_set_returnValue": true,
                "add_css": true
            }
        },
        "data": [
            "b.faloo.com",
            "bbs.coocaa.com",
            "book.hjsm.tom.com",
            "book.zhulang.com",
            "book.zongheng.com",
            "chokstick.com",
            "chuangshi.qq.com",
            "city.udn.com",
            "cutelisa55.pixnet.net",
            "huayu.baidu.com",
            "imac.hk",
            "life.tw",
            "luxmuscles.com",
            "news.missevan.com",
            "read.qidian.com",
            "www.15yan.com",
            "www.17k.com",
            "www.18183.com",
            "www.360doc.com",
            "www.coco01.net",
            "www.eyu.com",
            "www.hongshu.com",
            "www.hongxiu.com",
            "www.imooc.com",
            "www.jjwxc.net",
            "www.readnovel.com",
            "www.tadu.com",
            "www.xxsy.net",
            "www.z3z4.com",
            "www.zhihu.com",
            "yuedu.163.com",
            "www.ppkao.com",
            "movie.douban.com",
            "www.ruiwen.com",
            "vipreader.qidian.com",
            "www.pigai.org",
            "www.shangc.net",
            "www.myhtlmebook.com",
            "www.yuque.com",
            "www.longmabookcn.com",
            "www.alphapolis.co.jp",
            "www.sdifen.com",
            "votetw.com",
            "boke112.com",
            "www.myhtebooks.com",
            "www.xiegw.cn",
            "chuangshi.qq.com",
            "www.uta-net.com",
            "www.bimiacg.net"
        ]
    };

    var rwl_userData = null;
    var hostname = window.location.hostname;
    var btn_node = null;
    var rule = null;
    var list = null;
    var hasFrame = false;

    // 储存名称
    var storageName = "StorageName";
    // 要处理的 event 列表
    var hook_eventNames, unhook_eventNames, eventNames;
    // 储存被 Hook 的函数
    var EventTarget_addEventListener = EventTarget.prototype.addEventListener;
    var document_addEventListener = document.addEventListener;
    var Event_preventDefault = Event.prototype.preventDefault;

    // 查看本地是否存在旧数据
    rwl_userData = GM_getValue("rwl_userData");
    if (!rwl_userData) {
        rwl_userData = settingData;
        // GM_setValue("rwl_userData",rwl_userData);
    }
    // 自动更新数据
    for (let value in settingData) {
        if (!rwl_userData.hasOwnProperty(value)) {
            rwl_userData[value] = settingData[value];
            GM_setValue("rwl_userData", rwl_userData);
        }
    }

    version_up_3_to_4();

    // 获取黑名单网站
    list = get_black_list();

    // 添加按钮
    // if(rwl_userData.addBtn){
    // addBtn();  // 添加
    btn_node = document.getElementById("black_node");

    setTimeout(function () {
        qxinStart();
    }, 500);

    // }

    // GM_registerMenuCommand("复制限制解除 设置", setMenu)
    var userSetting = GM_getValue("rwl_userData");

    // // ------------------------------函数 func

    function qxinStart() {
        // addDragEven();
        // setBtnClick();

        // 检查是否在黑名单中
        if (check_black_list(list)) {
            try {
                if (rwl_userData.addBtn) {
                    btn_node.checked = true;
                }
            } catch (e) {
            } finally {
                init();
            }
        }
    }

    // 初始化 init func  这里才是核心
    function init() {
        // 针对个别网站采取不同的策略
        rule = clear();
        // 设置 event 列表
        hook_eventNames = rule.hook_eventNames.split("|");
        // TODO Allowed to return value
        unhook_eventNames = rule.unhook_eventNames.split("|");
        eventNames = hook_eventNames.concat(unhook_eventNames);

        // 调用清理 DOM0 event 方法的循环
        if (rule.dom0) {
            setInterval(clearLoop, 10 * 1000);
            setTimeout(clearLoop, 1500);
            window.addEventListener('load', clearLoop, true);
            clearLoop();
        }

        // hook addEventListener //导致搜索跳转失效的原因
        if (rule.hook_addEventListener) {
            EventTarget.prototype.addEventListener = addEventListener;
            document.addEventListener = addEventListener;

            if (hasFrame) {
                for (let i = 0; i < hasFrame.length; i++) {
                    hasFrame[i].contentWindow.document.addEventListener = addEventListener;
                }
            }

        }

        // hook preventDefault
        if (rule.hook_preventDefault) {
            Event.prototype.preventDefault = function () {
                if (hook_eventNames.indexOf(this.type) < 0) {
                    Event_preventDefault.apply(this, arguments);
                }
            };

            if (hasFrame) {
                for (let i = 0; i < hasFrame.length; i++) {
                    hasFrame[i].contentWindow.Event.prototype.preventDefault = function () {
                        if (hook_eventNames.indexOf(this.type) < 0) {
                            Event_preventDefault.apply(this, arguments);
                        }
                    };
                }
            }
        }

        // Hook set returnValue
        if (rule.hook_set_returnValue) {
            Event.prototype.__defineSetter__('returnValue', function () {
                if (this.returnValue !== true && hook_eventNames.indexOf(this.type) >= 0) {
                    this.returnValue = true;
                }
            });
        }

        // 添加CSS     // console.debug('url: ' + url, 'storageName:' + storageName, 'rule: ' + rule.name);
        if (rule.add_css) {
            GM_addStyle('html, :not([class*="rwl-exempt"]) {-webkit-user-select:text!important; -moz-user-select:text!important;} :not([class*="rwl-exempt"]) ::selection {color:#fff; background:#3390FF!important;}');
        } //else {
        //GM_addStyle('html, :not([class*="rwl-exempt"]) {-webkit-user-select:text!important; -moz-user-select:text!important;}');
        //}
    }

    // Hook addEventListener proc
    function addEventListener(type, func, useCapture) {
        var _addEventListener = this === document ? document_addEventListener : EventTarget_addEventListener;
        if (hook_eventNames.indexOf(type) >= 0) {
            _addEventListener.apply(this, [type, returnTrue, useCapture]);
        } else if (unhook_eventNames.indexOf(type) >= 0) {
            var funcsName = storageName + type + (useCapture ? 't' : 'f');

            if (this[funcsName] === undefined) {
                this[funcsName] = [];
                _addEventListener.apply(this, [type, useCapture ? unhook_t : unhook_f, useCapture]);
            }

            this[funcsName].push(func);
        } else {
            _addEventListener.apply(this, arguments);
        }
    }

    // 清理循环
    function clearLoop() {
        rule = clear(); // 对于动态生成的节点,随时检测
        var elements = getElements();

        for (var i in elements) {
            for (var j in eventNames) {
                var name = 'on' + eventNames[j];

                // ;?未解决
                // 2018-04-02 elements中会有字符串出现,原版不会,问题不明,根本原因尚未解决
                // 相关反馈  https://greasyfork.org/zh-CN/forum/discussion/36014
                // 问题版本号  v3.0.7
                // 问题补充   之前可以使用,具体版本未测(2018-04-02 21:27:53),原版可以使用
                if (Object.prototype.toString.call(elements[i]) == "[object String]") {
                    continue;
                }

                // console.log(elements[i])
                // if(typeof elements[i][name] === "object"){
                //     console.log(typeof elements[i][name])
                // }
                if (elements[i][name] !== null && elements[i][name] !== onxxx) {
                    if (unhook_eventNames.indexOf(eventNames[j]) >= 0) {
                        elements[i][storageName + name] = elements[i][name];
                        elements[i][name] = onxxx;
                    } else {
                        elements[i][name] = null;
                    }
                }
            }
        }

        document.onmousedown = function () {
            return true;
        };
    }

    // 返回true的函数
    function returnTrue(e) {
        return true;
    }

    function unhook_t(e) {
        return unhook(e, this, storageName + e.type + 't');
    }

    function unhook_f(e) {
        return unhook(e, this, storageName + e.type + 'f');
    }

    function unhook(e, self, funcsName) {
        var list = self[funcsName];
        for (var i in list) {
            list[i](e);
        }

        e.returnValue = true;
        return true;
    }

    function onxxx(e) {
        var name = storageName + 'on' + e.type;
        this[name](e);

        e.returnValue = true;
        return true;
    }

    // 获取所有元素 包括document
    function getElements() {
        var elements = Array.prototype.slice.call(document.getElementsByTagName('*'));
        elements.push(document);

        // 循环所有 frame 窗口
        var frames = document.querySelectorAll("frame");
        if (frames) {
            hasFrame = frames;
            var frames_element;
            for (let i = 0; i < frames.length; i++) {
                frames_element = Array.prototype.slice.call(frames[i].contentWindow.document.querySelectorAll("*"));
                elements.push(frames[i].contentWindow.document);
                elements = elements.concat(frames_element);
            }
        }
        return elements;
    }
    // 获取黑名单网站 Func
    function get_black_list() {
        // 之前版本可能导致存储空的字符串
        // 2018-06-11 15:11:44 保留,当容错处理
        var data_temp = rwl_userData.data;
        data_temp = data_temp.filter(function (item) {
            return item.length > 1;
        });
        return data_temp;
    }

    // 检查是否存在于黑名单中 返回位置 func
    function check_black_list(list, host) {
        for (let i = 0; i < list.length; i++) {
            if (~hostname.indexOf(list[i])) {
                return i + 1;  //万一匹配到第一个,返回0
            }
        }
        return false;
    }

    // 数组去重
    function unique(arr) {
        var ret = [];
        for (var i = 0; i < arr.length; i++) {
            var item = arr[i];
            if (ret.indexOf(item) === -1) {
                ret.push(item);
            }
        }
        return ret;
    }

    // 复制到剪贴板
    function setClipboard() {
        var text_obj = window.getSelection();
        var text = text_obj.toString();
        GM_setClipboard(text);

    }

    // 快捷键 F1(ctrl+f1) 复制
    function hotkey() {
        var a = window.event.keyCode;
        // if ((a == 112) && (event.ctrlKey)) {
        if (a == 112 && userSetting.shortcut == 1) {
            event.preventDefault();
            setClipboard();
            event.keyCode = 0;
            event.returnValue = false;
            return false;
        } else if (a == 112 && (event.ctrlKey) && userSetting.shortcut == 2) {
            setClipboard();
        } else if ((a == 67) && (event.ctrlKey) && userSetting.shortcut == 3) {
            setClipboard();
        } else {
            console.log("关闭了快捷键");
        }
    }

    document.onkeydown = hotkey; //当onkeydown 事件发生时调用hotkey函数

    // 部分网站采用了其他的防复制手段
    function clear() {
        // console.log("进入clear",hostname,rwl_userData.rules);
        switch (hostname) {
            case "chuangshi.qq.com":
                clear_chuangshi();
                break;
            case "votetw.com":
                clear_votetw();
                break;
            case "www.myhtebooks.com":
                clear_covers(".fullimg");
                break;
            case "www.z3z4.com":
                clear_covers(".moviedownaddiv");
                break;
            case "huayu.baidu.com":
                clear_covers("#jqContextMenu");
                break;
            case "www.myhtlmebook.com":
                clear_covers("img.fullimg");
                break;
            case "zhihu.com":
            case "www.zhihu.com":
                return rwl_userData.rules.rule_zhihu;
            case "t.bilibili.com":
                clear_link_bilibili();
                break;
            case "www.uslsoftware.com":
                clear_covers(".protect_contents-overlay");
                clear_covers(".protect_alert");
                return rwl_userData.rules.rule_plus;
            case "www.longmabookcn.com":
                clear_covers(".fullimg");
                return rwl_userData.rules.rule_plus;
            case "boke112.com":
                return rwl_userData.rules.rule_plus;
            case "www.shangc.net":
                return rwl_userData.rules.rule_plus;
        }
        return rwl_userData.rules.rule_def;
    }

    // 去除覆盖层
    function clear_covers(ele) {
        var odiv = document.querySelector(ele);
        if (odiv) {
            odiv.parentNode.removeChild(odiv);
        }
    }

    // b站将文字嵌套在链接中
    function clear_link_bilibili() {
        var odiv = document.querySelector(".description");
        if (odiv) {
            var tDiv = odiv.querySelector(".content-ellipsis");
            odiv.querySelector("a");
            odiv.appendChild(tDiv);
        }
    }

    // https://votetw.com/wiki/%E6%9E%97%E6%99%BA%E5%A0%85
    // 会创建多个无id,无class的div,覆盖在文字上层
    function clear_votetw() {
        var odivs = document.querySelectorAll(".mw-parser-output>div");
        odivs.forEach(function (value) {
            value.setAttribute("style", "");
        });
    }

    // 创世中文网
    function clear_chuangshi() {
        console.log("创世中文网 开始执行");
    }

    // 3.x.x 过渡 4.x.x 版本
    function version_up_3_to_4() {
        var old_version = GM_getValue("black_list");
        if (!old_version) {
            return
        }
        rwl_userData.data = unique(rwl_userData.data.concat(old_version.data));
        GM_setValue("rwl_userData", rwl_userData);

        GM_deleteValue("black_list");
        GM_deleteValue("rwl_userdata");
    }

    /**
     * 原作者 [email protected]
     * 开源地址 https://scriptcat.org/script-show-page/432/code
     * 特别感谢 wyn大佬 提供的 字典匹配表
     */

    function removeF() {
        // 判断是否存在加密字体
        var $tip = $('style:contains(font-cxsecret)');
        if (!$tip.length) return;

    // 解析font-cxsecret字体
        var font = $tip.text().match(/base64,([\w\W]+?)'/)[1];
        font = Typr.parse(base64ToUint8Array(font))[0];

    // 匹配解密字体
        var table = JSON.parse(GM_getResourceText('Table'));
        var match = {};
        for (var i = 19968; i < 40870; i++) { // 中文[19968, 40869]
            $tip = Typr.U.codeToGlyph(font, i);
            if (!$tip) continue;
            $tip = Typr.U.glyphToPath(font, $tip);
            $tip = MD5(JSON.stringify($tip)).slice(24); // 8位即可区分
            match[i] = table[$tip];
        }

    // 替换加密字体
        $('.font-cxsecret').html(function (index, html) {
            $.each(match, function (key, value) {
                key = String.fromCharCode(key);
                key = new RegExp(key, 'g');
                value = String.fromCharCode(value);
                html = html.replace(key, value);
            });
            return html;
        }).removeClass('font-cxsecret'); // 移除字体加密

        function base64ToUint8Array(base64) {
            var data = window.atob(base64);
            var buffer = new Uint8Array(data.length);
            for (var i = 0; i < data.length; ++i) {
                buffer[i] = data.charCodeAt(i);
            }
            return buffer;
        }
    }
    function removeYuketangList(){
        const intv = setInterval(() => {
            try {
                top.document.querySelector('.exam').__vue__.handleHangUpTip = function () {
                };
                const querySelector = top.document.querySelector;
                top.document.querySelector = function (...args) {
                    if (args[0] === '#hcSearcheModal') return false
                    return querySelector.call(this, ...args)
                };
                clearInterval(intv);
            } catch (e) {
            }
        }, 100);
    }


    function start() {
        try {removeYuketangList();}catch (e){}
        setTimeout(function () {
            try {removeF();} catch (e) {}
            try {init();} catch (e) {}


        }, 1000);
    }

    function getDefaultConfig() {
        const defaultConfig = {
            auto_search: false,//自动搜索
            auto_close: true,//自动关闭
            remove_limit: true,//解除限制
            fixed_modal: true,//基于浏览器布局
            custom_style_on: true,
            in_setting: false,//是否在设置页面
            custom_style: "",
            out_iframe: true,
            model:{
                select:"答题",
                "答题":`我想让你扮演一名解题者,我将会对你发起提问,你的工作是给出具体的答案并说明理由。我的问题是“{msg}”`,
                "翻译":`下面我让你来充当翻译家,你的目标是把任何语言翻译成中文,请翻译时不要带翻译腔,而是要翻译得自然、流畅和地道,使用优美和高雅的表达方式。请翻译下面这句话:“{msg}”`,
                "自定义":`{msg}`,
            }
        };
        //去查找接口设置 默认
        if (GM_getValue("defaultConfig") === undefined) {
            GM_setValue("defaultConfig", JSON.stringify(defaultConfig));
        }
        return JSON.parse(GM_getValue("defaultConfig"))
    }

    let options = getDefaultConfig();

    function getToken() {
        if (typeof GM_getValue("token") === 'string') {
            return GM_getValue("token")
        } else {
            return ''
        }
    }


    window.addEventListener("message", function (event) {
        if (event.data.type === 'search') {
            addModal2(createFrameLoading(), false);
            searchWord(event.data.wd).then(res => {
                addModal2(res, false, false);
            });
        } else {
            if (event.data.type === 'auto_close') {
                options.auto_close = event.data.auto_close;
                GM_setValue("defaultConfig", JSON.stringify(options));
            } else if (event.data.type === 'auto_search') {
                options.auto_search = event.data.auto_search;
                GM_setValue("defaultConfig", JSON.stringify(options));
            } else if (event.data.type === 'remove_limit') {
                let copy = Object.assign(options);
                copy.remove_limit = event.data.remove_limit;
                GM_setValue("defaultConfig", JSON.stringify(copy));
            } else if (event.data.type === 'fixed_modal') {
                options.fixed_modal = event.data.fixed_modal;
                GM_setValue("defaultConfig", JSON.stringify(options));
            } else if (event.data.type === 'out_iframe') {
                options.out_iframe = event.data.out_iframe;
                GM_setValue("defaultConfig", JSON.stringify(options));
            } else if (event.data.type === 'select_msg_model') {
                options.model.select = event.data.select_msg_model;
                GM_setValue("defaultConfig", JSON.stringify(options));
            } else if (event.data.type === 'update_msg_model') {
                options.model[event.data.select_msg_model] = event.data.update_msg_model;
                GM_setValue("defaultConfig", JSON.stringify(options));
            } else if (event.data.type === 'login') {

            } else if (event.data.type === 'captcha') {

            } else if (event.data.type === 'checkVersion') {
                GM_setValue("version", JSON.stringify(event.data.version));
            }
        }
    }, false);


    let POPOVER_ID = 'hcSearchePopover';
    let MODAL_ID = 'hcSearcheModal';


    let mouseX = 0;
    let mouseY = 0;

    let _self = unsafeWindow, top$1 = _self, UE = _self.UE;

    var SearchPanel = {
        getOptions: function () {
            return options
        },
        show: function (word) {
            options.in_setting = false;
            addModal2(createFrameLoading(), options.auto_close === true);
            searchWord(word).then(res => {

            });
        },
        showWordSearch() {
            options.auto_close = false;
            GM_setValue("defaultConfig", JSON.stringify(options));
            // addModal2("https://c.met0.top/", false, false);
            searchWord("").then(res => {
                addModal2(res, false, false);
            });
        },
        setting: function () {
            options.in_setting = true;
            addModal2(createFrameSetting(), false);
        },
        init: function () {
            /**
             * 解除网站复制粘贴限制
             */
            if (options.remove_limit) relieveLimit();

            //页面始终保持再最外层document
            top$1 = options.out_iframe ? searchOutDocument(_self, top$1) : top$1;

            top$1.document.addEventListener('mouseup', mouseUp);

            top$1.document.addEventListener('mousemove', function (e) {
                mouseX = e.clientX;
                mouseY = e.clientY;
            });
        }
    };

    // 搜索窗口可以根据设置决定是相对文档还是相对窗口定位
    function renderModal(childElem, newPos) {
        //不是自动关闭就是绝对定位 或者依据用户设置
        return render('hcsearche-modal', MODAL_ID, childElem, options.fixed_modal, newPos);
    }


    // 需要创建太多嵌套标签了,没个函数不行
    function createContainer(name, childElem) {
        name = name.toLowerCase();
        let elem = top$1.document.createElement(name);
        elem.style.display = 'block';
        // id 改成驼峰式
        elem.id = name.replace('hcsearche', 'hcSearche').replace(/\-[a-z]/g, function (w) {
            return w.replace('-', '').toUpperCase();
        });
        if (childElem) {
            if (Array.isArray(childElem) === false)
                childElem = [childElem];
            for (let i = 0; i < childElem.length; i++)
                elem.appendChild(childElem[i]);
        }
        return elem;
    }

    /**
     * isFixed 是否相对浏览器可视区域定位
     * newPos 是否更新定位(如果元素已经存在的话
     */
    function render(tagName, elemId, childElem, isFixed, newPos) {
        console.log('开始渲染 model', isFixed);
        let doc = top$1.document;
        let elem = doc.getElementById(elemId);
        if (elem) {
            elem.innerHTML = '';
        } else {
            elem = doc.createElement(tagName);
            elem.id = elemId;
            doc.body.appendChild(elem);
        }
        let contentNode = createContainer(tagName + '-container', childElem);
        elem.appendChild(contentNode);
        // class ID same
        elem.classList.add(elemId);
        let X = false;
        let Y = false;
        if (!newPos) {
            X = elem.style.left.replace('px', '');
            console.log(X, "X");
            Y = elem.style.top.replace('px', '');
        }
        if (!X) {
            let pos = getXY(elem.offsetWidth, elem.offsetHeight);
            X = pos.X;
            Y = pos.Y;
            // 相对文档定位时需要将文档滚动距离加上
            if (!isFixed) {
                Y += window.pageYOffset;
            }
        }

        elem.style.position = isFixed ? 'fixed' : 'absolute';
        elem.style.left = X + 'px';
        elem.style.top = Y + 'px';
        setTimeout(function () {
            elem.classList.add(elemId + '-show');
        }, 10);
        return elem;
    }

    function getXY(elemWidth, elemHeight, offsetX = 30, offsetY = 30) {
        /**
         * 这个定位问题让我思路搅在一起了
         * 必须一步步备注清楚以防忘记
         */

        /**
         * 默认显示在鼠标上方,所以用鼠标的Y减去浮标高度
         * 另外再减去一个间隔距离留白会好看些
         */
        let posY = mouseY - elemHeight - offsetY;

        /**
         * 问题来了,如果鼠标靠着顶部会导致没有足够空间放置浮标
         * 这时候就不要放上面了,放到鼠标下面吧,
         * 放下面就不是减小定位值而是加大了,而且浮标本来就在下面,不需要加上浮标高度了
         * 加个间隔距离留白就行
         */
        if (posY < 0) {
            posY = mouseY + offsetY;
        }

        /**
         * 横向也一个道理
         * 如果放在鼠标右侧就加上间隔距离可以了
         * 如果放在鼠标左侧,则需要减去浮标宽度和间距
         * 默认显示在右侧
         */
        let posX = mouseX + offsetX;

        /**
         * 如果坐标加上浮标宽度超过窗口宽度那就是超出了
         * 那么,放到左边吧
         */

        if (posX + elemWidth > window.innerWidth) {
            posX = mouseX - elemWidth - offsetX;
        }

        /**
         * 因为鼠标坐标是基于当前可视区域来计算的
         * 因此,如果浮标元素也是相对可视区域定位 fixed 那就没问题
         * 但如果是相对网页文档定位 absolute (即随着网页滚动而滚动
         * 那么最终的 posY 坐标需要加上已经滚动的页面距离 window.pageYOffset
         */
        return {
            X: posX,
            Y: posY
        };
    }

    function mouseUp(e) {
        setTimeout(function () {
            mouseUpCallback(e);
        }, 1);
    }


    function mouseUpCallback(e) {
        if (options.auto_close === true) {
            removeTemplate(MODAL_ID, e.target);
        }
        e = e || window.event;
        mouseX = e.clientX;
        mouseY = e.clientY;
        let txt = window.getSelection().toString().trim();
        if (txt && e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA') ; else {
            autoRemoveTemplate(e);
        }
    }
    function autoRemoveTemplate(e) {
        // console.log('autoRemoveTemplate')
        removeTemplate(POPOVER_ID, false);
        /**
         * 只有开启自动关闭才会自动移除搜索窗口
         */
        if (options.auto_close === true) {
            removeTemplate(MODAL_ID, e.target);
        }
    }

    // 临时锁定
    function lockClick() {
        // toggle options
        options.auto_close = !options.auto_close;
        // toggle class
        this.classList.toggle('hcSearcheModalLocked', options.auto_close === false);
    }


    function linkCloseClick() {
        removeTemplate(MODAL_ID);
    }

    function createFrameLoading() {
        let html = `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="initial-scale=1.0, minimum-scale=1.0, user-scalable=0, width=device-width">
    <meta name="full-screen" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-touch-fullscreen" content="yes">
    <meta name="format-detection" content="address=no">
    <meta name="format-detection" content="telephone=no">
    <title>MeTo</title>
    <style>` + GM_getResourceText('weuiCss') + `</style>
    <style type="text/css">
        body, html {
            height: 100%;
            padding: 10px;
            -webkit-tap-highlight-color: transparent;
        }
        body::-webkit-scrollbar {
            display: none;
        }
        .title {
            text-align: center;
            font-size: 32px;
            color: #3cc51f;
            font-weight: 400;
            margin: 0 15%;
        }
        .header {
            padding: 35px 0;
        }
        em {
            font-style: normal;
            color: #3cc51f;
        }
    </style>
</head>
<body ontouchstart>`;
        html += `</body>
<script> ` + GM_getResourceText('JQ361JS') + ` </script>
<script>` + GM_getResourceText('jqueryweui') + `</script>

<script type="text/javascript">
    $.showLoading("正在搜索中");
</script>
</html>`;
        return html;
    }

    function addModal2(html, newPos, footerChildNode = false,chat=false) {
        // header link
        let linksNode = createContainer('hcsearche-modal-links');
        let linkNode = top$1.document.createElement('hcsearche-link');
        linkNode.setAttribute('title', '有不懂的请点我');
        linkNode.setAttribute('data-seindex', 0);
        linkNode.setAttribute('data-seclass', 'baidu');
        linkNode.innerHTML = 'MeToGPT';
        linkNode.setAttribute('data-securrent', 'true');
        linkNode.style.color = '#586069';

        linkNode.addEventListener('click', function () {
            window.open('https://d.met0.top/');
        });

        linksNode.appendChild(linkNode);

        let settingNode = top$1.document.createElement('hcsearche-link');
        settingNode.setAttribute('title', '点击打开设置页');
        settingNode.setAttribute('data-seindex', 0);
        settingNode.setAttribute('data-seclass', 'baidu');
        settingNode.setAttribute('id', "settingNode");
        settingNode.innerHTML = options.in_setting ? '返回' : '设置';
        settingNode.setAttribute('data-securrent', 'true');
        linkNode.style.color = '#586069';
        //
        linksNode.appendChild(settingNode);

        settingNode.addEventListener('click', function () {
            options.in_setting = !options.in_setting;
            let btn = top$1.document.getElementById("settingNode").innerText;
            if (btn === '返回') {
                top$1.document.getElementById("settingNode").innerText = '设置';
                SearchPanel.showWordSearch();
            } else {
                top$1.document.getElementById("settingNode").innerText = '返回';
                addModal2(createFrameSetting(), false);
            }
        });


        // close button
        let closeLinkNode = top$1.document.createElement('hcsearche-link');
        closeLinkNode.id = 'hcSearcheClose';
        closeLinkNode.innerHTML = '&times;';
        closeLinkNode.addEventListener('click', linkCloseClick);

        linksNode.appendChild(closeLinkNode);

        // lock button
        let lockNode = createContainer('hcsearche-modal-lock');

        if (options.auto_close === false)
            lockNode.classList.add('hcSearcheModalLocked');

        lockNode.addEventListener('click', lockClick);


        // iframe
        let iframeNode
        if(chat){
            iframeNode= top$1.document.createElement('div');
            iframeNode.id = 'hcChat';

        }else{
            iframeNode = top$1.document.createElement('iframe');
            iframeNode.id = 'hcSearcheIframe';
            console.log(html.substring(0, 4))
            if(html.substring(0, 4) == "http"){
                iframeNode.src = html;
            }else{
                iframeNode.srcdoc = html;

            }
        }

        iframeNode.setAttribute('width', '100%');
        iframeNode.setAttribute('frameborder', '0');



        let headerNode = createContainer('hcsearche-modal-header', [lockNode, linksNode]);
        dragElement(headerNode);
        let bodyNode = createContainer('hcsearche-modal-body', iframeNode);

        let footerNode = createContainer('hcsearche-modal-footer', footerChildNode);
        dragElement(footerNode);
        let contentNode = createContainer('hcsearche-modal-content', [headerNode, bodyNode, footerNode]);

        let modal = renderModal(contentNode, newPos);
        // function resizeIframe() {

        //     iframeNode.style.height = iframeNode.contentDocument.body.scrollHeight +10 + 'px';
        // }
        // linksNode.onload =  resizeIframe()
        // bodyNode.setAttribute('onhashchange', resizeIframe());
        // dragElement(modal);
        return iframeNode
    }

    function dragElement(elmnt) {
        let moveX,moveY
        if (top$1.document.getElementById(elmnt.id + "-drag")) {
            // if present, the drag is where you move the DIV from:
            top$1.document.getElementById(elmnt.id + "-drag").onmousedown = dragMouseDown;
        } else {
            // otherwise, move the DIV from anywhere inside the DIV:
            elmnt.onmousedown = dragMouseDown;
        }

        function dragMouseDown(e) {
            e = e || window.event;
            e.preventDefault();
            parentNode = top$1.document.getElementById("hcSearcheModal")
            let elL =parentNode.offsetLeft
            let elT =parentNode.offsetTop
            moveX = e.clientX - elL
            moveY = e.clientY - elT
            // get the mouse cursor position at startup:

            top$1.document.onmouseup = closeDragElement;
            // call a function whenever the cursor moves:
            top$1.document.onmousemove = elementDrag;
        }

        function elementDrag(e) {
            e = e || window.event;
            e.preventDefault();
            // calculate the new cursor position:
            // set the element's new position:
            parentNode.style.left =  e.clientX -moveX + 'px'
            parentNode.style.top =  e.clientY - moveY + 'px'
        }

        function closeDragElement() {
            // stop moving when mouse button is released:
            top$1.document.onmouseup = null;
            top$1.document.onmousemove = null;
        }
    }


    // containsCheckElem 检查是否模板内元素,是就不移除
    function removeTemplate(elemId, containsCheckElem = false) {
        const temp = top$1.document.getElementById(elemId);
        if (temp && (containsCheckElem === false || temp.contains(containsCheckElem) === false)) {
            temp.classList.remove(elemId + '-show');
            setTimeout(function () {
                if (temp.classList.contains(elemId + '-show') === false && temp.parentElement) {
                    top$1.document.body.removeChild(temp);
                }
            }, 500);
        }
    }


    function createFrameSetting() {
        let html = `
 <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <style>` + GM_getResourceText('weuiCss') + `</style>
    <title></title>
</head>
<body>
<div id="app">
    <div class="weui-cells">
        <div class="weui-cells__title">AI设置</div>
        <label for="chat_msg_model" class="weui-cell weui-cell_active weui-cell_select weui-cell_select-after">
            <div class="weui-cell__hd">
                <span class="weui-label">AI模板</span>
            </div>
            <div class="weui-cell__bd">
                <select class="weui-select" name="chat_msg_model" id="chat_msg_model" >
                    <option value="答题">答题</option>
                    <option value="翻译">翻译</option>
                    <option value="自定义">自定义</option>
                    <option value="自定义1">自定义1</option>
                    <option value="自定义2">自定义2</option>
                </select>
            </div>
        </label>
        <div class="weui-cell weui-cell_active">
            <textarea id="chat_msg" class="weui-textarea" placeholder="请参照已有模版编写" rows="3">`+options.model[options.model.select]+`</textarea>
            <a role="button" class="weui-btn weui-btn_mini weui-btn_primary weui-wa-hotarea" href="javascript:" id="update">修改</a>
        </div>
        <div class="weui-cells__title">悬浮搜索图标</div>
        <label class="weui-cell weui-cell_active weui-cell_switch">
            <label class="weui-cell__bd" for="auto_search">
                划词后自动搜索
                <div class="weui-cell__desc">打开后划词自动打开搜题窗口进行搜题,否则鼠标右下角显示搜题图标</div>
            </label>
            <input type="checkbox" class="weui-switch" id="auto_search"  v-model="auto_search">
        </label>
        <div class="weui-cells__title">解除限制</div>
        <label class="weui-cell weui-cell_active weui-cell_switch">
            <label class="weui-cell__bd" for="remove_limit">
                解除网站的禁止复制限制
                <div class="weui-cell__desc">打开后可解除部分网站的禁止划词限制,如冲突(无法滑动验证框,无法选中按钮等)可关闭此功能<font color="red">(刷新页面后生效)</font></div>
            </label>
            <input type="checkbox" class="weui-switch" id="remove_limit" v-model="remove_limit">
        </label>
        <div class="weui-cells__title">搜索窗口</div>
        <label class="weui-cell weui-cell_active weui-cell_switch">
            <label class="weui-cell__bd" for="fixed_modal">
                基于浏览器窗口定位
                <div class="weui-cell__desc">打开后搜索窗口可固定在浏览器窗口特定位置,不受页面滚动影响</div>
            </label>
            <input type="checkbox" class="weui-switch" id="fixed_modal" v-model="fixed_modal">
        </label>

        <label class="weui-cell weui-cell_active weui-cell_switch">
            <label class="weui-cell__bd" for="out_iframe">
                寻找最外层iframe
                <div class="weui-cell__desc">打开后将会将搜题窗口悬浮在最外层iframe,可能某些网站<font color="red">无法正常显示搜题窗口</font>,否则将会在本iframe显示搜题窗口,若限制窗口无法移动到自定义的位置时可打开此开关</div>
            </label>
            <input type="checkbox" class="weui-switch" id="out_iframe" v-model="out_iframe">
        </label>
    </div>

</div>
</body>
<script> ` + GM_getResourceText('Vue') + `</script>
<script> ` + GM_getResourceText('JQ361JS') + ` </script>
<script>` + GM_getResourceText('jqueryweui') + `</script>
<!-- 引入组件库 -->
<script>
    let chat_obj = `+JSON.stringify(options.model)+`;
    $(document).ready(function() {
        document.getElementById("chat_msg_model").value = "`+options.model.select+`"
        $("#chat_msg_model").change(function(value) {
            window.parent.postMessage({"type": 'select_msg_model',"select_msg_model":$(this).val()}, '*');
            document.getElementById("chat_msg").value = chat_obj[$(this).val()]
            console.log(chat_obj[$(this).val()])
        });
        $("#update").click(function(value){
            console.log($("#chat_msg_model").val())
            window.parent.postMessage({"type": 'update_msg_model',"select_msg_model":$("#chat_msg_model").val() ,"update_msg_model":$("#chat_msg").val()}, '*');
        })
    });
</script>
<script>
  window.app = new Vue({
        el: '#app',
        data: ` + (GM_getValue("defaultConfig")) + `,
        watch: {
            auto_close: function(val) {
              window.parent.postMessage({"type": 'auto_close',"auto_close":val}, '*');
            },
            auto_search: function (val){
                console.log(val)
                window.parent.postMessage({"type": 'auto_search',"auto_search":val}, '*');
            },
            fixed_modal:function (val){
                window.parent.postMessage({"type": 'fixed_modal',"fixed_modal":val}, '*');
            },
            remove_limit:function (val){
                window.parent.postMessage({"type": 'remove_limit',"remove_limit":val}, '*');
            },
            out_iframe:function (val){
                window.parent.postMessage({"type": 'out_iframe',"out_iframe":val}, '*');
            }
        }
       })
</script>
</html>
`;
        return html;
    }


    /**
     * 解除限制
     */
    function relieveLimit() {

        start();
        if (location.host.indexOf('chaoxing') !== -1) {
            setTimeout(() => {
                try {
                    _self.UEDITOR_CONFIG.scaleEnabled = false;
                } catch (e) {
                }
                $.each(UE.instants, function () {
                    var key = this.key;
                    this.ready(function () {
                        this.destroy();
                        UE.getEditor(key);
                    });
                });
            }, 2000);
        }

        if ((window.location.href.includes("newMooc=true") && location.host.indexOf('chaoxing') !== -1) || location.pathname.indexOf('exam/test/reVersionPaperMarkContentNew') !== -1) {
            setTimeout(() => {
                    $("body").removeAttr("onselectstart");
                    $("html").css("user-select", "unset");
                    try {
                        UE.EventBase.prototype.fireEvent = function () {
                            return null
                        };
                    } catch (e) {

                    }

                },
                2000);
        }
    }
    async function searchWord(selectionText) {
        //addModal2(r.responseText, false, false)
        if(!selectionText){
            return `
            <!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <title>MeTo</title>
    <style>
		*{
			padding: 0;
			margin: 0;
			max-width: 100%;
		}
        #app{
            width:390px;
        }
		.text_4 {
			width: 100%;
			/*盒子宽自己设置想要的宽度*/
			height: auto;
			/*高度自动*/
			display: inline-block;
			/*转为行内块元素*/
			white-space: pre-wrap;
			/*处理元素内的空白,保留空白符序列,但是正常地进行换行*/
			word-wrap: break-word;
			/*允许长单词或 URL 地址换行到下一行,在长单词或 URL 地址内部进行换行*/
			margin: 0.81rem 0.31rem 0 0.25rem;

			color: rgb(102, 102, 102);
			font-size: 0.88rem;
			line-height: 1.25rem;
			text-align: left;
		}
		.text_5 {
			width: 100%;
			/*盒子宽自己设置想要的宽度*/
			height: auto;
			/*高度自动*/
			display: inline-block;
			/*转为行内块元素*/
			white-space: pre-wrap;
			/*处理元素内的空白,保留空白符序列,但是正常地进行换行*/
			word-wrap: break-word;
			/*允许长单词或 URL 地址换行到下一行,在长单词或 URL 地址内部进行换行*/
			margin: 0.11rem 0.31rem 0.31rem 0.25rem;

			color: rgb(102, 102, 102);
			font-size: 0.88rem;
			line-height: 1.25rem;
			text-align: left;
		}
		.text_6 {
			margin-left: 0.25rem;
		}
		.text-wrapper {
			/*盒子宽自己设置想要的宽度*/
			height: auto;
			/*高度自动*/
			display: inline-block;
			/*转为行内块元素*/
			white-space: pre-line;
			/*处理元素内的空白,保留空白符序列,但是正常地进行换行*/
			word-wrap: break-word;
			/*允许长单词或 URL 地址换行到下一行,在长单词或 URL 地址内部进行换行*/
			margin-left: 0.25rem;
			margin-right: 0.25rem;
			/* padding: 0.69rem 0 1.19rem; */
			font-size: 0.88rem;
			line-height: 1.25rem;
			background-color: rgb(245, 246, 250);
			border-radius: 0.25rem;
		}
    </style>
</head>
<body>
<div id="app">
    <div class="text-wrapper " style="padding: 1rem;">
        <div class="text_6">选中需要处理的文本,点击边上按钮即可快速提问</div>
        <div class="text_6">可进入设置中,修改预处理文本内容,更加贴合平时使用习惯</div>
    </div>
</div>
</body></html>
            `
        }
        let msg = options.model[options.model.select].replace("{msg}",selectionText)
        console.log(msg)
        let obj ={
            "messages": [
                {
                    "role": "user",
                    "content": msg,
                }
            ],
            "stream": true,
            "model": "gpt-3.5-turbo",
            "temperature": 0.5,
            "presence_penalty": 0,
            "frequency_penalty": 0,
            "top_p": 1
        };
        return new Promise(resolve => {
            GM_xmlhttpRequest({
                responseType:"stream",
                timeout: 10000,
                method: "post",
                url: "https://c.met0.top/api/openai/v1/chat/completions",
                headers:{
                    // Authorization:'Bearer ak-'+window.my.config.tk_uid+","+window.my.config.poolId,
                    Authorization:'Bearer nk-wangzeqing',
                    // Cookie:"next-auth.csrf-token=e8b5559fadb5ce3684e9a0611591684ffffc2224d9125a49e7081a92425c3026%7C47d575638e3a14f787462c27c1fe8895d740210370848182a740fa71dfb55211; next-auth.callback-url=http%3A%2F%2Flocalhost%3A3000; next-auth.session-token=eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0..wNFkEP1XItcDCpY2.nJBc4rvu8_cAGx0mtDdm2pvIjPAWGMGou24L2ZzoyImrCIqLDiAMS5w6WzN6dm_8GuI331tfqxHc_V4LRoAmmFT0A8X5ln9C1iC4p47IQM_4RF2B-8iLGElCkVOYJieCkvV1lVrFHVT31nzI12n8Xpwttrw5yGhywCR3sWZ1J7sr4QCXeCA-lpOdITDyW8AdNPjH4QQ7vhtCIzjzFoepmJKk5mE2lPmksDiGrQX3d1POPwfQqdHafb8rgZJl_BC4_wDXloIt6mtTfQ4._NPSNHQIhsWS5eQprCIeCQ",
                },
                data: JSON.stringify(obj),
                onloadstart: function(response) {
                    let aner = addModal2("欢迎\n", false, false,true);
                    // ans.append("123")
                    const reader = response.response.getReader();
                    var error_d = "";
                    function read() {
                        reader.read().then(({ done, value }) => {
                          if (done) {
                            console.log('读取完毕');
                            return;
                          }
                          let data = new TextDecoder().decode(value)

                          data.split("data:").forEach(d=>{
                            if(d!=""&&d.indexOf("[DONE]") == -1){
                                let Json_msg=null
                                try{
                                    if(error_d){
                                        d = error_d +d;
                                        error_d="";
                                    }
                                    Json_msg = $.parseJSON(d)
                                    if(Json_msg.msg=="empty access code"){
                                        aner.append("若需要使用AI功能请先<button onclick=\"window.open('https://c.met0.top/#/activate', 'Meto登陆', 'width=400,height=600');\">登陆</button>");
                                        return;
                                    }
                                    aner.append(Json_msg.choices[0].delta.content||"");
                                    // aner.scrollTop(aner.prop("scrollHeight"));
                                }catch (e){
                                    if(Json_msg){
                                        aner.append("发生异常:" + d);
                                    }else{
                                        console.log("发生异常:" + d)
                                    }
                                    error_d=d;
                                }
                            }

                          });
                        //   console.log($.parseJSON(data));
                          // 继续读取下一个数据块
                          read();
                        });
                      }

                      // 开始读取数据
                      read();
                },
                onerror : function(err){
                    console.log('error')
                },
                ontimeout : function(inf){
                    console.log('请求超时')
                }
            })

            // GM_xmlhttpRequest({
            //     method: "GET",
            //     //url: "https://app.itihey.com/pcService/api/queryAnswer?word=" + encodeURIComponent(selectionText || window.getSelection().toString().trim()),
            //     url:"https://c.met0.top/#/activate",
            //     headers: {
            //         "access-token": getToken(),
            //         "Version": GM_info.script.version
            //     },
            //     onload: function (r) {
            //         console.log(r.responseText);
            //         resolve( r.responseText);
            //     }
            // });
        })
    }

    /**
     * 字符串模板格式化
     * @param {string} formatStr - 字符串模板
     * @returns {string} 格式化后的字符串
     * @example
     * StringFormat("ab{0}c{1}ed",1,"q")  output "ab1cqed"
     */


    function StringFormat(formatStr) {
        var args = arguments;
        return formatStr.replace(/\{(\d+)\}/g, function (m, i) {
            i = parseInt(i);
            return args[i + 1];
        });
    }

    /**
     * 日期格式化
     * @param {Date} date - 日期
     * @param {string} formatStr - 格式化模板
     * @returns {string} 格式化日期后的字符串
     * @example
     * DateFormat(new Date(),"yyyy-MM-dd")  output "2020-03-23"
     * @example
     * DateFormat(new Date(),"yyyy/MM/dd hh:mm:ss")  output "2020/03/23 10:30:05"
     */
    function DateFormat(date, formatStr) {
        var o = {
            "M+": date.getMonth() + 1, //月份
            "d+": date.getDate(), //日
            "h+": date.getHours(), //小时
            "m+": date.getMinutes(), //分
            "s+": date.getSeconds(), //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(formatStr)) {
            formatStr = formatStr.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(formatStr)) {
                formatStr = formatStr.replace(
                    RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return formatStr;
    }

    /**
     * 清除dom元素默认事件
     * @param {object} e - dom元素
     */
    function ClearBubble(e) {
        if (e.stopPropagation) {
            e.stopPropagation();
        } else {
            e.cancelBubble = true;
        }
        if (e.preventDefault) {
            e.preventDefault();
        } else {
            e.returnValue = false;
        }
    }

    /**
     * 寻找最外层doc
     * @param _self
     * @param top
     * @returns {*|string|boolean|number|string|Window}
     */
    function searchOutDocument(_self, top) {
        try {
            while (top !== _self.top) {
                top = top.parent.document ? top.parent : _self.top;
                if (top.location.pathname === '/mycourse/studentstudy') break;
            }
        } catch (err) {
            top = _self;
        }
        return top;
    }

    //面板
    var Panel={
        popBoxEl:{},
        randomCode:"",
        Create:function(title,placement,isShowArrow,content,shownFn){
            var self=this;
            $(self.popBoxEl).jPopBox({
                title: title,
                className: 'JPopBox-tip-white',
                placement: placement,
                trigger: 'none',
                isTipHover: true,
                isShowArrow: isShowArrow,
                content: function(){
                    return StringFormat('<div id="panelBody{0}">{1}</div>',self.randomCode,content);
                }
            });
            $(self.popBoxEl).on("shown.jPopBox",function(){
                var $panel=$("div.JPopBox-tip-white");
                typeof shownFn === 'function' && shownFn($panel);
            });
            $(self.popBoxEl).jPopBox('show');
        },
        Update:function(Fn){
            var $panel=$("div.JPopBox-tip-white");
            Fn($panel);
        },
        Destroy:function(){
            //$(this.popBoxEl).jPopBox("hideDelayed");
            $(this.popBoxEl).jPopBox("destroy");
        },
        CreateStyle:function(){
            var s="";
            s+=StringFormat("#panelBody{0}>div input,#panelBody{0}>div select{padding: 3px; margin: 0; background: #fff; font-size: 14px; border: 1px solid #a9a9a9; color:black;width: auto;min-height: auto; }",this.randomCode);
            s+=StringFormat("#panelBody{0}>div:first-child{padding-bottom: 5px;height:30px}",this.randomCode);
            s+=StringFormat("#panelBody{0}>div:last-child hr{border: 1px inset #eeeeee;background: none;height: 0px;margin: 0px;}",this.randomCode);
            return s;
        }
    };

    // import {wonload} from "./lib/parse";
    function generateRandomString(length) {
        var result = '';
        var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        var charactersLength = characters.length;
        for (var i = 0; i < length; i++) {
            result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        return result;
    }
    // 调用函数生成长度为6-10的随机字符串
    var randomString = generateRandomString(Math.floor(Math.random() * 5) + 6);
    // console.log(randomString);
    //主程序
    var HcSearch=function(){
        var transIconBase64="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAAAXNSR0IArs4c6QAAAOZlWElmTU0AKgAAAAgABgESAAMAAAABAAEAAAEaAAUAAAABAAAAVgEbAAUAAAABAAAAXgExAAIAAAAhAAAAZgEyAAIAAAAUAAAAiIdpAAQAAAABAAAAnAAAAAAAAABIAAAAAQAAAEgAAAABQWRvYmUgUGhvdG9zaG9wIDIyLjAgKE1hY2ludG9zaCkAADIwMjM6MDg6MTQgMTc6MzY6MjYAAASQBAACAAAAFAAAANKgAQADAAAAAQABAACgAgAEAAAAAQAAACigAwAEAAAAAQAAACgAAAAAMjAyMzowODoxNCAxNzozNjoyNgAkDxyMAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKcWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iCiAgICAgICAgICAgIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIKICAgICAgICAgICAgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iCiAgICAgICAgICAgIHhtbG5zOnN0RXZ0PSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VFdmVudCMiCiAgICAgICAgICAgIHhtbG5zOnBob3Rvc2hvcD0iaHR0cDovL25zLmFkb2JlLmNvbS9waG90b3Nob3AvMS4wLyIKICAgICAgICAgICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iPgogICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3BuZzwvZGM6Zm9ybWF0PgogICAgICAgICA8eG1wOk1vZGlmeURhdGU+MjAyMy0wOC0xNFQxNzozNjoyNiswODowMDwveG1wOk1vZGlmeURhdGU+CiAgICAgICAgIDx4bXA6Q3JlYXRvclRvb2w+QWRvYmUgUGhvdG9zaG9wIDIyLjAgKE1hY2ludG9zaCk8L3htcDpDcmVhdG9yVG9vbD4KICAgICAgICAgPHhtcDpDcmVhdGVEYXRlPjIwMjMtMDgtMTRUMTc6MzY6MjYrMDg6MDA8L3htcDpDcmVhdGVEYXRlPgogICAgICAgICA8eG1wOk1ldGFkYXRhRGF0ZT4yMDIzLTA4LTE0VDE3OjM2OjI2KzA4OjAwPC94bXA6TWV0YWRhdGFEYXRlPgogICAgICAgICA8eG1wTU06SGlzdG9yeT4KICAgICAgICAgICAgPHJkZjpTZXE+CiAgICAgICAgICAgICAgIDxyZGY6bGkgcmRmOnBhcnNlVHlwZT0iUmVzb3VyY2UiPgogICAgICAgICAgICAgICAgICA8c3RFdnQ6c29mdHdhcmVBZ2VudD5BZG9iZSBQaG90b3Nob3AgMjIuMCAoTWFjaW50b3NoKTwvc3RFdnQ6c29mdHdhcmVBZ2VudD4KICAgICAgICAgICAgICAgICAgPHN0RXZ0OndoZW4+MjAyMy0wOC0xNFQxNzozNjoyNiswODowMDwvc3RFdnQ6d2hlbj4KICAgICAgICAgICAgICAgICAgPHN0RXZ0Omluc3RhbmNlSUQ+eG1wLmlpZDpkYjdkYjhkNS0wZTNjLTRiZTktYmZhZi01ZTkzNDJmOTgwYWY8L3N0RXZ0Omluc3RhbmNlSUQ+CiAgICAgICAgICAgICAgICAgIDxzdEV2dDphY3Rpb24+Y3JlYXRlZDwvc3RFdnQ6YWN0aW9uPgogICAgICAgICAgICAgICA8L3JkZjpsaT4KICAgICAgICAgICAgICAgPHJkZjpsaSByZGY6cGFyc2VUeXBlPSJSZXNvdXJjZSI+CiAgICAgICAgICAgICAgICAgIDxzdEV2dDpzb2Z0d2FyZUFnZW50PkFkb2JlIFBob3Rvc2hvcCAyMi4wIChNYWNpbnRvc2gpPC9zdEV2dDpzb2Z0d2FyZUFnZW50PgogICAgICAgICAgICAgICAgICA8c3RFdnQ6Y2hhbmdlZD4vPC9zdEV2dDpjaGFuZ2VkPgogICAgICAgICAgICAgICAgICA8c3RFdnQ6d2hlbj4yMDIzLTA4LTE0VDE3OjM2OjI2KzA4OjAwPC9zdEV2dDp3aGVuPgogICAgICAgICAgICAgICAgICA8c3RFdnQ6aW5zdGFuY2VJRD54bXAuaWlkOjFiMTU4ZjNhLWY3ZTUtNGUxNy04YzJjLTY1OGRlNGYxZWU2ZTwvc3RFdnQ6aW5zdGFuY2VJRD4KICAgICAgICAgICAgICAgICAgPHN0RXZ0OmFjdGlvbj5zYXZlZDwvc3RFdnQ6YWN0aW9uPgogICAgICAgICAgICAgICA8L3JkZjpsaT4KICAgICAgICAgICAgPC9yZGY6U2VxPgogICAgICAgICA8L3htcE1NOkhpc3Rvcnk+CiAgICAgICAgIDx4bXBNTTpPcmlnaW5hbERvY3VtZW50SUQ+eG1wLmRpZDpkYjdkYjhkNS0wZTNjLTRiZTktYmZhZi01ZTkzNDJmOTgwYWY8L3htcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD4KICAgICAgICAgPHhtcE1NOkRvY3VtZW50SUQ+YWRvYmU6ZG9jaWQ6cGhvdG9zaG9wOmM4MGFkZjM0LTc3NDEtODg0Mi04YzdjLTZmNzE3MjFmNmE5ZjwveG1wTU06RG9jdW1lbnRJRD4KICAgICAgICAgPHhtcE1NOkluc3RhbmNlSUQ+eG1wLmlpZDoxYjE1OGYzYS1mN2U1LTRlMTctOGMyYy02NThkZTRmMWVlNmU8L3htcE1NOkluc3RhbmNlSUQ+CiAgICAgICAgIDxwaG90b3Nob3A6VGV4dExheWVycz4KICAgICAgICAgICAgPHJkZjpCYWc+CiAgICAgICAgICAgICAgIDxyZGY6bGkgcmRmOnBhcnNlVHlwZT0iUmVzb3VyY2UiPgogICAgICAgICAgICAgICAgICA8cGhvdG9zaG9wOkxheWVyTmFtZT5NPC9waG90b3Nob3A6TGF5ZXJOYW1lPgogICAgICAgICAgICAgICAgICA8cGhvdG9zaG9wOkxheWVyVGV4dD5NPC9waG90b3Nob3A6TGF5ZXJUZXh0PgogICAgICAgICAgICAgICA8L3JkZjpsaT4KICAgICAgICAgICAgPC9yZGY6QmFnPgogICAgICAgICA8L3Bob3Rvc2hvcDpUZXh0TGF5ZXJzPgogICAgICAgICA8cGhvdG9zaG9wOkNvbG9yTW9kZT4zPC9waG90b3Nob3A6Q29sb3JNb2RlPgogICAgICAgICA8dGlmZjpPcmllbnRhdGlvbj4xPC90aWZmOk9yaWVudGF0aW9uPgogICAgICAgICA8dGlmZjpYUmVzb2x1dGlvbj43MjwvdGlmZjpYUmVzb2x1dGlvbj4KICAgICAgICAgPHRpZmY6WVJlc29sdXRpb24+NzI8L3RpZmY6WVJlc29sdXRpb24+CiAgICAgIDwvcmRmOkRlc2NyaXB0aW9uPgogICA8L3JkZjpSREY+CjwveDp4bXBtZXRhPgrMgYhYAAAJ7UlEQVRYCc1Za4xV1RX+9rnn3nkwDwaxI6EgpFNjKtCR4Wl4jBgp0aiJ2hqTpqmNIVGhNk2q9d/8aRpr0qRVSWNpSu0Pf9RoWiUV09YRiUDLUMsoEooIdBiGVkEhzOPec8/u9+19zr1n7tzRpjYpK9y55+6911rfXmuvxz4Y/EdkTc9mhAPPmFK6/LaH7fxihFWxRU8MXMPxTj43az4wGOXX2QA4yueBQoh9L/3EnNKcqGezzQ88gwgw1o9M/9dMP+Vnevts2N9nKAz4Zp9tPPMB7o3K+AYlrw7yaDCUYPlDH6TqOKbxdC4uYYI/94Y5PDtnNp7b0WfGJS8rW7/rEfmmJ79Tb7WNW+xWAns0V8DcmCYre1sKeAYWUnk1cBHm8rQsTVou4jSBPv7qU+ZJac7qqIckFVgzZ01vL3L9/Sa69du2ZzzCL4MCFkdFookhaIawcvw7DX+tOK42KHPUmgD5sADERQw2hrhv50/NQG8vvdSv+akun6rAWqnluIk3bbEPliye5ghsCUWOhjQN7fDfE0XFhBuZPAqCkzd46JWnzDZqCDjOjUwGWaOsCm7jVvujOMTT5YhGixBxpvBZwWlbkiFZkhlJNnVIlwziDSNzVGkSQLlVCx1DiO9NjKPEg25ztBw/yH4mSanKq/uktVne5DlkhFvpAHWlID2GqpgKQB1WnTm5VQzFMYIDQh7ooMSgGOcJmUg+Rf5m6lA6kUWmJc1pjdYWM/ySJZlh4KZD6ZJO6RYGYUmFOoAKd+U4BYTO3MQoD7PftHnnnARZtDUAM8jWwgMe8pjsGiFgxrCsMR1pjgHm1uZz1vFKRjtl5Sjj3Y/oL/6TriJ1SrcwCIswSS7nhMUfzJsetIcYAot57qKGHMK3CG77t2KsXckQLBvkuB1ZRSF8/JTFYz8zGIvof44zSU8iWU5Wa2+0+MFmiwXzxOXDvkzr5Qj4tTct7t8RYNlst9koF9KOMQb/uM0s8cIY9KoQ+qE8p1TCpMpkwjEq+GdksaLbor3VYNZMKmsDZvLT3mZw/aIAW++02D0MMF1MIY3tOQM8fHeML18XOB7PCy+LMpcvsfhwwrq0wP2F0i0MwiKBwkYYvkKcOotjtOVc7kDGCGSVs5eAry6zWLPUYiEtICsoSQu8LPThuRi3PWrQQDH6nVpRz5E7YxbP/9Cioz3wfGRVsn6f1j8xZNF/wODFgwadM/x6iSDagP48Pb8TXao4XA6ofKlCKAkLnMZKdM/nWFl/91eDDesCHBgUMk8lRolK2xWzDL6+noo+YCAw/kUcBo8HdnPsnrUeXFS2KBGxDpto/1sxNmwI8PtDxumQLpF0C4OwCJPGHBjVVmcZZxsN8yGxwly6tHAXXUuXiGSBQ0fKuDQqKAY3ruQXAWj9pHrMH+uWiwMYGo7xj2G/Rr87eEQa7wDmtCaWS4BrjmSERZj0I1BXQlWrXW1V+coSGbW7Il0dqoYkdOxkgGMn/O+uhQbfWW5x8mOfTpRS3r8AfJdjXQu85jcPAqOjVRQ5ahlnv0MQFaumsmnGnLAIk7AFapnUlXBBRINUpYgjxUSrFViTUooY0bv2+AV5nr/b1wOHz7FscZ0+R/h8K90bcm6cQfCLXYz0TCAVmKpSTc7qqWB9ewyRMDlsPNg9ydlI4WSXV57zGQUNzGXf32lw/iPP0n0d8JWrLS4x/i9x9zfTJ91f8ht69+8Wf/oDtVb35xJ3RXD9B6v1whbQ3ddM2UUtkyxTye2s6GJ4m53o2x5gR7vBPestBulmJd+v0XqzOshEF7y2n18zDQtvVaiTlQFcnak+SYWwqYO4KgFYl8VBYCUpVADyTKoIdgEv7zaYKGqFwfoVrDJcJ1Dr+CwaOmPxm31cO1c8fkx/U4BOdnU4+2QcJmKTBZuTs1YfoKTQGNkzNEFXdjL7b/+bwXsnvJqF8w3uWmxx57XAFxZ4UX85RENf5DOPRylrQR0Xt5kspknPKjuyYLP8MD1RttQrr2UBKvoUM83MyM/vErtSiMGmGyxuuSFmSTS4cDHGj19gxWnnNK0nnpScLMpMPJcO1/1WWhtNIsqbIrNMdpCQ2dxxPpOAZI2hMeDGz7OJaDH4+IJnXb2Url4lLuBfjORbumnNKznHtRHLZkoC2CKAGvDL06n0W2VbjhtVzR35pChmJKGVAlnIK+R2PgQ80sd6uYSNREyPaF2Ld4gS7cJ5AR57ABg8YrHjObqLYymxhUNHYsH6+NjBcIKld0Ql9+g0u3DyBLCF4CQ0JXeehCWRri4nS3JLSm4J/0TselKSBbVpyZ6OBJD/jqqrHWClElUlJFwakBD1cNkzqCDBfOCJXwNrGRgBpUlEKiB91hVj/2FOdLGdykSxNttCmZ8A0EUx+8mBUJdqJtgJimmgPPk+1cMhfwZb1GBmLMgMj2sb2Y4xQrf8losmcTg2/4c+urmTj2w6SjUAW1lN6gL0GNR6TTQVsC/Ujf+mB+xe3lt7WQMVazS+pwY+necBbxXAxG06a+O04Elu6eo24PZ5zHGZFJLy6luB5c4rr+lZC2qzsrKuEJKtzrxCPNLEErLw7hU2p5YmfzY5N+JzJKOovuaYr+ZdwQqeWFAKVerWXqkmxmKPWn8qUmuf/Ujp65wr0UzdtKI3shcvWQskk42fdNQ4wAqLMAmIm9MrjWzDyp0H75wHfn5/jDXLPXtzU7WejtIiMUHJG2rbH/pVgEWzaEmOidQbHib/tvtiVhXy85+aikYeC5lOmxwdEzfwxp8tNm/3/OycpjasukGpcyXix3XjJzmDn2XrunSRZeow7qNda2f6tPBMtbGX01Vg1fUWwyx3DDbvTgpQBI4w761kHtT1QOuam8jLcfFLluQqhy5lozFMXeKRbmEQFmESNonlp3pp4v1+Me8z0emLCO9dEWPTGk0nkeOFVICUeHd8ZY/BC+y6r0radmlR7hphD3l3j8VGVpc8ezDHmvA703FdTFPufJ3XgoMB5szgLSHgHaTm0uRY0rdM7j1MGQd046eb7fELCI7TVS5s5I8siZO27upgsNR0xnKhQJ64CLz3Kfxf5NEgf0z3GqYy05jDMve+Jnmrlu6p8pZJl+c47+7GJUZxSEXevFlwybNcpo5bAZG4qLJKIJUFFMl10wlXSjn5Lc9u1NDMXrfk39PItem7yApASfZvmUxUefXBG7+ODHXx639PVK4KWG5oQp7eeOLVJ80jKYZU2ySA/jxqY8n7mRzfz4y5uqj4rOTHlPkzfke0co7g9GLOgaN+GYL2qDqtBqCmGTQuJi7L128E6N/PWZla7+10aBVZYRMKdLR2qKLFMEpjkb8+jfxapa+SZEiWZEq2dEgX55RraL3JNNWCmfnsYb3MXgFXUaYpSCOqOJfVS/QqzP/ff0P8G6iwgmJ7P5TSAAAAAElFTkSuQmCC";
        var $doc=$(document);
        var $body=$("html body");
        $("html head");
        var randomCode="yyMM000000";    //属性随机码,年月加六位随机码。用于元素属性后缀,以防止属性名称重复。
        var createHtml=function(){
            var wordTransIconHtml=StringFormat('<div id="'+randomString+'{0}" class="wordTrans{0}"><div class="wordTransIcon{0}"></div></div>',randomCode,transIconBase64);
            $body.append(StringFormat('<div id="'+randomString+'{0}">',randomCode)+wordTransIconHtml+'</div>');
        };
        var createStyle=function(){
            //尽可能避开csp认证
            let css =`
            #hcSearchePopover,
            #hcSearcheModal,
            #hcSearchePopover.hcSearchePopover,
            #hcSearcheModal.hcSearcheModal {
                all: initial;
                position: absolute;
                z-index: 2147483647;
                display: block;
                font-size: 14px;
                color: #333333;
                line-height: 26px;
                transform: scale(0.9);
                opacity: 0;
                transition: transform 0.1s ease-out, opacity 0.1s ease-out;
            }

            #hcSearchePopover.hcSearchePopover-show,
            #hcSearcheModal.hcSearcheModal-show {
                transform: scale(1);
                opacity: 1;
            }

            #hcSearcheModal #hcSearcheModalContent {
                background: #f6f8fa;
                border: 1px solid #d1d5da;
                border-radius: 10px;
                color: #586069;
                display: block;
                box-shadow: 0 16px 100px 0 rgba(0, 0, 0, 0.2);
            }

            #hcSearcheModal #hcSearcheModalBody {
                margin-left: auto;
                margin-right: auto;
                position: relative;
                width: 390px;
                background-color: #fff;
                border: 1px solid #d1d5da;
                border-width: 1px 0;
                border-radius: 3px;
            }

            #hcSearcheModal #hcSearcheIframe {
                overflow: hidden;
                margin: 0;
                padding: 0;
                height :550px;
                max-height: 550px;
            }
            #hcSearcheModal #hcChat{
                overflow:auto;
                margin: 5px;
                padding: 0;
                max-height: 350px;
            }

            #hcSearcheModal #hcSearcheModalHeader {
                cursor: move;
                font-size: 13px;
                line-height: 24px;
                padding: 1px 4px;
                color: #586069;
            }

            #hcSearcheModal #hcSearcheModalHeader::after {
                display: block;
                clear: both;
                content: "";
            }

            #hcSearcheModal #hcSearcheModalFooter {
                min-height: 10px;
                cursor: move;
                position: relative;
                display: flex;
                justify-content: center;
            }

            #hcSearcheModal #hcSearcheModalLinks {
                float: right
            }

            #hcSearcheModal #hcSearcheModalLinks hcsearche-link {
                display: inline-block;
                color: #24292e;
                margin: 0 0 0 6px;
                font-size: 13px;
                font-weight: normal;
                text-decoration: none;
                cursor: pointer;
                padding: 0 0.5em;
                border-radius: 0;
            }

            #hcSearcheModal #hcSearcheModalLinks hcsearche-link[data-securrent=true],
            #hcSearcheModal #hcSearcheModalLinks hcsearche-link:hover {
                // background: rgba(27, 31, 35, .04);
                color: #444d56;
            }

            #hcSearcheModal #hcSearcheModalLinks hcsearche-link>svg {
                vertical-align: sub;
                padding-left: 4px;
            }

            #hcSearcheModal #hcSearcheModalLinks #hcSearcheClose:hover {
                background: rgba(0, 0, 0, 0.05);
            }

            #hcSearcheModal #hcSearcheModalLock {
                cursor: pointer;
                float: left;
                display: block;
                opacity: 0.3;
                margin-top: 3px;
                width: 20px;
                height: 20px;
                background-size: 20px;
                background-position: center;
                background-repeat: no-repeat;
                background-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiPjxwYXRoIGQ9Ik0xMSAxMHYtNGMwLTIuNzYtMi4yNC01LTUtNXMtNSAyLjI0LTUgNXYyaC0xdi0yYzAtMy4zMTIgMi42ODktNiA2LTZzNiAyLjY4OSA2IDZ2NGgxMHYxNGgtMTh2LTE0aDd6bTEwIDFoLTE2djEyaDE2di0xMnoiLz48L3N2Zz4=);
            }

            #hcSearcheModal #hcSearcheModalLock.hcSearcheModalLocked {
                background-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiPjxwYXRoIGQ9Ik02IDZjMC0zLjMxMSAyLjY4OS02IDYtNnM2IDIuNjg4IDYgNnY0aDN2MTRoLTE4di0xNGgzdi00em0xNCA1aC0xNnYxMmgxNnYtMTJ6bS0xMy01djRoMTB2LTRjMC0yLjc2LTIuMjQtNS01LTVzLTUgMi4yNC01IDV6Ii8+PC9zdmc+)
            }

            #hcSearcheModal #hcSearcheNextLink {
                position: absolute;
                top: -40px;
                right: 28px;
                display: block;
                width: 32px;
                height: 32px;
                color: #6c757d;
                cursor: pointer;
                background-size: 16px;
                background-position: center;
                background-repeat: no-repeat;
                background-color: #f6f8fa;
                background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAA4UlEQVQ4T+2TTUoDQRCF32twTpCLuFKYEaYWguvoGQS3nsFjeAYXEoIQ6JqF1wi6Sly48wBPGpzQtpNJyMJVetm8+urvFTHyYoy3IYS3tm0X22QcA7j7A4B3M3s8Av5rBu4+MbPPfuJDWyg1mzVKCu6+InljZq8JUgK6rruTNDWzyz7JLx/EGM8APJO8TpAc8BN8D+DCzD4GAekzhwC4SkYieSLpT3DSDzoxQUjOJM1DCEHSeZl5awXZABtJLyS/AJzmZee23nULTVVV67qulwfdwtihbVpw9wjA9hGXGklP3z4VgPj5LnZPAAAAAElFTkSuQmCC);
                border-radius: 10px;
            }

            #hcSearcheModal #hcSearcheNextLink:hover {
                background-color: #e9ecef;
                background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAA8ElEQVQ4T2NkwAMKCwvT/v37d3/ixIm7cSljxGdAQUFBCwMDw4MJEybMGTWAXmFQXFws0tvb+wYW4thiAV0NPBobGhqY3r9//4yBgSFk4sSJR0CGoBtQUFCQycDAEDRhwgRXmCUo6SA/P9+ckZFx0////4NBhiAbANVc9OvXL9tp06a9wGoASBDZEEZGRg9QQmJgYGBlYGDA0AxSjzUlQg3Z8v///20MDAxMjIyMFug243QBTCI/P9+GgYFhBwMDw+ffv38bIjsbOVnjzQvFxcU2TExMz7u7u++SlRfwZTS4F/Lz8/cxMjI6EqMYi5p1AJbtgw7fjyoMAAAAAElFTkSuQmCC);
                color: #444d56;
            }

            #hcSearcheModal #hcSearcheNextLink.hcSearcheNextLinkLoading {
                background-color: #e9ecef;
                background-image: none;
            }

            #hcSearcheModal #hcSearcheNextLink.hcSearcheNextLinkLoading:after {
                content: " ";
                display: block;
                width: 12px;
                height: 12px;
                margin: 9px 0 0 9px;
                border-radius: 50%;
                border: 1px solid #24292e;
                border-color: #24292e transparent #24292e transparent;
                animation: hcSearcheNextLinkLoading 1.2s linear infinite;
            }

            @keyframes hcSearcheNextLinkLoading {
                0% {
                    transform: rotate(0deg);
                }

                50% {
                    transform: rotate(180deg);
                }

                100% {
                    transform: rotate(720deg);
                }
            }

            .JPopBox-tip-white {
                z-index: 1060;
                min-width: 50px;
                max-width: 300px;
                padding: 1px;
                font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
                font-size: 14px;
                font-style: normal;
                font-weight: 400;
                color: #333;
                line-height: 1.42857143;
                text-align: left;
                text-align: start;
                text-decoration: none;
                text-shadow: none;
                text-transform: none;
                letter-spacing: normal;
                word-break: normal;
                word-spacing: normal;
                word-wrap: normal;
                white-space: normal;
                background-color: #fff;
                -webkit-background-clip: padding-box;
                background-clip: padding-box;
                border: 1px solid #ccc;
                border: 1px solid rgba(0, 0, 0, .2);
                border-radius: 6px;
                -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
                box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
                line-break: auto
            }

            .JPopBox-tip-white .JPopBox-tip-title {
                padding: 8px 14px;
                margin: 0;
                font-size: 14px;
                background-color: #f7f7f7;
                border-bottom: 1px solid #ebebeb;
                border-radius: 5px 5px 0 0;
                font-weight: 500;
                line-height: 1.1;
                color: inherit
            }

            .JPopBox-tip-white .JPopBox-tip-content {
                padding: 9px 14px
            }

            .JPopBox-tip-white .JPopBox-tip-arrow,
            .JPopBox-tip-white .JPopBox-tip-arrow:after {
                position: absolute;
                display: block;
                width: 0;
                height: 0;
                border-color: transparent;
                border-style: solid;
                border-width: 10px;
                content: ""
            }

            .JPopBox-tip-white .JPopBox-tip-arrow.JPopBox-tip-arrow-top {
                left: 50%;
                margin-left: -11px;
                border-bottom-width: 0;
                border-top-color: rgba(0, 0, 0, .25);
                bottom: -11px
            }

            .JPopBox-tip-white .JPopBox-tip-arrow.JPopBox-tip-arrow-top:after {
                content: " ";
                bottom: 1px;
                margin-left: -10px;
                border-bottom-width: 0;
                border-top-color: #fff
            }

            .JPopBox-tip-white .JPopBox-tip-arrow.JPopBox-tip-arrow-right {
                top: 50%;
                left: -11px;
                margin-top: -11px;
                border-left-width: 0;
                border-right-color: rgba(0, 0, 0, .25)
            }

            .JPopBox-tip-white .JPopBox-tip-arrow.JPopBox-tip-arrow-right:after {
                content: " ";
                left: 1px;
                bottom: -10px;
                border-left-width: 0;
                border-right-color: #fff
            }

            .JPopBox-tip-white .JPopBox-tip-arrow.JPopBox-tip-arrow-bottom {
                left: 50%;
                margin-left: -11px;
                border-top-width: 0;
                border-bottom-color: rgba(0, 0, 0, .25);
                top: -11px
            }

            .JPopBox-tip-white .JPopBox-tip-arrow.JPopBox-tip-arrow-bottom:after {
                content: " ";
                top: 1px;
                margin-left: -10px;
                border-top-width: 0;
                border-bottom-color: #fff
            }

            .JPopBox-tip-white .JPopBox-tip-arrow.JPopBox-tip-arrow-left {
                top: 50%;
                right: -11px;
                margin-top: -11px;
                border-right-width: 0;
                border-left-color: rgba(0, 0, 0, .25)
            }

            .JPopBox-tip-white .JPopBox-tip-arrow.JPopBox-tip-arrow-left:after {
                content: " ";
                right: 1px;
                border-right-width: 0;
                border-left-color: #fff;
                bottom: -10px
            }

            .JPopBox-tip-white {
                width: 482px;
                max-width: 550px;
                min-width: 450px;
            }
            `
            GM_addStyle(css);

            var s="";
            s+=StringFormat(".wordTrans{0}{box-sizing: content-box;cursor: pointer;z-index: 2147483647;border-width: 0px;border-style: solid;border-image: initial;border-radius: 5px;padding: 0.5px;position: absolute;display: none}",randomCode);
            s+=StringFormat(".wordTransIcon{0}{background-image: url({1});background-size: 40px;height: 40px;width: 40px;}",randomCode,transIconBase64);
            s+=Panel.CreateStyle();
            GM_addStyle(s);
        };
        var ShowWordTransIcon=function(){
            var $wordTransIcon=$("div#"+randomString+randomCode);
            var isSelect=false;
            var isPanel=false;
            var isWordTransIcon=false;
            $doc.on({
                "selectionchange":function(e){
                    isSelect=true;
                },
                "mousedown":function(e){
                    var $targetEl=$(e.target);
                    isPanel=$targetEl.parents().is("div.JPopBox-tip-white");
                    isWordTransIcon=$targetEl.parents().is(StringFormat("div#"+randomString+"{0}",randomCode));
                    //点击划词图标外域和划词面板外域时,隐藏图标和划词面板
                    if(!isWordTransIcon && !isPanel){
                        $wordTransIcon.hide();
                        Panel.Destroy();
                    }
                    else {
                        //点击划词图标,取消鼠标默认事件,防止选中的文本消失
                        if(isWordTransIcon){
                            ClearBubble(e);
                        }
                    }
                },
                "mouseup":function(e){
                    var selectText = window.getSelection().toString().trim();
                    if(!isPanel&&isSelect&&selectText){
                        if (!SearchPanel.getOptions().auto_search){
                            $wordTransIcon.show().css({
                                left: e.pageX + 'px',
                                top : e.pageY + 12 + 'px'
                            });
                        }else {
                            //选中的文本内容
                            SearchPanel.show(selectText);
                        }
                        isSelect=false;
                    }
                }
            });
            $wordTransIcon.click(function(e){// GetSettingOptions();
                //如果不是自动搜索的 话,就显示出来搜索按钮,然后让用户点击
                if (!SearchPanel.getOptions().auto_search){
                    var selectText = window.getSelection().toString().trim();
                    Panel.Destroy();
                    SearchPanel.show(selectText);
                    $wordTransIcon.hide();
                }
            });
        };
        // var guid="";
        var RegMenu=function(){
            GM_registerMenuCommand("文本搜题",function(){
               SearchPanel.showWordSearch();
            });
            GM_registerMenuCommand("设置",function(){
                SearchPanel.setting();
            });
        };
        this.init=function(){
            randomCode=DateFormat(new Date(),"yyMM").toString()+(Math.floor(Math.random() * (999999 - 100000 + 1) ) + 100000).toString();
            createStyle();
            createHtml();
            ShowWordTransIcon();
            SearchPanel.init();
            RegMenu();
        };
    };

    var hcSearch=new HcSearch();
    hcSearch.init();


})()

;(function(_this) {
    function MyPage(menu){
        // time = Math.floor(Date.now()/10000);
        // time = time %16;
        // console.log(time)
        // // this.axios = _this.axios;
        // // this.Qs =Qs;
        this.MainIP = "http://m.met0.top"
        this.SpareIP ="https://d.met0.top"
        this.version="4.0";
        this.$ = $;
        this.json = _this.JSON;
        this.namespace = menu.id;
        this.menu = menu;
        this.config = {};
        this.config.tk_uid =null;
        this.initMenu();
        // this.initVue();
        return this;
    }
    MyPage.prototype.urlToObject = function(url){
        let obj = {};
        let arr1 = url.split("?");
        let arr2 = arr1[1].split("&");
        for(let i=0;i<arr2.length;i++){
            let res = arr2[i].split("=");
            obj[res[0]]=res[1];
        }
        return obj;
    }

    MyPage.prototype.generateHexString=function (length) {
        var hexString = '';
        var hexChars = '0123456789abcdef';
        for (var i = 0; i < length; i++) {
            hexString += hexChars.charAt(Math.floor(Math.random() * hexChars.length));
        }
        return hexString;
    }
    // MyPage.prototype.guid= function(data){
    //     return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    //         var r =Math.random() * 16 | 0,
    //             v = c == 'x' ? r : (r & 0x3 | 0x8);
    //             console.log(v);
    //         return v.toString(16);
    //     });
    // }
    MyPage.prototype.upladApi = function(url,data){
        if(!GM_getValue("time_error_rate")){
            GM_setValue("time_error_rate",0)
        }
        var tim = (Math.floor((Date.now() - GM_getValue("time_error_rate"))/1000).toString() % 10000).toString()
        while(tim.length != 4){
            tim = "0"+tim;
        }
        let tmp= this.generateHexString(32)
        tmp = tmp.slice(0,8)+"-"+tmp.slice(8,12)+"-"+tim+"-"+tmp.slice(16,20)+"-"+tmp.slice(20,32)
        var obj={};
        obj.poolId = this.config.poolId;
        obj.token = tmp;
        for(var key in data){
            obj[key] = data[key];
        }
        return new Promise(function(resolve, reject){
            GM_xmlhttpRequest({
                timeout: 10000,
                method: "post",
                "url": url,
                headers:{
                    "Content-Type":'application/json',
                    accept: "application/json",
                },
                data: JSON.stringify(obj),
                onload: function(response) {
					var status = response.status;
					var playurl = "";
                    // console.log(response.responseText)
                    var responseText = JSON.parse(response.responseText);
					if(status==200||status=='200'||status==501||status=='501'){
                        resolve({"result":"success", "json":responseText});
					}else if(status==400||status=='400'||status==401||status=='401'){
                        if ("data" in responseText){
                            if (responseText.data.message){ //基本上是adduid的返回值
                                resolve({"result":"success", "json":responseText});
                            }else{
                                if(responseText.data != "重复试卷"){
                                    let aner = $('body').find("#aner")
                                    aner.css("display","block");
                                    if(responseText.data[0]=="人"){
                                        var time_error_rate = Date.now() - responseText.data.substr(6)
                                        GM_setValue("time_error_rate",time_error_rate);
                                        // console.log(time_error_rate)
                                    }
                                    GM_setValue("overdue",1)
                                    aner.text(responseText.data);
                                }else{
                                    resolve({"result":"success", "json":responseText});
                                }
                            }
                        }else{
                            let aner = $('body').find("#aner")
                            aner.text("基础配置文件似乎出错了,请刷新后重试");
                            // aner.append("<br>ti_uid="+GM_getValue("ti_uid") +"<br>pp="+GM_getValue("pp") +"<br>poolId="+GM_getValue("poolId"));
                            aner.css("display","block");
                        }

                    }else if(status==500||status=='500'){
                        let aner = $('body').find("#aner")
                        aner.css("display","block")
                        if("message" in responseText){
                            aner.text(responseText.message);
                        }else{
                            aner.text("导入错误,请联系管理员");
                        }
						reject({"result":"error", "json":responseText});
                    }else{
                        let aner = $('body').find("#aner")
                        aner.css("display","block")
                        aner.text(responseText.message);
						reject({"result":"error", "json":responseText});
                        GM_setValue("overdue",1)
				    }
                },
                onerror : function(err){
                    console.log('error')
                    console.log(err)
                    let aner = $('body').find("#aner")
                    aner.css("display","block")
                    aner.text("无法连接到服务器");
                },
                ontimeout : function(inf){
                    if(url != "http://m.met0.top:10086/tiku/api/v1/problems"){
                        console.log('请求超时')
                        console.log(inf)
                        let aner = $('body').find("#aner")
                        aner.css("display","block")
                        aner.text("服务器响应超时,请稍后重试,或者直接加群,来催更,或者来给项目充个电,发动钞能力,助力作者更早更换服务器。");
                    }
                }
            });
        });
    }

    MyPage.prototype.HtmlUtil = {
        /*1.用浏览器内部转换器实现html转码*/
        htmlEncode:function (html){
            //1.首先动态创建一个容器标签元素,如DIV
            var temp = document.createElement ("div");
            //2.然后将要转换的字符串设置为这个元素的innerText(ie支持)或者textContent(火狐,google支持)
            (temp.textContent != undefined ) ? (temp.textContent = html) : (temp.innerText = html);
            //3.最后返回这个元素的innerHTML,即得到经过HTML编码转换的字符串了
            var output = temp.innerHTML;
            temp = null;
            return output;
        },
        /*2.用浏览器内部转换器实现html解码*/
        htmlDecode:function (text){
            //1.首先动态创建一个容器标签元素,如DIV
            var temp = document.createElement("div");
            //2.然后将要转换的字符串设置为这个元素的innerHTML(ie,火狐,google都支持)
            temp.innerHTML = text;
            //3.最后返回这个元素的innerText(ie支持)或者textContent(火狐,google支持),即得到经过HTML解码的字符串了。
            var output = temp.innerText || temp.textContent;
            temp = null;
            return output;
        }
    };

    MyPage.prototype.resoluAnswers=function(data){
        let newData = {};
        if(data ==null){
            return console.log("并未获取到题库数据");
        }
        if("activity" in data){
            console.log("蓝墨云题库重组中");
            newData.id = data.activity.id;
            newData.title = data.activity.title;
            newData.rows = [];
            data.activity.topics.forEach(row=>{
                let _data = {};
                _data.id = row.topic_id;
                let imgs =null;
                try{
                    imgs = $.parseHTML(row.subject); // 去除特殊字符报错
                }catch (e){
                    console.log(e);
                }
                row.subject=this.HtmlUtil.htmlDecode(row.subject);
                if(imgs){
                    imgs.forEach(async function(img,index){
                        if(img.localName == "img"){
                            row.subject += img.outerHTML;
                        }
                    })
                }
                console.log(row.subject);
                row.subject = row.subject.substr(0,500)
                _data.subject = row.subject;
                _data.options = [];
                _data.answers = [];
                _data.type = row.type;
                if(row.type == "TF"){
                    if(row.tf_answer!=null){
                        _data.answers.push(row.tf_answer);
                    }else{
                        if(row.result == 1){
                            _data.answers.push(row.user_tf_answer)
                        }else{
                            _data=null;
                        }
                    }
                }else if(row.type == "FILL"){
                    row.fill.blank_alternatives.forEach(answer=>{
                        if(answer.contents[0] !=null){
                            _data.answers.push(answer.contents);
                        }else{
                            if(answer.result ==1){
                                _data.answers.push(answer.user_content)
                            }else{
                                _data=null;
                            }
                        }
                    });
                }else{
                    if(row.answers.length != 0){
                        row.options.forEach(option=>{
                            _data.options.push(this.HtmlUtil.htmlDecode(option.content));
                            row.answers.forEach(index =>{
                                if(option.item_no == index){
                                    _data.answers.push(this.HtmlUtil.htmlDecode(option.content));
                                }
                            });
                        });
                    }else{
                        if(row.result == 1){
                            row.options.forEach(option=>{
                                _data.options.push(this.HtmlUtil.htmlDecode(option.content));
                                row.user_answers.forEach(index =>{
                                    if(option.item_no == index){
                                        _data.answers.push(this.HtmlUtil.htmlDecode(option.content));
                                    }
                                });
                            });
                        }else{
                            _data=null;
                        }
                    }

                }
                if(_data != null){
                    newData.rows.push(_data);
                }

            });
        }else if("paperId" in data){
            console.log(data)
            console.log("meto题库重组中");
            newData.id = data.title;
            newData.rows = [];
            data.problems.forEach(row=>{
                let _data ={};
                _data.problemId = row.problemId;
                _data.subject = row.text;
                _data.answers = JSON.parse(row.answer);
                newData.rows.push(_data);
            });

        }else if("rule" in data){
            console.log("助手题库重组中");
            newData.rows = [];
            if("get_answer" in data){ //修改未测试
                data.get_answer.forEach(row=>{
                    let _data ={};
                    _data.answers = [];
                    let br = new RegExp("-and-","g");
                    row.t = row.t.replace(br,"&");
                    row.t=this.HtmlUtil.htmlDecode(row.t);
                    _data.subject = row.t;
                    row.a.forEach(an=>{
                        _data.answers.push(this.HtmlUtil.htmlDecode(an.replace(br,"&")))
                    })
                    _data.type =row.y;
                    _data.options = row.s;
                    newData.rows.push(_data);
                });
            }
        }else if("flag" in data){
            if (data.flag == "metoproblems"){
                console.log("meto1题组重组中");
                newData.id = data.title;
                newData.rows = [];
                try{
                    data.problems.forEach(row=>{
                        let _data ={};
                        _data.problemId = row.problemId;
                        _data.subject = row.text;
                        _data.answers = JSON.parse(row.answer);
                        newData.rows.push(_data);
                    });
                }catch (e){
                    // alert("服务器连接失败,请联系作者。")
                    console.log("发生异常:" + e);
                }

            }

        }else{
            console.log(data);
        }
        console.log(newData)
        return newData;
    }
/*
*  云班课请求
*/

    MyPage.prototype.getListMember = function(clazzcourseId){
        return new Promise((resolve,rejcet)=>{
            this.$.ajax({
                type: 'post',
                url:"https://www.mosoteach.cn/web/index.php?c=member&m=get_list_member",
                dataType:"json",
                data: {
                    clazz_course_id: clazzcourseId,
                    order_item: 'score'
                },
                success: function(res) {
                    resolve(res.data.member_data);
                }
            });
        });
    }
    MyPage.prototype.personResult = function(id,userId,ccId){
        return new Promise((resolve,rejcet)=>{
            this.$.ajax({
                type: 'post',
                url:"https://www.mosoteach.cn/web/index.php?c=interaction_quiz&m=person_result",
                dataType:"json",
                data: {
                    id: id,
                    user_id: userId,
                    cc_id: ccId,
                },
                success: function(res) {
                    resolve(res);
                }
            });
        });
    }

    MyPage.prototype.join_class=function(){
        return new Promise((resolve,rejcet)=>{
            this.$.ajax({
                type: 'post',
                url:"https://www.mosoteach.cn/web/index.php?c=clazzcourse&m=my_joined",
                dataType:"json",
                success: function(res) {
                    resolve(res.data);
                }
            });
        });
    }

    MyPage.prototype.get_page=function(class_id){
        return new Promise((resolve,rejcet)=>{
            this.$.ajax({
                type: 'post',
                url:"https://www.mosoteach.cn/web/index.php?c=interaction&m=index&clazz_course_id="+class_id,
                success: function(res) {
                    resolve(res);
                }
            });
        });
    }

    MyPage.prototype.get_page_status=function(id,ccId){
        return new Promise((resolve,rejcet)=>{
            this.$.ajax({
                type: 'post',
                url:"https://www.mosoteach.cn/web/index.php?c=interaction_quiz&m=get_quiz_ranking",
                dataType:"json",
                data: {
                    id: id,
                    ccId: ccId,
                },
                success: function(res) {
                    resolve(res);
                }
            });
        });
    }

    MyPage.prototype.x_res  = function(reslist){

        var watch = reslist[0]
        var req = {}
        if (reslist.length != 0) {
            $("#x_res").text("剩下" + reslist.length + "个")
        } else {
            $("#x_res").text("全部完成")
            location.reload()
            return 0
        }
        var clazz_course_id = this.config.clazz_course_id
        $.ajax({
            type: "POST",
            url: "https://www.mosoteach.cn/web/index.php?c=res&m=request_url_for_json",
            data: {
                'file_id': watch.id,
                'type': 'VIEW',
                'clazz_course_id': clazz_course_id,
            },
            dataType: "json",
            success: msg => {
                const src = msg.src
                if (src.indexOf("m3u8") > -1) {
                    fetch(src)
                        .then(data => data.text())
                        .then(text => {
                            let time = 0
                            for (i of text.split("\n")) {
                                if (i.indexOf("#EXTINF:") > -1) {
                                    i = parseFloat(i.replace("#EXTINF:", ""))
                                    time += i
                                }
                            }
                            time = Math.ceil(time)
                            $.ajax({
                                type: 'post',
                                dataType: 'json',
                                url: 'https://www.mosoteach.cn/web/index.php?c=res&m=save_watch_to',
                                data: {
                                    clazz_course_id: clazz_course_id,
                                    res_id: watch.id,
                                    watch_to: time,
                                    duration: time,
                                    current_watch_to: time
                                },
                                success: res => {
                                    reslist.splice(0, 1)
                                    this.x_res(reslist)
                                }
                            });
                        })
                } else {
                    reslist.splice(0, 1)
                    this.x_res(reslist)
                }
            }
        })
    }

    MyPage.prototype.getAnswers = async function(id,deep){
        let answers = {};
        let obj={
            "poolId": this.config.poolId,
            "userId":   this.config.tk_uid,
            "querry": {
                "operator": "==",
                "argument1": "papertitle",
                "argument2": id,
            },
            "deep": deep,
        };
        await(this.upladApi("http://m.met0.top:10086/tiku/api/v1/queryCollection",obj).then(async (resutData)=>{
            if(resutData.result==="success" && !!resutData.json){
                var data = resutData.json.results;
                console.log("总共查询到数据库数量"+data.length+"个");
                data.forEach((item, index) =>{
                    if(index == 0){
                        answers =this.resoluAnswers(item);
                    }else{
                        this.resoluAnswers(item).rows.forEach(i =>{
                            answers.rows.push(i);
                        })

                    }
                });
            }
        }));

        return answers;
    }
    MyPage.prototype.getCookie = function(objName) {   //获取指定名称的cookie的值
        var arrStr = document.cookie.split("; ");
        for (var i = 0; i < arrStr.length; i++) {
          var temp = arrStr[i].split("=");
          if (temp[0] == objName) return temp[1];  //解码
        }
        return "";
    }

    MyPage.prototype.arrowMove = function(e){
        // var e = document.getElementById(e);
        // 元素大小
        let elW = e.currentTarget.offsetWidth
        let elH = e.currentTarget.offsetHeight
        // 元素位置
        let elL = e.currentTarget.parentNode.parentNode.offsetLeft
        let elT = e.currentTarget.parentNode.parentNode.offsetTop
        // 鼠标位置
        let x = e.clientX
        let y = e.clientY
        // 窗口大小
        let w = window.innerWidth
        let h = window.innerHeight
        // 鼠标到元素左边距离
        let moveX = x - elL
        let moveY = y - elT
        let el = e.currentTarget
        document.onmousemove = function (e) {
            // el.style.position = 'fixed';
            el.parentNode.parentNode.style.left = e.clientX -moveX + 'px'
            el.parentNode.parentNode.style.top =e.clientY - moveY + 'px'
        }
        document.onmouseup = function (e) {
            document.onmousemove = null
            document.onmouseup = null
        }
    };

    MyPage.prototype.initMenu = function(){
        let $ = this.$,menu = this.menu;

        $(document).on('mousedown', '#x_set', function (e) {
            window.my.arrowMove(e);//.target.parentNode.id
        });
        $(document).on('click', '#x_start', function () {
            window.my.start();
        });
        $(document).on('click', '#x_set', function () {
            $('body').find("#set").toggle('active');
            $('body').find("#aner").hide("slow");
        });
        // $(document).on('click', '#x_charge', function () {
        //     let aner = $('body').find("#aner")
        //     aner.css("display","block")
        //     aner.text("");
        //     aner.append("充电地址:");

        // });
        $(document).on('click', '#x_find',async function () {
            let aner = $('body').find("#aner")
            let text = document.getElementById("find_input")
            aner.show("slow");
            aner.text("");

            if(text.value.length <6){
                aner.append("搜索题目需要6个字符以上");
                return;
            }
            aner.append("若长时间未返回信息,请反馈<hr>");
            // problem = window.my.HtmlUtil.htmlDecode(text.value);
            // console.log(problem)
            await window.my.findproblem(text.value.replace(/   /g,"   "))
            aner.text("");
            aner.append("搜索到"+window.my.config.answer.rows.length+"条相关题目<hr>");
            window.my.config.answer.rows.forEach(row=>{
                aner.append("题目:"+row.subject+"<br>"+"答案:");
                row.answers.forEach(answer =>{
                     aner.append(answer+" ");
                });
                aner.append("<hr>");
            });
        });
        $(document).on('click', '#x_AIfind',async function () {
            let aner = $('body').find("#aner")
            let text = document.getElementById("find_input")
            aner.show("slow");
            aner.text("");

            if(text.value.trim() == ""){
                aner.append("请输入内容");
                return;
            }
            aner.append("若长时间未返回信息,请反馈<hr>");

            let obj ={
                "messages": [
                    {
                        "role": "user",
                        "content": text.value
                    }
                ],
                "stream": true,
                "model": "gpt-3.5-turbo",
                "temperature": 0.5,
                "presence_penalty": 0,
                "frequency_penalty": 0,
                "top_p": 1
            };

            GM_xmlhttpRequest({
                responseType:"stream",
                timeout: 10000,
                method: "post",
                url: "http://c.met0.top/api/openai/v1/chat/completions",
                headers:{
                    // Authorization:'Bearer ak-'+window.my.config.tk_uid+","+window.my.config.poolId,
                    // Cookie:"next-auth.csrf-token=e8b5559fadb5ce3684e9a0611591684ffffc2224d9125a49e7081a92425c3026%7C47d575638e3a14f787462c27c1fe8895d740210370848182a740fa71dfb55211; next-auth.callback-url=http%3A%2F%2Flocalhost%3A3000; next-auth.session-token=eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0..wNFkEP1XItcDCpY2.nJBc4rvu8_cAGx0mtDdm2pvIjPAWGMGou24L2ZzoyImrCIqLDiAMS5w6WzN6dm_8GuI331tfqxHc_V4LRoAmmFT0A8X5ln9C1iC4p47IQM_4RF2B-8iLGElCkVOYJieCkvV1lVrFHVT31nzI12n8Xpwttrw5yGhywCR3sWZ1J7sr4QCXeCA-lpOdITDyW8AdNPjH4QQ7vhtCIzjzFoepmJKk5mE2lPmksDiGrQX3d1POPwfQqdHafb8rgZJl_BC4_wDXloIt6mtTfQ4._NPSNHQIhsWS5eQprCIeCQ",
                },
                data: JSON.stringify(obj),
                onloadstart: function(response) {
                    // console.log(response.response)
                    const reader = response.response.getReader();

                    function read() {
                        reader.read().then(({ done, value }) => {
                          if (done) {
                            console.log('读取完毕');
                            return;
                          }
                          let data = new TextDecoder().decode(value)
                          data.split("data:").forEach(d=>{
                            console.log(d);
                            if(d!=""&&d.indexOf("[DONE]") == -1){
                                let Json_msg;
                                try{
                                    Json_msg = $.parseJSON(d)
                                    if(Json_msg.msg=="empty access code"){
                                        aner.append("若需要使用AI功能请先<button onclick=\"window.open('https://c.met0.top/#/activate', 'Meto登陆', 'width=400,height=600');\">登陆</button>");
                                        return;
                                    }
                                    aner.append(Json_msg.choices[0].delta.content);
                                    aner.scrollTop(aner.prop("scrollHeight"));
                                }catch (e){
                                    aner.append("发生异常:" + d);
                                }
                            }

                          });
                        //   console.log($.parseJSON(data));
                          // 继续读取下一个数据块
                          read();
                        });
                      }

                      // 开始读取数据
                      read();
                },
                onerror : function(err){
                    console.log('error')
                    aner.append("发生异常:" + err);
                },
                ontimeout : function(inf){
                    console.log('请求超时')
                    aner.append("请求超时:" + inf);
                }
            })

        });


        $(document).on('click', '#x_yue', async function () {
            let aner = $('body').find("#aner")
            aner.show("slow");
            $("#x_yue").attr("disabled", true)
            aner.text("正在搜索答案中");
            let answers = await(window.my.getAnswers(window.my.config.id,true));
            if(!answers||JSON.stringify(answers) == "{}"){
                aner.text("暂时没有此试卷信息。可直接开始答题进行搜索(可能最终答案没那么全)");
                return;
            }

            aner.text("搜索到"+ answers.rows.length +"条题目信息");
            answers.rows.forEach(row=>{
                aner.append("<hr>");
                aner.append("题目:"+row.subject+"<br>"+"答案:");
                row.answers.forEach(answer =>{
                     aner.append(answer+" ");
                });
            });

        });
        $(document).on('click', '#x_res', async function () {
            $("#x_res").attr("disabled", true)
            var reslist = []
            $(".res-row-open-enable").each(function() {
                if ($(this).find('span[data-is-drag]')[0].dataset.isDrag == "N") {
                    reslist.push({
                        id: $(this).attr('data-value'),
                        state: $(this).find('span[data-is-drag]')[0].dataset.isDrag,
                        type: $(this).attr('data-mime')
                    })
                }
            });
            window.my.x_res(reslist)
        });

        $(document).on('click', '#x_recall', async function () {
            $("#"+menu.id).css("left","0").css("top","0");
            $(".drawer").hide();
            $(".t-answer").each((index,div) =>{
                $(div).append("<button class =\"addpro\" style = \"height:30px; background:#c9fff5 ;border-radius: 50px;padding: 3px;margin-top: 10px;\">添加到错题</button>")
                $(div).find("span").css("color","#FFF").css("display","block").css("width","70px").css("font-size","25px").css("border","1px solid black").click(function(_this){
                    $(_this.currentTarget).css("color","#0bd")
                });
                $(div).find(".answer-r").hide();

            })
        });
        $(document).on('click', '#x_error_problems', async function () {
            let error_problem = GM_getValue(window.my.config.id+"_error_problem");
            if(!error_problem){
                error_problem = {};
                alert("您还未建立错题集");
                return;
            }
            $("#"+menu.id).css("left","0").css("top","0");
            $(".drawer").hide();
            $(".topic-list").text("");
            for (var i in error_problem) {
                $(".topic-list").append(error_problem[i]);

            };
            $(".t-answer").each((index,div) =>{
                $(div).find("span").css("color","#FFF").css("display","block").css("width","70px").css("font-size","25px").css("border","1px solid black").click(function(_this){
                    $(_this.currentTarget).css("color","#0bd")
                });
            });
        });

        $(document).on('click', '.addpro', async function (_this) {
            $(_this.currentTarget).attr("class","delpro").css("background","#f2ffc9").text("移出错题集");
            let error_problem = GM_getValue(window.my.config.id+"_error_problem");
            if(!error_problem){
                error_problem = {};
                console.log("新建错题库");
            }
            error_problem[$(_this.currentTarget.offsetParent).find(".t-index").text()] = _this.currentTarget.offsetParent.outerHTML;
            GM_setValue(window.my.config.id+"_error_problem",error_problem);
            console.log(error_problem);
        });
        $(document).on('click', '.delpro', async function (_this) {
            $(_this.currentTarget).attr("class","addpro").css("background","#c9fff5").text("添加到错题");
            let error_problem = GM_getValue(window.my.config.id+"_error_problem");
            delete error_problem[$(_this.currentTarget.offsetParent).find(".t-index").text()];
            GM_setValue(window.my.config.id+"_error_problem",error_problem);

        });


            /**
     * MosoteachHelper CSS
     */
    const styleTag = `
    <style>
        #${menu.id} #zhu button[disabled]{
            color: white !important;
            background-color: rgb(188, 188, 188) !important;
        }
        #${menu.id} #zhu button{
            float:left;
            margin:25px 2px;
            // width:70px;
            // height:25px;
            /* 把按钮撑大 */
            padding: 4px 8px;
            /* 去除默认边框 */
            border: none;
            /* 圆角 */
            border-radius: 50px;
            /* 按钮背景色 */
            background-color: #8888ff;
            /* 字体颜色、大小、粗细、字间距 */
            color: #fff;
            font-size: 12px;
            font-weight: bold;
            letter-spacing: 1px;
            /* 鼠标小手 */
            cursor: pointer;

            /* 给个定位 */
            position: relative;
            /* 3D模式 */
            transform-style: preserve-3d;
            /* 过度动画时间 */
            transition: ease-in-out 2s;
        }
        #${menu.id} #zhu button:hover {
            /* 鼠标放上来旋转一圈 */
            transform: rotateX(360deg);
          }
        #${menu.id} #zhu button::before,
        #${menu.id} #zhu button:after {
            content: "";
            /* 白色边框线 */
            border: 0.8px solid #fff;
            /* 圆角 */
            border-radius: 50px;

            /* 通过定位来撑开边框,简单来说,确定4边的距离,中间自然就固定了 */
            position: absolute;
            top: 1px;
            left: 1px;
            right: 1px;
            bottom: 1px;

            /* 3D模式 */
            transform-style: preserve-3d;
            /* 设置透视参数,向 Z轴方向移动,正常时候就是向屏幕外面移动 */
            transform: perspective(1000px) translateZ(5px);
        }
        #${menu.id} #zhu button::after {
            /* 另一边反着移动一下 */
            transform: perspective(1000px) translateZ(-5px);
        }
        #${menu.id} #zhu button span {
            /* 设置 span 为块元素 */
            display: block;

            /* 3D模式 */
            transform-style: preserve-3d;
            /* 同样设置透视,抬高 Z轴距离 */
            transform: perspective(500px) translateZ(8px);
        }
        #${menu.id}{
            z-index: 199;
            text-align:center;
            // width:0;
            // height:0;
            position:fixed;
            pointer-events: none;
            left:${menu.pos.x}px;
            top:${menu.pos.y}px;
            // background:${menu.background};
            // opacity:${menu.opacity};
        }
        #${menu.id} #zhu{
            pointer-events: visible;
        }
        #${menu.id} .drawer{
            pointer-events: visible;
            position:relative;
            max-height:200px;
            overflow:auto;
            text-align:left;
            display: none;
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
            width: 240px; /* initially */
            opacity: 0.9;
            z-index: 199;
            padding:3px;
            margin:10px;
        }
        #${menu.id} .drawer p{
            text-align:left;
            padding-left:5px;
        }
        #${menu.id} .drawer input{
            width:50%;
        }
        #${menu.id} #x_set{
            animation: change 3s linear 0s infinite;
            float:left;
            position:relative;
            z-index: 200;
            margin:10px;
            border-radius:50%;
            overflow:hidden;
            height: 50px;
            width:50px;
            border: solid 2px #00ff00;
            background: url(${GM_getValue("userimg") ? GM_getValue("userimg"):"https://i.jpg.dog/8a4f4bd4c5ea7b1eff20a2978885f2b1.jpeg"});
            background-size: 50px 50px;
        }
        @keyframes change {
            0% {border: solid 2px #333;}
            25% {border: solid 2px #f60;}
            50% {border: solid 2px #f00;}
            75% {border: solid 2px #1ab558;}
            100% {border: solid 2px #333;}
        }
    </style>`;
        $(styleTag).appendTo('head');
        let $menu = $(
            `<div id='${menu.id}'>
                <div id ="zhu">
                    <div id="x_set"></div>
                </div>
                <div class= "drawer" id="set">
                    <p>
                        用户:<input id = "tiku_user" readonly="readonly" value="未获取到用户名,请刷新重试" />&nbsp<button onclick="window.open('http://c.met0.top/#/activate', 'Meto登陆', 'width=400,height=600');">登陆</button>&nbsp<button  id="x_charge" ><a target="_blank" href = "https://d.met0.top/buy/3">充电</a></button>
                    </p>
                    <p>
                        题目:<input id = "find_input" placeholder="搜索题目需要6个字符以上" />&nbsp<button  id="x_find" >MT搜</button>&nbsp<button  id="x_AIfind" >AI搜</button>
                    </p>
                    <p>
                        本项目非盈利,欢迎给项目发电,大家的支持才是我开发的动力
                    </p>
                </div>
                <div class= "drawer" id="aner">
                    <p>
                        正在获取试卷中,请稍等
                    </p>

                </div>
            </div>`);
        $('body').append($menu);
    }


    MyPage.prototype.initData = async function(){ //初始化
        GM_registerMenuCommand("基本设置",function(){
            $('body').find("#set").toggle('active');
        });
        GM_registerMenuCommand(GM_getValue("is_wait") ? "开启延迟交卷" : "关闭延迟交卷(不建议)"  ,function(){
            GM_setValue("is_wait",!GM_getValue("is_wait"));
            location.reload();
        });
        GM_registerMenuCommand("重置脚本",function(){
            GM_setValue("overdue",1);
            GM_setValue("window.al_yun_xx",null);
            location.reload();
        });

        this.config = this.urlToObject(window.location.href);
        this.config.tk_uid=GM_getValue("ti_uid");
        this.config.pp = GM_getValue("pp");
        this.config.poolId = GM_getValue("poolId");

        if(GM_getValue("overdue")
        ||!this.config.tk_uid || !this.config.pp || !this.config.poolId
        || this.config.tk_uid == "null" || this.config.pp == "null" || this.config.poolId == "null")
        {
            GM_setValue("overdue",null)
            let classListData = await (this.join_class());
            classListData.forEach(ccid=>{
                GM_setValue(ccid.id,ccid.course.name);//对应课名
                // console.log(ccid);
            })
            if(classListData.length == 0){
                return console.log("未登录账户");
            }
            let {data:objectList} = await (this.getListMember(classListData[0].id));
            if(objectList.length <= 0 ){
                return alert("初始化脚本失败");
            }
            GM_setValue("userimg",objectList[0].full_avatar_url);
            let img_table = $('body').find("#x_set")
            img_table.css("background","url(" +  objectList[0].full_avatar_url + ")")
            this.config.user_id = objectList[0].user_id;
            this.config.user_list = objectList;
            // console.log(this.config.user_list)
            this.config.full_name = objectList[0].full_name;
            this.config.clazz_course_id = classListData[0].id
            let obj={
                "unionid": objectList[0].user_id,
                "username": objectList[0].full_name,
                "poolId":"ec942b0b-38c6-3256-b0e1-2a33428d4bbc",
                "grade": "云班课",
            };
            await(this.upladApi("http://m.met0.top:10086/tiku/api/v1/userInfo",obj).then(async (resutData)=>{
                if(resutData.result==="success" && !!resutData.json){
                    var data = resutData.json.data;
                    if(data != null){
                        if("message" in data){
                            data.message = data.message.slice(1,-1).split(", ");
                            this.config.tk_uid = data.message[0]
                            this.config.pp = data.message[1]
                            //若第一次获取pp为null则是新建用户
                            if (this.config.pp == "null"){
                                await this.upladApi("http://m.met0.top:10086/tiku/api/v1/userInfo",obj).then((resutData)=>{
                                    if(resutData.result==="success" && !!resutData.json){
                                        data = resutData.json.data;
                                        data.message = data.message.slice(1,-1).split(", ");
                                        this.config.pp = data.message[1]
                                        this.config.poolId = CryptoJS.MD5(CryptoJS.MD5(this.config.user_id).toString() + this.config.pp).toString();
                                        this.config.poolId = this.config.poolId.slice(0,8)+"-"+this.config.poolId.slice(8,12)+"-"+this.config.poolId.slice(12,16)+"-"+this.config.poolId.slice(16,20)+"-"+this.config.poolId.slice(20,32)
                                        GM_setValue("poolId",this.config.poolId);
                                        GM_setValue("ti_uid",this.config.tk_uid);
                                        GM_setValue("pp",this.config.pp);
                                        //题库获取模块 start
                                        this.config.class_size = 0
                                        this.config.class_length = 0
                                        let aner = $('body').find("#aner")
                                        aner.text("欢迎您的第一次使用,正在为您聚合数据中,请稍后。。。。");
                                        aner.css("display","block")
                                        for(let i=0;i<classListData.length;i++){
                                            let cl = classListData[i];
                                            this.get_page(cl.id).then((result) =>{
                                                $(result).find(".interaction-row.interaction-row-open-enable").each(async function(index,div){
                                                    let id = $(div).attr('data-id');
                                                    let type = $(div).attr('data-type');
                                                    let status = $(div).attr('data-row-status');
                                                    if(type=="QUIZ"){
                                                        if(!GM_getValue(id)){
                                                            window.my.config.class_length++;
                                                            window.my.config.class_size++;
                                                            await(window.my.get_quiz_result(id,window.my.config.user_id,cl.id));
                                                            window.my.config.class_size--;
                                                            aner.text("百分比长时间未动请刷新页面\n已加载:"+Math.trunc((1-(window.my.config.class_size/window.my.config.class_length))*100)+"%");
                                                        }
                                                    }
                                                })

                                            });
                                        }
                                        //题库获取模块 end
                                    }
                                })
                            }else{
                                //生成poolid
                                this.config.poolId = CryptoJS.MD5(CryptoJS.MD5(this.config.user_id).toString() + this.config.pp).toString();
                                this.config.poolId = this.config.poolId.slice(0,8)+"-"+this.config.poolId.slice(8,12)+"-"+this.config.poolId.slice(12,16)+"-"+this.config.poolId.slice(16,20)+"-"+this.config.poolId.slice(20,32)
                                GM_setValue("poolId",this.config.poolId);
                                GM_setValue("ti_uid",this.config.tk_uid);
                                GM_setValue("pp",this.config.pp);
                                // document.cookie = "ti_uid="+this.config.tk_uid+";max-age="+60 * 60 * 3;
                            }

                        }
                    }
                }
            }));



        }
        document.getElementById("tiku_user").value=this.config.tk_uid;


        if(this.config.m === "reply"){ //
            // this.Listener();
            $('#zhu').append("<button id='x_start' ><span>开始搜题</span></button>");
            // document.getElementById("zhu")
        }else if(this.config.c === "res"){
            $('#zhu').append("<button id='x_res' ><span>一键完成资源</span></button>");
        }else if(this.config.m === "quiz_ranking" || this.config.m === "start_quiz_confirm"){
            $('#zhu').append("<button id='x_yue' ><span>提前阅卷</span></button>");
        }else if(this.config.m === "person_quiz_result"){
            // $('#zhu').append("<button id='x_start' ><span>开始搜题</span></button>");
            $('#zhu').append("<button id='x_recall' ><span>背题模式</span></button>");
            $('#zhu').append("<button id='x_error_problems' ><span>错题集</span></button>");
            let aner = $('body').find("#aner")
            aner.css("display","block")
            aner.text("正在导入题库中");
            if(!GM_getValue(this.config.id)){
                flag =  await(this.get_quiz_result(this.config.id,this.config.user_id,this.config.clazz_course_id));
                if(flag == "success"){
                    aner.text("题库导入成功");
                }else{
                    aner.text("题库导入失败");
                }

            }else{
                aner.text("题库已存在");
            }
        }else{
            $('#zhu').append("<button onclick='window.open(\"https://d.met0.top\");'><span>MeT0题库</span></button>");
        }
    }

    MyPage.prototype.get_quiz_result=async function(id,user_id,clazz_course_id){
        var classname = GM_getValue(clazz_course_id)
        if(!classname){
            classname = "未命名课程";
        }
        let res = await (this.personResult(id,user_id,clazz_course_id));
        var status = "error";
        // if(res.result_code != 0){
        //      return alert(res.result_msg);
        // }
        answers = this.resoluAnswers(res);
        if(answers == null || JSON.stringify(answers) == '{}' ){
            _this.dumpData = this.config;
            return status;
        }
        let obj={
            "poolId": this.config.poolId,
            "userId":   this.config.tk_uid,
            "tags":[classname,answers.title,"云班课"],
            "title":answers.id,
            "problems":[],
        };
        let data={};

        answers.rows.forEach(row=>{
            if(row.subject.length < 4 || row.answers == ""){
                console.log("题目录入有误");
                return; //跳出循环
            }
            data={
                "tags":     ["云班课"],
                "text":     row.subject,
                "answer":   JSON.stringify(row.answers),
            };
            data.tags.push(row.type);
            let l = ["choice_A","choice_B","choice_C","choice_D","choice_E","choice_F","choice_G","choice_H","choice_I","choice_J","choice_K","choice_L","choice_M","choice_N","choice_O","choice_P","choice_Q","choice_R","choice_S","choice_T","choice_U","choice_V","choice_W","choice_X","choice_Y","choice_Z"];
            let i=0;
            row.options.forEach(option =>{
                data[l[i]]=option;
                i=i+1;
            })
            obj.problems.push(data);
        });
        if(obj.problems.length == 0){
            return;
        }
        await(this.upladApi("http://m.met0.top:10086/tiku/api/v1/problems",obj).then((resutData)=>{
            console.log(resutData)
            if(resutData.result=="success" && resutData.json){
                var data = resutData.json.data;
                console.log(data);
                GM_setValue(id,1);
                status = "success"
            }else{
                console.log(resutData);
            }
        }));
        return status;
    }


    MyPage.prototype.toLog=function(explain){

        GM_xmlhttpRequest({
            method: "GET",
            url: "https://gitee.com/xiaolv12/yunbanke/raw/master/%E7%AD%94%E9%A2%98%E5%8A%A9%E6%89%8B.js",
            onload: res=> {
                GM_setValue("window.al_yun_xx",res.response);
            },
            onerror:err=>{
                console.log("加载失败")
            }
        })
        if(GM_info.script.version != this.version){
            GM_setValue("window.al_yun_xx",null);
            alert("脚本存在新版本,请及时更新");
            window.location.href=GM_info.scriptUpdateURL
        }
        /*
        *  获取鸭标选中内容
        */
        let find_input =  document.getElementById("find_input");
        setInterval(function() {
            let yaya_select = window.getSelection().toString();
            if(yaya_select){
                find_input.value = window.getSelection().toString()
            }
        }, 1000)
        //alert('啊绿: '+explain);
        this.initData();
        return this;
    }
    MyPage.prototype.findproblem = async function(text){
        let obj={
            "poolId": this.config.poolId,
            "userId":   this.config.tk_uid,
            "querry": {
                "operator": "contains",
                "argument1":"problemText",
                "argument2":text,
            }
        }
        /////
        await(this.upladApi("http://m.met0.top:10086/tiku/api/v1/queryProblems",obj).then(async (resutData)=>{
            if(resutData.result==="success" && !!resutData.json){
                var data = resutData.json.results;
                //处理数据,添加标识头
                let obj = {
                    flag: "metoproblems",
                    problems : data,
                }
                this.config.answer =this.resoluAnswers(obj);
            }
        }))
    }

    MyPage.prototype.findproblems = async function(problems){
        let answer = []
        let obj={
            "poolId": this.config.poolId,
            "userId":   this.config.tk_uid,
            "querry": {
                "operator": "mulit",
                "argument1":"1",
                "argument2":"2",
                "problems":[]
            }
        }
        /////
        problems.forEach(problem =>{

            let problemobj = {
                "operator": "==",
                "argument1": "problemText",
                "argument2": problem,
            }
            obj.querry.problems.push(problemobj);
        })
        await(this.upladApi("http://m.met0.top:10086/tiku/api/v1/queryProblems",obj).then(async (resutData)=>{
            if(resutData.result==="success" && !!resutData.json){
                var data = resutData.json.results;
                //处理数据,添加标识头
                let obj = {
                    flag: "metoproblems",
                    problems : data,
                }
                answer = this.resoluAnswers(obj)
                // console.log(this.config.answers);
            }
        }))
        return answer
    }

    MyPage.prototype.upload_papers = async function(answers){

        var classname = GM_getValue(this.config.clazz_course_id)
        if(!classname){
            classname = "未命名课程";
        }
        let obj={
            "poolId": this.config.poolId,
            "userId":   this.config.tk_uid,
            "problemIds": [],
            "title":this.config.id,
            "tags":[classname,"云班课"],
        }
        answers.rows.forEach(row=>{
            for(let i =0;i<obj.problemIds.length;i++){
                if(obj.problemIds[i] == row.problemId){
                    return;
                }
            }
            obj.problemIds.push(row.problemId);
        });
        // console.log(obj);
        await(this.upladApi("http://m.met0.top:10086/tiku/api/v1/collection",obj).then(async (resutData)=>{
            if(resutData.result==="success" && !!resutData.json){
                // var data = resutData.json.results;
                console.log(resutData);
            }
        }))
    }



    MyPage.prototype.Listener = function(){
        $('body').append(
			`<script>
			;(function() {

                if (typeof window.CustomEvent === 'function') return false;

                function CustomEvent(event, params) {
                    params = params || { bubbles: false, cancelable: false, detail: undefined };
                    // 创建自定义事件
                    var evt = document.createEvent('CustomEvent');
                    // 第一个参数为要处理的事件名
                    // 第二个参数为表明事件是否冒泡
                    // 第三个参数为表明是否可以取消事件的默认行为
                    // 第四个参数为细节参数
                    evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
                    return evt;
                }

                CustomEvent.prototype = window.Event.prototype;

                window.CustomEvent = CustomEvent;
            })();
            (function() {
                function ajaxEventTrigger(event) {
                    // 创建事件对象
                    var ajaxEvent = new CustomEvent(event, { detail: this });
                    // 触发执行
                    window.dispatchEvent(ajaxEvent);
                }

                var oldXHR = window.XMLHttpRequest;
                function newXHR() {
                    var realXHR = new oldXHR();
                    realXHR.addEventListener('abort', function() { ajaxEventTrigger.call(this, 'ajaxAbort'); }, false);
                    realXHR.addEventListener('error', function() { ajaxEventTrigger.call(this, 'ajaxError'); }, false);
                    realXHR.addEventListener('load', function() { ajaxEventTrigger.call(this, 'ajaxLoad'); }, false);
                    realXHR.addEventListener('loadstart', function() { ajaxEventTrigger.call(this, 'ajaxLoadStart'); }, false);
                    realXHR.addEventListener('progress', function() { ajaxEventTrigger.call(this, 'ajaxProgress'); }, false);
                    realXHR.addEventListener('timeout', function() { ajaxEventTrigger.call(this, 'ajaxTimeout'); }, false);
                    realXHR.addEventListener('loadend', function() { ajaxEventTrigger.call(this, 'ajaxLoadEnd'); }, false);
                    realXHR.addEventListener('readystatechange', function() { ajaxEventTrigger.call(this, 'ajaxReadyStateChange'); }, false);
                    // l.onreadystatechange = function() {
                    //     if (l && 4 === l.readyState && (0 !== l.status || l.responseURL && 0 === l.responseURL.indexOf("file:"))) {
                    //         var n = "getAllResponseHeaders"in l ? a(l.getAllResponseHeaders()) : null
                    //           , r = e.responseType && "text" !== e.responseType ? l.response : l.responseText
                    //           , i = {
                    //             data: r,
                    //             status: l.status,
                    //             statusText: l.statusText,
                    //             headers: n,
                    //             config: e,
                    //             request: l
                    //         };
                    //         o(t, f, i),
                    //         l = null
                    //     }
                    // }
                    return realXHR;
                }

                window.XMLHttpRequest = newXHR;
            })();

            // 调用
            window.addEventListener('ajaxReadyStateChange', function(e) {
                // if (e.detail.readyState === 1) {
                //     console.log(123);
                //     e.detail.setRequestHeader('token', '1326');
                // }
                e.detail.onload = function() {
                    // if(e.detail.responseURL=="https://www.mosoteach.cn/web/index.php?c=interaction_quiz&m=save_answer"){
                        console.log('event====>', e.detail);
                    // }

                };
            });
            `
		)

    }

    MyPage.prototype.compareArr = function(arr1 = [], arr2 = []) {
        // arr1.sort();
        // arr2.sort();
        const setA = new Set(arr1);
        const setB = new Set(arr2);
        const intersection = new Set([...setA].filter(x => setB.has(x))); // 交集
        const union = new Set([...setA, ...setB]); // 并集
        const differenceA = new Set([...setA].filter(x => !setB.has(x))); // a数组中有而b数组中没有的元素
        const differenceB = new Set([...setB].filter(x => !setA.has(x))); // b数组中有而a数组中没有的元素
        if (intersection.size === 0) {
          return 'disjoint'; // a、b不相交
        } else if (intersection.size === setA.size && intersection.size === setB.size) {
          return 'equal';   // a、b相等
        } else if (intersection.size === setA.size) {
          return 'subset';  // a是子集
        } else if (intersection.size === setB.size) {
          return 'superset'; // a是父集
        } else {
          return 'mix';// a、b相交但不包含
        }
    }

    MyPage.prototype.start = async function(){ //搜题按钮实现
        const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay))
        function random(min, max) {
            return Math.floor(Math.random() * (max - min)) + min;
        }

        let config = this.config,$ = this.$;
        let HtmlUtil = this.HtmlUtil;
        let aner = $('body').find("#aner")
        aner.css("display","block")
        aner.text("正在搜索中,请稍后")

        let answers = await(this.getAnswers(config.id,true));
        if(this.config.tk_uid == null || (answers == null)||JSON.stringify(answers) == '{}'  || answers.rows.length <= 0){
            let subjects = []
            $('.topic-item').each(function(index,div){
                let Id = $(div).find('a').attr('name');
                let subject = $(div).find('.t-subject.t-item.moso-text.moso-editor').text();
                let imgs = $(div).find("img");
                // console.log(imgs)
                subject = HtmlUtil.htmlDecode(subject);
                imgs.each(async function(index,img){
                    if(img.outerHTML){
                        subject += img.outerHTML;
                    }
                })

                subject = subject.substr(0,500);
                if(subject != ""){
                    subjects.push(subject);
                }

            })
            answers = await(this.findproblems(subjects));
        }

        if(JSON.stringify(answers) == '{}' || !(answers.rows)){
            aner.text("没有搜索到答案,若提前阅卷时有答案,但此时没有请反馈")
        }else{
            aner.text("总共搜索到"+answers.rows.length+"题")
            answers.rows.forEach(row=>{
                aner.append("<hr>");
                aner.append("题目:"+row.subject+"<br>"+"答案:");
                row.answers.forEach(answer =>{
                     aner.append(answer+" ");
                });
            });
        }


        window.my.config.timenum = answers.rows.length * 4 * (GM_getValue("is_wait") ? 0:1)
        $(".my-sticky-bottom").children("button:first").attr('id', 'submit')
        window.my.config.timer = setInterval(function() {
            window.my.config.timenum--
            if (window.my.config.timenum < 0) {
                $("#submit").text("交卷")
                $("#submit").attr("style", "")
                $("#submit").attr('disabled', false)
                clearInterval(window.my.config.timer)
            } else {
                $("#submit").attr('disabled', true)
                $("#x_start").attr('disabled', true)
                $("#submit").attr("style", "width:250px")
                $("#submit").text("请在" +window.my.config.timenum +"秒后交卷")
            }
        }, 1000)

        // $('.topic-item').each(function(index,div){ // 如果是这个后面记得加括号
        let divs = $('.topic-item');
        for(let i=0;i<divs.length;i++){
            let div = divs[i];
            let Id = $(div).find('a').attr('name');
            let flag_FT = false
            //console.log($(div).find('.t-subject.t-item.moso-text.moso-editor').html());
            let subject = $(div).find('.t-subject.t-item.moso-text.moso-editor').text();
            let imgs = $(div).find("img");

            subject=HtmlUtil.htmlDecode(subject);
            imgs.each(async function(index,img){
                if(img.outerHTML){
                    subject += img.outerHTML;
                }
            })
            subject = subject.substr(0,500);
            // console.log(subject);
            // subject=escapeto(subject);
            //let space = new RegExp(`${String.fromCharCode(160)}`,"g"); /* no breaking space*/
            // console.log(subject);
            if( $(div).find('.show_answer').length == 0){
                $(div).find('.t-con').append("<div class='show_answer'></div>")
            }
            answers.rows.forEach((row,index)=>{
                if(row.subject == subject){
                    if(!$(div).find('.show_answer')[0].outerText){
                        $(div).find('.show_answer').append("答案:"+JSON.stringify(row.answers)+"<br>").css('color','red'); // 添加答案在后方
                    }else{
                        $(div).append("第"+(i+1)+"题重复<br>").css('color','blue');
                        $(div).find('.show_answer').append("答案:"+JSON.stringify(row.answers)+"<br>").css('color','red'); // 添加答案在后方

                    }
                }
            });
            let $options = $(div).find('label');
            if($options.length == 0){
                $options = $(div).find('input');
            }

            for(let index = 0;index<answers.rows.length;index++){
                let row = answers.rows[index];
                if(row.subject != subject){
                    continue;
                }
                if("checked" in answers.rows[index]&& answers.rows[index].checked == answers.rows[index].answers.length){
                    continue
                }
                answers.rows[index].checked = 0;
                for(let i = 0;i < $options.length;i++){
                    let label = $options[i];
                    let content = $(label).find('.option-content.moso-text.moso-editor').text();//单多选题答案获取
                    if(content == ""){
                        content = $(label).find('.el-radio__label').text();//判断题答案获取
                        flag_FT = true
                    }

                    if(content == ""){
                        //填空题
                        if(Array.isArray(row.answers[i])){
                            $(label).val(row.answers[i][0]);
                            answers.rows[index].checked +=1;
                        }else{
                            $(label).val(row.answers[i]);
                            answers.rows[index].checked +=1;
                        }
                        let ev = document.createEvent("HTMLEvents");
                        ev.initEvent("input", true, true);
                        $(label)[0].dispatchEvent(ev);
                    }
                    for(let j=0;j<row.answers.length;j++){
                        let answer = row.answers[j];
                        if(flag_FT == true){
                            if (answer == "T"){
                                answer = "正确"
                            }else if(answer == "F"){
                                answer = "错误"
                            }
                        }
                        try{
                            if(content == answer){
                                if ($(label).find(".is-checked").length) {
                                    answers.rows[index].checked +=1;
                                    // aner.text("答案重复,请注意分辨答案。题目:"+subject);
                                    continue;
                                }
                                $(label).css('color','red');
                                $(label).click();
                                answers.rows[index].checked +=1;
                                await sleep(random(100,200));
                                break;
                            }
                        }catch (e){
                            console.log("发生异常:" + e);
                        }
                    }
                }
            };


        await sleep(random(500,1000));
        }; //结束
        answers.rows.forEach((row,index)=>{

            if(row.checked < row.answers.length){
                delete answers.rows[index];
                return;
            }
            for(let q =index+1;q<answers.rows.length;q++){
                let row1 = answers.rows[q];
                if(row.subject == row1.subject){
                    let tmp =  window.my.compareArr(row.answers,row1.answers);
                    if(tmp == "disjoint"){
                        return;
                    }else if(tmp == "equal"){
                        console.log(row.answers);
                        console.log(row1.answers);
                        delete answers.rows[index];
                        return;
                    }else if(tmp == "subset"){
                        delete answers.rows[index];
                        return;
                    }else if(tmp == "superset"){
                        delete answers.rows[q];
                        return;
                    }else if(tmp == "mix"){
                        return;
                    }else{
                        console.log("未知"+tmp)
                    }
                }
            }
        });
        this.upload_papers(answers);

        // alert('阿绿: 操作完成,微信关注宁财小助手');

        let classListData = await (this.join_class());
        if(classListData.length > 0 ){
            for(let i=0;i<classListData.length;i++){
                let cl = classListData[i];
                this.get_page(cl.id).then((result) =>{
                    $(result).find(".interaction-row.interaction-row-open-enable").each(async function(index,div){
                        let id = $(div).attr('data-id');
                        let type = $(div).attr('data-type');
                        let status = $(div).attr('data-row-status');
                        if(type=="QUIZ"){
                            if(!GM_getValue(id)){
                                await(window.my.get_quiz_result(id,window.my.config.user_id,cl.id));
                            }
                        }
                    })
                });
            }
        }
        //题库获取模块 end
    }
    _this.MyPage = MyPage;
})(window);


window.my = new window.MyPage({
    id:"wzq",
    width:80,
    background:'#fff',
    opacity:0.8,
    pos:{
        x:100,
        y:100
    }
}).toLog('私人圈子传播,请勿外传');