import { get } from 'lodash-es'
import { ElMessage } from 'element-plus'
import { DateTime } from 'luxon'
import usePermissionBtnStore from '@/store/permission'

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function val<T>(data: T, key: string | ((data: T) => any)) {
  if (typeof key === 'function') return key(data)
  return get(data, key)
}

/**
 * @param {*} text
 */
export function copyText(text: string) {
  if (navigator.clipboard?.writeText) {
    navigator.clipboard.writeText(text).then(() => {
      ElMessage.success('复制成功')
    })
    return
  }

  const oTextarea = document.createElement('textarea')
  oTextarea.value = text
  oTextarea.style.position = 'fixed'
  oTextarea.style.left = '-9999px'
  document.body.appendChild(oTextarea)
  oTextarea.select()
  document.execCommand('Copy')
  document.body.removeChild(oTextarea)
  ElMessage.success('复制成功')
}

/**
 * 将本地时间转换为北京时间（自动检测时区）
 * @param {string} localTime - 本地时间字符串，格式 YYYY-MM-DD HH:mm:ss
 * @returns {string} 北京时间，格式 YYYY-MM-DD HH:mm:ss
 */
export function convertToChinaTime(
  timeString: string,
  currentZone: string = 'local',
  targetZone: string = 'Asia/Shanghai',
) {
  // 将输入的时间字符串解析为本地时间，假设输入时间是本地时间
  const inputTime = DateTime.fromFormat(timeString, 'yyyy-MM-dd HH:mm:ss', {
    zone: currentZone,
  })

  const chinaTime = inputTime.setZone(targetZone)
  return chinaTime.toFormat('yyyy-MM-dd HH:mm:ss')
}

export function isPermissionBtn(key: string) {
  const permissionBtns = usePermissionBtnStore().permissionBtns

  if (!permissionBtns) return false
  return permissionBtns.includes(key)
}

export function downloadByUrl(url: string, filename?: string) {
  const a = document.createElement('a')
  a.href = url
  a.download = filename || url.split('/').pop() || 'download'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}