const { request } = require('../../utils/request')

Page({
  data: {
    username: '',
    password: '',
    loading: false
  },

  onLoad() {
    const app = getApp()
    if (app.globalData.token) {
      wx.reLaunch({ url: '/pages/home/index' })
    }
  },

  onInput(e) {
    const field = e.currentTarget.dataset.field
    this.setData({ [field]: (e.detail.value || '').trim() })
  },

  fillDemo() {
    this.setData({ username: 'admin', password: 'Admin@123456' })
  },

  async submit() {
    if (this.data.loading) return
    const { username, password } = this.data
    if (!username || !password) {
      wx.showToast({ title: '请输入用户名和密码', icon: 'none' })
      return
    }

    this.setData({ loading: true })
    try {
      const data = await request({
        url: '/auth/login',
        method: 'POST',
        data: { username, password }
      })
      getApp().setAuth(data.token, data.user)
      wx.showToast({ title: '登录成功', icon: 'success' })
      setTimeout(() => wx.reLaunch({ url: '/pages/home/index' }), 250)
    } finally {
      this.setData({ loading: false })
    }
  },

  goRegister() {
    wx.navigateTo({ url: '/pages/register/index' })
  }
})
