import { MessageBox, Message, Notification } from 'element-ui'

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) => {
  // console.log(btnRole)
  // let condition = btnRole === undefined ? [] : btnRole
  if (!btnRole) {
    return false
  }
  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,')
}

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