import { login, getUserInfo, setSelfInfo, loginKey, getToken } from '@/api/user'
import { jsonInBlacklist } from '@/api/jwt'
import router from '@/router/index'
import { ElLoading, ElMessage } from 'element-plus'
import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { useRouterStore } from './router'
import cookie from 'js-cookie'

export const useUserStore = defineStore(
  'user',
  () => {
    const loadingInstance = ref(null)
    const userType = ref(cookie.get('userType') || '')

    const loginType = ref(1)
    const setLoginType = type => {
      loginType.value = type
    }

    const userInfo = ref({
      orgId: '',
      userId: '',
      uuid: '',
      nickName: '',
      headerImg: '',
      authority: {},
      sideMode: 'dark',
      activeColor: 'var(--el-color-primary)',
      baseColor: '#fff'
    })
    const token = ref(
      window.localStorage.getItem('token') || cookie.get('x-token') || ''
    )
    const setUserInfo = val => {
      userInfo.value = val
    }

    const setToken = val => {
      token.value = val
    }

    const NeedInit = () => {
      token.value = ''
      window.localStorage.removeItem('token')
      localStorage.clear()
      router.push({ name: 'Init', replace: true })
    }

    const ResetUserInfo = (value = {}) => {
      userInfo.value = {
        ...userInfo.value,
        ...value
      }
    }
    /* 获取用户信息*/
    const GetUserInfo = async() => {
      const res = await getUserInfo()
      if (res.code === 100000) {
        setUserInfo(res.data.userInfo)
      }
      return res
    }
    /* 登录*/
    const LoginIn = async loginInfo => {
      userType.value = 'admin'
      loadingInstance.value = ElLoading.service({
        fullscreen: true,
        text: '登录中，请稍候...'
      })
      try {
        let res
        // 兼容多种登录方式

        // 动态口令登录

        // 账号密码登录
        if (loginType.value === 1) {
          res = await login(loginInfo)
          if (res.code === 100000) {
            setUserInfo(res.data.user)
            setToken(res.data.token)
            const routerStore = useRouterStore()
            await routerStore.SetAsyncRouter()
            const asyncRouters = routerStore.asyncRouters

            // 查询机构状态
            /* if (res.data.user.authorityId !== 1){
              // 非超管登录
              const orgStatusRes = await getOrgStatus()

              if (orgStatusRes.code === 100000 && orgStatusRes.data){
                asyncRouters.forEach(asyncRouter => {
                  router.addRoute(asyncRouter)
                })

                if (!router.hasRoute(userInfo.value.authority.defaultRouter)) {
                  ElMessage.error('请联系管理员进行授权')
                } else {
                  await router.replace({
                    name: userInfo.value.authority.defaultRouter
                  })
                }

                loadingInstance.value.close()

                const isWin = ref(/windows/i.test(navigator.userAgent))
                if (isWin.value) {
                  window.localStorage.setItem('osType', 'WIN')
                } else {
                  window.localStorage.setItem('osType', 'MAC')
                }
                return true
              }
            } else {*/
            asyncRouters.forEach(asyncRouter => {
              router.addRoute(asyncRouter)
            })

            if (!router.hasRoute(userInfo.value.authority.defaultRouter)) {
              ElMessage.error('请联系管理员进行授权')
            } else {
              await router.replace({
                name: userInfo.value.authority.defaultRouter
              })
            }

            loadingInstance.value.close()

            const isWin = ref(/windows/i.test(navigator.userAgent))
            if (isWin.value) {
              window.localStorage.setItem('osType', 'WIN')
            } else {
              window.localStorage.setItem('osType', 'MAC')
            }
            return true
            // }
          }
        }

        // u-key 登录
        if (loginType.value === 2) {
          res = await loginKey(loginInfo)
          if (res.code === 100000) {
            setUserInfo(res.data.user)
            setToken(res.data.token)
            const routerStore = useRouterStore()
            await routerStore.SetAsyncRouter()
            const asyncRouters = routerStore.asyncRouters
            asyncRouters.forEach(asyncRouter => {
              router.addRoute(asyncRouter)
            })

            if (!router.hasRoute(userInfo.value.authority.defaultRouter)) {
              ElMessage.error('请联系管理员进行授权')
            } else {
              await router.replace({
                name: userInfo.value.authority.defaultRouter
              })
            }

            loadingInstance.value.close()

            const isWin = ref(/windows/i.test(navigator.userAgent))
            if (isWin.value) {
              window.localStorage.setItem('osType', 'WIN')
            } else {
              window.localStorage.setItem('osType', 'MAC')
            }
            return true
          }
        }
      } catch (e) {
        loadingInstance.value.close()
      }
      loadingInstance.value.close()
    }
    /* 登出*/
    const LoginOut = async() => {
      const res = await jsonInBlacklist()
      if (res.code === 100000) {
        await ClearStorage()
        router.push({ name: 'Login', replace: true })
      }
    }
    /* 清理数据 */
    const ClearStorage = async() => {
      token.value = ''
      sessionStorage.clear()
      localStorage.clear()
      cookie.remove('Authorization')
    }
    /* 设置侧边栏模式*/
    const changeSideMode = async data => {
      const res = await setSelfInfo({ sideMode: data })
      if (res.code === 100000) {
        userInfo.value.sideMode = data
        ElMessage({
          type: 'success',
          message: '设置成功'
        })
      }
    }

    const mode = computed(() => userInfo.value.sideMode)
    const sideMode = computed(() => {
      if (userInfo.value.sideMode === 'dark') {
        return '#191a23'
      } else if (userInfo.value.sideMode === 'light') {
        return '#fff'
      } else {
        return userInfo.value.sideMode
      }
    })
    const baseColor = computed(() => {
      if (userInfo.value.sideMode === 'dark') {
        return '#fff'
      } else if (userInfo.value.sideMode === 'light') {
        return '#191a23'
      } else {
        return userInfo.value.baseColor
      }
    })
    const activeColor = computed(() => {
      return 'var(--el-color-primary)'
    })

    watch(
      () => token.value,
      () => {
        window.localStorage.setItem('token', token.value)
      }
    )
    watch(
      () => userType.value,
      () => {
        cookie.set('userType', userType.value)
      }
    )

    return {
      userInfo,
      token,
      NeedInit,
      ResetUserInfo,
      GetUserInfo,
      LoginIn,
      LoginOut,
      changeSideMode,
      mode,
      sideMode,
      setToken,
      baseColor,
      activeColor,
      loadingInstance,
      ClearStorage,
      setLoginType
    }
  },
  {
    persist: true // 启用持久化
  }
)
