import { wxLogin, getUserInfo, updateUserInfo, uploadAvatar, logout } from '../api/user.js';
import { ref } from 'vue';

export function useUserApi() {
  const loading = ref(false);
  const error = ref(null);
  
  // 微信登录
  const login = async (code, userInfo = {}) => {
    loading.value = true;
    error.value = null;
    
    try {
      const result = await wxLogin(code, userInfo);
      loading.value = false;
      return result;
    } catch (err) {
      loading.value = false;
      error.value = err;
      throw err;
    }
  };
  
  // 获取用户信息
  const fetchUserInfo = async () => {
    loading.value = true;
    error.value = null;
    
    try {
      const result = await getUserInfo();
      loading.value = false;
      return result;
    } catch (err) {
      loading.value = false;
      error.value = err;
      throw err;
    }
  };
  
  // 更新用户信息
  const updateUser = async (userData) => {
    loading.value = true;
    error.value = null;
    
    try {
      const result = await updateUserInfo(userData);
      loading.value = false;
      return result;
    } catch (err) {
      loading.value = false;
      error.value = err;
      throw err;
    }
  };
  
  // 上传头像
  const uploadUserAvatar = async (filePath) => {
    loading.value = true;
    error.value = null;
    
    try {
      const result = await uploadAvatar(filePath);
      loading.value = false;
      return result;
    } catch (err) {
      loading.value = false;
      error.value = err;
      throw err;
    }
  };
  
  // 退出登录
  const logoutUser = async () => {
    loading.value = true;
    error.value = null;
    
    try {
      const result = await logout();
      loading.value = false;
      return result;
    } catch (err) {
      loading.value = false;
      error.value = err;
      throw err;
    }
  };
  
  return {
    loading,
    error,
    login,
    fetchUserInfo,
    updateUser,
    uploadUserAvatar,
    logoutUser
  };
} 