/*
 * @Author       : wfl
 * @LastEditors: zqf
 * @description  :
 * @updateInfo   :
 * @Date         : 2022-11-02 14:32:10
 * @LastEditTime: 2024-03-01 10:18:57
 */
import useUserStore from '@main/store/modules/user'
import { ikStore, ikTree } from 'iking-utils'
import { useI18n } from 'vue-i18n'
import type { Ref } from 'vue'
import type { ISearchForm } from '@main/enums/search'
import { postApi } from '@main/api/modules/post'
import { depApi } from '@main/api/modules/dep'
import { roleApi } from '@main/api/modules/role'
import { commonApi } from '@main/api/modules/common'

// 自动生成TS返回参数类型
import '@intlify/core-base'
import useSettingsStore from '@main/store/modules/settings'

export enum ETableIconType {
  图标 = 'icon',
  文字 = 'title',
  文字图标 = 'all',
}

// 通用配置及规范配置
export function useConfig() {
  const userStore = useUserStore()
  const settingStore = useSettingsStore()
  // 国际化
  const { t, te, locale } = useI18n()

  // dialog大小
  const dialog = {
    // 大
    xl: 1024,
    // 中
    l: 683,
    // 小
    sl: 512,
  }

  // drawer 大小
  const drawer = {
    // 全屏
    full: '100%',
    // 大
    xl: '1024px',
    // 中
    l: '683px',
    // 小
    sl: '512px',
  }

  // 表格操作列宽度 - 按照按钮个数
  const operateCol = {
    three: '148px',
    two: '106px',
    one: '64px',
  }

  // 仅在setup内适用
  // 当前路由信息
  const { path } = useRoute()
  // 当前登录用户信息
  const user = userStore.userInfo

  const isDark = computed(() => settingStore.settings.app.colorScheme === 'dark')
  const theme = computed(()=> settingStore.settings.menu.menuMode)

  return {
    t,
    te,
    locale,
    dialog,
    drawer,
    path,
    user,
    operateCol,
    isDark,
    theme
  }
}

// 字段长度
export function useLength() {
  return {
    // 短名称
    lenShort: 8,
    // 长名称
    lenLong: 20,
    // 手机号
    lenPhone: 11,
    // 名称、标题
    lenName: 45,
    // 描述、内容
    lenContent: 200,
    // 链接
    lenLink: 128,
    // 长文本
    lenLargeContent: 2000,
  }
}

// token
export function useToken() {
  return ikStore.local.getItem(import.meta.env.VITE_GLOB_APP_TOKEN_NAME)
}

// menu-id
export async function useMenuId() {
  return await ikStore.forage.getItem('menuid')
}

// 抛出系统内各地址
export function useHttpUrl() {
  const { VITE_APP_API_BASEURL, VITE_APP_UPLOAD_URL, VITE_APP_DOWNLOAD_URL, VITE_APP_SOCKET_URL, VITE_APP_PREVIEW_URL, VITE_APP_APPLICATION_PAGE_MOBILE_URL }
    = import.meta.env

  const setFileUrl = (url: string) => {
    return url
      ? url.startsWith('http')
        ? url
        : `${VITE_APP_DOWNLOAD_URL}${url}`
      : ''
  }

  return {
    baseUrl: VITE_APP_API_BASEURL,
    uploadUrl: VITE_APP_UPLOAD_URL,
    loadUrl: VITE_APP_DOWNLOAD_URL,
    socketUrl: VITE_APP_SOCKET_URL,
    previewUrl: VITE_APP_PREVIEW_URL,
    applicationPageMobileUrl: VITE_APP_APPLICATION_PAGE_MOBILE_URL,
    // 拼接URL
    setFileUrl,
  }
}

let deptCache: Array<any> | null = null
// 部门数据
export async function useDep(): Promise<{ [key: string]: any }> {
  if (deptCache) {
    return deptCache
  }
  const { success, data } = await depApi.getAllDeps()
  if (success) {
    const fixData = data?.map((li: { name: any, id: any, [key: string]: any }) => {
      return {
        ...li,
        label: li.name,
        value: li.id,
      }
    })
    deptCache = fixData
      ? ikTree.listToTree(fixData, { sort: 'sortOrder', needSort: true })
      : []
    return deptCache!
  }
  return []
}

// 岗位数据
export async function usePost(): Promise<{ [key: string]: any }> {
  const { success, data } = await postApi.getAllPosts()
  if (success) {
    const fixData = data?.map((li: { name: any, id: any, [key: string]: any }) => {
      return {
        ...li,
        label: li.name,
        value: li.id,
      }
    })
    return fixData
      ? ikTree.listToTree(fixData, { sort: 'sortOrder', needSort: true })
      : []
  }
  return []
}

// 角色数据
export async function useRole(): Promise<{ [key: string]: any }> {
  const { success, data } = await roleApi.getRoleList()
  if (success) {
    const fixData = data?.map((li: { name: any, id: any, [key: string]: any }) => {
      return {
        ...li,
        label: li.name,
        value: li.id,
      }
    })
    return fixData
      ? ikTree.listToTree(fixData, { sort: 'sortOrder', needSort: true })
      : []
  }
  return []
}

// 表格通用字段 默认不显示
export function useTableKey(): ISearchForm[] {
  return [
    {
      key: 'createTime',
      value: '',
      label: '创建时间',
      width: 170,
      valueFormat: 'YYYY-MM-DD',
      type: EFormType.date,
      search: false,
    },
    {
      key: 'updateTime',
      value: '',
      label: '更新时间',
      valueFormat: 'YYYY-MM-DD',
      width: 170,
      type: EFormType.date,
      search: false,
    },
  ]
}

// 表格列 排序
export function useSortMethod() {
  const tableKeys: Ref<any[]> = ref([])
  const handSortList = (sorts: ISearchForm[]) => {
    tableKeys.value = sorts
  }
  return {
    tableKeys,
    handSortList,
  }
}

export function usePickerData() {
  const userList = ref([])
  const depList = ref([])
  const roleList = ref([])
  const postList = ref([])

  const handData = async (val?: any) => {
    const isStr = typeof val === 'string'
    const param = {
      parentDepartmentId: isStr ? val : val?.id,
      name: isStr ? '' : val?.name,
    }
    const { success, data } = await commonApi.getAllComData(param)
    if (!success) { return }
    const { departments, roles, posts, users } = data
    depList.value = departments
    userList.value = users
    roleList.value = roles
    postList.value = posts
    return {
      departments,
      users,
      roles,
      posts,
    }
  }
  handData()

  const handSetChild = (item: any) => {
    handData(item?.elementId)
  }

  return {
    userList,
    depList,
    roleList,
    postList,
    handData,
    handSetChild,
  }
}

// 设置tag颜色
export function useTagColor() {
  const map = new Map()
  let i = 1
  const setColor = (list: any[]) => {
    return list.map((li: any) => {
      const title = li?.title || li
      if (!map.has(title)) {
        map.set(title, `var(--ik-statu-color-${i})`)
        map.set(`${title}-bg`, `var(--ik-statu-color-${i}-light)`)
        i++
        if (i > 8) { i = 1 }
      }
      return {
        title,
        type: '',
        color: map.get(title),
        background: map.get(`${title}-bg`),
      }
    })
  }

  return {
    setColor,
  }
}

// 统一前缀
export function usePrefix() {
  return 'ik'
}

// 表格按钮显示样式
export function useTableIconType() {
  return systemConfig.table?.btnType || ETableIconType.图标
}

export const SYSTEM_ICON_TYPE = systemConfig.table?.btnType

const _ICON_TYPE = systemConfig.table?.btnType === ETableIconType.图标

export function useOperateWidth(min: number, max: number) {
  return _ICON_TYPE ? min : max
}
