import Clipboard from 'clipboard'
import { ElMessage } from 'element-plus'

const formatDate = function (time, format) {
  var t = new Date(time)
  var tf = function(i) {
    return (i < 10 ? "0" : "") + i
  }
  return format.replace(/Y|m|d|H|i|s/g, function(a) {
    switch (a) {
      case "Y":
        return tf(t.getFullYear())
      case "m":
        return tf(t.getMonth() + 1)
      case "d":
        return tf(t.getDate())
      case "H":
        return tf(t.getMinutes())
      case "i":
        return tf(t.getHours())
      case "s":
        return tf(t.getSeconds())
    }
  })
}
// 时间戳转日期
const timestampToTime = function (timestamp, type) {
  var date = new Date(timestamp * 1000) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear()
  var M =
    date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  var dateStr = ''
  switch (type) {
    case 1:
      dateStr = Y + '年' + M + '月' + D + '日'
      break
    case 2:
      dateStr = Y + '-' + M + '-' + D
      break
    default:
      dateStr = Y + '年' + M + '月' + D + '日'
  }
  return dateStr
}

// 标准化时间 即将 2015年12月31日 转为 2015-12-31
const dateFormat = function (dateStr) {
  if (dateStr) {
    dateStr = dateStr.replace('年', '-')
    dateStr = dateStr.replace('月', '-')
    dateStr = dateStr.replace('日', '')
    return dateStr
  } else {
    return ''
  }
}


// 存储本地浏览器 mainKey是唯一标识  aryy是存储书 ，type - save 是存  getdata是取
const saveactionDate = function (mainKey, arry, type) {
  const _this = this
  if (arry) {
    arry.forEach(item => {
      if (type === 'save') {
        // 保存操作
        window.localStorage.setItem(mainKey + '-' + item, JSON.stringify(_this[item]))
      } else {
        // 回显
        _this[item] = JSON.parse(window.localStorage.getItem(mainKey + '-' + item) ? window.localStorage
          .getItem(mainKey + '-' + item) : [])
      }
    })
  }
}

// 小数位去零
const unitPriceMethods = function(value) {
  if(value.toString().indexOf('.') != -1){
    let valStr4 = value.toString()
    let ind = valStr4.lastIndexOf('.')
    let firstVal = valStr4.substring(0,ind)
    let lastVal = valStr4.substring(ind + 1,valStr4.length)
    if(lastVal * 1 === 0){
      return firstVal
    }else{
      let newVal = parseFloat(value.toString())
      return newVal + ''
    }
  }else{
    let newVal = parseFloat(value.toString())
    return newVal + ''
  }
}

// 获取年-月-日
const getYeMoDa = function(value){       
  var date = new Date();
  var year = date.getFullYear();
  var month = (date.getMonth() + 1) < 10?'0'+(date.getMonth() + 1):(date.getMonth() + 1);
  var day = date.getDate()<10?'0'+date.getDate():date.getDate();
  return year + "-" + month + "-" + day;
} 

export { 
  formatDate,
  timestampToTime,
  dateFormat,
  saveactionDate,
  unitPriceMethods
};

