import useMainStore from '@/store/main'
import Big from 'big.js'
/**
 * @description 是否被定义
 * @param {any} val
 * @returns {Boolean}
 */

export function isDefine(val: any) {
  return val !== void 0 && val !== null
}

/**
 * @description 类型判断
 * @param {any} data
 * @returns {String}
 */
export function typeOf(data: any) {
  return Object.prototype.toString
    .call(data)
    .match(/\[object\s+(.*)\]/)?.[1]
    ?.toLocaleLowerCase()
}

/**
 * @description 对象空属性(undefined | null)过滤
 * @param  {Object} data 过滤对象
 * @returns {Object}
 */
export function filterEmpty(data: Record<string, unknown>) {
  if (typeOf(data) === 'object') {
    data = Object.entries(data).reduce<Record<string, unknown>>((d, [k, v]) => {
      if (isDefine(v)) {
        d[k] = v
      }
      return d
    }, {})
  }
  return data
}

/**
 * @description 数字转中文
 * @param {Number} number
 * @return {string}
 */

export const numberToChinese = (num: number) => {
  const DICT = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
  const UNIT = ['', '十', '百', '仟', '萬', '億', '点', '']
  const a = ('' + num).replace(/(^0*)/g, '').split('.')
  let k = 0
  let re = ''

  for (let i = a[0].length - 1; i >= 0; i--) {
    switch (k) {
      case 0:
        re = UNIT[7] + re
        break
      case 4:
        if (!new RegExp('0{4}//d{' + (a[0].length - i - 1) + '}$').test(a[0])) re = UNIT[4] + re
        break
      case 8:
        re = UNIT[5] + re
        UNIT[7] = UNIT[5]
        k = 0
        break
    }
    if (k % 4 == 2 && a[0].charAt(i + 2) !== '0' && a[0].charAt(i + 1) === '0') re = DICT[0] + re
    if (a[0].charAt(i) !== '0') re = DICT[+a[0].charAt(i)] + UNIT[k % 4] + re
    k++
  }
  if (a.length > 1) {
    // 加上小数部分(如果有小数部分)
    re += UNIT[6]
    for (let i = 0; i < a[1].length; i++) re += DICT[+a[1].charAt(i)]
  }
  if (re == '一十') re = '十'
  if (re.match(/^一/) && re.length == 3) re = re.replace('一', '')
  return re
}

/**
 * @description 从content-disposition中提取文件名
 */
export const extractFileName = (str: string) => {
  if (/filename=([^;\s]*)/gi.test(str)) {
    return decodeURIComponent(RegExp.$1)
  }
  return ''
}

/**
 * @description 文件下载 Blob
 */
export const downloadBlob = (blob: Blob, filename = '') => {
  const a = document.createElement('a')
  a.download = filename
  const blobUrl = URL.createObjectURL(blob)
  a.href = blobUrl
  document.body.appendChild(a)
  a.click()
  a.remove()
  URL.revokeObjectURL(blobUrl)
}

/**
 *
 * @param { String } eleName // elementName
 * @returns { HTMLElement }
 */
export const createFakeDom = <K extends keyof HTMLElementTagNameMap>(eleName: K) => {
  const dom = document.createElement(eleName)
  dom.style.position = 'fixed'
  dom.style.zIndex = '-999999'
  return dom
}

/**
 * @param { Number } number
 * @returns { Number[] } []
 */
export const getNumbers = (n: number, interval: number) => {
  if (!n) {
    return [0]
  }

  if (!interval || n < interval) {
    return [0, n]
  }

  let current = new Big(0)
  const numbers = [0]
  while (current.toNumber() < n) {
    current = current.add(interval)
    const curValue = current.toNumber()
    if (curValue >= n) {
      numbers.push(n)
    } else {
      numbers.push(curValue)
    }
  }
  return numbers
}

/**
 * @return { Number }
 */
export const add = (...args: number[]) => {
  const result = args.reduce((total, n) => {
    return total.add(n)
  }, new Big(0))
  return result.toNumber()
}

/**
 * @return { Number }
 */
export const minus = (num: number, ...args: number[]) => {
  const result = args.reduce((total, n) => {
    return total.minus(n)
  }, new Big(num))
  return result.toNumber()
}

/**
 * @param { any } val
 * @return { Boolean } is HTMLElement
 */

export const isDom = <T extends HTMLElement>(val: any): val is T => {
  return typeof HTMLElement === 'function'
    ? val instanceof HTMLElement
    : val && typeof val === 'object' && val.nodeType === 1 && typeof val.nodeName === 'string'
}

/**
 * @param { Number } time
 * @return { Object }
 */

export const timeFormat = (time: number) => {
  if (!time) {
    return ''
  }
  const DAY = 24 * 60 * 60 * 1000
  const HOUR = 60 * 60 * 1000
  const MINUTE = 60 * 1000
  const SECOND = 1000

  const timeObject: Record<string, number> = {
    d: (time / DAY) | 0,
    h: ((time % DAY) / HOUR) | 0,
    m: ((time % HOUR) / MINUTE) | 0,
    s: ((time % MINUTE) / SECOND) | 0,
  }

  const unitMap: Record<keyof typeof timeObject, string> = {
    d: '天',
    h: '时',
    m: '分',
    s: '秒',
  }

  return Object.entries(unitMap).reduce((format, [key, unit]) => {
    if (timeObject[key] || format) {
      format += `${timeObject[key]} ${unit}`
    }
    return format
  }, '')
}

export const getCurDayRange = () => {
  const date = new Date()
  const tomorrow = new Date(date.getTime() + 1000 * 60 * 60 * 24)
  const year = date.getFullYear()
  const tomorrowYear = tomorrow.getFullYear()
  let month: number | string = date.getMonth() + 1
  let tomorrowMonth: number | string = tomorrow.getMonth() + 1
  let day: number | string = date.getDate()
  let tomorrowDay: number | string = tomorrow.getDate()
  month < 10 && (month = '0' + month)
  tomorrowMonth < 10 && (tomorrowMonth = '0' + tomorrowMonth)
  day < 10 && (day = '0' + day)
  tomorrowDay < 10 && (tomorrowDay = '0' + tomorrowDay)
  return [`${year}${month}${day}000000`, `${tomorrowYear}${tomorrowMonth}${tomorrowDay}000000`]
}

export function getTodayByDay() {
  const date = new Date()
  const year = date.getFullYear()
  let month: number | string = date.getMonth() + 1
  let day: number | string = date.getDate()
  month < 10 && (month = '0' + month)
  day < 10 && (day = '0' + day)
  return `${year}${month}${day}`
}

export const transHtmlContent = (content: string) => {
  return content
    .replaceAll(/<[^>]+>/gim, '')
    .replace('&quot;', '"')
    .replace('&amp;', '&')
    .replace('&lt;', '<')
    .replace('&gt;', '>')
    .replace('&nbsp;', ' ')
}

// 首先判断当前dom是否已经包含了要添加的类
export function hasClass(el: any, className: string) {
  const reg = new RegExp('(^|\\s)' + className + '(\\s|$)')
  return reg.test(el.className)
}
// 动态添加class
export function toggleClass(el: any, className: string) {
  const newClass = el.className.split(' ')
  if (hasClass(el, className)) {
    newClass.splice(newClass.indexOf(className), 1)
  } else {
    newClass.push(className)
  }
  el.className = newClass.join(' ')
}

export const myColorList = [
  '#3B99D4',
  '#8ED14B',
  '#F06B49',
  '#ECC2F1',
  '#82C7C3',
  '#E3698A',
  '#1776EB',
  '#F5B2AC',
  '#533085',
  '#89363A',
  '#19413E',
  '#D92B45',
  '#60C9FF',
  '#1B9F2E',
  '#BA217D',
  '#076B82',
  '#FF7F00',
  '#6B238E',
  '#238E23',
  '#23238E',
  '#FF2400',
  '#5C4033',
  '#E9C2A6',
  '#4A766E',
  '#9F5F9F',
]

export const setPaneSize = (e: any) => {
  const mainStore = useMainStore()
  mainStore.setPaneSizeConfig(location.pathname, e[0].size)
}

const images: any = []
export const preloadImg = (url: any) => {
  const find = images.find((img: any) => img.src == url)
  if (url && !find) {
    const img = new Image()
    img.src = url
    images.push(img)
  }
}
