// import { parseTime } from '@/ruoyi'
import _ from 'lodash'
import dayjs from 'dayjs'
import i18n from '@/i18n/index'

/**
 * 表格时间格式化
 */
export function formatDate(cellValue) {
  if (cellValue == null || cellValue == '') return ''
  var date = new Date(cellValue)
  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()
  var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d: any = 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() + '分'
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xdc00 && code <= 0xdfff) i--
  }
  return s
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray: Array<any> = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map((key) => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach((v) => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach((property) => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString = classString.substr(0, nameIndex) + classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
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: any) {
    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
  }
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + ''
  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  return (+(randomNum + timestamp)).toString(32)
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

export function makeMap(str, expectsLowerCase) {
  const map = Object.create(null)
  const list = str.split(',')
  for (let i = 0; i < list.length; i++) {
    map[list[i]] = true
  }
  return expectsLowerCase ? (val) => map[val.toLowerCase()] : (val) => map[val]
}

export const exportDefault = 'export default '

export const beautifierConf = {
  html: {
    indent_size: '2',
    indent_char: ' ',
    max_preserve_newlines: '-1',
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: 'separate',
    brace_style: 'end-expand',
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: false,
    end_with_newline: true,
    wrap_line_length: '110',
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true,
  },
  js: {
    indent_size: '2',
    indent_char: ' ',
    max_preserve_newlines: '-1',
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: 'normal',
    brace_style: 'end-expand',
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: true,
    end_with_newline: true,
    wrap_line_length: '110',
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true,
  },
}

// 首字母大小
export function titleCase(str: string) {
  return str.replace(/( |^)[a-z]/g, (L) => L.toUpperCase())
}

// 下划转驼峰
export function camelCase(str: string) {
  return str.replace(/_[a-z]/g, (str1) => str1.substr(-1).toUpperCase())
}

export function isNumberStr(str: string) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
}

/**
 * 根据时间段生成欢迎语
 */
export const welcomeMsg = () => {
  const t = i18n.global.t
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? t('message.user.helloMessage1') : hour <= 11 ? t('message.user.helloMessage2') : hour <= 13 ? t('message.user.helloMessage3') : hour < 18 ? t('message.user.helloMessage4') : t('message.user.helloMessage5')
}

/**
 * 将接口返回的多条json数据（带label的），转为一条json数据
 * @param {*} apiRes
 */
export const reformateObjectRes = (apiRes) => {
  const obj = {}
  for (const key in apiRes) {
    obj[key] = apiRes[key].value
  }
  return obj
}

/**
 * 过滤掉返回对象中不需要的字段
 */
export const filterObject = (obj, fields) => {
  const newObj = {}
  for (const key in obj) {
    if (fields.includes(key)) {
      newObj[key] = obj[key]
    }
  }
  return newObj
}

/**
 * 传入角色id列表、角色详细列表、key，根据key，获取key对应的值的合并集合，并转为string返回
 */
export const getMergeValue = (roleIds, roleDetailList, key) => {
  let arr = []
  for (const roleId of roleIds) {
    const roleDetail = roleDetailList.find((item) => item.id === roleId)
    if (roleDetail) {
      let innerArr = roleDetail[key].split(',')
      if (innerArr.length) {
        innerArr.forEach((innerItem) => {
          if (innerItem) arr.push(innerItem)
        })
      }
    }
  }
  if (arr.length) return _.uniq(arr).join(',')
  return ''
}

/**
 * 转化后台请求的时间范围工具
 */
export const transApiQueryTimeRange = (timeData, num) => {
  let result = {}
  if (timeData && timeData.length) {
    const startTime = dayjs(timeData[0]).format('YYYY-MM-DD HH:mm:ss')
    const endTime = dayjs(timeData[1]).format('YYYY-MM-DD HH:mm:ss')
    result[`search_startdate${num}`] = startTime
    result[`search_enddate${num}`] = endTime
    return result
  }
  return {}
}

/**
 *
 * @param {*} type near:近N个单位（从此时此刻往前倒推） ,this:当前N个单位(从当前单位的结束时刻往前倒推)
 * @param {*} range DD:天，MM:月，YYYY:年
 * @param {*} num 数量
 * @param {*} formate 日期格式化
 * @returns
 */
export const getTimeRange = (type, range, num, formate) => {
  let result = []
  if (type === 'near') {
    switch (range) {
      case 'DD':
        result = [dayjs().subtract(num, 'day').format(formate), dayjs().format(formate)]
        break

      case 'MM':
        break

      case 'YYYY':
        break

      default:
        break
    }
  } else if (type === 'this') {
    switch (range) {
      case 'DD':
        result = [
          dayjs()
            .subtract(num - 1, 'day')
            .startOf('day')
            .format(formate),
          dayjs().endOf('day').format(formate),
        ]
        break

      case 'MM':
        break

      case 'YYYY':
        break

      default:
        break
    }
  }

  return result
}

/**
 * 将字典数据转为title显示
 * @param {*} dictsData
 * @param {*} cellValue
 * @returns
 */
export const transDict = (dictsData, cellValue) => {
  if (dictsData) {
    const filter = dictsData.filter((item) => {
      return String(item.substance) === String(cellValue)
    })
    return filter.length > 0 ? filter[0].title : '-'
  }
}

/**
 * 根据身份证号，得到姓别、生日、精确计算年龄、生肖
 * @param {*} IDCard
 * @returns
 */
export const analyzeIDCard = (IDCard) => {
  var result = {}
  //获取用户身份证号码
  var userCard = IDCard
  //如果身份证号码为undefind则返回空
  if (!userCard) {
    return result
  }
  //获取性别
  if (parseInt(userCard.substr(16, 1)) % 2 == 1) {
    result.sex = '男'
  } else {
    result.sex = '女'
  }
  //获取出生年月日
  //userCard.substring(6,10) + "-" + userCard.substring(10,12) + "-" + userCard.substring(12,14);
  var yearBirth = userCard.substring(6, 10)
  var monthBirth = userCard.substring(10, 12)
  var dayBirth = userCard.substring(12, 14)

  result.birth = yearBirth + '-' + monthBirth + '-' + dayBirth

  //获取当前年月日并计算年龄
  var myDate = new Date()
  var monthNow = myDate.getMonth() + 1
  var dayNow = myDate.getDay()
  var age = myDate.getFullYear() - yearBirth
  if (monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)) {
    age--
  }
  //得到年龄
  result.age = age

  //算生肖
  let zodiac = ''
  let yearStart = 1901
  let calcNum = (yearStart - yearBirth) % 12
  if (calcNum == 1 || calcNum == -11) {
    zodiac = '鼠'
  }

  if (calcNum == 0) {
    zodiac = '牛'
  }
  if (calcNum == 11 || calcNum == -1) {
    zodiac = '虎'
  }
  if (calcNum == 10 || calcNum == -2) {
    zodiac = '兔'
  }
  if (calcNum == 9 || calcNum == -3) {
    zodiac = '龙'
  }
  if (calcNum == 8 || calcNum == -4) {
    zodiac = '蛇'
  }
  if (calcNum == 7 || calcNum == -5) {
    zodiac = '马'
  }
  if (calcNum == 6 || calcNum == -6) {
    zodiac = '羊'
  }
  if (calcNum == 5 || calcNum == -7) {
    zodiac = '猴'
  }
  if (calcNum == 4 || calcNum == -8) {
    zodiac = '鸡'
  }
  if (calcNum == 3 || calcNum == -9) {
    zodiac = '狗'
  }
  if (calcNum == 2 || calcNum == -10) {
    zodiac = '猪'
  }
  result.zodiac = zodiac

  //返回性别和年龄
  return result
}

/**
 * 判断对象数组中是否包含某个指定的值
 * @param {*} originArr
 * @param {*} param1
 */
export const hasOnlyKey = (originArr, { keyName, keyValue }) => {
  return originArr.some((val, index) => {
    return val[keyName] === keyValue
  })
}

/**
 * 传入一个对象数组，返回获取指定key的值的arr
 * @param {*} originArr
 * @param {*} key
 */
export const getArrJsonValue2Arr = (originArr, key) => {
  const tarArr = []
  if (key) {
    originArr.forEach((item, index) => {
      tarArr.push(item[key])
    })
  } else {
    originArr.forEach((item, index) => {
      tarArr.push(Object.values(item))
    })
  }

  return tarArr
}

/**
 * chart趋势图数据格式化
 * @param {*} param
 * @returns
 */
export const fitChartData = ({ startDate, endDate, originData }) => {
  // console.log('startDate:', startDate)
  // console.log('endDate:', endDate)
  // console.log('originData:', originData)
  const allData = []

  const daysNum = dayjs(endDate).diff(dayjs(startDate), 'day')

  for (let index = 0; index <= daysNum; index++) {
    let currentDate = dayjs(startDate).add(index, 'day').format('YYYY-MM-DD')

    const filter = originData.filter((item) => {
      return item['日期'] === currentDate
    })

    if (dayjs().isSameOrAfter(currentDate, 'day')) {
      if (filter.length) {
        allData.push({
          date: currentDate,
          type: 'orderNum',
          value: filter[0]['订单数量'],
        })
        allData.push({
          date: currentDate,
          type: 'contract',
          value: filter[0]['今日合同金额'],
        })
        allData.push({
          date: currentDate,
          type: 'collected',
          value: filter[0]['今日收款金额'],
        })
      } else {
        allData.push({
          date: currentDate,
          type: 'orderNum',
          value: 0,
        })
        allData.push({
          date: currentDate,
          type: 'contract',
          value: 0,
        })
        allData.push({
          date: currentDate,
          type: 'collected',
          value: 0,
        })
      }
    }
  }

  return allData
}

/**
 * 将wangEditor返回的html字符串处理图片和视频样式
 */
export const handleEditorHtml = (html, type) => {
  var doc = new DOMParser().parseFromString(html, 'text/html')

  var videoTags = doc.getElementsByTagName('video')
  // 处理所有video标签
  for (var i = 0; i < videoTags.length; i++) {
    videoTags[i].setAttribute('width', type === 'save' ? '100%' : '400')
    videoTags[i].setAttribute('height', 'auto')
    videoTags[i].setAttribute('autoplay', 'autoplay')
  }
  // 处理所有img标签
  var imgTags = doc.getElementsByTagName('img')
  for (var i = 0; i < imgTags.length; i++) {
    imgTags[i].setAttribute('width', '100%')
    imgTags[i].setAttribute('height', 'auto')
  }

  return doc.documentElement.innerHTML
}
