export const formatDate = (datetime) => {
    var date = new Date(datetime); // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var year = date.getFullYear(),
        month = ('0' + (date.getMonth() + 1)).slice(-2),
        sdate = ('0' + date.getDate()).slice(-2),
        hour = ('0' + date.getHours()).slice(-2),
        minute = ('0' + date.getMinutes()).slice(-2),
        second = ('0' + date.getSeconds()).slice(-2);
    // 拼接
    var result =
        year + '-' + month + '-' + sdate + ' ' + hour + ':' + minute + ':' + second;
    // 返回
    return result;
};

export const formatDay = (datetime) => {
    var date = new Date(datetime);
    var year = date.getFullYear(),
        month = ('0' + (date.getMonth() + 1)).slice(-2),
        day = ('0' + date.getDate()).slice(-2);
    // 拼接
    var result = year + '-' + month + '-' + day;
    // 返回
    return result;
};

// 判断是否是微信
export function isWeixin() {
  const ua = window.navigator.userAgent.toLowerCase();
  if(ua.match(/MicroMessenger/i) == 'micromessenger' || ua.match(/_SQ_/i) == '_sq_') {
    return true;
  } else{
    return false;
  }
}

// 时间戳 格式化为 时分秒（00: 00: 00）
export const formatDuring = (time) => {
    const s = Math.floor(time / 1000);
    if (!s) {
        return '';
    }
    let t = '';
    if (s > -1) {
        const hour = Math.floor(s / 3600);
        const min = Math.floor(s / 60) % 60;
        const sec = s % 60;
        if (hour) {
            if (hour < 10) {
                t = '0' + hour + ':';
            } else {
                t = hour + ':';
            }
        }
        if (min < 10) {
            t += '0';
        }
        t += min + ':';
        if (sec < 10) {
            t += '0';
        }
        t += sec.toFixed(0);
    }
    return t;
};

export function toDecimal2(x) {
    if (isNaN(x)) {
        return '';
    }
    const f = x / 100;
    let s = f.toString();
    let rs = s.indexOf('.');
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + 2) {
        s += '0';
    }
    return s;
}

/**
 * 通过身份证获取出生日期及性别
 * @param idCard 15/18位身份证号码
 * @return JSON对象
 *         sex：0-女、1-男；
 *         birthDay：yyyy-MM-dd
 */
export function getBirthdayAndSex(idCard) {
    const info = {};
    const birth = (idCard.length === 18) ? idCard.slice(6, 14) : idCard.slice(6, 12);
    // 18位：提取第17位数字；15位：提取最后一位数字
    const order = (idCard.length === 18) ? idCard.slice(-2, -1) : idCard.slice(-1);
    info.birthDay = (idCard.length === 18) ? ([birth.slice(0, 4),
        birth.slice(4, 6), birth.slice(-2)
    ]).join('-') : ([
        '19' + birth.slice(0, 2), birth.slice(2, 4),
        birth.slice(-2)
    ]).join('-');
    // 余数为0代表女性，不为0代表男性
    info.sex = (order % 2 === 0 ? 0 : 1);
    return info;
}

