import { MessageBox, Message, Notification } from '@zjlib/element-ui2'

export function addHours(str) {
  // 获取当前时间
  var currentDate = new Date(str)

  // 增加一小时
  currentDate.setHours(currentDate.getHours() + 1)

  // 转换 "YYYY-MM-DD HH:mm:ss" 格式
  var formattedDate =
    currentDate.getFullYear() +
    '-' +
    ('0' + (currentDate.getMonth() + 1)).slice(-2) +
    '-' +
    ('0' + currentDate.getDate()).slice(-2) +
    ' ' +
    ('0' + currentDate.getHours()).slice(-2) +
    ':' +
    ('0' + currentDate.getMinutes()).slice(-2) +
    ':' +
    ('0' + currentDate.getSeconds()).slice(-2)

  return formattedDate
}

export function tableDataParsing(fieldBeans) {
  return fieldBeans
    .filter(item => !item.hide)
    .map((item, index) => {
      var tiling = item.tiling || item.tiling === null || item.tiling === undefined ? true : false
      return {
        tiling,
        exportField: item,
        hidden: item.isShow === null ? false : !item.isShow,
        isCopy: item.isCopy || false,
        isTotal: item.isTotal || false,
        sortNum: item.sortNum || 0,
        recordType: item.type,
        columnAttributes: {
          fixed: item.fixed ? item.fixed : false,
          label: item.label || '',
          prop: item.jname,
          width: item.width || 'auto',
          'min-width': (label => label.length * 16 + 64)(item.label || ''),
          align: ~['number', 'amount'].indexOf(item.type) ? 'right' : 'left'
        }
      }
    })
}

export const successMsg = msg => {
  Message({
    showClose: true,
    message: msg || '操作成功',
    type: 'success'
  })
}

export const errorMsg = msg => {
  Message({
    showClose: true,
    message: msg || '操作成功',
    type: 'error'
  })
}

export const warningNotify = msg => {
  Notification({
    title: '提示',
    message: msg,
    type: 'warning',
    duration: 2000
  })
}

/**
 * 查询按钮权限
 * @param {*} value 当前按钮对应code
 * @param {*} btnRole 当前路由所有按钮权限
 * @returns
 */
export const checkBtnRole = (value, btnRole) => {
  if (!btnRole) {
    return true
  }
  let index = btnRole.indexOf(value)
  return index >= 0
}

/**
 * table合计方法
 * 注意：sums1，sums2: 需要在获取列表数据时遍历传入需要合计的字段名
 * 其中：sums1: 数量，不需要toFixed
 *      sums2: 金额，需要toFixed
 * 例如：res.data.items.forEach(item => {
          item.sums1 = ['number'];
          item.sums2 = ['totalAmount', 'payAmount'];
        })
 * @param {*} param
 * @returns
 */
export const getSummaries = param => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    // console.log(columns);
    try {
      const values = data.map(item => Number(item[column.property]))
      if (data[0] && data[0].sums1.includes(column.property)) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)
        sums[index]
      }
      if (data[0] && data[0].sums2.includes(column.property)) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)
        sums[index] = numToFixed(sums[index])
        sums[index]
      }
    } catch {
      console.log('error')
    }
  })
  return sums
}

/**
 * 保留2位小数点
 * @param {number} num
 * @returns
 */
export const numToFixed = num => {
  if (!num) return '0.00'
  if (isNaN(Number(num))) return num
  num = num.toFixed(2)
  if (num.includes('.')) {
    return num.slice(0, -3).replace(/(\d)(?=(\d{3})+$)/g, '$1,') + num.slice(-3)
  }
  return num.replace(/(\d)(?=(\d{3})+$)/g, '$1,')
}

/**
 * 深拷贝
 * @param
 * @returns
 */
export const deepClone = obj => {
  //判断拷贝的要进行深拷贝的是数组还是对象，是数组的话进行数组拷贝，对象的话进行对象拷贝
  var objClone = Array.isArray(obj) ? [] : {}
  //进行深拷贝的不能为空，并且是对象或者是
  if (obj && typeof obj === 'object') {
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        if (obj[key] && typeof obj[key] === 'object') {
          objClone[key] = deepClone(obj[key])
        } else {
          objClone[key] = obj[key]
        }
      }
    }
  }
  return objClone
}

/**
 *
 * @param {*} fn  是我们需要包装的事件回调
 * @param {*} delay 是每次推迟执行的等待时间
 */
export const debounce = (fn, delay = 1000) => {
  // 定时器
  let timer = null
  // 将debounce处理结果当作函数返回
  return function () {
    // 保留调用时的this上下文
    let context = this
    // 保留调用时传入的参数
    let args = arguments
    // 每次事件被触发时，都去清除之前的旧定时器
    // console.log(timer)
    if (timer) {
      clearTimeout(timer)
    }
    // 设立新定时器
    timer = setTimeout(function () {
      fn.apply(context, args)
    }, delay)
  }
}

export function thousands(num) {
  if (num === null) {
    return ''
  }
  var n = Number(num).toFixed(2)
  if (isNaN(n)) {
    return n
  }
  n = n + ''
  var [a, b] = n.split('.')
  var aq = Number(a).toLocaleString()
  return `${aq}.${b}`
}

export default {
  successMsg,
  errorMsg,
  warningNotify,
  checkBtnRole,
  getSummaries,
  numToFixed,
  deepClone
}
