import { defineStore } from 'pinia'
import { ref } from 'vue'
import globalApi from '@/api/global'
import settingApi from '@/api/system/setting'
import loginApi from '@/api/login'
import type { accountLoginType } from '@/api/login'
import type { Option, UserData } from '@/api/global'
import type { School } from '@/api/studentManage'
import { setCache, clearCache, getSN, getManufacturer, isStudyMachine } from '@/utils'
import { useSocket } from '@/hooks'
import { globalStore } from '@/stores'
import { storeToRefs } from 'pinia'
import obj from '@/utils/obj'

interface History_Account {
  account: string
  avatarFrameUrl: string
  avatarUrl: string
  nickName: string
  nickNameFrameUrl: string
  token: string
}

export const userStore = defineStore('user', () => {
  // State
  const userInfo = ref<UserData>({} as UserData)
  const token = ref('')
  const workToken = ref('')
  const userRecords = ref<History_Account[]>([]) // 登录记录
  const auth = ref<string[]>([])
  // const personalMusicConfig = ref<any>({})

  // 学校班级相关
  const schoolList = ref([] as School[])
  const schoolOptions = ref<Option[]>([])
  const schoolMap = ref({} as Record<string, School>)
  const classOptionsMap = ref({} as any)
  const classesMap = ref({} as any)

  function initSchoolList(schoolData: any) {
    if (!schoolData?.length) {
      schoolList.value = [] as any
      schoolOptions.value = [] as any
      schoolMap.value = {} as any
      classOptionsMap.value = {} as any
      classesMap.value = {} as any
      return
    }
    schoolList.value = []
    schoolList.value = schoolData
    schoolMap.value = obj.list2map(schoolList.value, 'schoolId')
    schoolOptions.value = schoolList.value.map((item: School) => ({
      value: item.schoolId,
      label: item.schoolName,
    }))
    const tmpClassesMap = {} as any
    const tmpClassOptionsMap = {} as any
    for (const school of schoolList.value) {
      const classOptions = school.classList.map((c: any) => {
        tmpClassesMap[c.classId] = c
        return {
          value: c.classId,
          label: c.className,
        }
      })
      tmpClassOptionsMap[school.schoolId] = classOptions
    }
    classOptionsMap.value = tmpClassOptionsMap
    classesMap.value = tmpClassesMap
  }

  // Actions
  // 获取用户信息
  const getUserInfo = async () => {
    if (!token.value) return
    await updateUserInfo(await globalApi.getUserInfoApi())
  }

  const getUserSchool = () => {
    return userInfo.value.schoolClass?.[0]
  }

  const getUserClass = () => {
    return userInfo.value.schoolClass?.[0]?.classList?.[0]
  }

  // 更新用户信息
  const updateUserInfo = async (info: any) => {
    if (!info) return
    info = { ...userInfo.value, ...info }

    if (isStudyMachine) {
      // 锁屏
      const { system } = storeToRefs(globalStore())
      system.value.isLock = info.lockFlag === 0
    }

    if (typeof info.schoolClass === 'string') {
      info.schoolClass = JSON.parse(info.schoolClass)
      if (info.schoolClass?.length) {
        const school = info.schoolClass[0]
        info.schoolName = school.schoolName
        const cls = school.classList?.[0]
        info.className = cls?.className
        info.classId = cls?.classId
      }
      initSchoolList(info.schoolClass)
    }
    // 是否为老师账号
    info.isTeacher = info.schoolPersonType === 1
    info.isTaskStudent = !info.isTeacher && !!info.classId

    // 设置
    userInfo.value = info
  }

  // // 获取用户音乐配置
  // const getUserConfig = async () => {
  //     const { data } = await getPersonalConfigApi();
  //     personalMusicConfig.value = data.data;
  // }

  // 修改用户配置
  const updateUserConfig = async (data: anyObj) => {
    await settingApi.modifyPersonalConfigApi(data)
  }

  // 判断是否首次绑定
  const isFirstBind = async () => {
    const {
      data: { data: res },
    } = await loginApi.getFirstBind(getSN())
    return res
  }

  // 获取用户个性化配置
  const getUserCustom = (key: 1 | 2 | 3 | 4) => {
    // 1为头像 2为头像框 3为背景 4为昵称框
    return (
      userInfo.value.personInUsePersonalities?.find((i: anyObj) => i.remark === key)
        ?.homePageResourceUrl || ''
    )
  }

  // 获取当前登录用户
  const getUserNow = () => {
    return userRecords.value.find(i => i.account === userInfo.value.account) || {}
  }

  // 清除失效登录用户
  const clearUser = (account: string) => {
    userRecords.value = userRecords.value.filter(i => i.account !== account)
  }

  const setToken = (tokenValue: string) => {
    if (!tokenValue) console.error('token 不能为空')
    token.value = `Bearer ${tokenValue}`
    setCache('token', `Bearer ${tokenValue}`)
  }

  // 账号登录
  const accountLogin = async (data: accountLoginType) => {
    const res = await loginApi.psdLogin({
      ...data,
      simSerialNumber: getSN(),
      model: getManufacturer(),
    })
    await loginBefore()
    setToken(res as any)
    await loginAfter()
  }

  // 教师登录
  const workLogin = async (data: anyObj) => {
    workToken.value = ''
    const { data: res } = await loginApi.workLogin(data)
    const tokenValue = res.data.token
    workToken.value = `Bearer ${tokenValue}`
    setCache('workToken', `Bearer ${tokenValue}`)
  }

  // 账号切换
  const changeAccount = async (tokenValue: string) => {
    await loginBefore()
    setToken(tokenValue)
    await loginAfter()
  }

  const loginBefore = async () => {
    clearCache()
  }

  const loginAfter = async () => {
    await getUserInfo()

    // 注册sk
    const { init: socketInit } = useSocket()
    socketInit()

    const accountIdx = userRecords.value.findIndex(i => i.account === userInfo.value.account)
    const account = {
      account: userInfo.value.account,
      avatarFrameUrl: getUserCustom(2),
      avatarUrl: getUserCustom(1),
      nickName: userInfo.value.nickName,
      nickNameFrameUrl: getUserCustom(4),
      token: token.value,
    }

    if (accountIdx !== -1) {
      // 存在账号更新
      userRecords.value[accountIdx] = account
    } else {
      userRecords.value.push(account)
    }

    const { syncApps } = globalStore()
    // 同步Apps
    syncApps()

    // 教师登录
    try {
      // await workLogin({
      //   stuId: userInfo.value.smartUserIdentifier,
      // })
    } catch {
      //
    }
  }

  const logout = async () => {
    await loginApi.logout()
    try {
      // await workLogout()
    } catch {
      //
    }
    clearUser(userInfo.value.account)
    const { stop } = useSocket()
    stop()
    clearCache()
  }

  const getMenuAuth = (menus: anyObj[]) => {
    const authList: string[] = []
    const getAuth = (menus: anyObj[]) => {
      menus.forEach((item: anyObj) => {
        if (item.children.length > 0) {
          getAuth(item.children)
        } else {
          authList.push(item.componentName)
        }
      })
    }
    getAuth(menus)
    return authList
  }

  const $reset = () => {
    token.value = ''
    workToken.value = ''
    userInfo.value = {} as any
    userRecords.value = []
    auth.value = []

    // 学校班级相关
    initSchoolList(undefined)
  }

  return {
    // State
    userInfo,
    token,
    workToken,
    userRecords,
    auth,
    // personalMusicConfig,

    schoolList,
    schoolMap,
    schoolOptions,
    classOptionsMap,
    classesMap,

    // Actions
    $reset,
    getUserInfo,
    getUserSchool,
    getUserClass,
    updateUserInfo,
    updateUserConfig,
    isFirstBind,
    getUserCustom,
    getUserNow,
    clearUser,
    setToken,
    accountLogin,
    workLogin,
    changeAccount,
    loginBefore,
    loginAfter,
    logout,
    getMenuAuth,
  }
})
