import { Modal, message } from 'ant-design-vue'
import { defineStore } from 'pinia'
import { reactive } from 'vue'

import { UserController } from '@/controller'
import { useRouter, useRoute } from 'vue-router'
import { routes } from '@/router'

const initState: USER.Tenant.Detail = {
  id: '',
  tenantId: '',
  token: '',
  email: '',
  account: '',
  label: '蛟龙云'
}

export const useUserStore = defineStore('userStore', () => {
  const router = useRouter()

  const route = useRoute()

  let userInfo = reactive<USER.Tenant.Detail>(JSON.parse(window.localStorage.getItem('userInfo') as string) || initState)

  const clearUserInfo = () => {
    return new Promise((resolve) => {
      // 做些什么
      message.loading('清除用户信息中......', 0.5)
      window.localStorage.removeItem('userInfo')
      setTimeout(() => {
        resolve(true)
      }, 500)
    })
  }

  const login = async (data: USER.Params.Login) => {
    // 存储用户信息 跳转页面
    const { data: tenant, code } = await UserController.login({
      ...data,
      password: encryptPassWord(data.password)
    })
    if (code === 200) {
      window.localStorage.setItem('userInfo', JSON.stringify(tenant))
      const userInfoLocal = JSON.parse(window.localStorage.getItem('userInfo') as string)
      userInfo = reactive(userInfoLocal) || initState
      message.success('登录成功')
      if (route.query.redirectUrl) {
        router.push({ path: route.query.redirectUrl as string })
      } else {
        router.push({ path: routes[0].path })
      }
    }
  }

  const openUserInfoModal = () => {
    Modal.success({
      title: userInfo.label + '的信息',
      content: '需要想到优雅的方式来打开个人信息弹窗',
      cancelText: '取消',
      okText: '确定',
      onCancel: () => {},
      onOk: () => {}
    })
  }

  const logout = () => {
    Modal.confirm({
      title: '您确定要退出吗？',
      cancelText: '取消',
      okText: '确定',
      onCancel: () => {},
      onOk: async () => {
        await clearUserInfo()
        message.success('登出成功')
        // 退出
        router.push({ path: '/login' })
      }
    })
  }

  const encryptPassWord = (password: string) => encodeURI(btoa(password))

  return {
    userInfo,
    login,
    logout,
    clearUserInfo,
    openUserInfoModal,
    encryptPassWord
  }
})
