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

const USER_MODULES = [
  { name: '信息发布', desc: '发布公开 / 私有 / 私信文本并实时检测', tag: '发布检测', path: '/pages/detect/index' },
  { name: '批量识别', desc: '多条文本批量检测并给出风险汇总', tag: '批量筛查', path: '/pages/batch/index' },
  { name: '发布历史', desc: '查看发布状态、概率和申诉进度', tag: '历史追踪', path: '/pages/history/index' },
  { name: '私信收件箱', desc: '查看通过检测后成功送达的私信', tag: '私信查看', path: '/pages/inbox/index' },
  { name: '个人中心', desc: '维护个人资料与密码设置', tag: '账号设置', path: '/pages/profile/index' }
]

const ADMIN_MODULES = [
  { name: '运营看板', desc: '监控发布、拦截、样本和模型状态', tag: '数据概览', path: '/pages/admin-dashboard/index' },
  { name: '复核与申诉', desc: '处理拦截复核和用户申诉', tag: '审核处理', path: '/pages/admin-review/index' },
  { name: '样本管理', desc: '维护训练样本并触发模型重训', tag: '模型迭代', path: '/pages/admin-samples/index' },
  { name: '用户管理', desc: '编辑用户信息和权限', tag: '权限管理', path: '/pages/admin-users/index' }
]

Page({
  data: {
    loading: true,
    user: null,
    modelInfo: null,
    threshold: null,
    thresholdText: '--',
    userModules: USER_MODULES,
    adminModules: ADMIN_MODULES
  },

  onShow() {
    this.bootstrap()
  },

  async bootstrap() {
    const app = getApp()
    if (!app.globalData.token) {
      wx.reLaunch({ url: '/pages/login/index' })
      return
    }

    this.setData({ loading: true })
    try {
      const [user, modelInfo] = await Promise.all([
        request({ url: '/auth/me' }),
        request({ url: '/spam/model/info' })
      ])

      app.globalData.user = user
      wx.setStorageSync('user', user)
      const threshold = modelInfo.threshold || null
      const thresholdText = threshold === null || threshold === undefined ? '--' : `${(Number(threshold) * 100).toFixed(1)}%`
      this.setData({ user, modelInfo, threshold, thresholdText })
    } finally {
      this.setData({ loading: false })
    }
  },

  goto(e) {
    const path = e.currentTarget.dataset.path
    if (!path) return
    wx.navigateTo({ url: path })
  },

  logout() {
    getApp().clearAuth()
    wx.reLaunch({ url: '/pages/login/index' })
  }
})
