import { Modal, message } from 'ant-design-vue'
import { defineStore } from 'pinia'
import { reactive, h } from 'vue'
import { useSchedulerOnce } from 'flicker-vue-hooks'
import { UserController } from '@/controller'
import { useRouter, useRoute } from 'vue-router'

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

  const userInfo = reactive({})

  const clearUserInfo = () => {
    return new Promise((resolve) => {
      // 做些什么
      message.loading('清除用户信息中......')
      window.localStorage.removeItem('userInfo')
      useSchedulerOnce(() => 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))
      message.success('登录成功, 正在为您跳转页面...')
      if (route.query.redirectUrl) {
        router.push({ path: route.query.redirectUrl as string })
      } else {
        router.push({ path: router.getRoutes()[0].path })
      }
    }
  }

  const openUserInfoModal = () => {
    Modal.confirm({
      title: '您确定要退出吗？',
      content: h('a-form', null, [h('a-form-item', { label: '任务名称' }, [h('a-input', null, 2233)])]),
      cancelText: '取消',
      okText: '确定',
      onCancel: () => {},
      onOk: async () => {
        await clearUserInfo()
        // 退出
      }
    })
  }

  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
  }
})
