import _Vue from 'vue'
/**
 * 全局filter
 */

/**
 * 手机号掩码处理
 * @param str
 */
export let filterPhone = (str: string) => String(str).substr(0, 3) + '****' + String(str).substr(-4);

/**
 * 时间戳转换
 * @param timestamp 时间戳
 * @param 转换格式 默认yy-mm-dd hh:mm:ss
 */
export let formatTime = (timestamp: any, format: string = 'Y-M-D h:m:s') => {
  if (timestamp == null || timestamp == undefined || timestamp == 0) {
    return ''
  }
  let date = new Date(parseInt(timestamp, 10) * 1000)
  let fmtList = [{ k: 'Y', v: "date.getFullYear()" },
  { k: 'M', v: "date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1" },
  { k: 'D', v: "date.getDate() < 10 ? '0' + date.getDate() : date.getDate()" },
  { k: 'h', v: "date.getHours() < 10 ? '0' + date.getHours() : date.getHours()" },
  { k: 'm', v: "date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()" },
  { k: 's', v: "date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()" },
  ]
  for (let i = 0; i < fmtList.length; i++) {
    let fmt = fmtList[i];
    let k = fmt.k;
    if (format.indexOf(k) != -1) {
      format = format.replace(k, eval(fmt.v));
    }
  }
  return format;
}

const globalFilters = (Vue: typeof _Vue) => {
  Vue.filter('filterPhone', filterPhone)
  Vue.filter('formatTime', formatTime)
}

export default globalFilters