
/**
 * 用到的和业务相关的
 * 各种静态方法汇总
 * 
 * 获取修改链接参数
 * 获取cookie
 * 缓存相关
 * 数组相关
 * 
 */
export class GTool {
    /**
    * 获取url参数
    * @param name 字段名
    */
    // public static getQueryString(name): any {
    //     const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    //     const r = window.location.search.substr(1).match(reg);
    //     if (r != null) {
    //         return unescape(r[2]);
    //     }
    //     return null;
    // }

    /**
     * 获取链接字段信息
     * @param name 字段名
     */
    public static getParamString(name) {
        var paramUrl = window.location.search.substr(1);
        var paramStrs = paramUrl.split('&');
        var params = {};
        for (var index = 0; index < paramStrs.length; index++) {
            params[paramStrs[index].split('=')[0]] = decodeURIComponent(paramStrs[index].split('=')[1]);//考虑是否用decodeURI
        }
        return params[name];
    }

    /**
     * 替换或添加url里的参数
     * @param url 修改的url
     * @param arg 参数名
     * @param arg_val 参数值
     */
    public static changeURLArg(url: string, arg: string, arg_val: string | number) {
        var pattern = arg + '=([^&]*)';
        var replaceText = arg + '=' + arg_val;
        if (url.match(pattern)) {
            var tmp = '/(' + arg + '=)([^&]*)/gi';
            // tmp = url.replace(eval(tmp), replaceText);
            tmp = url.replace(new RegExp(tmp), replaceText);
            return tmp;
        } else {
            if (url.match('[\?]')) {
                return url + '&' + replaceText;
            } else {
                return url + '?' + replaceText;
            }
        }
    }

    /**
     * 获取cookie
     * @param key 
     */
    public static getCookie(key) {
        var arr1 = document.cookie.split("; ");//由于cookie是通过一个分号+空格的形式串联起来的，所以这里需要先按分号空格截断,变成[name=Jack,pwd=123456,age=22]数组类型；
        for (var i = 0; i < arr1.length; i++) {
            var arr2 = arr1[i].split("=");//通过=截断，把name=Jack截断成[name,Jack]数组；
            if (arr2[0] == key) {
                return decodeURIComponent(arr2[1]);
            }
        }
        return null
        //有些时候cookie还要分，范例如下
        // var str = GTool.getCookie("dcustom");
        // if (str) {
        //     //&分割
        //     var arr = str.split("&");
        //     for (var i = 0; i < arr.length; i++) {
        //         //找memberId
        //         if (arr[i].indexOf("memberId=") == 0) {
        //             var memberId = arr[i].replace("memberId=", "");
        //             if (memberId != "null") {                        
        //             }
        //         }
        //     }
        // }
    }

    /**
     * 读取缓存
     */
    public static readCache(key: string, type: string = 'localStorage') {
        if (!window.localStorage) {
            return false;
        }
        return window[type].getItem(key);
    }

    /**
     * 写缓存
     */
    public static writeCache(key: string, value: any = 'true', type: string = 'localStorage') {
        if (!window.localStorage) {
            // trace(Func.replace(SysLang.lang_012, [type]));
            return;
        }
        window[type].setItem(key, value);
    }

    /**
     * 获得cacheKey今日次数
     * 第二天归0重新计数
     * @param cacheKey 
     */
    public static returnTodayTimes(cacheKey: string): number {
        var year1 = this.readCache("year" + cacheKey);
        var month1 = this.readCache("month" + cacheKey);
        var day1 = this.readCache("day" + cacheKey);

        var date = new Date();
        var year2 = date.getFullYear().toString();
        var month2 = date.getMonth().toString();
        var day2 = date.getDate().toString();

        if (this.int(year2) <= this.int(year1)) {
            if (this.int(month2) <= this.int(month1)) {
                if (this.int(day2) <= this.int(day1)) {
                    return this.int(this.readCache(cacheKey));
                }
            }
        }
        //如果不是同一天了，归0
        var today = "0";
        this.writeCache("year" + cacheKey, year2);
        this.writeCache("month" + cacheKey, month2);
        this.writeCache("day" + cacheKey, day2);
        this.writeCache(cacheKey, today);
        return 0;
    }

    /**
     * 随机，两个参数时是数值范围，比如randomT(1,10),一个参数时是数组
     * @param e 
     * @param n 
     */
    public static randomT(e, n?) {
        return e && "number" == typeof e.length && e.length ? e[Math.floor(Math.random() * e.length)] : ("number" != typeof n && (n = e || 1, e = 0), e + Math.random() * (n - e))
    }

    /**
     * 从数组中移除一个元素
     * @param e 元素
     * @param arr 数组
     */
    public static removeEle(e, arr) {
        var index = arr.indexOf(e);
        if (index >= 0) {
            arr.splice(index, 1)
        }
    }

    /**
     * 数组中插入一个数值，按顺序的
     * 数组是从小到大的
     * @param num 
     * @param arr 
     */
    public static insert(num, arr) {
        for (var i = arr.length - 1; i >= 0; i--) {
            if (num > arr[i]) {
                //在arr[i]后加num
                arr.splice(i + 1, 0, num);
                break
            }
        }
    }

    /**
     * 获取start到end里的n个整数
     * @param start 0
     * @param end 19
     * @param n 3
     */
    public static getRandomNumber(start: number, end: number, n: number): number[] {
        var arr = [];
        for (var i = 0; i < n; i++) {
            var number = Math.floor(Math.random() * (end - start + 1) + start);
            if (arr.indexOf(number) < 0) {
                arr.push(number);
            } else {
                i--;
            }
        }
        return arr;
    }
    /**
     * 打乱数字数组，改变原数组
     * @param arr 
     */
    public static disturbNumberArr(arr: number[]) {
        arr.sort(function () {
            return (0.5 - Math.random());
        });
    }

    /**
     * 其实打乱数组取前几个就行
     * 随机取数组arr中count个元素，不改变原数组
     * @param arr 
     * @param count 
     */
    public static getRandomArrayElements(arr: any[], count: number) {
        var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
        //如果count大于等于数组长度，返回所有数组
        if (min <= 0) return shuffled;
        if (count <= 0) return [];
        //随机排序，然后取出后面的元素
        while (i-- > min) {
            index = Math.floor((i + 1) * Math.random());
            temp = shuffled[index];
            shuffled[index] = shuffled[i];
            shuffled[i] = temp;
        }
        return shuffled.slice(min);
    }
    /**
     * 随机取数组arr中count个元素，原数组减少count个
     * @param arr 
     * @param count 
     */
    public static getRandomArrayElementsEx(arr: any[], count: number): any[] {
        //如果count大于等于数组长度，返回所有数组
        if (arr.length <= count) return arr.slice();
        if (count <= 0) return [];
        var arrCopy = arr.slice();
        var outArr = [];
        while (count--) {
            var rand = Math.floor(Math.random() * arrCopy.length);
            var ele = arrCopy.splice(rand, 1)[0];
            outArr.push(ele);
        }
        return outArr
    }


    /**
     * 向下取整，或把字符串执行parseInt(字符串转数字取整数部分)
     * @param n 数字或字符串
     */
    private static int(n: any): number {
        return n >> 0;//~~n
    };

    /**
     * emoji正则式
     */
    public static emojiReg = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/ig


    /**
     * 在字符串间加空格
     * @param str 
     */
    public static addSpaceInString(str: string) {
        if (!str.length || str.length == 1) return str;
        var txt = "";
        //每个字符后加空格
        for (var i = 0; i < str.length - 1; i++) {
            txt = txt + str[i] + " ";
        }
        txt = txt + str[str.length - 1]
        return txt
    }

    /**
     * 初始化微信分享信息
     * 范例，到时随便改
     */
    public static initShare() {
        var shareTitleO = window["shareTitle"] || "";
        var shareDesc = window["shareDesc"] || "";
        var shareLink = window["shareLink"] || "";
        //带https，不然不显示图片
        //https://yun.duiba.com.cn/db_games/activity/etc/share.png
        var shareImg = window["shareImg"] || "";

        //朋友圈
        // var timelineLink = GTool.changeURLArg(shareLink, "channel", "7");
        //好友
        // var appMessageLink = GTool.changeURLArg(shareLink, "channel", "8");

        //微信分享参数,需在皮肤html写，或者用接口取
        // wx.config({
        //     debug: false,
        //     appId: '$wxappid',
        //     timestamp: '$wxtimestamp',
        //     nonceStr: '$wxnonceStr',
        //     signature: '$wxsignature',
        //     jsApiList: ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ']
        // });
        //微信分享
        window["wx"].ready(function () {
            var shareTitle = shareTitleO;  //【微信分享好友的标题
            var shareWord = shareDesc;  //【微信分享好友的描述
            var shareTitle2 = shareTitleO; //【微信分享朋友圈的标题
            var link = shareLink;  //【微信分享出去的链接地址
            // var tLink = timelineLink; //发送朋友圈链接
            // var aLink = appMessageLink; //发送好友链接
            var imgUrl = shareImg;  //【微信分享图标路径
            //监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口
            window["wx"].onMenuShareTimeline({
                title: shareTitle2,
                desc: shareTitle2,
                link: link,
                imgUrl: imgUrl,
                success: function (res) {
                }
            });
            //监听“分享给朋友”按钮点击、自定义分享内容及分享结果接口
            window["wx"].onMenuShareAppMessage({
                title: shareTitle,
                desc: shareWord,
                link: link,
                imgUrl: imgUrl,
                success: function (res) {
                }
            });
        });
        window["wx"].error(function (res) {
            // alert(JSON.stringify(res))
        });

        //下面接口方式
        $.ajax({
            type: 'get',
            url: 'http://activity.m.duiba.com.cn/wechatShare/getShareInfo/v2',
            data: { url: window.location.href },
            cache: false,
            dataType: 'json',
            success: function (data) {
                if (data.success) {
                    window["wx"].config({
                        debug: false,
                        appId: data.wxappid,
                        timestamp: data.wxtimestamp,
                        nonceStr: data.wxnonceStr,
                        signature: data.wxsignature,
                        jsApiList: ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'chooseImage']
                    });
                    window["wx"].ready(function () {

                    })
                }
            },
            error: function (data) {

            }
        });
    }

    /**
     * 根据权重roll
     * @param args 
     */
    public static roll(args: { item: any, weight: number }[]) {
        let sum_weight = 0;
        let result = null;
        const items = args.slice().map(item => (sum_weight += item.weight) && item);   // 计算总权重
        const random = Math.random() * sum_weight;              // 随机抽取的物品位置
        let start = 0;                                  // 区间的开始，第一个是为0
        while (items.length) {
            const item = items.shift();                   // 取出第一个商品
            const end = start + item.weight;    // 计算区间的结束
            if (random >= start && random <= end) {        // 如果随机数在这个区间内，说明抽中了该商品，终止循环
                result = item;
                break;
            }
            start = end;                                  // 当前区间的结束，作为下一个区间的开始
        }

        return result ? result.item : null;
        //console.log(roll([{ item: 1, weight: 0.5 }, { item: 2, weight: 0.2 }]))
    }


}