import { defineStore } from 'pinia'
import { logout } from '@/api/login'
import { getCode } from '@/api/system'
import CacheManager from '../utils/CacheManager'

// 码表类型
interface dicType {
  length: number
  createBy: string | null
  createTime: string | null
  dicCode: string | null
  dicId: string | null
  dicName: string | null
  isDeleted: boolean | null
  updateBy: string | null
  updateTime: string | null
  values: any[] | null

}

export const useAppStore = defineStore(
  'app',
  () => {
    /**
     * 跳转首页
     */
    const loginJump = () => {
      // tabbarStore.setAutoCurIdx('/pages/index/index')
      // /pages/index/index
      // /pages/me/me
      setTimeout(() => {
        uni.switchTab({ url: '/pages/home/home' })
      }, 100)
    }
    /**
     * 判断用户是否登录
     */
    const autoLogin = () => {
      const token = CacheManager.get('token')
      if (token) {
        loginJump()
        return
      }
    }

    /**
     * 设置码表
     */
    const setDictData = async () => {
      const res = await getCode()
      if (res) {
        CacheManager.set('dictData', res)
      }
    }

    /**
     * 设置用户信息
     */
    const setUserInfo = async (userInfo: any) => {
      if (userInfo) {
        CacheManager.set('userInfo', userInfo)
      }
    }

    /**
     * 退出登录
     */
    const Logout = async () => {
      try {
        await logout()
        CacheManager.remove('userInfo')
        CacheManager.remove('token')
        CacheManager.remove('dictData')
      }
      catch (e) {
        console.error(e)
      }
      finally {
        uni.reLaunch({
          url: '/pages/login/login',
        })
      }
    }

    /**
     * 401
     */

    /**
     * 获取用户信息
     */
    const getUserInfo = () => {
      const user = CacheManager.get('userInfo')
      return user || {}
    }

    /**
     * 根据code查找字典数据
     */
    const getDictByCode = (code: string) => {
      const dictData: any = CacheManager.get('dictData')
      if (!dictData) {
        return []
      }
      const list: dicType = dictData.filter((item: any) => item.dicCode === code)
      return list.length > 0 ? list[0].values : []
    }

    /**
     * 根据value值对字典数据进行翻译
     * @param value 值
     * @param code 字典code
     * @returns 字典值
     */
    const translateDictValue = (value: any, code: string) => {
      const dictData: any = CacheManager.get('dictData')
      if (!dictData) {
        return value
      }
      const list: dicType = dictData.filter((item: any) => item.dicCode === code)
      if (list.length > 0) {
        const values = list[0].values
        if (values && values.length > 0) {
          return values.find((item: any) => item.dicValue === value?.toString())?.dicValueName || value
        }
      }
      return value
    }

    return {
      autoLogin,
      loginJump,
      setDictData,
      getDictByCode,
      setUserInfo,
      getUserInfo,
      Logout,
      translateDictValue,
    }
  },
)
