wpsjsrpcsdk.js 38.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
(function (global, factory) {

    "use strict";

    if (typeof module === "object" && typeof module.exports === "object") {
        module.exports = factory(global, true);
    } else {
        factory(global);
    }

})(typeof window !== "undefined" ? window : this, function (window, noGlobal) {

    "use strict";

    var bFinished = true;

    function getHttpObj() {
        var httpobj = null;
        if (IEVersion() < 10) {
            try {
                httpobj = new XDomainRequest();
            } catch (e1) {
                httpobj = new createXHR();
            }
        } else {
            httpobj = new createXHR();
        }
        return httpobj;
    }
    //兼容IE低版本的创建xmlhttprequest对象的方法
    function createXHR() {
        if (typeof XMLHttpRequest != 'undefined') { //兼容高版本浏览器
            return new XMLHttpRequest();
        } else if (typeof ActiveXObject != 'undefined') { //IE6 采用 ActiveXObject, 兼容IE6
            var versions = [ //由于MSXML库有3个版本,因此都要考虑
                'MSXML2.XMLHttp.6.0',
                'MSXML2.XMLHttp.3.0',
                'MSXML2.XMLHttp'
            ];

            for (var i = 0; i < versions.length; i++) {
                try {
                    return new ActiveXObject(versions[i]);
                } catch (e) {
                    //跳过
                }
            }
        } else {
            throw new Error('您的浏览器不支持XHR对象');
        }
    }

    function startWps(options) {
        if (!bFinished && !options.concurrent) {
            if (options.callback)
                options.callback({
                    status: 1,
                    message: "上一次请求没有完成"
                });
            return;
        }
        bFinished = false;

        function startWpsInnder(tryCount) {
            if (tryCount <= 0) {
                if (bFinished)
                    return;
                bFinished = true;
                if (options.callback)
                    options.callback({
                        status: 2,
                        message: "请允许浏览器打开WPS Office"
                    });
                return;
            }
            var xmlReq = getHttpObj();
            //WPS客户端提供的接收参数的本地服务,HTTP服务端口为58890,HTTPS服务端口为58891
            //这俩配置,取一即可,不可同时启用
            xmlReq.open('POST', options.url);
            xmlReq.onload = function (res) {
                bFinished = true;
                if (options.callback) {
                    options.callback({
                        status: 0,
                        response: IEVersion() < 10 ? xmlReq.responseText : res.target.response
                    });
                }
            }
            xmlReq.ontimeout = xmlReq.onerror = function (res) {
                xmlReq.bTimeout = true;
                if (tryCount == options.tryCount && options.bPop) { //打开wps并传参
                    window.location.href = "ksoWPSCloudSvr://start=RelayHttpServer" //是否启动wps弹框
                }
                setTimeout(function () {
                    startWpsInnder(tryCount - 1)
                }, 1000);
            }
            if (IEVersion() < 10) {
                xmlReq.onreadystatechange = function () {
                    if (xmlReq.readyState != 4)
                        return;
                    if (xmlReq.bTimeout) {
                        return;
                    }
                    if (xmlReq.status === 200)
                        xmlReq.onload();
                    else
                        xmlReq.onerror();
                }
            }
            xmlReq.timeout = options.timeout;
            xmlReq.send(options.sendData)
        }
        startWpsInnder(options.tryCount);
        return;
    }

    var fromCharCode = String.fromCharCode;
    // encoder stuff
    var cb_utob = function (c) {
        if (c.length < 2) {
            var cc = c.charCodeAt(0);
            return cc < 0x80 ? c :
                cc < 0x800 ? (fromCharCode(0xc0 | (cc >>> 6)) +
                    fromCharCode(0x80 | (cc & 0x3f))) :
                    (fromCharCode(0xe0 | ((cc >>> 12) & 0x0f)) +
                        fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) +
                        fromCharCode(0x80 | (cc & 0x3f)));
        } else {
            var cc = 0x10000 +
                (c.charCodeAt(0) - 0xD800) * 0x400 +
                (c.charCodeAt(1) - 0xDC00);
            return (fromCharCode(0xf0 | ((cc >>> 18) & 0x07)) +
                fromCharCode(0x80 | ((cc >>> 12) & 0x3f)) +
                fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) +
                fromCharCode(0x80 | (cc & 0x3f)));
        }
    };
    var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
    var utob = function (u) {
        return u.replace(re_utob, cb_utob);
    };
    var _encode = function (u) {
        var isUint8Array = Object.prototype.toString.call(u) === '[object Uint8Array]';
        if (isUint8Array)
            return u.toString('base64')
        else
            return btoa(utob(String(u)));
    }

    if (typeof window.btoa !== 'function') window.btoa = func_btoa;

    function func_btoa(input) {
        var str = String(input);
        var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
        for (
            // initialize result and counter
            var block, charCode, idx = 0, map = chars, output = '';
            // if the next str index does not exist:
            //   change the mapping table to "="
            //   check if d has no fractional digits
            str.charAt(idx | 0) || (map = '=', idx % 1);
            // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
            output += map.charAt(63 & block >> 8 - idx % 1 * 8)
        ) {
            charCode = str.charCodeAt(idx += 3 / 4);
            if (charCode > 0xFF) {
                throw new InvalidCharacterError("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
            }
            block = block << 8 | charCode;
        }
        return output;
    }

    var encode = function (u, urisafe) {
        return !urisafe ?
            _encode(u) :
            _encode(String(u)).replace(/[+\/]/g, function (m0) {
                return m0 == '+' ? '-' : '_';
            }).replace(/=/g, '');
    };

    function IEVersion() {
        var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串  
        var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器  
        var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器  
        var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
        if (isIE) {
            var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
            reIE.test(userAgent);
            var fIEVersion = parseFloat(RegExp["$1"]);
            if (fIEVersion == 7) {
                return 7;
            } else if (fIEVersion == 8) {
                return 8;
            } else if (fIEVersion == 9) {
                return 9;
            } else if (fIEVersion == 10) {
                return 10;
            } else {
                return 6; //IE版本<=7
            }
        } else if (isEdge) {
            return 20; //edge
        } else if (isIE11) {
            return 11; //IE11  
        } else {
            return 30; //不是ie浏览器
        }
    }

    function WpsStart(options) {
        var startInfo = {
            "name": options.name,
            "function": options.func,
            "info": options.param.param,
            "jsPluginsXml": options.param.jsPluginsXml
        };
        var strData = JSON.stringify(startInfo);
        if (IEVersion() < 10) {
            try {
                eval("strData = '" + JSON.stringify(startInfo) + "';");
            } catch (err) {

            }
        }

        var baseData = encode(strData);
        var url = options.urlBase + "/" + options.clientType + "/runParams";
        var data = "ksowebstartup" + options.clientType + "://" + baseData;
        startWps({
            url: url,
            sendData: data,
            callback: options.callback,
            tryCount: options.tryCount,
            bPop: options.bPop,
            timeout: 5000,
            concurrent: false,
            client: options.wpsclient
        });
    }

    function WpsStartWrap(options) {
        WpsStart({
            clientType: options.clientType,
            name: options.name,
            func: options.func,
            param: options.param,
            urlBase: options.urlBase,
            callback: options.callback,
            tryCount: 4,
            bPop: true,
            wpsclient: options.wpsclient,
        })
    }

    /**
     * 支持浏览器触发,WPS有返回值的启动
     *
     * @param {*} clientType	组件类型
     * @param {*} name			WPS加载项名称
     * @param {*} func			WPS加载项入口方法
     * @param {*} param			参数:包括WPS加载项内部定义的方法,参数等
     * @param {*} callback		回调函数
     * @param {*} tryCount		重试次数
     * @param {*} bPop			是否弹出浏览器提示对话框
     */
    var exId = 0;
    function WpsStartWrapExInner(options) {
        var infocontent = options.param.param;
        if (!options.wpsclient) {
            infocontent = JSON.stringify(options.param.param);
            var rspUrl = options.urlBase + "/transferEcho/runParams";
            var time = new Date();
            var cmdId = "js" + time.getTime() + "_" + exId;
            var funcEx = "var res = " + options.func;
            var cbCode = "var xhr = new XMLHttpRequest();xhr.open('POST', '" + rspUrl + "');xhr.send(JSON.stringify({id: '" + cmdId + "', response: res}));" //res 为func执行返回值
            var infoEx = infocontent + ");" + cbCode + "void(0";
            options.func = funcEx;
            infocontent = infoEx;
        }
        var startInfo = {
            "name": options.name,
            "function": options.func,
            "info": infocontent,
            "showToFront": options.param.showToFront,
            "jsPluginsXml": options.param.jsPluginsXml,
        };

        var strData = JSON.stringify(startInfo);
        if (IEVersion() < 10) {
            try {
                eval("strData = '" + JSON.stringify(startInfo) + "';");
            } catch (err) {

            }
        }

        var baseData = encode(strData);
        var wrapper;

        if (!options.wpsclient) {
            var url = options.urlBase + "/transfer/runParams";
            var data = "ksowebstartup" + options.clientType + "://" + baseData;
            wrapper = {
                id: cmdId,
                app: options.clientType,
                data: data
            };
        }
        else {
            var url = options.urlBase + "/transferEx/runParams";
            wrapper = {
                id: options.wpsclient.clientId,
                app: options.clientType,
                data: baseData,
                mode: options.wpsclient.silentMode ? "true" : "false"
            };
        }
        wrapper = JSON.stringify(wrapper);
        startWps({
            url: url,
            sendData: wrapper,
            callback: options.callback,
            tryCount: options.tryCount,
            bPop: options.bPop,
            timeout: 0,
            concurrent: options.concurrent,
            client: options.wpsclient
        });
    }

    var serverVersion = "wait"
    var cloudSvrStart = true;
    function WpsStartWrapVersionInner(options) {
        if (serverVersion == "wait") {
            if (cloudSvrStart == false) {
                window.location.href = "ksoWPSCloudSvr://start=RelayHttpServer" //是否启动wps弹框
            }
            startWps({
                url: options.urlBase + '/version',
                data: "",
                callback: function (res) {
                    if (res.status !== 0) {
                        options.callback(res)
                        return;
                    }
                    serverVersion = res.response;
                    cloudSvrStart = true;
                    options.tryCount = 1
                    options.bPop = false
                    if (serverVersion === "") {
                        WpsStart(options)
                    } else if (serverVersion < "1.0.1" && options.wpsclient) {
                        if (options.callback) {
                            options.callback({
                                status: 4,
                                message: "当前客户端不支持,请升级客户端"
                            })
                        }
                    } else {
                        WpsStartWrapExInner(options);
                    }
                },
                tryCount: 4,
                bPop: true,
                timeout: 5000,
                concurrent: options.concurrent
            });
        } else {
            if (serverVersion === "") {
                WpsStartWrap(options)
            } else if (serverVersion < "1.0.1" && options.wpsclient) {
                if (options.callback) {
                    options.callback({
                        status: 4,
                        message: "当前客户端不支持,请升级客户端"
                    })
                }
            } else {
                options.tryCount = 1
                options.bPop = true
                WpsStartWrapExInner(options);
            }
        }
    }

    var HeartBeatCode =
        "function getHttpObj() {\n"
+"            var httpobj = null;\n"
+"            if (IEVersion() < 10) {\n"
+"                try {\n"
+"                    httpobj = new XDomainRequest();\n"
+"                } catch (e1) {\n"
+"                    httpobj = new createXHR();\n"
+"                }\n"
+"            } else {\n"
+"                httpobj = new createXHR();\n"
+"            }\n"
+"            return httpobj;\n"
+"        }\n"
+"        \n"
+"        function createXHR() {\n"
+"            if (typeof XMLHttpRequest != 'undefined') {\n"
+"                return new XMLHttpRequest();\n"
+"            } else if (typeof ActiveXObject != 'undefined') {\n"
+"                var versions = [\n"
+"                    'MSXML2.XMLHttp.6.0',\n"
+"                    'MSXML2.XMLHttp.3.0',\n"
+"                    'MSXML2.XMLHttp'\n"
+"                ];\n"
+"        \n"
+"                for (var i = 0; i < versions.length; i++) {\n"
+"                    try {\n"
+"                        return new ActiveXObject(versions[i]);\n"
+"                    } catch (e) {\n"
+"                        \n"
+"                    }\n"
+"                }\n"
+"            } else {\n"
+"                throw new Error('您的浏览器不支持XHR对象');\n"
+"            }\n"
+"        }\n"
+"        \n"
+"        function IEVersion() {\n"
+"            var userAgent = navigator.userAgent; \n"
+"            var isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1;\n"
+"            var isEdge = userAgent.indexOf('Edge') > -1 && !isIE; \n"
+"            var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf('rv:11.0') > -1;\n"
+"            if (isIE) {\n"
+"                var reIE = new RegExp('MSIE (\\d+\\.\\d+);');\n"
+"                reIE.test(userAgent);\n"
+"                var fIEVersion = parseFloat(RegExp['$1']);\n"
+"                if (fIEVersion == 7) {\n"
+"                    return 7;\n"
+"                } else if (fIEVersion == 8) {\n"
+"                    return 8;\n"
+"                } else if (fIEVersion == 9) {\n"
+"                    return 9;\n"
+"                } else if (fIEVersion == 10) {\n"
+"                    return 10;\n"
+"                } else {\n"
+"                    return 6; \n"
+"                }\n"
+"            } else if (isEdge) {\n"
+"                return 20; \n"
+"            } else if (isIE11) {\n"
+"                return 11; \n"
+"            } else {\n"
+"                return 30; \n"
+"            }\n"
+"        }\n"
+"        var heartBeatStart = false;\n"
+"        function checkLastRegTime() {\n"
+"            var now = new Date().valueOf();\n"
+"            var TimeGap = now - LastRegTime;\n"
+"            if (TimeGap > 5000 && !heartBeatStart) {\n"
+"                HeartBeat();\n"
+"                heartBeatStart = true;\n"
+"            }\n"
+"        }\n"
+"        \n"
+"        function HeartBeat() {\n"
+"            var heartBeatItem = function () {\n"
+"                var xhr = getHttpObj();\n"
+"                xhr.onload = function (e) {\n"
+"                    self.setTimeout(heartBeatItem, 5000);\n"
+"                }\n"
+"                xhr.onerror = function (e) {\n"
+"                    self.setTimeout(heartBeatItem, 5000);\n"
+"                }\n"
+"                xhr.ontimeout = function (e) {\n"
+"                    self.setTimeout(heartBeatItem, 5000);\n"
+"                }\n"
+"                xhr.open('POST', 'http://127.0.0.1:58890/askwebnotify', true);\n"
+"                xhr.timeout = 2000;\n"
+"                xhr.send(JSON.stringify(paramStr));\n"
+"            }\n"
+"            heartBeatItem();\n"
+"        }\n"
+"        \n"
+"        var paramStr;\n"
+"        var startCheck = false;\n"
+"        self.addEventListener('message', function (event) {\n"
+"            var data = event.data;\n"
+"                paramStr = data.param\n"
+"                paramStr.heartBeat = true\n"
+"                LastRegTime = data.LastRegTime;\n"
+"                if (!startCheck) {\n"
+"                    startCheck = true;\n"
+"                    self.setInterval(checkLastRegTime, 5000)\n"
+"                }\n"
+"        }, false);\n"

    function codeToBlob(code) {
        var blob = new Blob([code], { type: 'text/javascript' }); // 生成js文件对象
        var objectURL = window.URL.createObjectURL(blob); // 生成js文件的url
        return objectURL;
    }

    var RegWebNotifyMap = { wps: {}, wpp: {}, et: {} }
    var bWebNotifyUseTimeout = true
    function WebNotifyUseTimeout(value) {
        bWebNotifyUseTimeout = value ? true : false
    }
    var g_businessId = Number(Math.random().toString().substr(3, 5) + Date.parse(new Date())).toString(36);
    var HeartBeatWorker
    if (window.Worker) {
        try {
            HeartBeatWorker = new Worker(codeToBlob(HeartBeatCode));
        } catch (error) {
            //
        }
    }
    var g_LastRegTime;
    /**
     * 注册一个前端页面接收WPS传来消息的方法
     * @param {*} clientType wps | et | wpp
     * @param {*} name WPS加载项的名称
     * @param {*} callback 回调函数
     */
    function RegWebNotify(clientType, name, callback, wpsclient) {
        if (clientType != "wps" && clientType != "wpp" && clientType != "et")
            return;
        var paramStr = {}
        if (wpsclient) {
            if (wpsclient.notifyRegsitered == true) {
                return
            }
            wpsclient.notifyRegsitered = true;
            paramStr = {
                clientId: wpsclient.clientId,
                name: name,
                type: clientType
            }
            if (HeartBeatWorker)
                paramStr.businessId = g_businessId
        }
        else {
            if (typeof callback != 'function')
                return
            if (RegWebNotifyMap[clientType][name]) {
                RegWebNotifyMap[clientType][name] = callback;
                return
            }
            var RegWebNotifyID = new Date().valueOf() + ''
            paramStr = {
                id: RegWebNotifyID,
                name: name,
                type: clientType
            }
            if (HeartBeatWorker)
                paramStr.businessId = g_businessId
            RegWebNotifyMap[clientType][name] = callback
        }

        var askItem = function () {
            var xhr = getHttpObj()
            xhr.onload = function (e) {
                if (xhr.responseText == "WPSInnerMessage_quit") {
                    RegWebNotifyMap[clientType][name] = undefined;
                    return;
                }
                try {
                    var resText = JSON.parse(xhr.responseText);
                    if(typeof resText == 'object'){
                        paramStr.messageId = resText.msgId;
                    } 
                    if (wpsclient) {
                        wpsclient.OnRegWebNotify(resText.data)
                    } else {
                        var func = RegWebNotifyMap[clientType][name]
                        func(resText.data)
                    }
                }
                catch (e) {
                    if (wpsclient) {
                        wpsclient.OnRegWebNotify(xhr.responseText)
                    } else {
                        var func = RegWebNotifyMap[clientType][name]
                        func(xhr.responseText)
                    }
                }
                window.setTimeout(askItem, 300)
            }
            xhr.onerror = function (e) {
                if (bWebNotifyUseTimeout)
                    window.setTimeout(askItem, 1000)
                else
                    window.setTimeout(askItem, 10000)
            }
            xhr.ontimeout = function (e) {
                if (bWebNotifyUseTimeout)
                    window.setTimeout(askItem, 300)
                else
                    window.setTimeout(askItem, 10000)
            }
            if (IEVersion() < 10) {
                xhr.onreadystatechange = function () {
                    if (xhr.readyState != 4)
                        return;
                    if (xhr.bTimeout) {
                        return;
                    }
                    if (xhr.status === 200)
                        xhr.onload();
                    else
                        xhr.onerror();
                }
            }
            xhr.open('POST', GetUrlBase() + '/askwebnotify', true)
            if (bWebNotifyUseTimeout)
                xhr.timeout = 2000;
            if (HeartBeatWorker){
                g_LastRegTime = new Date().valueOf();
                var param = {
                    param : {
                        name: projInfo.name,
                        type: projInfo.type,
                        businessId: g_businessId
                    },
                    LastRegTime: g_LastRegTime
                }
                HeartBeatWorker.postMessage(param)
            }
            xhr.send(JSON.stringify(paramStr));
        }
        window.setTimeout(askItem, 2000)
    }

    function GetUrlBase() {
        if (location.protocol == "http:")
            return "http://127.0.0.1:58890"
        return "https://127.0.0.1:58891"
    }

    function WpsStartWrapVersion(clientType, name, func, param, callback, showToFront, jsPluginsXml) {
        var paramEx = {
            jsPluginsXml: jsPluginsXml ? jsPluginsXml : "",
            showToFront: typeof (showToFront) == 'boolean' ? showToFront : true,
            param: (typeof (param) == 'object' ? param : JSON.parse(param))
        }
        var options = {
            clientType: clientType,
            name: name,
            func: func,
            param: paramEx,
            urlBase: GetUrlBase(),
            callback: callback,
            wpsclient: undefined,
            concurrent: true
        }
        WpsStartWrapVersionInner(options);
    }

    //从外部浏览器远程调用 WPS 加载项中的方法
    var WpsInvoke = {
        InvokeAsHttp: WpsStartWrapVersion,
        InvokeAsHttps: WpsStartWrapVersion,
        RegWebNotify: RegWebNotify,
        ClientType: {
            wps: "wps",
            et: "et",
            wpp: "wpp"
        },
        CreateXHR: getHttpObj,
        IsClientRunning: IsClientRunning
    }

    window.wpsclients = [];
    /**
     * @constructor WpsClient           wps客户端
     * @param {string} clientType       必传参数,加载项类型,有效值为"wps","wpp","et";分别表示文字,演示,电子表格
     */
    function WpsClient(clientType) {
        /**
         * 设置RegWebNotify的回调函数,加载项给业务端发消息通过该函数
         * @memberof WpsClient
         * @member onMessage
         */
        this.onMessage;

        /**
         * 设置加载项路径
         * @memberof WpsClient
         * @member jsPluginsXml
         */
        this.jsPluginsXml;

        /**
         * 内部成员,外部无需调用
         */
        this.notifyRegsitered = false;
        this.clientId = "";
        this.concurrent = false;
        this.clientType = clientType;
        this.firstRequest = true;

        /**
         * 内部函数,外部无需调用
         * @param {*} options 
         */
        this.initWpsClient = function (options) {
            options.clientType = this.clientType
            options.wpsclient = this
            options.concurrent = this.firstRequest ? true : this.concurrent
            this.firstRequest = false;
            WpsStartWrapVersionInner(options)
        }

        /**
         * 以http启动
         * @param {string} name              加载项名称
         * @param {string} func              要调用的加载项中的函数行
         * @param {string} param             在加载项中执行函数func要传递的数据
         * @param {function({int, string})} callback        回调函数,status = 0 表示成功,失败请查看message信息
         * @param {bool} showToFront         设置wps是否显示到前面来
         * @return {string}                  "Failed to send message to WPS." 发送消息失败,客户端已关闭;
         *                                   "WPS Addon is not response." 加载项阻塞,函数执行失败
         */
        this.InvokeAsHttp = function (name, func, param, callback, showToFront) {
            function clientCallback(res) {
                //this不是WpsClient
                if (res.status !== 0 || serverVersion < "1.0.1") {
                    if (callback) callback(res);
                    return;
                }
                var resObject = JSON.parse(res.response);
                if (this.client.clientId == "") {
                    this.client.clientId = resObject.clientId;
                }
                this.client.concurrent = true;
                if (typeof resObject.data == "object")
                    res.response = JSON.stringify(resObject.data);
                else
                    res.response = resObject.data;
                if (IEVersion() < 10)
                    eval(" res.response = '" + res.response + "';");
                if (callback)
                    callback(res);
                this.client.RegWebNotify(name);
            }
            var paramEx = {
                jsPluginsXml: this.jsPluginsXml ? this.jsPluginsXml : "",
                showToFront: typeof (showToFront) == 'boolean' ? showToFront : true,
                param: (typeof (param) == 'object' ? param : JSON.parse(param))
            }
            this.initWpsClient({
                name: name,
                func: func,
                param: paramEx,
                urlBase: GetUrlBase(),
                callback: clientCallback
            })
        }

        /**
         * 以https启动
         * @param {string} name              加载项名称
         * @param {string} func              要调用的加载项中的函数行
         * @param {string} param             在加载项中执行函数func要传递的数据
         * @param {function({int, string})} callback        回调函数,status = 0 表示成功,失败请查看message信息
         * @param {bool} showToFront         设置wps是否显示到前面来
         */
        this.InvokeAsHttps = function (name, func, param, callback, showToFront) {
            var paramEx = {
                jsPluginsXml: this.jsPluginsXml ? this.jsPluginsXml : "",
                showToFront: typeof (showToFront) == 'boolean' ? showToFront : true,
                param: (typeof (param) == 'object' ? param : JSON.parse(param))
            }
            this.initWpsClient({
                name: name,
                func: func,
                param: paramEx,
                urlBase: GetUrlBase(),
                callback: callback
            })
        }

        /**
         * 内部函数,外部无需调用
         * @param {*} name 
         */
        this.RegWebNotify = function (name) {
            RegWebNotify(this.clientType, name, null, this);
        }

        this.OnRegWebNotify = function (message) {
            if (this.onMessage)
                this.onMessage(message)
        }

        /**
         * 以静默模式启动客户端
         * @param {string} name                 必传参数,加载项名称
         * @param {function({int, string})} [callback]         回调函数,status = 0 表示成功,失败请查看message信息
         */
        this.StartWpsInSilentMode = function (name, callback) {
            function initCallback(res) {
                //this不是WpsClient
                if (res.status !== 0 || serverVersion < "1.0.1") {
                    if (callback) callback(res);
                    return;
                }
                if (this.client.clientId == "") {
                    this.client.clientId = JSON.parse(res.response).clientId;
                    window.wpsclients[window.wpsclients.length] = { name: name, client: this.client };
                }
                res.response = JSON.stringify(JSON.parse(res.response).data);
                this.client.concurrent = true;
                if (callback) {
                    callback(res);
                }
                this.client.RegWebNotify(name);
            }
            var paramEx = {
                jsPluginsXml: this.jsPluginsXml,
                showToFront: false,
                param: { status: "InitInSilentMode" }
            }
            this.silentMode = true;
            this.initWpsClient({
                name: name,
                func: "",
                param: paramEx,
                urlBase: GetUrlBase(),
                callback: initCallback
            })
        }

        /**
         * 显示客户端到最前面
         * @param {string} name             必传参数,加载项名称
         * @param {function({int, string})} [callback]     回调函数
         */
        this.ShowToFront = function (name, callback) {
            if (serverVersion < "1.0.1") {
                if (callback) {
                    callback({
                        status: 4,
                        message: "当前客户端不支持,请升级客户端"
                    });
                    return;
                }
                return;
            }
            if (this.clientId == "") {
                if (callback) callback({
                    status: 3,
                    message: "没有静默启动客户端"
                });
                return;
            }
            var paramEx = {
                jsPluginsXml: "",
                showToFront: true,
                param: { status: "ShowToFront" }
            }
            this.initWpsClient({
                name: name,
                func: "",
                param: paramEx,
                urlBase: GetUrlBase(),
                callback: callback
            })
        }

        /**
         * 关闭未显示出来的静默启动客户端
         * @param {string} name             必传参数,加载项名称
         * @param {function({int, string})} [callback]     回调函数
         */
        this.CloseSilentClient = function (name, callback) {
            if (serverVersion < "1.0.1") {
                if (callback) {
                    callback({
                        status: 4,
                        message: "当前客户端不支持,请升级客户端"
                    });
                    return;
                }
                return;
            }
            if (this.clientId == "") {
                if (callback) callback({
                    status: 3,
                    message: "没有静默启动客户端"
                });
                return;
            }
            var paramEx = {
                jsPluginsXml: "",
                showToFront: false,
                param: undefined
            }
            var func;
            if (this.clientType == "wps")
                func = "wps.WpsApplication().Quit"
            else if (this.clientType == "et")
                func = "wps.EtApplication().Quit"
            else if (this.clientType == "wpp")
                func = "wps.WppApplication().Quit"

            function closeSilentClient(res) {
                if (res.status == 0)
                    this.client.clientId = ""
                if (callback) callback(res);
                return;
            }
            this.initWpsClient({
                name: name,
                func: func,
                param: paramEx,
                urlBase: GetUrlBase(),
                callback: closeSilentClient
            })
        }

        /**
         * 当前客户端是否在运行,使用WpsClient.IsClientRunning()进行调用
         * @param {function({int, string})} [callback]      回调函数,"Client is running." 客户端正在运行
         *                                                  "Client is not running." 客户端没有运行
         */
        this.IsClientRunning = function (callback) {
            if (serverVersion < "1.0.1") {
                if (callback) {
                    callback({
                        status: 4,
                        message: "当前客户端不支持,请升级客户端"
                    });
                    return;
                }
                return;
            }
            IsClientRunning(this.clientType, callback, this)
        }
    }

    function InitSdk() {
        var url = GetUrlBase() + "/version";
        startWps({
            url: url,
            data: "",
            callback: function (res) {
                if (res.status !== 0) {
                    cloudSvrStart = false;
                    return;
                }
                if (serverVersion == "wait") {
                    serverVersion = res.response;
                    cloudSvrStart = true;
                }
            },
            tryCount: 1,
            bPop: false,
            timeout: 5000
        });
    }
    InitSdk();

    if (typeof noGlobal === "undefined") {
        window.WpsInvoke = WpsInvoke;
        window.WpsClient = WpsClient;
        window.WebNotifyUseTimeout = WebNotifyUseTimeout;
    }

    /**
     * 当前客户端是否在运行,使用WpsInvoke.IsClientRunning()进行调用
     * @param {string} clientType       加载项类型
     * @param {function} [callback]      回调函数,"Client is running." 客户端正在运行
     *                                   "Client is not running." 客户端没有运行
     */
    function IsClientRunning(clientType, callback, wpsclient) {
        var url = GetUrlBase() + "/isRunning";
        var wrapper = {
            id: wpsclient == undefined ? undefined : wpsclient.clientId,
            app: clientType
        }
        wrapper = JSON.stringify(wrapper);
        startWps({
            url: url,
            sendData: wrapper,
            callback: callback,
            tryCount: 1,
            bPop: false,
            timeout: 2000,
            concurrent: true,
            client: wpsclient
        });
    }

    function WpsAddonGetAllConfig(callBack) {
        var baseData;
        startWps({
            url: GetUrlBase() + "/publishlist",
            type: "GET",
            sendData: baseData,
            callback: callBack,
            tryCount: 3,
            bPop: true,
            timeout: 5000,
            concurrent: true
        });
    }

    function WpsAddonVerifyStatus(element, callBack) {
        var xmlReq = getHttpObj();
        var offline = element.online === "false";
        var url = offline ? element.url : element.url + "ribbon.xml";
        xmlReq.open("POST", GetUrlBase() + "/redirect/runParams");
        xmlReq.onload = function (res) {
            if (offline && !res.target.response.startsWith("7z")) {
                callBack({ status: 1, msg: "不是有效的7z格式" + url });
            } else if (!offline && !res.target.response.startsWith("<customUI")) {
                callBack({ status: 1, msg: "不是有效的ribbon.xml, " + url })
            } else {
                callBack({ status: 0, msg: "OK" })
            }
        }
        xmlReq.onerror = function (res) {
            xmlReq.bTimeout = true;
            callBack({ status: 2, msg: "网页路径不可访问,如果是跨域问题,不影响使用" + url })
        }
        xmlReq.ontimeout = function (res) {
            xmlReq.bTimeout = true;
            callBack({ status: 3, msg: "访问超时" + url })
        }
        if (IEVersion() < 10) {
            xmlReq.onreadystatechange = function () {
                if (xmlReq.readyState != 4)
                    return;
                if (xmlReq.bTimeout) {
                    return;
                }
                if (xmlReq.status === 200)
                    xmlReq.onload();
                else
                    xmlReq.onerror();
            }
        }
        xmlReq.timeout = 5000;
        var data = {
            method: "get",
            url: url,
            data: ""
        }
        var sendData = FormatSendData(data)
        xmlReq.send(sendData);
    }

    function WpsAddonHandleEx(element, cmd, callBack) {
        var data = FormatData(element, cmd);
        startWps({
            url: GetUrlBase() + "/deployaddons/runParams",
            type: "POST",
            sendData: data,
            callback: callBack,
            tryCount: 3,
            bPop: true,
            timeout: 5000,
            concurrent: true
        });
    }

    function WpsAddonEnable(element, callBack) {
        WpsAddonHandleEx(element, "enable", callBack)
    }

    function WpsAddonDisable(element, callBack) {
        WpsAddonHandleEx(element, "disable", callBack)
    }

    function FormatData(element, cmd) {
        var data = {
            "cmd": cmd, //"enable", 启用, "disable", 禁用, "disableall", 禁用所有
            "name": element.name,
            "url": element.url,
            "addonType": element.addonType,
            "online": element.online,
            "version": element.version
        }
        return FormatSendData(data);
    }

    function FormatSendData(data) {
        var strData = JSON.stringify(data);
        if (IEVersion() < 10)
            eval("strData = '" + JSON.stringify(strData) + "';");
        return encode(strData);
    }
    //管理 WPS 加载项
    var WpsAddonMgr = {
        getAllConfig: WpsAddonGetAllConfig,
        verifyStatus: WpsAddonVerifyStatus,
        enable: WpsAddonEnable,
        disable: WpsAddonDisable,
    }

    if (typeof noGlobal === "undefined") {
        window.WpsAddonMgr = WpsAddonMgr;
    }

    return { WpsInvoke: WpsInvoke, WpsAddonMgr: WpsAddonMgr, version: "1.0.15" };
});