const _ = require('lodash');
const moment = require('moment');
const numeral = require('numeral');
const { BEAUTIFY_Y } = require('../constant');

exports.transformDate = array => {
  if (!_.isArray(array)) {
    return [];
  }
  const sample = _.toString(_.sample(array)) || '';
  // 需要保证后端时间格式
  if (moment(sample.slice(0, 10), 'YYYY-MM-DD', true).isValid()) {
    const momentArray = array.map(v => moment(v));
    // 服务端数据与格式化输出格式不一致，需要hack
    const orginFormat = 'YY年MM月DD日HH时mm分ss秒'.slice(0, sample.length - 1);

    let format = orginFormat;
    let outputFormat = '';
    while (format.length >= 3) { // YYYY
      const group = _.groupBy(momentArray, v => v.format(format));
      if (_.keys(group).length === 1) {
        break;
      }
      // YYYY年MM月DD日HH时mm分ss秒
      // output: ss秒, groupFormat: YYYY年MM月DD日HH时mm分
      outputFormat = format.substr(-3, 3) + outputFormat;
      format = format.slice(0, -3);
    }
    return momentArray.map(v => {
      const out = v.format(outputFormat || orginFormat);
      // 不是很舒服的按需调整，去掉多余的0
      return out.replace(/0\d[月|日|时]/g, str => str.substring(1));
    });
  }
  return array;
}

exports.formatNumber = (number, format = '0,0.00', defaultFormat = '0,0[.]00') => {
  if (!_.isNumber(number)) {
    return number;
  }
  const _number = numeral(number);
  let out = _number.format(defaultFormat);

  for (const o of BEAUTIFY_Y) {
    const v = _number.value();
    if (Math.abs(v) >= o.min) {
      out = `${numeral(v/o.min).format(format)}${o.label}`;
      return out;
    }
  }

  return out;
}
