/**
 * 登录页
 * 支持密码登录、短信验证码登录
 */
const api = require('../../utils/api');
const auth = require('../../utils/auth');

Page({
  data: {
    loginMode: 'password',
    phone: '',
    password: '',
    smsCode: '',
    showPassword: false,
    loading: false,
    smsTimer: 0,
    redirect: ''
  },

  onLoad(options) {
    if (options.redirect) {
      this.setData({ redirect: decodeURIComponent(options.redirect) });
    }
  },

  switchMode(e) {
    this.setData({ loginMode: e.currentTarget.dataset.mode });
  },

  onPhoneInput(e) { this.setData({ phone: e.detail.value }); },
  onPasswordInput(e) { this.setData({ password: e.detail.value }); },
  onSmsCodeInput(e) { this.setData({ smsCode: e.detail.value }); },
  togglePassword() { this.setData({ showPassword: !this.data.showPassword }); },

  async onPasswordLogin() {
    const { phone, password, loading } = this.data;
    if (loading) return;
    if (!phone || !password) {
      wx.showToast({ title: '请填写完整', icon: 'none' });
      return;
    }
    if (!/^1\d{10}$/.test(phone)) {
      wx.showToast({ title: '手机号格式不正确', icon: 'none' });
      return;
    }

    this.setData({ loading: true });
    try {
      const result = await api.login({ phone, password });
      if (result.token) {
        api.setToken(result.token);
        wx.setStorageSync('userInfo', result.user || {});
        wx.showToast({ title: '登录成功', icon: 'success' });
        this.handleLoginSuccess();
      }
    } catch (err) {
      // api.js handles error toast
    } finally {
      this.setData({ loading: false });
    }
  },

  async onSendSms() {
    if (this.data.smsTimer > 0) return;
    const { phone } = this.data;
    if (!/^1\d{10}$/.test(phone)) {
      wx.showToast({ title: '请输入正确手机号', icon: 'none' });
      return;
    }

    // 开始倒计时
    this.startSmsTimer();
    wx.showToast({ title: '验证码已发送（模拟）', icon: 'success' });
  },

  startSmsTimer() {
    this.setData({ smsTimer: 60 });
    const timer = setInterval(() => {
      if (this.data.smsTimer <= 1) {
        clearInterval(timer);
        this.setData({ smsTimer: 0 });
      } else {
        this.setData({ smsTimer: this.data.smsTimer - 1 });
      }
    }, 1000);
    this._smsTimer = timer;
  },

  async onSmsLogin() {
    const { phone, smsCode, loading } = this.data;
    if (loading) return;
    if (!phone || !smsCode) {
      wx.showToast({ title: '请填写完整', icon: 'none' });
      return;
    }

    this.setData({ loading: true });
    try {
      const result = await api.smsLogin({ phone, sms_code: smsCode });
      if (result.token) {
        api.setToken(result.token);
        wx.setStorageSync('userInfo', result.user || {});
        wx.showToast({ title: '登录成功', icon: 'success' });
        this.handleLoginSuccess();
      }
    } catch (err) {
      // handled
    } finally {
      this.setData({ loading: false });
    }
  },

  handleLoginSuccess() {
    const { redirect } = this.data;
    if (redirect && redirect !== '/pages/index/index') {
      wx.redirectTo({ url: redirect });
    } else {
      wx.switchTab({ url: '/pages/index/index' });
    }
  },

  goRegister() {
    // 注册使用密码登录的注册页面，简化：直接跳转H5
    wx.showModal({
      title: '提示',
      content: '注册功能请使用密码登录模式，直接输入手机号注册',
      showCancel: false
    });
  },

  onUnload() {
    if (this._smsTimer) clearInterval(this._smsTimer);
  }
});
