import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {loginApi, registerApi} from "@/api/request/user.js";
import {message, notification} from "ant-design-vue";

export const useUserStore = defineStore('user', () => {
  const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))
  const modal = ref(localStorage.getItem('authModal') || 'false')

  // 添加初始化状态校验
  const initUser = () => {
    const userData = localStorage.getItem('user')
    if (!userData) return null
    try {
      return JSON.parse(userData)
    } catch {
      localStorage.removeItem('user')
      localStorage.removeItem('token')
      return null
    }
  }
  
  const isAuthenticated = computed(() => !!user.value?.nick_name)
  
  function login(credentials, functionName) {
    console.log(functionName, 'sssssssssssss')
    loginApi({
      account: credentials.username,
      password: credentials.password,
      remember: credentials.remember,
    }).then((res) => {
      const userData = {
        nick_name: res.nick_name,
        role_name: res.role_name,
        role_value: res.role_value,
      }
      user.value =  userData;
      localStorage.setItem('user', JSON.stringify(userData))
      localStorage.setItem('token', res.token)
      notification.success({
        message: '登录成功',
        description: `欢迎回来${res.nick_name}`,
      })
      functionName()
    })
  }
  function register(credentials, functionName) {
    registerApi({
      account: credentials.username,
      password: credentials.password,
      email: credentials.email,
      code: credentials.code,
    }).then((res) => {
      const userData = {
        nick_name: res.nick_name,
        role_name: res.role_name,
        role_value: res.role_value,
      }
      user.value =  userData;
      localStorage.setItem('user', JSON.stringify(userData))
      localStorage.setItem('token', res.token)
      message.success('注册成功')
      functionName()
    })
  }

  function logout() {
    user.value = null
    localStorage.removeItem('user')
    localStorage.removeItem('token')
  }

  function setModal(value) {
    modal.value = modal.value === 'false' ? 'true' : 'false';
    localStorage.setItem('authModal', value)
  }

  return {
    modal,
    user,
    isAuthenticated,
    setModal,
    login,
    register,
    logout
  }
})