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

Page({
  data: {
    keyword: '',
    loading: false,
    users: [],
    editUserId: null,
    editForm: {
      nickname: '',
      company: '',
      title: '',
      phone: '',
      is_admin: false,
      password: '',
      credit_score: 100
    },
    importText: '[{"username":"operator01","password":"123456","nickname":"运营同学","company":"示例科技公司"}]'
  },

  onShow() {
    this.fetchUsers()
  },

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

  onEditInput(e) {
    const field = e.currentTarget.dataset.field
    this.setData({ [`editForm.${field}`]: e.detail.value || '' })
  },

  onAdminSwitch(e) {
    this.setData({ 'editForm.is_admin': !!e.detail.value })
  },

  async fetchUsers() {
    this.setData({ loading: true })
    try {
      const data = await request({
        url: `/admin/users?keyword=${encodeURIComponent(this.data.keyword)}&page=1&page_size=80`
      })
      this.setData({ users: data.items || [] })
    } finally {
      this.setData({ loading: false })
    }
  },

  startEdit(e) {
    const id = Number(e.currentTarget.dataset.id)
    const row = this.data.users.find((item) => item.id === id)
    if (!row) return

    this.setData({
      editUserId: row.id,
      editForm: {
        nickname: row.nickname || '',
        company: row.company || '',
        title: row.title || '',
        phone: row.phone || '',
        is_admin: !!row.is_admin,
        password: '',
        credit_score: row.credit_score || 100
      }
    })
  },

  cancelEdit() {
    this.setData({ editUserId: null })
  },

  async saveEdit() {
    const id = this.data.editUserId
    if (!id) return

    const payload = { ...this.data.editForm }
    if (!payload.password) delete payload.password

    await request({ url: `/admin/users/${id}`, method: 'PUT', data: payload })
    wx.showToast({ title: '用户已更新', icon: 'success' })
    this.setData({ editUserId: null })
    this.fetchUsers()
  },

  removeUser(e) {
    const id = Number(e.currentTarget.dataset.id)
    wx.showModal({
      title: '删除用户',
      content: `确认删除用户 ID ${id} 吗？`,
      success: async (res) => {
        if (!res.confirm) return
        await request({ url: `/admin/users/${id}`, method: 'DELETE' })
        wx.showToast({ title: '删除成功', icon: 'success' })
        this.fetchUsers()
      }
    })
  },

  async importUsers() {
    let items = []
    try {
      items = JSON.parse(this.data.importText)
    } catch (err) {
      wx.showToast({ title: 'JSON 格式错误', icon: 'none' })
      return
    }

    await request({ url: '/admin/users/import', method: 'POST', data: { items } })
    wx.showToast({ title: '导入完成', icon: 'success' })
    this.fetchUsers()
  }
})
