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

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

/**
 * @description 过滤树形结构，移除满足条件的节点
 * @param {Array} data 树形数据数组
 * @param {Object} filter 过滤条件，如 { type: 2 }
 * @param {Object} props 配置项，默认 { children: 'children' }
 * @returns {Array} 过滤后的树形数据
 */
export const filterTree = (data: any[], filter: Record<string, any>, props = { children: 'children' }) => {
  data = cloneDeep(data)
  const { children } = props
  const filterNode = (node: any) => {
    const shouldRemove = Object.entries(filter).every(([key, value]) => {
      return node[key] === value
    })
    if (shouldRemove) {
      return null
    }
    if (node[children] && Array.isArray(node[children])) {
      const filteredChildren = node[children].map(filterNode).filter(Boolean)
      node[children] = filteredChildren
    }
    return node
  }
  return data.map(filterNode).filter(Boolean)
}

/**
 * @description 将多个路径片段解析为一个绝对路径
 * @param {...string} paths - 要解析的路径片段
 * @returns {string} - 解析后的绝对路径
 */
export function resolvePath(...paths: string[]): string {
  if (paths.length === 0) {
    return '/'
  }
  let resolvedPath = ''
  let isAbsolute = false
  for (let i = paths.length - 1; i >= 0; i--) {
    const path = paths[i]
    if (!path) {
      continue
    }
    resolvedPath = `${path}/${resolvedPath}`
    if (path.startsWith('/')) {
      isAbsolute = true
      break
    }
  }
  if (!isAbsolute) {
    resolvedPath = `/${resolvedPath}`
  }
  const parts = resolvedPath.split('/').filter(Boolean)
  const resolved: string[] = []
  for (const part of parts) {
    if (part === '.') {
      continue
    } else if (part === '..') {
      resolved.pop()
    } else {
      resolved.push(part)
    }
  }
  return '/' + resolved.join('/')
}

/**
 * 设置主题色
 */
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} path
 * @returns {Boolean}
 */
export function isExternal(path: string) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

/**
 * @description 解析字符串为对象，支持JSON字符串和URL查询字符串
 * @param {string} str - 要解析的字符串
 * @returns {Record<string, any>} - 解析后的对象
 */
export function parseStringToObject(str: string): Record<string, any> {
  if (!str || typeof str !== 'string') {
    return {}
  }
  try {
    const jsonObj = JSON.parse(str)
    if (isObject(jsonObj)) {
      return jsonObj
    }
  } catch (error) {
    if (str.includes('=')) {
      const queryStr = str.startsWith('?') ? str.slice(1) : str
      return queryStr.split('&').reduce(
        (prev, cur) => {
          const [key, value] = cur.split('=')
          if (key) {
            prev[key] = decodeURIComponent(value || '')
          }
          return prev
        },
        {} as Record<string, any>
      )
    }
  }
  return {}
}

/**
 * @description 将对象转换为GET参数字符串
 * @param {Record<string, any>} obj - 要转换的对象
 * @returns {string} - 转换后的GET参数字符串
 */
export function objectToGetParams(obj: Record<string, any>): string {
  return Object.entries(obj)
    .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
    .join('&')
}

/**
 * @description 提取字符串中的数字
 * @param {string | number} value - 要提取数字的字符串或数字
 * @returns {number} - 提取到的数字
 */
export function extractNumber(value: string | number): number {
  return Number(String(value).replace(/[^\d.-]/g, ''))
}

/**
 * @description 从URL中提取文件类型
 * @param {string} url - 要提取文件类型的URL
 * @returns {string} - 提取到的文件类型
 */
export function getFileType(url: string): string {
  if (!url) return 'file'
  const lastDotIndex = url.lastIndexOf('.')
  if (lastDotIndex === -1) return 'file'
  const extension = url.slice(lastDotIndex + 1)
  return extension || 'file'
}
