import { ElMessageBox } from 'element-plus'

/**
 * 工位守卫：「请重新就座」类错误的一次性提示 + 轮询停止辅助。
 *
 * 背景
 * ----
 * 工作台（叫号检查 / 设备领用 / 设备装机）每 **5 秒** 轮询一次 `bed-doctor-get`。
 * 当当前账号已经不是该工位的主人（工位被释放 / 在别的电脑入座 / 被管理员清空）时，
 * 后端返回业务码 `1_010_002_001`「请重新就座」，前端原先**每轮都弹一次**，
 * 现场看到的就是"系统一直跳出请重新就座!"。
 *
 * 这里提供两个能力：
 *   · 只提示一次（一次性弹窗，带「去选工位」），不再刷屏；
 *   · 页面据此**停掉轮询定时器**，等重新选到工位后再恢复。
 *
 * 判定依据：后端 {@code ErrorCodeConstants.ROOM_NOT_SIT = 1_010_002_001}。
 */

/** 「请重新就座」业务码（后端 ROOM_NOT_SIT） */
export const SEAT_INVALID_CODE = 1010002001

/** 某个请求异常是否属于"已不是该工位主人" */
export function isSeatInvalidError(e: any): boolean {
  if (!e) return false
  const code = Number(e.code ?? e.bizCode ?? NaN)
  if (Number.isFinite(code) && code === SEAT_INVALID_CODE) return true
  // 兜底：个别链路只把 msg 传上来
  const msg = String(e.message ?? e.msg ?? e)
  return msg.indexOf('请重新就座') !== -1
}

let notified = false

/** 是否已经提示过（便于页面判断） */
export function isSeatInvalidNotified(): boolean {
  return notified
}

/**
 * 工位失效提示：**整个会话只弹一次**，避免 5 秒轮询把提示刷成"一直跳"。
 *
 * 点「去选工位」→ 整页跳转到选工位页（用 location 而非 router.push：
 * 选工位页是顶层路由，整页跳转能顺带重置各工作台的定时器与本地状态）。
 */
export function notifySeatInvalidOnce(): void {
  if (notified) return
  notified = true
  ElMessageBox.confirm(
    '当前账号已不是这个工位的主人（可能工位已被释放、在其它电脑上入座，或被管理员清空）。\n' +
      '请重新选择工位后再操作。',
    '请重新就座',
    {
      confirmButtonText: '去选工位',
      cancelButtonText: '稍后',
      type: 'warning',
      closeOnClickModal: false
    }
  )
    .then(() => {
      window.location.href = '/roomselect'
    })
    .catch(() => {
      /* 用户选择「稍后」：保持页面只读，不再重复弹 */
    })
}

/**
 * 重新获得工位（重新入座 / 切换工位 / 自动恢复）后复位，允许下次再提示一次。
 */
export function resetSeatInvalidNotify(): void {
  notified = false
}
