/**
 * 用到的和业务相关的
 * 各种静态方法汇总
 * 
 * 获取修改链接参数
 * 获取cookie
 * 缓存相关
 * 数组相关
 * 
 */
export const GTool = {
    /**
     * 替换或添加url里的参数，小程序有问题，别用，new RegExp有问题，在查
     * @param url 修改的url
     * @param arg 参数名
     * @param arg_val 参数值
     */
    changeURLArg(url, arg, arg_val) {
        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;
            }
        }
    },



    /**
     * 读取缓存 用到时重写
     */
    readCache(key /*, type: string = 'localStorage'*/ ) {
        //@ts-ignore
        return my ? my.getStorageSync({
            key: key
        }).data : localStorage.getItem(key);
        // if (!window.localStorage) {
        //     return false;
        // }
        // return window[type].getItem(key);
    },
    /**
     * 写缓存 用到时重写
     */
    writeCache(key, value = 'true' /*, type: string = 'localStorage'*/ ) {
        //@ts-ignore
        my ? my.setStorageSync({
            key: key,
            data: value
        }) : localStorage.setItem(key, value);
        // if (!window.localStorage) {
        //     // trace(Func.replace(SysLang.lang_012, [type]));
        //     return;
        // }
        // window[type].setItem(key, value);
    },

    /**
     * 获得cacheKey今日次数
     * 第二天归0重新计数  用到时重写
     * @param cacheKey 
     */
    returnTodayTimes(cacheKey) {
        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 
     */
    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 数组
     */
    removeEle(e, arr) {
        var index = arr.indexOf(e);
        if (index >= 0) {
            arr.splice(index, 1)
        }
    },

    /**
     * 数组中插入一个数值，按顺序的
     * 数组是从小到大的
     * @param num 
     * @param arr 
     */
    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
     */
    getRandomNumber(start, end, n) {
        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 
     */
    disturbNumberArr(arr) {
        arr.sort(function () {
            return (0.5 - Math.random());
        });
    },

    /**
     * 设置cookie
     * @param name cookie的名称
     * @param value cookie的值
     * @param day cookie的过期时间
     */
    setCookie(name, value, day) {
        if (day !== 0) { //当设置的时间等于0时，不设置expires属性，cookie在浏览器关闭后删除
            var expires = day * 24 * 60 * 60 * 1000;
            var date = new Date(+new Date() + expires);
            document.cookie = name + "=" + escape(value) + ";expires=" + date.toUTCString();
        } else {
            document.cookie = name + "=" + escape(value);
        }
    },

    /**
     * 获取对应名称的cookie
     * @param name cookie的名称
     * @returns {null} 不存在时，返回null
     */
    getCookie(name) {
        let arr;
        let reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg))
            return unescape(arr[2]);
        else
            return null;
    },

    /**
     * 删除cookie
     * @param name cookie名称
     */
    removeCookie(name) {
        this.setCookie(name, 1, -1);
    },

    /**
     * 其实打乱数组取前几个就行
     * 随机取数组arr中count个元素，不改变原数组
     * @param arr 
     * @param count 
     */
    getRandomArrayElements(arr, count) {
        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 
     */
    getRandomArrayElementsEx(arr, count) {
        //如果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 数字或字符串
     */
    int(n) {
        return n >> 0; //~~n
    },



    /**
     * 在字符串间加空格
     * @param str 
     */
    addSpaceInString(str) {
        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
    },

    /**
     * 毫秒剩余时间转成时分秒
     * 1小时1分1秒
     * @param timeStamp 
     */
    getShiFenMiaoByTimeStamp(timeStamp) {
        var hours = Math.floor((timeStamp % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((timeStamp % (1000 * 60 * 60)) / (1000 * 60));
        // var seconds: any = (timeStamp % (1000 * 60)) / 1000;
        var seconds = Math.floor((timeStamp % (1000 * 60)) / 1000);
        hours = hours < 10 ? ('0' + hours) : hours;
        minutes = minutes < 10 ? ('0' + minutes) : minutes;
        seconds = seconds < 10 && seconds >= 1 ? ('0' + seconds) : seconds;
        // return hours + " :" + minutes + " :" + seconds;
        return hours + "小时" + minutes + "分" + seconds + "秒";
    }
}