import querystring from "querystring"
import _this from "../main"
import $CONFIG from "../config"
var CryptoJS = require('crypto-js');
var Md5 = require("js-md5");


const utils = {
    // 设置cookie
    setCookie(name, value, days) {
        var exp = new Date();
        exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
        document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
    },

    // 读取cookie
    getCookie(name) {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg)) {
            return unescape(arr[2]);
        }
        return null;
    },

    // 删除cookies
    delCookie(name) {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval = this.getCookie(name);
        if (cval != null) {
            document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
        }
    },
    /**
     * 用来遍历传入的浏览器标识，查询其中包含的build/下标
     * @param {*} msg 浏览器标识，手机型号
     * @param {*} str 从msg中寻找的参数
     */
    getModels(msg, str) {
        for (let i in msg) {
            if (msg[i].indexOf(str) > 0) {
                return i;
            }
        }
        return -1;
    },

    /**
     * 手机号格式校验
     * @param {number} tel 手机号
     */
    checkVerification(tel) {
        // 判断手机号格式是否正确
        if (!/^((1[3,5,8,7,9][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/.test(
                tel
            )) {
            return false;
        }
        return true;
    },

    /**
     * cryptoJs base64 加密
     * @param {string} encStr 需要加密的值
     */
    encrypt(encStr) {
        const wordArray = CryptoJS.enc.Utf8.parse(encStr);
        const base64EncStr = CryptoJS.enc.Base64.stringify(wordArray);
        return base64EncStr;
    },

    /**
     * cryptoJs base64 解密
     * @param {string} decStr  需要解密的值
     */
    decrypt(decStr) {
        const parsedWordArray = CryptoJS.enc.Base64.parse(decStr);
        const parsedStr = parsedWordArray.toString(CryptoJS.enc.Utf8);
        return parsedStr;
    },

    /**
     * 判断是否微信内
     */
    isWeChat() {
        if (typeof WeixinJSBridge !== "undefined") {
            return 1;
        }
        return 0;
    },

    /**
     * 判断是否pc
     * @returns 是否pc端
     */
    IsPC() {
        if (!navigator.userAgent.match(/AppleWebKit.*Mobile.*/)) {
            // pc
            return true
        }
        return false
    },

    /**
     * 判断是否ios
     * @returns 是否ios端(已排除pc)
     */
    isiOS() {
        if (!this.IsPC()) {
            var u = navigator.userAgent;
            var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
            return isiOS
        }
    },

    /**
     *  获取支付类型
     * @param {string} pay_platform  支付平台
     */
    payType(pay_platform) {
        const payType = {}
        switch (pay_platform) {
            case "ALIPAY":
                payType.h5 = "ALIPAY-H5"
                break;
            case "WECHATPAY":
                const isWeChat = this.isWeChat()
                payType.h5 = isWeChat ? "WECHAT-JSAPI" : "WECHAT-H5"
                break;
            case "HB":
                payType.h5 = "HB"
                break;
        }
        return payType
    },

    /**
     * md5 加密
     * @param {string} str  需要加密的字符串
     */
    md5(str) {
        return Md5(str)
    },

    /**
     * 查找query  不传即为查找window.location中的参数
     * @param {*} name 需要查找的字符串的key
     * @param {*} search 查找search中的name
     */
    getQueryString(name, search) {
        const str =
            search ||
            window.location.hash.split("?")[1] ||
            window.location.search.substr(1);
        let result = querystring.parse(str)[name];
        // 当有重复参数时querystring.parse返回的是数组
        if (result instanceof Array) {
            result = result[0];
        }
        return result || null;
    },

    /**
     * 获取url中所有的参数
     * @param {string} search 查找search中  ? 后面带的 所有的参数
     */
    getAllQueryString(search) {
        const str =
            search ||
            window.location.hash.split("?")[1] ||
            window.location.search.substr(1)

        if (!str) {
            return null
        }

        let resuleObj = new Object();
        let strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            resuleObj[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
        }
        return resuleObj
    },

    // 删除url参数值
    delQueStr(url, ref) {
        var str = "";

        if (url.indexOf('?') != -1)
            str = url.substr(url.indexOf('?') + 1);
        else
            return url;
        var arr = "";
        var returnurl = "";
        if (str.indexOf('&') != -1) {
            arr = str.split('&');
            for (i in arr) {
                if (arr[i].split('=')[0] != ref) {
                    returnurl = returnurl + arr[i].split('=')[0] + "=" + arr[i].split('=')[1] + "&";
                }
            }
            return url.substr(0, url.indexOf('?')) + "?" + returnurl.substr(0, returnurl.length - 1);
        } else {
            arr = str.split('=');
            if (arr[0] == ref)
                return url.substr(0, url.indexOf('?'));
            else
                return url;
        }
    },

    // 记住密码工具函数
    rememberFun(account, password) {
        const platform = this.getQueryString("platform");
        // 忘川伏魔录
        if (platform === "wcfml") {
            return this.onRememberFun(account, password)
        }
    },

    //  记住密码工具函数
    onRememberFun(account, password) {
        const accountEnc = this.encrypt(account);
        const pwdEnc = this.encrypt(password);
        const accountPwd = `${accountEnc}&&${pwdEnc}`;
        let accountLocal = this.readStorage("", "jhremember");
        accountLocal = accountLocal && JSON.parse(accountLocal);

        let accountList = []

        // 获取账号密码列表
        accountLocal &&
            accountLocal.length &&
            accountLocal.map((ele) => {
                const _account = ele.split("&&")[0];
                const _pwd = ele.split("&&")[1];
                const account = this.decrypt(_account);
                const pwd = this.decrypt(_pwd);
                accountList.push({
                    account,
                    pwd,
                });
            });

        // 初始状态
        if (!accountLocal) {
            accountLocal = [accountPwd];
            accountList.unshift({
                account,
                pwd: password,
            });
            this.writeStorage("", "jhremember", JSON.stringify(accountLocal));

            return accountList;
        }

        // 已经存有账密
        // 1.  判断账号是否存在
        const reAccount = accountList.filter((ele) => {
            return ele.account == account;
        });
        // 1 如果账号存在
        if (reAccount.length > 0) {
            //  删除原来的账密 存
            accountLocal = accountLocal.filter((ele) => {
                const _accountEcv = ele.split("&&")[0];
                return _accountEcv !== accountEnc;
            });
            accountList = accountList.filter((ele) => {
                return ele.account !== account
            })
        }
        // 2. 账号不存在 存
        accountLocal = accountLocal ? [accountPwd, ...accountLocal] : [accountPwd];
        accountList.unshift({
            account,
            pwd: password,
        });
        this.writeStorage("", "jhremember", JSON.stringify(accountLocal));
        return accountList
    },

    // 读取数据
    readStorage(bookName, keyName) {
        const platform = this.getQueryString("platform");
        // 忘川伏魔录
        if (platform == "wcfml") {
            let data = JSON.parse(decodeURI(decodeURIComponent(this.getQueryString('data')))) || {}
            return localStorage.getItem(keyName) || data[keyName];
        }
    },

    //  存数据
    writeStorage(bookName, keyName, value) {
        // 忘川伏魔录
        const platform = this.getQueryString("platform");
        if (platform == "wcfml") {
            localStorage.setItem(keyName, value);
            const query = this.getAllQueryString();
            let data = decodeURI(decodeURIComponent(query.data));
            query.data = data ? JSON.parse(data) : {}
            query.data[keyName] = value;
            query.data = JSON.stringify(query.data)
            this.routeLink("", query, "", _this)
            return
        }
    },

    // 删除数据(keyName)
    deleteStorage(bookName, keyName) {
        // 忘川伏魔录特制版
        const platform = this.getQueryString("platform");
        if (platform == "wcfml") {
            return
        }
    },

    /**
     * 判断是否pc
     * @returns 是否pc端
     */
    IsPC() {
        if (!navigator.userAgent.match(/AppleWebKit.*Mobile.*/)) {
            // pc
            return true
        }
        return false
    },

    // 销毁数据(bookName)
    destoryStorage(bookName) {
        // 忘川伏魔录特制版
    },

    // 获取所有bookName里面的key列表
    getKeysInStorage(bookName) {
        // 忘川伏魔录特制版
    },

    // 对象序列化工具函数
    queryStringUtil(query) {
        return querystring.stringify(query)
    },

    // vue-router跳转页面
    routeLink(routeName, query, params) {
        let _routeName = routeName || _this.$route.name
        _this.$router
            .push({
                name: _routeName,
                query,
                params,
            })
            .catch((err) => {
                //   console.log(err);
            });
    },

    // 关闭支付页面工具函数
    closePage(uid) {
        // 忘川伏魔录
        const platform = this.getQueryString("platform");
        const data = this.getQueryString("data");
        if (platform == "wcfml") {
            window.location.href = `${$CONFIG.wcfmlCloseUrl}?uid=${uid}&data=${data}`
            return
        }
    },

    // 联系qq客服
    onQQService() {
        const { kfQQ } = $CONFIG;
        const isPc = this.IsPC()
        const urlMobil = `mqqwpa://im/chat?chat_type=wpa&uin=${kfQQ}&version=1&src_type=web&web_src=http:://wpa.b.qq.com`;
        const urlPc = `http://wpa.qq.com/msgrd?v=3&uin=${kfQQ}&site=qq&menu=yes`;
        const url = isPc ? urlPc : urlMobil;
        window.open(url, "_brank");
    },

    // wcfml 游戏内登录工具函数
    wcfmlLoginUtils(data) {
        // 记住密码 todo
        const savedata = decodeURIComponent(this.getQueryString("data"));
        // 跳转对应登录链接
        const query = this.queryStringUtil({
            uid: data.uid,
            data: encodeURIComponent(savedata),
        });
        window.location.href = `${$CONFIG.wcfmlLoginUrl}?${query}`;
    },

    // 倒计时
    countDown(startTime, endTime) {
        // 两个日期对象，相差的秒数
        let interval = endTime - startTime;
        interval /= 1000
            // 求 相差的天数/小时数/分钟数/秒数
        let hour, minute, second;

        hour = Math.floor(interval / 60 / 60);
        minute = Math.floor(interval / 60 - hour * 60);
        second = Math.floor(interval - hour * 60 * 60 - minute * 60);

        hour = hour < 10 ? `0${hour}` : hour
        minute = minute < 10 ? `0${minute}` : minute
        second = second < 10 ? `0${second}` : second

        return {
            hour,
            minute,
            second
        }
    },
};
export default utils;