import { defineStore } from 'pinia'
import { apiLogout, apiRegister, apiLogin, apiUserInfo } from 'API/user'
import type { AxiosResponse } from 'axios'
import type { LoginData } from 'Types/api'
import router from 'Plugins/router'
import { Modal, message } from 'ant-design-vue'

interface ILogin {
  account: string
  password: string
}
// 第一个参数是该 store 的唯一 id
const userStore = defineStore(
  'user',
  {
    state: () => {
      return {
        token: localStorage.getItem('token') || '',
        userInfo: localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo') as string) : {},
      }
    },
    actions: {
      login(params: LoginData) {
        return apiLogin(params).then((response) => {
          const { data } = response
          if (data?.code === 200) {
            console.log(data, 'login')
            const info = data.result
            if (info.userInfo.state) {  // 暂时模拟，后续删除
            // if (!info.userInfo.state) {
              //账号状态 0禁用，1正常
              Modal.error({
                title: '提示',
                content: '您的账号已被冻结，暂时无法登录',
                centered: true,
                okText: '确定',
                onOk: () => {
                  // window.location.reload()
                },
              })
            } else {
              this.token = info.token
              localStorage.setItem('token', this.token)
              this.userInfo = info.userInfo
              localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
              router.push('/dashboard')
            }
          }
        })
      },
      register(params: ILogin) {
        apiRegister(params).then((response: AxiosResponse) => {
          console.log(response)
          const { data } = response
          if (data?.code === 200) {
            // router.push('/accountStatus?step=0')
            message.success('注册成功！')
            router.push('/login')
          }
          // this.token = 'token'
          // localStorage.setItem('token', this.token)
          // this.userInfo = { name: 'test' }
          // localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        })
      },
      getUserInfo() {
        apiUserInfo().then((response) => {
          const data = response.data.result
          this.token = data.token
          localStorage.setItem('token', this.token)
          this.userInfo = data
          localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        })
      },
      logout() {
        apiLogout().then((response: AxiosResponse) => {
          if (response.data.success) {
            this.feLogout()
          }
        })
      },
      // 前端登出(清空存储)
      feLogout() {
        this.token = ''
        localStorage.removeItem('token')
        this.userInfo = {}
        localStorage.removeItem('userInfo')
        router.push('/login')
      },
    },
    // other options...
  },
  {
    persist: {
      enabled: true,
    },
  }
)

export default userStore
