import Vue from 'vue';
import moment from 'moment';

Vue.filter('moment', (time) => time ? moment(time).format('YYYY-MM-DD HH:mm:ss') : '');
Vue.filter('momentWu', (time) => time ? moment(time).format('YYYY-MM-DD HH:mm:ss') : '无');
Vue.filter('momentDate', (time) => time ? moment(time).format('YYYY-MM-DD') : '');
Vue.filter('momentMM', (time) => time ? moment(time).format('MM-DD HH:mm') : '');
Vue.filter('momentY', (time) => time ? moment(time).format('YYYY') : '');

/**
 * 车牌管道
 */
Vue.filter('formatCarno', carno => {
  if (!carno) return ''
  const arr = carno.split('');
  arr.splice(2, 0, ' ');
  return arr.join('');
});

/**
 * 金额管道
 */
const digitsRE = /(\d{3})(?=\d)/g;
Vue.filter('currency', (value, currency, decimals) => {
  value = parseFloat(value);
  if (!isFinite(value) || (!value && value !== 0)) return '';
  currency = currency != null ? currency : '￥';
  decimals = decimals != null ? decimals : 2;
  const stringified = Math.abs(value).toFixed(decimals);
  const _int = decimals ? stringified.slice(0, -1 - decimals) : stringified;
  const i = _int.length % 3;
  const head = i > 0 ? (_int.slice(0, i) + (_int.length > 3 ? ',' : '')) : '';
  const _float = decimals ? stringified.slice(-1 - decimals) : '';
  const sign = value < 0 ? '-' : '';
  return sign + currency + head + _int.slice(i).replace(digitsRE, '$1,') + _float;
});