/**
 * components util
 */

import triggerEvent from 'ant-design-vue/es/_util/triggerEvent'
import { inBrowser } from 'ant-design-vue/es/_util/env'

/**
 * 清理空值，对象
 * @param children
 * @returns {*[]}
 */
export function filterEmpty (children = []) {
  return children.filter(c => c.tag || (c.text && c.text.trim() !== ''))
}

/**
 * 获取字符串长度，英文字符 长度1，中文字符长度2
 * @param {*} str
 */
export const getStrFullLength = (str = '') =>
  str.split('').reduce((pre, cur) => {
    const charCode = cur.charCodeAt(0)
    if (charCode >= 0 && charCode <= 128) {
      return pre + 1
    }
    return pre + 2
  }, 0)

/**
 * 截取字符串，根据 maxLength 截取后返回
 * @param {*} str
 * @param {*} maxLength
 */
export const cutStrByFullLength = (str = '', maxLength) => {
  let showLength = 0
  return str.split('').reduce((pre, cur) => {
    const charCode = cur.charCodeAt(0)
    if (charCode >= 0 && charCode <= 128) {
      showLength += 1
    } else {
      showLength += 2
    }
    if (showLength <= maxLength) {
      return pre + cur
    }
    return pre
  }, '')
}

const getComponentFromProp = (instance, prop) => {
  const slots = instance.slots && instance.slots()
  return slots[prop] || instance.props[prop]
}

const isFun = (func) => {
  return typeof func === 'function'
}

// 兼容 0.3.4~0.3.8
export const contentWidthCheck = (contentWidth) => {
  return Object.prototype.toString.call(contentWidth) === '[object Boolean]'
    ? contentWidth === true && 'Fixed' || 'Fluid'
    : contentWidth
}

export const layoutContentWidth = (contentType) => {
  return contentType !== 'Fluid'
}

const themeConfig = {
  daybreak: 'daybreak',
  '#1890ff': 'daybreak',
  '#F5222D': 'dust',
  '#FA541C': 'volcano',
  '#FAAD14': 'sunset',
  '#13C2C2': 'cyan',
  '#52C41A': 'green',
  '#2F54EB': 'geekblue',
  '#722ED1': 'purple',
}

const invertKeyValues = (obj) =>
  Object.keys(obj).reduce((acc, key) => {
    acc[obj[key]] = key
    return acc
  }, {})

/**
 * #1890ff -> daybreak
 * @param val
 */
export function genThemeToString (val) {
  return val && themeConfig[val] ? themeConfig[val] : val
}

/**
 * daybreak-> #1890ff
 * @param val
 */
export function genStringToTheme(val) {
  const stringConfig = invertKeyValues(themeConfig)
  return val && stringConfig[val] ? stringConfig[val] : val
}


export {
  triggerEvent,
  inBrowser,
  getComponentFromProp,
  isFun
}
