import store from "@/store"
// 工具方法
export default {
  /**
   * @param {String}   传入query的字符 返回的对象
   */
  stringToObject(val) {
    const object = {}
    let arr = val.split("&")
    for (let i = 0, len = arr.length; i < len; i++) {
      let arrItem = arr[i]
      let item = arrItem.split("=")
      object[item[0]] = decodeURIComponent(item[1])
    }
    return object
  },
  /**
   * @param {Object} obj 传入的对象 返回的字符
   */
  objectToQueryString(obj) {
    return Object.keys(obj)
      .map(function(key) {
        return ""
          .concat(encodeURIComponent(key), "=")
          .concat(encodeURIComponent(obj[key]))
      })
      .join("&")
  },
  /**
   *  返回的时间字符串的格式类型编号
   *
   */
  getSampleId() {
    //**********
    let date = new Date()
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()
    let hour = date.getHours()
    let minute = date.getMinutes()
    let num = ""
    for (let i = 0; i < 3; i++) {
      num += Math.floor(Math.random() * 10)
    }
    if (month < 10) {
      month = "0" + month
    }
    if (day < 10) {
      day = "0" + day
    }
    if (hour < 10) {
      hour = "0" + hour
    }
    if (minute < 10) {
      minute = "0" + minute
    }
    // 编号获取
    return (
      year.toString() +
      month.toString() +
      day.toString() +
      "-" +
      hour.toString() +
      minute.toString() +
      "-" +
      num
    )
  },
  /**
   * @param {String} time 传入的时间 根据出生日期获取年龄
   *
   */
  getAge(strAge) {
    strAge = new Date(strAge).toLocaleDateString()
    let birArr = strAge.split("/")
    let birYear = birArr[0]
    let birMonth = birArr[1]
    let birDay = birArr[2]
    d = new Date()
    let nowYear = d.getFullYear()
    let nowMonth = d.getMonth() + 1 //记得加1
    let nowDay = d.getDate()
    let returnAge
    if (birArr == null) {
      return false
    }
    let d = new Date(birYear, birMonth - 1, birDay)
    if (
      d.getFullYear() == birYear &&
      d.getMonth() + 1 == birMonth &&
      d.getDate() == birDay
    ) {
      if (nowYear == birYear) {
        returnAge = 0 //
      } else {
        let ageDiff = nowYear - birYear //
        if (ageDiff > 0) {
          if (nowMonth == birMonth) {
            let dayDiff = nowDay - birDay //
            if (dayDiff < 0) {
              returnAge = ageDiff - 1
            } else {
              returnAge = ageDiff
            }
          } else {
            let monthDiff = nowMonth - birMonth //
            if (monthDiff < 0) {
              returnAge = ageDiff - 1
            } else {
              returnAge = ageDiff
            }
          }
        } else {
          return "出生日期晚于今天，数据有误" //返回-1 表示出生日期输入错误 晚于今天
        }
      }
      return returnAge
    } else {
      return "输入的日期格式错误！"
    }
  },
  /**
   * @param {Number} time 传入的时间
   * @param {Number} startType 要返回的时间字符串的格式类型，传入'year'则返回年开头的完整时间 传入'day'则返回当天时间
   */
  formateDate(time, startType) {
    const d = time ? new Date(time) : new Date()
    const year = d.getFullYear()
    const month = this.getHandledValue(d.getMonth() + 1)
    const date = this.getHandledValue(d.getDate())
    const hours = this.getHandledValue(d.getHours())
    const minutes = this.getHandledValue(d.getMinutes())
    const second = this.getHandledValue(d.getSeconds())
    let resStr = ""
    if (startType === "year") {
      resStr =
        year +
        "-" +
        month +
        "-" +
        date +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        second
    } else if (startType === "day") {
      resStr = year + "-" + month + "-" + date
    } else resStr = month + "-" + date + " " + hours + ":" + minutes
    return resStr
  },
  /**
   * @param {Number} num 数值
   * @returns {String} 处理后的字符串
   * @description 如果传入的数值小于10，即位数只有1位，则在前面补充0
   */
  getHandledValue(num) {
    return num < 10 ? "0" + num : num
  },
  /**
   * 根据list、value 得出 label
   * @export
   * @param {*} list 数据list
   * @param {*} value 对应值
   * @param {*} multiple value 是否是数组
   * @returns
   */
  formatDicList(list, value, multiple = false) {
    if (!list) return ""
    if (list.constructor !== Array) return ""
    if (!value && value != 0) return ""
    let result = ""
    if (multiple) {
      const resultList = []
      value.forEach((val) => {
        let obj = list.find((item) => item.value == val)
        if (obj) {
          resultList.push(obj.label)
        }
      })
      result = resultList.join(",")
    } else {
      list.some((item) => {
        if (item.value === value) {
          result = item.label
        }
      })
    }
    return result
  },
  // 递归获取权限菜单
  recursiveMenu(data, targetId = "root") {
    const menus = []
    if (data.length > 0) {
      data.forEach((item) => {
        if (item.parentId === targetId) {
          item.children = this.recursiveMenu(data, item.id)
          menus.push(item)
        }
      })
    }
    return menus
  },
  /**
   * 对象值清空
   * @param {Object} data
   */
  resetForm: (data) => {
    Object.keys(data).map((key) => {
      data[key] = ""
    })
  },
  /**
   * @param {String} str
   * @param {Boolean}
   * 是否是时间格式
   */
  isDate(str) {
    // console.log("判断时间",isNaN(str),Date.parse(str))
    return isNaN(str) && !isNaN(Date.parse(str))
  },
  /**
   * @param {Number} timeStamp 传入的时间戳
   * @param {Number} startType 要返回的时间字符串的格式类型，传入'year'则返回年开头的完整时间
   * 时间戳转时间格式
   */
  getDate: (dateStr) => {
    var date = new Date()
    if (dateStr) {
      date = new Date(dateStr)
    }
    var y = date.getFullYear()
    var m = date.getMonth() + 1
    var d = date.getDate()

    var h = date.getHours()
    var mm = date.getMinutes()
    var s = date.getSeconds()
    var ds =
      y +
      "-" +
      (m < 10 ? "0" + m : m + "") +
      "-" +
      (d < 10 ? "0" + d : d + "") +
      " " +
      (h < 10 ? "0" + h : h + "") +
      ":" +
      (mm < 10 ? "0" + mm : mm + "") +
      ":" +
      (s < 10 ? "0" + s : s + "")
    return ds
  },
  extend: function() {
    var src,
      copyIsArray,
      copy,
      name,
      options,
      clone,
      target = arguments[0] || {},
      i = 1,
      length = arguments.length,
      deep = false
    if (typeof target === "boolean") {
      deep = target
      target = arguments[i] || {}
      i++
    }
    if (typeof target !== "object" && typeof target !== "function") {
      target = {}
    }
    if (i === length) {
      return target
    }
    for (; i < length; i++) {
      if ((options = arguments[i]) != null) {
        for (name in options) {
          src = target[name]
          copy = options[name]
          if (target === copy) {
            continue
          }
          if (deep && copy && (copyIsArray = Array.isArray(copy))) {
            if (copyIsArray) {
              copyIsArray = false
              clone = src && Array.isArray(src) ? src : []
            } else {
              clone = src || {}
            }
            target[name] = this.extend(deep, clone, copy)
          } else if (copy !== undefined) {
            target[name] = copy
          }
        }
      }
    }
    return target
  },
  replace: function() {
    var target = arguments[0] || {},
      i = 1,
      options,
      name,
      item,
      copy,
      length = arguments.length,
      deep = false
    if (typeof target === "boolean") {
      deep = target
      target = arguments[1] || {}
      i = 2
    }
    while (i < length) {
      options = arguments[i]
      if (options !== null && options !== undefined) {
        for (name in target) {
          item = target[name]
          copy = options[name]
          if (target === copy) continue
          if (
            deep &&
            item &&
            typeof item === "object" &&
            !Array.isArray(item)
          ) {
            target[name] = this.replace(deep, item, copy)
          } else if (copy !== undefined) {
            target[name] = copy
          }
        }
      }
      i++
    }
    return target
  },
  /**
   * 获取URL中参数
   * @param     {[type]}    url [description]
   * @return    {[type]}        [description]
   */
  getRequestParam: function(url) {
    var data = {},
      index,
      len,
      param
    url = decodeURI(url || location.href)
    index = url.indexOf("?")
    if (index === -1) return data
    url = url.substr(index + 1)
    url = url.slice(0, url.indexOf("#")).split("&")
    index = 0
    len = url.length
    while (index < len) {
      param = url[index].split("=")
      if (param.length > 0) {
        data[param[0]] = param[1]
      }
      index++
    }
    return data
  },
  /**
   * 返回对象数组里某个key的所有值
   * @param     {[Array]}    data     [description]
   * @param     {[string]}    key      [description]
   * @param     {Boolean||function}   isfilter [description]
   * @return    {[Array]}             [返回对象数组里某个key的所有值]
   */
  getArrayKeys: function(data, key, callback) {
    var k = 0,
      len = data.length,
      item,
      value,
      res,
      arr = []
    if (Array.isArray(data) && typeof key === "string") {
      len = data.length
      while (k < len) {
        item = data[k]
        value = item[key]
        if (
          callback === true &&
          value !== null &&
          value !== undefined &&
          value !== ""
        ) {
          arr.push(value)
        } else if (typeof callback === "function") {
          res = callback.call(item, value, k)
          if (res === false) return arr
          arr.push(res || value)
        } else {
          arr.push(value)
        }
        k++
      }
    }
    return arr
  },
  getObjectKeys: function(items) {
    var k,
      len,
      item,
      data,
      args,
      arr = []
    if (Array.isArray(items)) {
      args = Array.prototype.slice.call(arguments, 1)
      k = 0
      len = items.length
      while (k < len) {
        item = items[k]
        data = {}
        args.map(function(value) {
          data[value] = item[value]
        })
        arr.push(data)
        k++
      }
    }
    return arr
  },
  /**
   * 数字转千分位
   * num 需要转换的数字 fixed 小数点保留几位
   */
  thousands: function(num, fixed) {
    if (!fixed) fixed = 2
    if (typeof num !== "number") num = Number(num)
    if (isNaN(num)) return ""
    num = num.toFixed(fixed).split(".")
    return [num[0].replace(/\d{1,3}(?=(\d{3})+$)/g, "$&,"), num[1]].join(".")
  },
  /**
   * 排序
   * @param {[string]} key
   */
  keysort: function(key) {
    return function(a, b) {
      return Number(b[key] - a[key])
    }
  },
  //导出表格以流的形式导出处理
  exportForm: function(res, name) {
    const link = document.createElement("a")
    let blob = new Blob([res], {
      type: "application/vnd.ms-excel",
    })
    link.style.display = "none"
    link.href = URL.createObjectURL(blob)
    link.download = `${name}` + ".xls" //下载的文件名
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  },
  flatten: function(arr) {
    while (arr.some((item) => Array.isArray(item))) {
      arr = [].concat(...arr)
    }
    return arr
  },
  getNumber: function(value) {
    return typeof value === "number" && !isNaN(value)
  },
  // 角色权限
  isPremssion: function(code) {
    return store.getters.permissionList.some((item) => item.route == code)
  },
  excelExport: function(data, title = "结果") {
    if ("msSaveOrOpenBlob" in navigator) {
      //兼容ie
      let blob = new Blob([data], {
        type: "application/vnd.ms-excel",
      })
      window.navigator.msSaveOrOpenBlob(blob, `${title}.xlsx`)
      return
    } else {
      const link = document.createElement("a")
      let blob = new Blob([data], {
        type: "application/vnd.ms-excel",
      })
      link.style.display = "none"
      link.href = URL.createObjectURL(blob)
      link.setAttribute("download", `${title}.xlsx`)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
  },
  /**
   * 深克隆
   *
   */
  deepClone: function(target) {
    if (target === null) return null
    if (typeof target !== "object") return target
    const cloneTarget = Array.isArray(target) ? [] : {}
    for (let prop in target) {
      if (target.hasOwnProperty(prop)) {
        cloneTarget[prop] = deepClone(target[prop])
      }
    }
    return cloneTarget
  },
  //身份证算年龄
  idToAge:function (IDCard){
    var age = 0,yearBirth,monthBirth,dayBirth;
    //获取用户身份证号码
    var userCard = IDCard;
    //如果身份证号码为undefind则返回空
    if(!userCard){
      return age;
    }
    var reg = /(^\d{15}$)|(^\d{17}([0-9]|X)$)/; //验证身份证号码的正则
    if (reg.test(userCard)) {
      if (userCard.length == 15) {
          var org_birthday = userCard.substring(6, 12);
          //获取出生年月日
          yearBirth = "19" + org_birthday.substring(0, 2);
          monthBirth = org_birthday.substring(2, 4);
          dayBirth = org_birthday.substring(4, 6);
          } else if (userCard.length == 18) {
          //获取出生年月日
          yearBirth = userCard.substring(6,10);
          monthBirth = userCard.substring(10,12);
          dayBirth = userCard.substring(12,14);
          
        }
        //获取当前年月日并计算年龄
        var myDate = new Date();
        var monthNow = myDate.getMonth() + 1;
        var dayNow = myDate.getDate();
        var age = myDate.getFullYear() - yearBirth;
        if(monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)){
          age--;
        }
        //返回年龄
        return age;
    } else {
      return ''
    }
    
  }
  
}
