import store from '@/store/index.js'

/*
 * 截断hash
 */
const filterHash = (str, num) => {
    let length = num || 16
    return String(str).substr(0, length) + '...' + String(str).substr(-4)
}

export const timeCustomCN = (val) => {
    val = timeStamp(val, 'Y-m-d H:i:s')
    let currentDate = new Date();
    let currentD = currentDate.getDate();
    let currentYear = currentDate.getFullYear();
    let currentMonth = currentDate.getMonth() + 1;
    let date = val.substring(0, 19);
    date = date.replace(/-/g, '/');
    let valDate = new Date(date);
    let valD = valDate.getDate();
    let valYear = valDate.getFullYear();
    let valMonth = valDate.getMonth() + 1;
    // 判断是否属于今天，计算时分
    let difftime = (currentDate - valDate) / 1000;
    if (currentYear === valYear && currentMonth === valMonth && currentD === valD) {
        if (difftime < 3600) {
            let minute = parseInt(difftime % 3600 / 60);
            return minute === 0 ? '刚刚' : minute + '分钟前';
        } else {
            return (difftime / 3600).toFixed(0) + '小时前';
        }
    } else {
        // 计算天
        if (currentYear === valYear && currentMonth === valMonth && currentD - 1 === valD) {
            return '昨天';
        } else {
            let days = Math.abs(currentDate.getTime() - valDate.getTime()) / (1000 * 60 * 60 * 24);
            return Math.ceil(days) + '天前';
        }
    }
}

const timeStamp = (timestamp, formats) => {
    /*
     ** 时间戳转换成指定格式日期
     ** eg. 
     ** dateFormat(11111111111111, 'Y年m月d日 H时i分')
     ** → "2322年02月06日 03时45分"
     */
    // formats格式包括
    // 1. Y-m-d
    // 2. Y-m-d H:i:s
    // 3. Y年m月d日
    // 4. Y年m月d日 H时i分
    formats = formats || 'Y-m-d';

    var zero = function(value) {
        if (value < 10) {
            return '0' + value;
        }
        return value;
    };
    var myDate = timestamp ? new Date(timestamp) : new Date();

    var year = myDate.getFullYear();
    var month = zero(myDate.getMonth() + 1);
    var day = zero(myDate.getDate());

    var hour = zero(myDate.getHours());
    var minite = zero(myDate.getMinutes());
    var second = zero(myDate.getSeconds());

    return formats.replace(/Y|m|d|H|i|s/ig, function(matches) {
        return ({
            Y: year,
            m: month,
            d: day,
            H: hour,
            i: minite,
            s: second
        })[matches];
    });
}

export default {
    filterHash,
    timeCustomCN
}
