import { useCssVar } from '@vueuse/core'
// @ts-ignore
import colorFunction from 'css-color-function'
import { isObject } from 'lodash-es'

/**
 * @description 添加单位
 * @param {String | Number} value 值 100
 * @param {String} unit 单位 px em rem
 */
export const addUnit = (value: string | number, unit = 'px') => {
  return !Object.is(Number(value), NaN) ? `${value}${unit}` : value
}

/**
 * 设置主题色
 */
export function setThemeColor(color: string, mode: string = 'light'): void {
  const colorConfig: any = {
    dark: {
      'light-3': 'shade(20%)',
      'light-5': 'shade(30%)',
      'light-7': 'shade(50%)',
      'light-8': 'shade(60%)',
      'light-9': 'shade(70%)',
      'dark-2': 'tint(20%)'
    },
    light: {
      'dark-2': 'shade(20%)',
      'light-3': 'tint(30%)',
      'light-5': 'tint(50%)',
      'light-7': 'tint(70%)',
      'light-8': 'tint(80%)',
      'light-9': 'tint(90%)'
    }
  }
  useCssVar('--el-color-primary', null).value = color
  Object.keys(colorConfig[mode]).forEach((key) => {
    useCssVar('--el-color-primary-' + key, null).value = colorFunction.convert(
      `color(${color} ${colorConfig[mode][key]})`
    )
  })
}

/**
 * @description 常用规则验证
 * @param {String} mode phone验证手机号，email验证邮箱，IDcard身份证号（简单验证），password密码
 * @param {String} info 需要验证的内容
 */
export function validation(mode: string, info: string) {
  if (mode == 'phone') {
    var reg = /^1[0-9]{10,10}$/
    if (reg.test(info)) return true;
    else return false;
  } else if (mode == 'email') {
    var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
    if (reg.test(info)) return true;
    else return false;
  } else if (mode == 'IDcard') {
    var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if (reg.test(info)) {
      const birth = (info.length === 18 ? info.slice(6, 14) : info.slice(6, 12));
      let month, day;
      if (birth.length == 8) {
        month = parseInt(birth.slice(4, 6), 10);
        day = parseInt(birth.slice(-2), 10);
      } else if (birth.length == 6) {
        month = parseInt(birth.slice(2, 4), 10);
        day = parseInt(birth.slice(-2), 10);
      } else {
        return false;
      }
      if (month > 12 || month === 0 || day > 31 || day === 0) {
        return false;
      }
      return true;
    } else return false;
  } else if (mode == 'password') {
    if (info.length >= 8) return true;
    else return false;
  }
}

/**
 * @description 是否为空对象
 * @param {Object} value
 * @return {Boolean}
 */
export const isEmptyObject = (target: object) => {
    return isObject(target) && !Object.keys(target).length
}