import { date, copyToClipboard, Notify } from 'quasar'
let IDRe18 = /^(([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx])$/
let IDre15 =  /^(([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3})$/
export function isCardNo(idVal){
  return RegExp(
    [IDRe18.source, IDre15.source].join('|')
  , 'g').test(idVal)
}

export function isPhone(phoneStr){
  return (/^1\d{10}$/g).test(phoneStr)
}

export const Rules = {
  cardNo: function(val){
    return isCardNo(val) || '请输入正确的身份证'
  },
  phone: function (val) {
    return isPhone(val) || "请填写正确的手机号码";
  },
  password: function (val) {
    return ((val+"").length >= 6) || "密码至少6位";
  },
  required: function (val) {
    return (val !== null && val !== "") || "必填项";
  },
  sameAs: function(filed,msg){
    return (val)=>{
      return val == filed || msg
    }
  },
  strLength: function(len,msg){
    return (val)=> {
      return val.length == len || msg
    }
  },
  greaterThan: function(min,msg){
    return (val)=> {
      return val*1 > min || msg||('需要大于'+min)
    }
  },
  lessThan: function(max,msg){
    return (val)=> {
      return val*1 <max || msg||('需要小于'+max)
    }
  },
  lessEqualThan: function(max,msg){
    return (val)=> {
      return val*1 <=max || msg||('需要小于等于'+max)
    }
  },
  number: function(decimal,msg){
    return (val)=> {
      let num = val * 1
      if(typeof num !== 'number'){
        return '必须是数字'
      }
      if(!num && num !==0){
        return '请填写正确的数字'
      }
      return num.toFixed(decimal)*1 == num || msg || (decimal?`小数位不能多于${decimal}位`:'必须为整数')
    }
  },
}

export function formatDate(str){
  try {
    let t = date.extractDate(str, 'YYYY-MM-DD HH:mm:ss')
    if(t.getFullYear() == '1900'){
      t = new Date(str)
    }
    let now = new Date()
    if(now.getFullYear()!= t.getFullYear()){
      return str
    }
    return date.formatDate(t.getTime(), 'MM-DD HH:mm')
  }catch(e){
    console.error(e)
    return str
  }
}

// 格式化金额，保留两位小数点
export function formatMoney(number = 0){
  number = parseFloat(number)
  // let old = number.toFixed(4)
  let n = number.toFixed(2)
  return n
  // return old*1 == n ? n : old
}

export function formatCanReadMoney(number){
  return (number*1).toLocaleString()
}

export function safeCopyToClipboard(text){
  return copyToClipboard(text).catch(e=>{
    return new Promise((resolve, reject) => {
      const area = document.createElement('textarea')
      area.value = text
      area.contentEditable = 'true'
      area.style.position = 'fixed' // avoid scrolling to bottom

      document.body.appendChild(area)
      area.focus()
      area.select()

      const res = document.execCommand('copy')

      area.remove()

      if (res) {
        resolve(true)
      }
      else {
        reject(res)
      }
    })
  }).then(() => {
    Notify.create({
      position: "center",
      message: '已复制'
    })
  })
}
