import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import request from '@/utils/request'
import { useRouter } from 'vue-router';
// import { jwtDecode } from 'jwt-decode';

export const useAuthStore = defineStore('auth', () => {

  const router = useRouter();

  const user = ref(null);
  const role = computed(() => {
    if (!user.value) return 0;
    return user.value.role;
  })
  
  const token = ref(localStorage.getItem('token') || '');

  const isAdmin = computed(() => {
    if (!user.value || user.value.role === 0) return false;
    return user.value.role > 0;
  });
  const isLoggedIn = computed(() => !!token.value);

  const loading = ref(false);
  const error = ref(null);

  const setToken = (newToken) => {
    token.value = newToken;
    localStorage.setItem('token', newToken);
  }

  const loadTokenFromStorage=()=> {
    const storedToken = localStorage.getItem('token');
    if (storedToken) {
      token.value = storedToken;
    }
  }

  const register = async (userInfo) => {
    error.value = null;
    try {
      const res = await request.post('/auth/register', userInfo)
      return res
    } catch (err) {
      error.value = err.response?.data?.error || '注册失败';
      throw error // 或者您可以在这里处理错误，例如显示错误消息
    }finally{
      loading.value = false;
    }
  }

  const login = async (userInfo) => {
    error.value = null;
    try {
      const res = await request.post('/auth/login', userInfo)
      if (res.status === 200 && !!res.data.data?.token) {
        setToken(res.data.data.token)
      }
      await getProfile() // 登录成功后获取用户信息
      return res
    } catch (err) {
      error.value = err.response?.data?.error || '登录失败';
      throw error // 或者您可以在这里处理错误，例如显示错误消息
    }finally{
      loading.value = false;
    }
  }

  const getProfile = async () => {
    loading.value = true;
    error.value = null;
    if (token.value && user.value) {
      return user.value
    }
    try {
      const res = await request.get('/profile')

      user.value = res.data.data
      return res
    } catch (err) {
      error.value = err.response?.data?.error || '获取用户信息失败';

      throw error
    }finally {
      loading.value = false;
    }
  }

  const refreshProfile = async () => {
    loading.value = true;
    error.value = null;
    try {
      const res = await request.get('/profile')
      if (res.data.code == 200) {
        user.value = res.data.data
      }
      return res
    } catch (err) {
      error.value = err.response?.data?.error || '获取用户信息失败'; 
      throw error
    }finally{
      loading.value = false;
    }
  }

  const updateProfile = async (userInfo) => {
    loading.value = true;
    error.value = null;
    try {
      const res = await request.post('/profile/update', userInfo)
      console.log('auth.js updateProfile', res.data);
      return res
    } catch (err) {
      error.value = err.response?.data?.error || '更新用户信息失败';
      throw error
    }finally{
      loading.value = false;
    }
  }

  const updatePassword = async (payload) => {
    loading.value = true;
    error.value = null;
    try {
      const res = await request.post('/profile/update/password', payload)
      console.log('auth.js updatePassword', res.data);
      return res
    } catch (err) {
      error.value = err.response?.data?.error || '更新密码失败';
      throw error
    }finally{
      loading.value = false;
    }
  }

  const createToken = async (newToken) => {

    loading.value = true;
    error.value = null;
    try {
      const response = await request.post('/tokens', newToken)
      console.log('createToken', response.data);
      return response
    } catch (err) {
      error.value = err.response?.data?.error || '创建token失败';
      throw error
    }finally{
      loading.value = false;
    }
  }

  const resetToken = async (id) => {
    loading.value = true;
    error.value = null;
    try {
      const response = await request.post(`/tokens/reset/${id}`)
      return response
    } catch (err) {
      error.value = err.response?.data?.error || '重置token失败';
      throw error
    }finally{
      loading.value = false;
    }
  }

  const updateToken = async (token) => {
    loading.value = true;
    error.value = null;
    try {
      const response = await request.put(`/tokens/${token.id}`, token)
      return response
    } catch (err) {
      error.value = err.response?.data?.error || '更新token失败';
      throw error
    }finally {
      loading.value = false;
    }

  }

  const deleteToken = async (id) => {
    loading.value = true;
    error.value = null;
    try {
      const response = await request.delete(`/tokens/${id}`)
      return response
    } catch (err) {
      error.value = err.response?.data?.error || '删除token失败';
      throw err
    }finally {
      loading.value = false;
    }
  }

  const clear = () => {
    user.value = null
    token.value = ''

    localStorage.removeItem('token')
  }

  const logout = () => {
    clear()
    router.push('/login')
  }

  return {
    loading,error,
    user,role,token,
    isLoggedIn,
    setToken,loadTokenFromStorage,
    login,register,
    getProfile,updateProfile,updatePassword,refreshProfile,
    createToken,deleteToken,resetToken,updateToken,
    clear,
    logout
  }
});