import { isIdCard } from "./validate"

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description 格式化时间
 * @param time
 * @param cFormat
 * @returns {string|null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}"
  let date
  if (typeof time === "object") {
    date = time
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value]
    }
    if (result.length > 0 && value < 10) {
      value = "0" + value
    }
    return value || 0
  })
  return time_str
}

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description 格式化时间
 * @param time
 * @param option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (("" + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return "刚刚"
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + "分钟前"
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + "小时前"
  } else if (diff < 3600 * 24 * 2) {
    return "1天前"
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      "月" +
      d.getDate() +
      "日" +
      d.getHours() +
      "时" +
      d.getMinutes() +
      "分"
    )
  }
}

/**
 * @description 计算时间差
 * @param startTime
 * @param endTime
 * @returns {string} xx天xx小时xx分xx秒
 */
export function getTimePoor(startTime, endTime) {
  if (!startTime || !endTime) {
    return ""
  }
  let result = ""
  let date = new Date(endTime).getTime() - new Date(startTime).getTime() //时间差的毫秒数
  //------------------------------
  //计算出相差天数
  let days = Math.floor(date / (24 * 3600 * 1000))
  if (days > 0) result += days + "天 "
  //计算出小时数

  let leave1 = date % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
  let hours = Math.floor(leave1 / (3600 * 1000))
  if (hours > 0) result += hours + "小时 "
  //计算相差分钟数
  let leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
  let minutes = Math.floor(leave2 / (60 * 1000))
  if (minutes > 0) result += minutes + "分 "
  //计算相差秒数
  let leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
  let seconds = Math.round(leave3 / 1000)
  if (seconds > 0) result += seconds + "秒"
  return result
}

/**
 * @description 根据身份证获取出生日期 年龄 性别
 * @param idCard
 * @param type birthDate age gender
 * @returns {string}
 */
export function getInfoByIdCard(idCard, type = "birthDate") {
  if (!isIdCard(idCard)) return
  let birthDate
  let age
  let gender

  const orgBirthDate = idCard.substring(6, 14)
  const orgGender = idCard.substring(16, 17)

  gender = orgGender % 2 == 1 ? "1" : "2"

  birthDate =
    orgBirthDate.substring(0, 4) +
    "-" +
    orgBirthDate.substring(4, 6) +
    "-" +
    orgBirthDate.substring(6, 8)

  const birthdays = new Date(birthDate.replace(/-/g, "/"))
  let d = new Date()
  age =
    d.getFullYear() -
    birthdays.getFullYear() -
    (d.getMonth() < birthdays.getMonth() ||
      (d.getMonth() == birthdays.getMonth() && d.getDate() < birthdays.getDate())
      ? 1
      : 0)

  switch (type) {
    case "birthDate":
      return birthDate
    case "age":
      return age
    case "gender":
      return gender
    default:
      return
  }
}

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description 将url请求参数转为json格式
 * @param url
 * @returns {{}|any}
 */
export function paramObj(url) {
  const search = url.split("?")[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"')
      .replace(/\+/g, " ") +
    '"}'
  )
}

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description 父子关系的数组转换成树形结构数据
 * @param data
 * @returns {*}
 */
export function translateDataToTree(data) {
  const parent = data.filter(
    (value) => value.parentId === "undefined" || value.parentId == null
  )
  const children = data.filter(
    (value) => value.parentId !== "undefined" && value.parentId != null
  )
  const translator = (parent, children) => {
    parent.forEach((parent) => {
      children.forEach((current, index) => {
        if (current.parentId === parent.id) {
          const temp = JSON.parse(JSON.stringify(children))
          temp.splice(index, 1)
          translator([current], temp)
          typeof parent.children !== "undefined"
            ? parent.children.push(current)
            : (parent.children = [current])
        }
      })
    })
  }
  translator(parent, children)
  return parent
}

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description 树形结构数据转换成父子关系的数组
 * @param data
 * @returns {[]}
 */
export function translateTreeToData(data) {
  const result = []
  data.forEach((item) => {
    const loop = (data) => {
      result.push({
        id: data.id,
        name: data.name,
        parentId: data.parentId,
      })
      const child = data.children
      if (child) {
        for (let i = 0; i < child.length; i++) {
          loop(child[i])
        }
      }
    }
    loop(item)
  })
  return result
}

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description 10位时间戳转换
 * @param time
 * @returns {string}
 */
export function tenBitTimestamp(time) {
  const date = new Date(time * 1000)
  const y = date.getFullYear()
  let m = date.getMonth() + 1
  m = m < 10 ? "" + m : m
  let d = date.getDate()
  d = d < 10 ? "" + d : d
  let h = date.getHours()
  h = h < 10 ? "0" + h : h
  let minute = date.getMinutes()
  let second = date.getSeconds()
  minute = minute < 10 ? "0" + minute : minute
  second = second < 10 ? "0" + second : second
  return y + "年" + m + "月" + d + "日 " + h + ":" + minute + ":" + second //组合
}

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description 13位时间戳转换
 * @param time
 * @returns {string}
 */
export function thirteenBitTimestamp(time) {
  const date = new Date(time / 1)
  const y = date.getFullYear()
  let m = date.getMonth() + 1
  m = m < 10 ? "" + m : m
  let d = date.getDate()
  d = d < 10 ? "" + d : d
  let h = date.getHours()
  h = h < 10 ? "0" + h : h
  let minute = date.getMinutes()
  let second = date.getSeconds()
  minute = minute < 10 ? "0" + minute : minute
  second = second < 10 ? "0" + second : second
  return y + "年" + m + "月" + d + "日 " + h + ":" + minute + ":" + second //组合
}

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description 获取随机id
 * @param length
 * @returns {string}
 */
export function uuid(length = 32) {
  const num = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
  let str = ""
  for (let i = 0; i < length; i++) {
    str += num.charAt(Math.floor(Math.random() * num.length))
  }
  return str
}

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description m到n的随机数
 * @param m
 * @param n
 * @returns {number}
 */
export function random(m, n) {
  return Math.floor(Math.random() * (m - n) + n)
}

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description addEventListener
 * @type {function(...[*]=)}
 */
export const on = (function () {
  return function (element, event, handler, useCapture = false) {
    if (element && event && handler) {
      element.addEventListener(event, handler, useCapture)
    }
  }
})()

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description removeEventListener
 * @type {function(...[*]=)}
 */
export const off = (function () {
  return function (element, event, handler, useCapture = false) {
    if (element && event) {
      element.removeEventListener(event, handler, useCapture)
    }
  }
})()

/**
 * @description 防抖
 * @param func
 * @param wait
 * @param immediate
 * @returns {Function}
 *
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }
  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * @description 节流
 * @param fn
 * @param delay
 * @param immediate
 * @returns {Function}
 */
export function throttle(fn, delay = 500, immediate = false) {
  let timer = null,
    immediateTimer = null,
    immediateRunning = !immediate

  return function () {
    let context = this,
      args = arguments

    if (immediate && !immediateRunning) {
      fn.apply(context, args)
      immediateRunning = true
      // // 重置首次执行标识
      immediateTimer = setTimeout(() => {
        immediateRunning = false
      }, delay)
      return
    }

    if (!timer) {
      // 如果有后续触发，在定时器中取消immediateTimer
      if (immediateTimer) {
        clearTimeout(immediateTimer)
        immediateTimer = null
      }

      timer = setTimeout(() => {
        fn.apply(context, args)
        timer = null
        immediateTimer = setTimeout(() => {
          immediateRunning = false
        }, delay)
      }, delay)
    }
  }
}

/**
 * @description excel导出
 * @param data
 * @param title
 *
 */

export function excelExport(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)
  }
}

/**
 * 根据list、value 得出 label
 * @export
 * @param {*} list 数据list
 * @param {*} value 对应值
 * @returns
 */
export function formatDicList(list, value, connector = ",") {
  if (!list) return ""
  if (list.constructor !== Array) return ""
  // if (!value && value != 0) return ""
  let result = "--"
  let multiple = Array.isArray(value) ? true : false
  if (multiple) {
    const resultList = []
    value.forEach((val) => {
      let obj = list.find((item) => item.value == val)
      if (obj) {
        resultList.push(obj.label)
      }
    })
    result = resultList.join(connector)
  } else {
    list.some((item) => {
      if (item.value === value) {
        result = item.label
      }
    })
  }
  return result
}
/**
 * base64编码转换成pdf
 * @export
 * @param {*} code base64字符串
 * @returns url pdf地址
 */
export function base64ToPdf(code) {
  code = res.data.replace(/\\r|\\n/g, "")
  let raw = window.atob(code)
  let rawLen = raw.length
  let arr = new Uint8Array(rawLen)
  for (let i = 0; i < rawLen; ++i) {
    arr[i] = raw.charCodeAt(i)
  }
  let bold = new Blob([arr], { type: "application/pdf" })
  return URL.createObjectURL(bold)
}

/**
 * 秒转换成天时分秒
 * @export
 * @param time
 * @returns {string}
 */
export function changeTime(time) {
  let day = Math.floor(time / 86400) //天
  let hours = Math.floor((time % 86400) / 3600) //时
  let minutes = Math.floor((time % 3600) / 60) //分
  let seconds = Math.floor(time % 60) //秒
  return `${day ? day + "天" : ""} ${hours ? hours + "小时" : ""}${
    minutes ? minutes + "分" : ""
    }${seconds}秒`
}

export default { formatDicList, excelExport }
