/**
 * 工具
 */

/**
 * 将图片文件转为DataUrl展示
 * @param file
 */
export function file2DataUrl(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = (e: any) => {
      resolve(e.target.result);
    };
    reader.onerror = () => {
      reject('err');
    };
  });
}

export function fmtTimeStamp(format: string, timestamp: number) {//时间戳转化
  if (timestamp == null || timestamp == undefined || timestamp == 0) {
    return ''
  }
  var date = null;
  if(String(timestamp).length > 10){
    date = new Date(timestamp);
  }
  else{
    date = new Date(timestamp * 1000);
  }
  var 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 (var 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;
}

/**
 * 获取一个本地用的随机id
 */
export function getUuid() {
  return `${Date.now()}${Math.random()}`;
}
