/**
 * 格式化时间
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || 'y-m-d h:i:s'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(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]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * @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 = 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 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
}

/**
 * 向上寻找最近的父组件
 * @params context当前 this
 * @params name 寻找父亲组件实例
 *
 *  */
export function findComponentUpward(context, componentName) {
  let parent = context.$parent
  let name = parent.$options.name
  while (parent && (!name || [componentName].indexOf(name) < 0)) {
    parent = parent.$parent
    if (parent) name = parent.$options.name
  }
  return parent
}

/**
 * 根据子集查找父集
 * @params tree tree树形数据
 *
 *  */
export function queryParent(tree, checkName, optionName, childName = 'children', targetName = '') {
  const level = [];
  (function queryParent(data, checkName, parent) {
    Array.isArray(data) &&
    data.forEach((item, index) => {
      if (item[optionName] !== checkName) {
        item[childName] && queryParent(item[childName], checkName, [data, index])
      } else {
        parent && queryParent(tree, parent[0][parent[1]][optionName])
        level.push(targetName === '' ? item[optionName] : item[targetName])
      }
    })
  })(tree, checkName)
  return level
}

// 处理tree children为空的情况
export function treeChildrenEmpty(tree, type = 'children') {
  return tree.map(item => {
    if (item[type] && item[type].length !== 0) {
      treeChildrenEmpty(item[type], type)
    } else {
      delete item[type]
    }
    return item
  })
}

// 处理tree label 和 value
export function treeLabelValue(tree, options, type = 'children') {
  tree.forEach(item => {
    const { label, value } = options
    if (item[type] && item[type].length) {
      treeLabelValue(item[type], options, type)
    }
    item.label = item[label]
    item.value = item[value]
  })
}

// 字符串首字母大写
export const strFirstUpper = str =>
  str.replace(/( |^)[a-z]/g, first => first.toUpperCase())

/**
 * @desc 函数防抖
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param immediate true 表立即执行，false 表非立即执行
 */
export function debounce(func, wait, immediate) {
  let timeout
  return function(...args) {
    if (timeout) clearTimeout(timeout)
    if (immediate) {
      const callNow = !timeout
      timeout = setTimeout(() => {
        timeout = null
      }, wait)
      if (callNow) func.apply(this, args)
    } else {
      timeout = setTimeout(() => {
        func.apply(this, args)
      }, wait)
    }
  }
}

/**
 * 字典数据把code转换成name
 * @params list list数据
 * @params code 所传的code值
 * @params codeType 查找的list对应的类型 例如 id或者code
 * @params type 返回list中所对应的值
 * */
export function codeChangeName(list, code, codeType = 'code', type = 'name') {
  if (Array.isArray(list)) {
    const row = list.filter(item => (item[codeType] === code))
    if (row.length) {
      return row[0][type]
    }
  }
}

/**
 * 过滤数组没有必要的值
 * @params list 所需的数组
 * @params code 所传的过滤的值即属性， 如果是一个字符串的话，过滤一项， 如果是数组的过滤两个属性的值
 * @params codeType 查找的list对应的类型 例如 id或者code
 * */
export function filterListData(list, code, codeType = 'code') {
  if (Array.isArray(list)) {
    var filterList = list
    const getList = (list, code, codeType) => {
      filterList = list.filter(item => (item[codeType] !== code))
      return filterList
    }
    if (Array.isArray(code)) {
      for (let i = 0; i < code.length; i++) {
        getList(filterList, code[i], codeType)
        if (code.length - 1 === i) return filterList
      }
    } else {
      return getList(list, code, codeType)
    }
  }
}

// 导出附件
export function exportFile(res, name) {
  if (!res.data) return
  const url = window.URL.createObjectURL(new Blob([res.data]))
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  // 获取文件的名字
  var newName = ''
  var filename = res.headers
  filename = filename['content-disposition']
  filename = filename.split(';')[1].split('filename=')[1]
  newName = decodeURI(filename)
  link.setAttribute(
    'download',
    name || newName
  )
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// Url打开一个新的页面
export function exportUrl(url, name) {
  if (!url) return
  window.open(url, '_blank') // 新窗口打开外链接
}

/**
 * 深拷贝
 * @param {Object} source
 * */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'shallowClone')
  }
  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
}

import { Message, Loading } from 'element-ui'
export function Loadings(text, time = 60 * 1000) {
  const loading = Loading.service({
    lock: true,
    text: text || '正在处理您的操作，请稍候...',
    spinner: 'el-icon-loading',
    color: '#fff',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  setTimeout(() => {
    if (loading.visible) {
      Message.error('请求超时')
      loading.close()
    }
  }, time)
  return loading
}

// 千分符并保留两位小数
export function handleMoney(str) {
  const strNum = Number(str)
  const num = strNum.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,')
  return num
}

// 千分符并保留四位小数
export function fourMoney(str) {
  const strNum = Number(str)
  const num = strNum.toFixed(4).replace(/(\d)(?=(\d{3})+\.)/g, '$1,')
  return num
}

/**
 * 结束实际的禁止选择
 * @param startDate 开始时间
 * @param isSelf 是否包含本身时间, 默认包含
 **/
export function endPickerDate(startDate, endDate, isSelf = true) {
  return {
    disabledDate: (time) => {
      if (startDate) {
        if (isSelf) {
          if (endDate) {
            return (time.getTime() < new Date(startDate).getTime() || time.getTime() > new Date(endDate).getTime())
          } else {
            return time.getTime() < new Date(startDate).getTime()
          }
        } else {
          if (endDate) {
            return (time.getTime() < new Date(startDate).getTime() + 3600 * 24 * 1000 || time.getTime() > new Date(endDate).getTime() - 3600 * 24 * 1000)
          } else {
            return time.getTime() < new Date(startDate).getTime() + 3600 * 24 * 1000
          }
        }
      } else {
        if (isSelf) {
          return time.getTime() > new Date(endDate).getTime()
        } else {
          return time.getTime() > new Date(endDate).getTime() + 3600 * 24 * 1000
        }
      }
    }
  }
}

/**
 * 计算两个时间的差值
 * @param start 开始时间
 * @param end 结束时间
 **/
export function startAndEndValue(end, start) {
  if (start && end) {
    return parseInt((new Date(end).getTime() - new Date(start).getTime()) / (1000 * 60 * 60 * 24) + 1)
  } else {
    return ''
  }
}

// 数组对象去重
export function deduplicateArray(array, key = 'id') {
  // 使用一个Map对象来存储已经出现过的id值
  const idMap = new Map()
  // 遍历数组进行去重
  const deduplicatedArray = []
  for (const item of array) {
    const id = item[key]
    // 如果id不存在于Map中，则将该对象添加到结果数组中，并将id添加到Map中
    if (!idMap.has(id)) {
      idMap.set(id, true)
      deduplicatedArray.push(item)
    }
  }
  return deduplicatedArray
}

export function amountInWords(value) {
  if (!value) {
    return ''
  }
  const fraction = ['角', '分']
  const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  const unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']]
  let num = Math.abs(Number(value.split(',').join('')))
  let s = ''
  fraction.forEach((item, index) => {
    s += (digit[Math.floor(num * 10 * (10 ** index)) % 10] + item).replace(/零./, '')
  })
  s = s || '整'
  num = Math.floor(num)
  for (let i = 0; i < unit[0].length && num > 0; i += 1) {
    let p = ''
    for (let j = 0; j < unit[1].length && num > 0; j += 1) {
      p = digit[num % 10] + unit[1][j] + p
      num = Math.floor(num / 10)
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
  }
  return s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/) || ''
}

// 金额格式化
// 金额的格式化s为要格式化的参数（浮点型），n为小数点后保留的位数
export function formatMoney(amount, decimalPlaces = 2) {
  const amountNum = Number(amount)
  const options = {
    minimumFractionDigits: decimalPlaces,
    maximumFractionDigits: decimalPlaces
  }
  return amountNum.toLocaleString(undefined, options)
}

// 处理后端字段为null的情况
export function replaceNull(obj) {
  for (const key in obj) {
    if (obj[key] === null) {
      obj[key] = ''
    } else if (typeof obj[key] === 'object') {
      replaceNull(obj[key]) // 递归调用
    }
  }
}

// 生成uuid
export function getUuid() {
  var s = []
  var hexDigits = '0123456789abcdef'
  for (var i = 0; i < 32; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  var uuid = s.join('')
  return uuid
}

// 简单的深拷贝
export function cloneDeep(value) {
  if (value == null) {
    return value;
  }

  if (typeof value !== 'object') {
    return value;
  }

  if (Array.isArray(value)) {
    const arrCopy = [];
    for (let i = 0; i < value.length; i++) {
      arrCopy[i] = cloneDeep(value[i]);
    }
    return arrCopy;
  }

  const objCopy = {};
  for (const key in value) {
    if (value.hasOwnProperty(key)) {
      objCopy[key] = cloneDeep(value[key]);
    }
  }
  return objCopy;
}
