function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

String.prototype.format = function(args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if(args[key]!=undefined){
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    var reg= new RegExp("({)" + i + "(})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
}


String.prototype.similar = function (t, f) {
    var s = this.toString();
    if (!s || !t) {
        return 0
    }
    var l = s.length > t.length ? s.length : t.length
    var n = s.length
    var m = t.length
    var d = []
    f = f || 3
    var min = function(a, b, c) {
        return a < b ? (a < c ? a : c) : (b < c ? b : c)
    }
    var i, j, si, tj, cost
    if (n === 0) return m
    if (m === 0) return n
    for (i = 0; i <= n; i++) {
        d[i] = []
        d[i][0] = i
    }
    for (j = 0; j <= m; j++) {
        d[0][j] = j
    }
    for (i = 1; i <= n; i++) {
        si = s.charAt(i - 1)
        for (j = 1; j <= m; j++) {
            tj = t.charAt(j - 1)
            if (si === tj) {
                cost = 0
            } else {
                cost = 1
            }
            d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost)
        }
    }
    let res = (1 - d[n][m] / l)
    return res.toFixed(f)
}


async function waitAndClickIfExist(selector, times, interval) {
    var _times = times || 30, //30次
        _interval = interval || 100, //100毫秒每次
        _result = false;

    for(let i = 0; i< _times; i++){
            elems = $(selector);
            if(elems.length){
                elems[0].click();
                _result = true;
                break;
            }
            await sleep(_interval);
    }
    return Promise.resolve(_result);
};


function focusAndInsertText(selector, textValue) {
    document.querySelector(selector).focus(),
    document.execCommand("selectAll", !1, null),
    document.execCommand("insertText", !1, textValue)
};


function showSimpleMessage(message, time) {
    if (typeof layui == 'undefined') {  //未注入layui的页面的弹层提示
        showSimpleMessageInjected(message, time);
        return ;
    }

    let layer = layui.layer;
    layer.msg(message, {
        time: time || 500,
        offset: ['45%', '45%'],
        success: function () {
            $("div[id^='layui-layer']").each(function (i, elem) {
                $(elem).css("z-index","198910150");
            });
        }
    });
}


function showMessage(message, time) {
    if (typeof layui == 'undefined') {  //未注入layui的页面的弹层提示
        showMessageInjected(message, time);
        return ;
    }

    var elems = $('#layui-layer-msg-crx');
    // console.log(elems);
    if (elems.length){
        elems.html(elems.html() + '<br>' + message);
    } else {
        var layer = layui.layer;
        layer.msg(message, {
            id: 'layui-layer-msg-crx',
            time: time || -1,
            offset: ['45%', '45%'],
            shade : [0.5 , '#000' , true],
            btn: ['确定'],
            yes: function(index, layero){
                layer.close(index);
            },
            success: function () {
                $("div[id^='layui-layer']").each(function (i, elem) {
                    $(elem).css("z-index","198910150");
                });
            }
        });
    }
}


function showConfirmMessage(message, time, callback) {
    var layer = layui.layer;
    layer.msg(message, {
        time: time || -1,
        offset: ['45%', '45%'],
        shade : [0.5 , '#000' , true],
        btn: ['确定', '取消'],
        yes: function(index, layero){
            layer.close(index);
            typeof callback == 'function' && callback();
        },
        cancel: function(index, layero){
            layer.close(index);
        },
        success: function () {
            $("div[id^='layui-layer']").each(function (i, elem) {
                $(elem).css("z-index","198910150");
            });
        }
    });
}


function showMessageCountDown(timeCount, callback) {
    var layer = layui.layer;
    var cancelFlag = false;
    layer.msg('(' + timeCount + ')' + '秒后提交订单', {
        time: 20000,
        // shade: 0.6,
        btn: ['取消'],
        success: function (layero, index) {
            var msg = layero.text().replace('取消', '');
            var i = timeCount;
            var timer = null;
            var fn = function () {
                layero.find(".layui-layer-content").text(msg.replace(/\d+/g, i));
                if (!i) {
                    layer.close(index);
                    clearInterval(timer);
                }
                i--;
            };
            timer = setInterval(fn, 1000);
        },
        yes: function (index, layero) {
            layer.close(index);
            cancelFlag = true;
        }
    }, function () {
        console.log('layer msg end');
        !cancelFlag && typeof callback == 'function' && callback();
    });
}


function showSimpleMessageInjected(message, time) {
    var tempElem = document.createElement('script');
    tempElem.setAttribute('type', 'text/javascript');
    tempElem.setAttribute('id', 'showSimpleMessageInjected');
    tempElem.innerHTML = '$(\'#showSimpleMessageInjected\').remove();layer.msg(\'{0}\',{time:{1},offset:[\'45%\',\'45%\'],success:function(){$("div[id^=\'layui-layer\']").each(function(i,elem){$(elem).css("z-index","198910150")})}});'.format(message, time || 500);
    document.head.appendChild(tempElem);
}


function showMessageInjected(message, time) {
    var tempElem = document.createElement('script');
    tempElem.setAttribute('type', 'text/javascript');
    tempElem.setAttribute('id', 'showMessageInjected');
    tempElem.innerHTML = '$(\'#showMessageInjected\').remove();layer.msg(\'{0}\',{id:\'layui-layer-msg-crx\',time:{1},offset:[\'45%\',\'45%\'],shade:[0.5,\'#000\',true],btn:[\'确定\'],yes:function(index,layero){layer.close(index)},success:function(){$("div[id^=\'layui-layer\']").each(function(i,elem){$(elem).css("z-index","198910150")})}});'.format(message, time || -1);
    document.head.appendChild(tempElem);
}


function timeStampToDate(secondTime) {
    var date = new Date(parseInt(secondTime)*1000);
    return '{0}-{1}-{2} {3}:{4}:{5}'.format(date.getFullYear(), (date.getMonth() + 1).toString().padStart(2, '0'), date.getDate().toString().padStart(2, '0'), date.getHours().toString().padStart(2, '0'), date.getMinutes().toString().padStart(2, '0'), date.getSeconds().toString().padStart(2, '0'));
}


function copyValueToClipboard(value) {
    var textarea = document.createElement('textarea');
    textarea.readOnly = 'readonly';
    textarea.style.position = 'absolute';
    textarea.style.left = '-9999px';
    textarea.value = value;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('Copy');
    textarea.remove();
}


function prefixInteger(num, n) {
    return (Array(n).join('0') + num).slice(-n);
}

function getTbSign(a) {function b(t,o){return t<<o|t>>>32-o}function c(t,o){var u,v,w,x,r;return w=2147483648&t,x=2147483648&o,r=(1073741823&t)+(1073741823&o),(u=1073741824&t)&(v=1073741824&o)?2147483648^r^w^x:u|v?1073741824&r?3221225472^r^w^x:1073741824^r^w^x:r^w^x}function d(t,o,u){return t&o|~t&u}function e(t,o,u){return t&u|o&~u}function f(t,o,u){return t^o^u}function g(t,o,u){return o^(t|~u)}function h(t,o,u,v,w,x,r){return c(b(t=c(t,c(c(d(o,u,v),w),r)),x),o)}function i(t,o,u,v,w,x,r){return c(b(t=c(t,c(c(e(o,u,v),w),r)),x),o)}function j(t,o,u,v,w,x,r){return c(b(t=c(t,c(c(f(o,u,v),w),r)),x),o)}function k(t,o,u,v,w,x,r){return c(b(t=c(t,c(c(g(o,u,v),w),r)),x),o)}function l(t){for(var o,u=t.length,v=u+8,w=16*((v-v%64)/64+1),x=new Array(w-1),r=0,n=0;u>n;)r=n%4*8,x[o=(n-n%4)/4]=x[o]|t.charCodeAt(n)<<r,n++;return r=n%4*8,x[o=(n-n%4)/4]=x[o]|128<<r,x[w-2]=u<<3,x[w-1]=u>>>29,x}function m(t){var o,u="",v="";for(o=0;3>=o;o++)u+=(v="0"+(t>>>8*o&255).toString(16)).substr(v.length-2,2);return u}function n(t){t=t.replace(/\r\n/g,"\n");for(var o="",u=0;u<t.length;u++){var v=t.charCodeAt(u);128>v?o+=String.fromCharCode(v):v>127&&2048>v?(o+=String.fromCharCode(v>>6|192),o+=String.fromCharCode(63&v|128)):(o+=String.fromCharCode(v>>12|224),o+=String.fromCharCode(v>>6&63|128),o+=String.fromCharCode(63&v|128))}return o}var o,p,q,r,s,t,u,v,w,x=[],y=7,z=12,A=17,B=22,C=5,D=9,E=14,F=20,G=4,H=11,I=16,J=23,K=6,L=10,M=15,N=21;for(a=n(a),x=l(a),t=1732584193,u=4023233417,v=2562383102,w=271733878,o=0;o<x.length;o+=16)p=t,q=u,r=v,s=w,u=k(u=k(u=k(u=k(u=j(u=j(u=j(u=j(u=i(u=i(u=i(u=i(u=h(u=h(u=h(u=h(u,v=h(v,w=h(w,t=h(t,u,v,w,x[o+0],y,3614090360),u,v,x[o+1],z,3905402710),t,u,x[o+2],A,606105819),w,t,x[o+3],B,3250441966),v=h(v,w=h(w,t=h(t,u,v,w,x[o+4],y,4118548399),u,v,x[o+5],z,1200080426),t,u,x[o+6],A,2821735955),w,t,x[o+7],B,4249261313),v=h(v,w=h(w,t=h(t,u,v,w,x[o+8],y,1770035416),u,v,x[o+9],z,2336552879),t,u,x[o+10],A,4294925233),w,t,x[o+11],B,2304563134),v=h(v,w=h(w,t=h(t,u,v,w,x[o+12],y,1804603682),u,v,x[o+13],z,4254626195),t,u,x[o+14],A,2792965006),w,t,x[o+15],B,1236535329),v=i(v,w=i(w,t=i(t,u,v,w,x[o+1],C,4129170786),u,v,x[o+6],D,3225465664),t,u,x[o+11],E,643717713),w,t,x[o+0],F,3921069994),v=i(v,w=i(w,t=i(t,u,v,w,x[o+5],C,3593408605),u,v,x[o+10],D,38016083),t,u,x[o+15],E,3634488961),w,t,x[o+4],F,3889429448),v=i(v,w=i(w,t=i(t,u,v,w,x[o+9],C,568446438),u,v,x[o+14],D,3275163606),t,u,x[o+3],E,4107603335),w,t,x[o+8],F,1163531501),v=i(v,w=i(w,t=i(t,u,v,w,x[o+13],C,2850285829),u,v,x[o+2],D,4243563512),t,u,x[o+7],E,1735328473),w,t,x[o+12],F,2368359562),v=j(v,w=j(w,t=j(t,u,v,w,x[o+5],G,4294588738),u,v,x[o+8],H,2272392833),t,u,x[o+11],I,1839030562),w,t,x[o+14],J,4259657740),v=j(v,w=j(w,t=j(t,u,v,w,x[o+1],G,2763975236),u,v,x[o+4],H,1272893353),t,u,x[o+7],I,4139469664),w,t,x[o+10],J,3200236656),v=j(v,w=j(w,t=j(t,u,v,w,x[o+13],G,681279174),u,v,x[o+0],H,3936430074),t,u,x[o+3],I,3572445317),w,t,x[o+6],J,76029189),v=j(v,w=j(w,t=j(t,u,v,w,x[o+9],G,3654602809),u,v,x[o+12],H,3873151461),t,u,x[o+15],I,530742520),w,t,x[o+2],J,3299628645),v=k(v,w=k(w,t=k(t,u,v,w,x[o+0],K,4096336452),u,v,x[o+7],L,1126891415),t,u,x[o+14],M,2878612391),w,t,x[o+5],N,4237533241),v=k(v,w=k(w,t=k(t,u,v,w,x[o+12],K,1700485571),u,v,x[o+3],L,2399980690),t,u,x[o+10],M,4293915773),w,t,x[o+1],N,2240044497),v=k(v,w=k(w,t=k(t,u,v,w,x[o+8],K,1873313359),u,v,x[o+15],L,4264355552),t,u,x[o+6],M,2734768916),w,t,x[o+13],N,1309151649),v=k(v,w=k(w,t=k(t,u,v,w,x[o+4],K,4149444226),u,v,x[o+11],L,3174756917),t,u,x[o+2],M,718787259),w,t,x[o+9],N,3951481745),t=c(t,p),u=c(u,q),v=c(v,r),w=c(w,s);var O=m(t)+m(u)+m(v)+m(w);return O.toLowerCase()}

async function getCookies(url) {
    var cookies = await chrome.cookies.getAll({url: url});
    var values = [];
    for(var i = 0; i < cookies.length; i++){
        cookies[i].name && values.push(cookies[i].name + '=' + cookies[i].value);
    }
    return values.join('; ');
}