const { login } = require('../../utils_new/auth');
const config = require('../../config/index');

Page({
  data: {
    baseUrl: 'https://ai-c.maimanji.com',
    statusBarHeight: 20,
    navBarHeight: 44,
    totalNavHeight: 64
  },
  onLoad() {
    const sys = wx.getSystemInfoSync();
    const menu = wx.getMenuButtonBoundingClientRect();
    const statusBarHeight = sys.statusBarHeight || 20;
    const navBarHeight = menu.height + (menu.top - statusBarHeight) * 2;
    this.setData({ 
      statusBarHeight,
      navBarHeight,
      totalNavHeight: statusBarHeight + navBarHeight
    });
    this.load();
  },
  onShow() {
    const defaultBaseUrl = String(config.API_BASE_URL || '').replace(/\/api$/, '') || 'https://ai-c.maimanji.com';
    const baseUrl = wx.getStorageSync('baseUrl') || defaultBaseUrl;
    this.setData({ baseUrl });
  },
  onBack() {
    wx.navigateBack({ delta: 1 });
  },
  onBaseUrl(e) {
    this.setData({ baseUrl: e.detail.value });
  },
  setOnline() {
    this.setData({ baseUrl: 'https://ai-c.maimanji.com' });
  },
  setLocalhost() {
    this.setData({ baseUrl: 'http://localhost:3000' });
  },
  save() {
    const baseUrl = (this.data.baseUrl || '').trim().replace(/\/$/, '');
    if (!baseUrl.startsWith('http')) {
      wx.showToast({ title: '请输入正确的URL', icon: 'none' });
      return;
    }
    wx.setStorageSync('baseUrl', baseUrl);
    const app = getApp();
    if (app?.globalData) app.globalData.baseUrl = baseUrl;
    wx.showToast({ title: '已保存', icon: 'success' });
  },
  logout() {
    wx.removeStorageSync('token');
    const app = getApp();
    if (app?.globalData) app.globalData.token = '';
    wx.showToast({ title: '已退出', icon: 'success' });
  },
  async syncProfile() {
    try {
      const userInfo = await new Promise((resolve, reject) => {
        wx.getUserProfile({
          desc: '用于完善个人信息',
          success: (res) => resolve(res.userInfo),
          fail: reject
        });
      });
      await login(userInfo);
      wx.showToast({ title: '已同步', icon: 'success' });
    } catch (e) {
      wx.showToast({ title: '取消或失败', icon: 'none' });
    }
  }
});
