import { defineStore } from 'pinia';
import { ref } from 'vue';
import { API_CONFIG, getApiUrl, getWebUrl } from '@/utils/config.js';

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref('');
  const nickName = ref('');
  const avatarUrl = ref('');
  const openid = ref('');
  const isLoggedIn = ref(false);
  const hasAgreedToTerms = ref(false);
  const hasVisitedMinePage = ref(false);

  // 初始化：从本地存储加载用户信息
  function init() {
    try {
      const userInfo = uni.getStorageSync('userInfo');
      if (userInfo) {
        const parsedInfo = JSON.parse(userInfo);
        token.value = parsedInfo.token || '';
        nickName.value = parsedInfo.nickName || '';
        avatarUrl.value = parsedInfo.avatarUrl || '';
        openid.value = parsedInfo.openid || '';
        isLoggedIn.value = !!parsedInfo.token;
      }
      
      const agreedStatus = uni.getStorageSync('hasAgreedToTerms');
      hasAgreedToTerms.value = agreedStatus === 'true';
      
      const visitedMine = uni.getStorageSync('hasVisitedMinePage');
      hasVisitedMinePage.value = visitedMine === 'true';
    } catch (e) {
      console.error('Failed to load user info from storage', e);
    }
  }

  // 登录
  async function login() {
    try {
      // 1. 获取用户信息
      const userProfileRes = await getUserProfile();
      
      // 2. 获取微信登录凭证
      const loginRes = await getWxLogin();
      
      // 3. 调用后端登录接口
      const loginData = await wxLogin(loginRes.code, userProfileRes.userInfo);
      
      // 4. 保存用户信息
      setUserInfo({
        token: loginData.data.token,
        nickName: userProfileRes.userInfo.nickName,
        avatarUrl: userProfileRes.userInfo.avatarUrl,
        openid: loginData.data.openid
      });
      
      return Promise.resolve(loginData);
    } catch (error) {
      console.error('Login failed:', error);
      return Promise.reject(error);
    }
  }

  // 获取用户信息
  function getUserProfile() {
    return new Promise((resolve, reject) => {
      uni.getUserProfile({
        desc: '用于完善用户资料',
        success: (res) => {
          resolve(res);
        },
        fail: (err) => {
          console.error('获取用户信息失败:', err);
          reject(err);
        }
      });
    });
  }

  // 获取微信登录凭证
  function getWxLogin() {
    return new Promise((resolve, reject) => {
      uni.login({
        provider: 'weixin',
        success: (res) => {
          if (res.code) {
            resolve(res);
          } else {
            reject(new Error('获取登录凭证失败'));
          }
        },
        fail: (err) => {
          console.error('微信登录失败:', err);
          reject(err);
        }
      });
    });
  }

  // 调用后端登录接口
  function wxLogin(code, userInfo) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: getApiUrl(API_CONFIG.ENDPOINTS.LOGIN), 
        method: 'POST',
        data: {
          code
        },
        header: {
          'Content-Type': 'application/json'
        },
        success: (res) => {
          console.log('登录响应:', res);
          const resData = res.data;
          if (resData.code === 200 && resData.data && resData.data.token) {
            resolve(resData);
          } else {
            reject(new Error('登录失败: ' + (resData.message || JSON.stringify(resData))));
          }
        },
        fail: (err) => {
          console.error('登录请求失败:', err);
          reject(err);
        },
        timeout: API_CONFIG.LOGIN_TIMEOUT
      });
    });
  }

  // 保存用户信息
  function setUserInfo(userInfo) {
    token.value = userInfo.token || '';
    nickName.value = userInfo.nickName || '';
    avatarUrl.value = userInfo.avatarUrl || '';
    openid.value = userInfo.openid || '';
    isLoggedIn.value = !!userInfo.token;
    
    // 保存到本地存储
    uni.setStorageSync('userInfo', JSON.stringify(userInfo));
  }

  // 退出登录
  function logout() {
    return new Promise((resolve, reject) => {
      try {
        // 获取token
        const currentToken = token.value;
        
        // 尝试调用登出接口
        uni.request({
          url: getWebUrl(API_CONFIG.ENDPOINTS.LOGOUT),
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': currentToken ? (currentToken.startsWith('Bearer ') ? currentToken : 'Bearer ' + currentToken) : ''
          },
          data: {
            token: currentToken || ''
          },
          success: (res) => {
            console.log('登出成功:', res);
            uni.showToast({
              title: '登出成功',
              icon: 'success'
            });
          },
          fail: (err) => {
            console.error('登出失败:', err);
            uni.showToast({
              title: '登出接口调用失败',
              icon: 'none'
            });
          },
          complete: () => {
            // 无论成功失败，都清除本地数据
            clearUserData();
            resolve();
          }
        });
      } catch (error) {
        console.error('登出过程发生异常:', error);
        // 发生异常时也要清除本地数据
        clearUserData();
        resolve(); // 用resolve而不是reject，确保登出操作总是成功
      }
    });
  }

  // 清除用户数据的辅助函数
  function clearUserData() {
    token.value = '';
    nickName.value = '';
    avatarUrl.value = '';
    openid.value = '';
    isLoggedIn.value = false;
    
    // 清除本地存储
    uni.removeStorageSync('userInfo');
    uni.removeStorageSync('custom_token');
    uni.removeStorageSync('user_token');
  }

  // 清理假登录数据
  function clearFakeLoginData() {
    console.log('清理假登录数据...');
    
    // 检查是否有无效的登录数据
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo) {
      try {
        const parsedInfo = JSON.parse(userInfo);
        // 如果没有token或token为空，清除数据
        if (!parsedInfo.token || parsedInfo.token.trim() === '') {
          console.log('发现无效的userInfo，清除中...');
          uni.removeStorageSync('userInfo');
        }
      } catch (e) {
        console.log('userInfo格式错误，清除中...');
        uni.removeStorageSync('userInfo');
      }
    }
    
    // 清除其他可能的假token
    const customToken = uni.getStorageSync('custom_token');
    if (customToken && customToken.trim() === '') {
      uni.removeStorageSync('custom_token');
    }
    
    const userToken = uni.getStorageSync('user_token');
    if (userToken && userToken.trim() === '') {
      uni.removeStorageSync('user_token');
    }
    
    // 重新初始化状态
    init();
  }

  // 新增：设置用户同意须知状态
  function setAgreedToTerms(status) {
    hasAgreedToTerms.value = status;
    uni.setStorageSync('hasAgreedToTerms', status.toString());
  }

  // 新增：设置用户已访问我的页面
  function setVisitedMinePage(status) {
    hasVisitedMinePage.value = status;
    uni.setStorageSync('hasVisitedMinePage', status.toString());
  }

  return {
    // 状态
    token,
    nickName,
    avatarUrl,
    openid,
    isLoggedIn,
    hasAgreedToTerms,
    hasVisitedMinePage,
    
    // 方法
    init,
    login,
    setUserInfo,
    logout,
    setAgreedToTerms,
    setVisitedMinePage,
    clearFakeLoginData
  };
}); 