import md5 from 'js-md5'
import plugin from './plugin'

export default {
    /**
     * 判断数据类型
     * @param obj
     * @returns {*}
     */
    getType(obj) {
        let toString = Object.prototype.toString
        let map = {
            '[object Boolean]': 'boolean',
            '[object Number]': 'number',
            '[object String]': 'string',
            '[object Function]': 'function',
            '[object Array]': 'array',
            '[object Date]': 'date',
            '[object RegExp]': 'regExp',
            '[object Undefined]': 'undefined',
            '[object Null]': 'null',
            '[object Object]': 'object',
        }
        return map[toString.call(obj)]
    },

    /**
     * 获取系统类型
     * @returns {{userAgent: string, isAndroid: boolean, isIphone: boolean, isIpad: boolean, isWeixin: boolean}}
     */
    getOsType() {
        //#ifdef H5
        return {
            userAgent: navigator.userAgent.toLowerCase(),
            isAndroid: Boolean(navigator.userAgent.match(/android/ig)),
            isIphone: Boolean(navigator.userAgent.match(/iphone|ipod/ig)),
            isIpad: Boolean(navigator.userAgent.match(/ipad/ig)),
            isWeixin: Boolean(navigator.userAgent.match(/MicroMessenger/ig)),
            isAlipay: Boolean(navigator.userAgent.match(/AlipayClient/ig)),
        }
        //#endif

        //#ifndef H5
        return {
            userAgent: '',
            isAndroid: false,
            isIphone: false,
            isIpad: false,
            isWeixin: false,
            isAlipay: false,
        }
        //#endif
    },

    /**
     * 深拷贝
     * @param data
     * @returns {*}
     */
    deepClone(data) {
        const self = this
        let result = {}
        let type = self.getType(data)

        if (type === 'array') {
            result = []
            data.forEach(item => {
                result.push(self.deepClone(item))
            })
        } else if (type === 'object') {
            for (let key in data) {
                if (data.hasOwnProperty(key)) {
                    result[key] = self.deepClone(data[key])
                }
            }
        } else {
            return data
        }

        return result
    },

    /**
     * 对象键值映射（默认从左到右）
     * @param data
     * @param map
     * @param orientation
     * @returns {*}
     */
    objSetKey(data, map, orientation = false) {
        const self = this

        if (self.getType(data) === 'object') {
            // 映射处理(对象数据处理)
            for (let key in map) {
                if (map.hasOwnProperty(key)) {
                    let val = map[key]
                    if (val && val !== key) {
                        if (orientation) {
                            [key, val] = [val, key]
                        }

                        if (data[key]) {
                            data[val] = data[key]
                            delete data[key]
                        }
                    }
                }
            }

            // 子数据处理
            for (let key in data) {
                if (data.hasOwnProperty(key)) {
                    let val = data[key]
                    if (self.getType(val) === 'array' || self.getType(val) === 'object') {
                        data[key] = self.objSetKey(val, map, orientation)
                    }
                }
            }
        } else if (self.getType(data) === 'array') {
            // 数组递归处理
            data.forEach((item, index) => {
                item = self.objSetKey(item, map, orientation)
                data.splice(index, 1, item)
            })
        }
        return data
    },

    /**
     * 对象排序
     * @param obj
     * @returns {{}}
     */
    objSort(obj) {
        let newKey = Object.keys(obj).sort()
        let newObj = {}
        for (let i = 0; i < newKey.length; i++) {
            newObj[newKey[i]] = obj[newKey[i]]
        }
        return newObj
    },

    /**
     * 生成uuid的没4位数
     * @returns {string}
     * @constructor
     */
    S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
    },

    /**
     * 生成uuid
     * @param separator
     * @returns {string}
     */
    uuid(separator = '-') {
        const self = this
        return (self.S4() + self.S4() + separator + self.S4() + separator + self.S4() + separator + self.S4() + separator + self.S4() + self.S4() + self.S4())
    },

    /**
     * 创建随机字符串
     * @param num
     * @returns {string} (0-9,a-z)
     */
    randomString(num) {
        let chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
        let res = ''
        for (let i = 0; i < num; i++) {
            let id = Math.ceil(Math.random() * 35)
            res += chars[id]
        }
        return res
    },

    /**
     * 去除2端空格
     * @param string
     */
    trim(string) {
        if (typeof string === 'string') {
            return string.replace(/^\s\s*/, '').replace(/\s\s*$/, '')
        } else {
            return string
        }
    },

    /**
     * md5加密
     * @param string
     * @returns {*}
     */
    md5(string) {
        return md5(string)
    },

    /**
     * 获取服务时间列表
     * @param startDay
     * @param length
     */
    getDateList(startDay = 0, length = 7) {
        let dateList = []
        let week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'] // 星期
        for (let i = 0; i < length; i++) {
            let tmp = ''
            let date = new Date()
            date.setDate(date.getDate() + i + startDay)
            tmp = date.getMonth() + 1 + '月' + (date.getDate()) + '日[' + week[date.getDay()] + ']'
            dateList.push(tmp)
        }
        return dateList
    },

    /**
     * 获取格式化后的时间
     * @param date
     * @param format
     * @returns {string}
     */
    getDateFormat(date, format = 'yyyy-MM-dd') {
        let o = {
            'M+': date.getMonth() + 1, //月份
            'd+': date.getDate(), //日
            'h+': date.getHours(), //小时
            'm+': date.getMinutes(), //分
            's+': date.getSeconds(), //秒
            'S': date.getMilliseconds(), //毫秒
            'q+': Math.floor((date.getMonth() + 3) / 3), //季度
        }

        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
        }
        for (let k in o) {
            if (new RegExp('(' + k + ')').test(format)) {
                format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
            }
        }

        return format
    },

    /**
     * 格式化时间
     * @param val
     * @param format
     * @returns {string|*}
     */
    timestampToDate(val, format = 'yyyy-MM-dd') {
        val = val.replace(/-/g, '/')

        if (val) {
            let date = new Date(val)

            let o = {
                'M+': date.getMonth() + 1, //月份
                'd+': date.getDate(), //日
                'h+': date.getHours(), //小时
                'm+': date.getMinutes(), //分
                's+': date.getSeconds(), //秒
                'S': date.getMilliseconds(), //毫秒
                'q+': Math.floor((date.getMonth() + 3) / 3), //季度
            }

            if (/(y+)/.test(format)) {
                format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
            }
            for (let k in o) {
                if (new RegExp('(' + k + ')').test(format)) {
                    format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
                }
            }
            return format
        } else {
            return val
        }
    },

    /**
     * 富文本标签添加class
     */
    classAdd(string, label, className) {
        if (this.getType(string) === 'string' && string) {
            if (label === 'p') {
                return string
                    .replace(/<p([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<p')
                    .replace(/<p([\s\w"=\/\.:;]+)((?:(class="[^"]+")))/ig, '<p')
                    .replace(/<p>/ig, '<p class="' + className + '">')
            } else if (label === 'img') {
                return string
                    .replace(/<img([\s\w"-=\/\.:;]+)((?:(height="[^"]+")))/ig, '<img$1')
                    .replace(/<img([\s\w"-=\/\.:;]+)((?:(width="[^"]+")))/ig, '<img$1')
                    .replace(/<img([\s\w"-=\/\.:;]+)((?:(style="[^"]+")))/ig, '<img$1')
                    .replace(/<img([\s\w"-=\/\.:;]+)((?:(alt="[^"]+")))/ig, '<img$1')
                    .replace(/<img([\s\w"-=\/\.:;]+)/ig, '<img$1 class="' + className + '"')
            }
        } else {
            return string
        }
    },

    /**
     * 数组转字符串逗号分隔
     * @param str
     * @returns {string}
     */
    arrToStr(arr) {
        let str = ''
        if (arr) {
            for (let item of arr) {
                str += item + ','
            }
            str = str.replace(/,$/igm, '')
        }

        return str
    },

    /**
     * 客服
     * @param str
     * @returns {string}
     */
    kefu() {
        //#ifdef H5
        window.doyoo.util.openChat('g=10085481')
        //#endif

        //#ifndef H5
        plugin.showToast('客服升级中')
        //#endif
    },

    /**
     * 数组切割
     * @param array
     * @param length
     * @returns {Array|default}
     */
    arrayChunk(array, length) {
        length = parseInt(length)

        //如果长度小于要划分的长度，返回原数组
        if (length <= 1 || this.length < length) {
            return array
        }

        let groups = []
        let number = Math.ceil(array.length / length)// 拆分成的二维数组的个数

        //用slice方法，每四个截取一次
        for (let i = 0; i < number; i++) {
            groups.push(array.slice(length * i, length * (i + 1)))
        }

        return groups
    },

    /**
     * guid
     */
    guid() {
        function S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    },
}
