/**
 * 开发调试面板页面
 *
 * 功能：
 * - 展示当前用户上下文（角色、权限、绑定、门店）
 * - 一键切换角色（后端真实修改 user_site_roles + 重签 token）
 * - 一键切换用户状态（后端真实修改 users.status + 重签 token）
 * - 页面跳转列表（点击跳转到任意已注册页面）
 */
import { request } from "../../utils/request"

// 页面列表分三段：正在迁移、已完成、未完成
const MIGRATING_PAGES = [
  { path: "pages/my-profile/my-profile", name: "个人中心" },
  { path: "pages/customer-service-records/customer-service-records", name: "客户服务记录" },
  { path: "pages/chat/chat", name: "AI 对话" },
  { path: "pages/chat-history/chat-history", name: "对话历史" },
]

const DONE_PAGES = [
  { path: "pages/performance-records/performance-records", name: "业绩明细" },
  { path: "pages/coach-detail/coach-detail", name: "助教详情" },
  { path: "pages/customer-detail/customer-detail", name: "客户详情" },
  { path: "pages/performance/performance", name: "业绩总览" },
  { path: "pages/task-detail/task-detail", name: "任务详情" },
  { path: "pages/no-permission/no-permission", name: "无权限" },
  { path: "pages/login/login", name: "登录" },
  { path: "pages/apply/apply", name: "申请" },
  { path: "pages/reviewing/reviewing", name: "审核中" },
  { path: "pages/board-coach/board-coach", name: "助教看板" },
  { path: "pages/board-customer/board-customer", name: "客户看板" },
  { path: "pages/board-finance/board-finance", name: "财务看板" },
  { path: "pages/task-list/task-list", name: "任务列表（新版）" },
  { path: "pages/notes/notes", name: "备忘录" },
]

const TODO_PAGES: typeof MIGRATING_PAGES = []

const ROLE_LIST = [
  { code: "coach", name: "助教" },
  { code: "staff", name: "员工" },
  { code: "site_admin", name: "店铺管理员" },
  { code: "tenant_admin", name: "租户管理员" },
]

const STATUS_LIST = ["new", "pending", "approved", "rejected", "disabled"]

Page({
  data: {
    ctx: null as any,
    loading: true,
    pages: [] as typeof TODO_PAGES,
    migratingPages: MIGRATING_PAGES,
    donePages: DONE_PAGES,
    todoPages: TODO_PAGES,
    roles: ROLE_LIST,
    statuses: STATUS_LIST,
    currentRole: "",
    rolesText: "-",
    permissionsText: "-",
    bindingText: "-",
    message: "",
    messageType: "",
  },

  onShow() {
    this.loadContext()
  },

  /** 加载当前用户调试上下文 */
  async loadContext() {
    // 没有 token 时不发请求，避免 401 → 刷新 → 跳转的无限循环
    const token = wx.getStorageSync("token")
    if (!token) {
      this.setData({ loading: false })
      this.showMsg("未登录，请先通过 dev-login 获取 token", "error")
      return
    }

    this.setData({ loading: true, message: "" })
    try {
      const ctx = await request({ url: "/api/xcx/dev-context", method: "GET" })
      const rolesText = ctx.roles?.length ? ctx.roles.join(", ") : "-"
      const permissionsText = ctx.permissions?.length ? ctx.permissions.join(", ") : "-"
      let bindingText = "-"
      if (ctx.binding) {
        const b = ctx.binding
        bindingText = `${b.binding_type} (助教:${b.assistant_id || '-'} 员工:${b.staff_id || '-'})`
      }
      // 当前角色取第一个（通常只有一个）
      const currentRole = ctx.roles?.length ? ctx.roles[0] : ""
      this.setData({ ctx, rolesText, permissionsText, bindingText, currentRole, loading: false })
    } catch (err: any) {
      this.setData({ loading: false })
      // 401 说明 token 无效或是受限令牌，不触发重试
      const detail = err?.data?.detail || "网络错误"
      this.showMsg("获取上下文失败: " + detail, "error")
    }
  },

  /** 切换角色 */
  async switchRole(e: any) {
    const code = e.currentTarget.dataset.code
    if (code === this.data.currentRole) return
    wx.showLoading({ title: "切换中..." })
    try {
      const res = await request({
        url: "/api/xcx/dev-switch-role",
        method: "POST",
        data: { role_code: code },
      })
      // 保存新 token
      this.saveTokens(res)
      this.showMsg(`已切换为 ${code}`, "success")
      // 重新加载上下文
      this.loadContext()
    } catch (err: any) {
      this.showMsg("切换角色失败: " + (err?.data?.detail || "网络错误"), "error")
    } finally {
      wx.hideLoading()
    }
  },

  /** 切换用户状态 */
  async switchStatus(e: any) {
    const status = e.currentTarget.dataset.status
    if (status === this.data.ctx?.status) return
    wx.showLoading({ title: "切换中..." })
    try {
      const res = await request({
        url: "/api/xcx/dev-switch-status",
        method: "POST",
        data: { status },
      })
      // 保存新 token
      this.saveTokens(res)
      this.showMsg(`状态已切换为 ${status}`, "success")
      this.loadContext()
    } catch (err: any) {
      this.showMsg("切换状态失败: " + (err?.data?.detail || "网络错误"), "error")
    } finally {
      wx.hideLoading()
    }
  },

  /** 跳转到指定页面 */
  goPage(e: any) {
    const url = "/" + e.currentTarget.dataset.url
    // 使用 reLaunch 确保能跳转到任意页面（包括 tabBar 页面）
    wx.reLaunch({ url })
  },

  /** 保存后端返回的新 token */
  saveTokens(res: any) {
    if (res.access_token && res.refresh_token) {
      const app = getApp<IAppOption>()
      app.globalData.token = res.access_token
      app.globalData.refreshToken = res.refresh_token
      wx.setStorageSync("token", res.access_token)
      wx.setStorageSync("refreshToken", res.refresh_token)
      if (res.user_id) {
        wx.setStorageSync("userId", res.user_id)
      }
      if (res.user_status) {
        wx.setStorageSync("userStatus", res.user_status)
      }
    }
  },

  /** 显示操作提示 */
  showMsg(msg: string, type: "success" | "error") {
    this.setData({ message: msg, messageType: type })
    setTimeout(() => this.setData({ message: "" }), 3000)
  },
})
