import store from '@/store'

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
    if (arguments.length === 0 || time == '' || time == null || time == 'null' || time == undefined) return '--'
    let regD1 = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/;
    let regD1T = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(\+|\-)[0-9]{4}$/;
    let regD2 = /^[1-9]\d{3}\/(0[1-9]|1[0-2])\/(0[1-9]|[1-2][0-9]|3[0-1])$/;
    let regD2T = /^[1-9]\d{3}\/(0[1-9]|1[0-2])\/(0[1-9]|[1-2][0-9]|3[0-1])\s+(\+|\-)[0-9]{4}$/;
    let regD1T1 = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d(\s+((\+|\-)[0-9]{4})){0,1}$/;
    let regD2T1 = /^[1-9]\d{3}\/(0[1-9]|1[0-2])\/(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d(\s+((\+|\-)[0-9]{4})){0,1}$/;
    let defaultFormat = '{y}-{m}-{d} {h}:{i}:{s}';
    if (regD1.test(time)) {
        time = time.replace(/\-/g, "/")
        defaultFormat = '{y}-{m}-{d}'
    } else if (regD1T.test(time)) {
        let T = time.split(' ')[0].replace(/\-/g, "/") + ' 08:00:00 ' + time.split(' ')[1]
        time = new Date(T)
        defaultFormat = '{y}-{m}-{d}'
    } else if (regD2.test(time)) {
        defaultFormat = '{y}/{m}/{d}'
    }
    if (regD2T.test(time)) {
        let T = time.split(' ')[0] + ' 08:00:00 ' + time.split(' ')[1]
        time = new Date(T)
        defaultFormat = '{y}/{m}/{d}'
    } else if (regD1T1.test(time)) {
        let arr = time.split(' ');
        let T = arr.length == 2 ? arr[0].replace(/\-/g, "/") + ' ' + arr[1] : arr[0].replace(/\-/g, "/") + ' ' + arr[1] + ' ' + arr[2]
        time = new Date(T)
        defaultFormat = '{y}-{m}-{d} {h}:{i}:{s}'
    } else if (regD2T1.test(time)) {
        defaultFormat = '{y}/{m}/{d} {h}:{i}:{s}'
    }
    const format = cFormat || defaultFormat;
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
            time = parseInt(time)
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000
        }
        date = new Date(time)
    }
    let GMT = date.getTimezoneOffset()
    let HH = Math.abs(GMT) / 60
    let MM = Math.abs(GMT) % 60
    HH = HH.toString().padStart(2, '0')
    MM = MM.toString().padStart(2, '0')
    let T = GMT < 0 ? '+' + HH + MM : HH + MM
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        // t: date.toString().split('T')[1].split(' ')[0],
        t: T,
        a: date.getDay()
    }
    const time_str = format.replace(/{([ymdhista])+}/g, (result, key) => {
        const value = formatObj[key]
            // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
            return ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][value]
        }
        return value.toString().padStart(2, '0')
    })
    return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
    if (('' + time).length === 10) {
        time = parseInt(time) * 1000
    } else {
        time = +time
    }
    const d = new Date(time)
    const now = Date.now()

    const diff = (now - d) / 1000

    if (diff < 30) {
        return '刚刚'
    } else if (diff < 3600) {
        // less 1 hour
        return Math.ceil(diff / 60) + '分钟前'
    } else if (diff < 3600 * 24) {
        return Math.ceil(diff / 3600) + '小时前'
    } else if (diff < 3600 * 24 * 2) {
        return '1天前'
    }
    if (option) {
        return parseTime(time, option)
    } else {
        return (
            d.getMonth() +
            1 +
            '月' +
            d.getDate() +
            '日' +
            d.getHours() +
            '时' +
            d.getMinutes() +
            '分'
        )
    }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
    const search = url.split('?')[1]
    if (!search) {
        return {}
    }
    return JSON.parse(
        '{"' +
        decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
        '"}'
    )
}

/**
 * 比较两个对象是否相同
 * @param {*} a 
 * @param {*} b 
 */
export function compareParams(a, b) {
    let aProps = Object.getOwnPropertyNames(a);
    let bProps = Object.getOwnPropertyNames(b);
    let flag = true;
    if (aProps.length !== bProps.length) return false;
    for (let i in a) {
        if (a[i] !== b[i]) {
            if (typeof(a[i]) === 'object') {
                if (!compareParams(a[i], b[i])) {
                    flag = false;
                    break;
                }
            } else {
                flag = false;
                break;
            }
        }
    }
    return flag;
}

/**
 * 标准值转化
 * @param {string} type 
 * @param {string|number} value 
 */
export function getStandard(type, value = '') {
    const standard = store.getters.standard || [];
    const arr = standard.filter(tmp => tmp.codeType === type)
    arr.forEach(item => {
        item.codeValue = item.codeValue == 'true' ? '1' : item.codeValue == 'false' ? '0' : item.codeValue
    })
    if (value == '') {
        return arr
    } else if (value == 'true') {
        value = '1'
    } else if (value == 'false') {
        value = '0'
    }

    if (arr.length > 0) {
        let str = '';
        const list = arr.filter(tmp => {
            if (tmp.codeValue == value) {
                str = tmp.codeDesc
            }
        })
        return str
    } else {
        return type
    }
};

// 数据容量单位转换（B KB B MB GB TB）
export function bytesToSize(bytes) {
    if (!bytes) return '--'
    bytes = Number(bytes)
    if (bytes == 0) return '0 B';
    let rate = 1024;
    let unit = ['B', 'KB', 'MB', 'GB', 'TB'];
    let i = Math.floor(Math.log(bytes) / Math.log(rate));
    return (bytes / Math.pow(rate, i)).toPrecision(3) + ' ' + unit[i];
}

// 状态值转换
export function formatType(type) {
    switch (type) {
        case '0':
            return '通用'
            break
        default:
            return type
    }
}
export function formatStatus(status) {
    switch (status) {
        case '1':
            return '可分配'
            break
        case '2':
            return '已分配'
            break
        case '3':
            return '已到期'
            break
        case '4':
            return '已删除'
            break
        default:
            return status
    }
}
export function formatState(state) {
    switch (state) {
        case '0':
            return '未申请资源'
            break
        case '1':
            return '申请中'
            break
        case '2':
            return '已分配'
            break
        case '3':
            return '审核失败'
            break
        case '4':
            return '审核超时'
            break
        case '5':
            return '已到期'
            break
        case '6':
            return '已手动释放'
            break
        default:
            return state
    }
}

export function formatSolverState(state) {
    switch (state) {
        case '0':
            return '未求解'
            break
        case '1':
            return '求解中'
            break
        case '2':
            return '求解完成'
            break
        default:
            return state
    }
}
export function upChainState(state) {
    switch (state) {
        case '0':
            return '未上链'
            break
        case '1':
            return '上链中'
            break
        case '2':
            return '已上链'
            break
        default:
            return state
    }
}

export function payState(state) {
    switch (state) {
        case '0':
            return '下单失败'
            break
        case '1':
            return '下单成功'
            break
        case '2':
            return '支付失败'
            break
        case '3':
            return '支付成功'
            break
        case '4':
            return '退款中'
            break
        case '6':
            return '退款失败'
            break
        case '6':
            return '退款成功'
            break
        case '7':
            return '订单关闭'
            break
        case '8':
            return '支付超时'
            break
        default:
            return state
    }
}