/*
 * @Author: donghao donghao@supervision.ltd
 * @Date: 2025-03-06 17:57:05
 * @LastEditors: donghao donghao@supervision.ltd
 * @LastEditTime: 2025-07-08 17:37:38
 * @FilePath: \5G-Loading-Bay-Web\src\stores\user.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from 'pinia'
import router, { resetRouter } from '@/router'
import { getLocal, setLocal, removeLocal } from '@/utils/local'
import { loginOutApi } from '@/api/user'
import { isSuccessApi } from '@/utils/forApi'
import { ElMessage } from 'element-plus'

interface UserState {
  token: string | null
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: getLocal('token')
  }),
  actions: {
    login(token: string, form: { remember: boolean; username: string; password: string }) {
      this.token = token
      setLocal('token', token)
      form.remember ? setLocal('userLoginInfo', form) : removeLocal('userLoginInfo')
    },
    async logout() {
      const res = await loginOutApi()
      if (isSuccessApi(res)) {
        ElMessage.success(`退出登录`)
      }
      this.token = null
      removeLocal('token')
      resetRouter()
      // TODO 暂未实现
      // router.replace("/login");
    }
  }
})
