import { store } from '@/store'
import { defineStore } from 'pinia'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { RoomApi, RoomVO, RoomSeatResp } from "@/api/ecg/room";
import { DoctorApi } from "@/api/ecg/doctor";
import { getConfigKey } from '@/api/infra/config'
import { useUserStore } from '@/store/modules/user'

const { wsCache } = useCache("sessionStorage")

/** 参数 key：选择工位模式（与后端 Constants.ECG_ROOM_SELECT_MODE_KEY 一致） */
const ROOM_SELECT_MODE_KEY = 'ecg.room.select.mode'

/**
 * 选择工位模式：
 *  0 = 按需要强制选择工位（=原行为）
 *  1 = 登录IP匹配工位（匹配不到按 0 执行）
 *  2 = 登录时手动选择工位，并写入本机IP
 *  3 = 按系统默认处理（该IP未绑定过→按2选一次并记住IP；已绑定→按1自动匹配；匹配不到→按0）
 */
export type RoomSelectMode = 0 | 1 | 2 | 3

/** 自动匹配工位的结果，供路由守卫分支用 */
export interface AutoSeatResult {
  /** 是否已成功入座 */
  seated: boolean
  /** 后端识别到的本机IP */
  clientIp: string | null
  /**
   * 未入座原因（seated=true 时无意义）：
   * - nomatch：该IP没匹配到工位
   * - occupied：匹配到但全被他人占用
   * - multi：**该IP对应多个可选工位**，无法只凭IP确定，需要人工点选
   * - ip_invalid：本机IP不可用（回环 / IPv6 / 未指定 / 非法），不能作为工位标识
   * - ip_is_server：识别到的是**服务器自身地址**（在服务器上/远程桌面里访问，或代理覆盖了客户端地址）
   * - error：接口异常或入座写库未生效
   */
  reason?: 'nomatch' | 'occupied' | 'multi' | 'ip_invalid' | 'ip_is_server' | 'error'
  /** 被占用时的占用人，便于提示 */
  occupiedBy?: string | null
  /** 【本需求】被占用时命中的候选工位（供"是否接管"确认后直接调用 takeOverBed） */
  roomId?: number | null
  bedNo?: string | null
  roomName?: string | null
}

interface RoomInfoVO {
  // 医生诊室选择（= 当前**查看**的工位：看自己就是自己入座的，看别人就是围观对象）
  isSetRoom: boolean
  room: RoomVO
  // 选择工位模式（-1 表示还没取到）
  roomSelectMode: number
  /**
   * 当前登录人**已入座**的工位（系统顶栏显示用；未入座为 null）。
   *
   * 与 `room` 的区别：`room` 是"我正在看哪个工位"（围观时是别人的工位），
   * 而 `currentSeat` 是"我入座在哪个工位"（服务端 clinic_room.doc_id = 我）。
   * 两者相同 → 可操作；不同 → 只读围观。
   */
  currentSeat: RoomSeatResp | null
  /**
   * 【本需求·一人多工位】当前登录人占据的**全部**工位（节假日值班多岗位）。
   *
   * 与 `currentSeat` 的区别：`currentSeat` 只是"默认/首选取"的那一个（顶栏文案用），
   * `mySeats` 才是完整集合；`getCanOperate` 用它判断"当前查看的工位是否属于我"。
   */
  mySeats: RoomSeatResp[]
  /** 当前查看工位的主人的姓名（围观时用于提示"正在围观 X（主人 张三）"） */
  viewOwnerName: string | null
  /** 当前查看的工位现在是否**无人操作**（主人已离座；只提示，不自动接管） */
  viewTargetVacant: boolean
}


export const useRoomStore = defineStore('current-room', {
  state: (): RoomInfoVO => ({
    // 医生诊室选择
    isSetRoom: false,
    room: {
      id: null,
      roomId: null,
      roomName: null,
      bedNo: null,
      ip: null,
      status: null,
      docId: null,
      docName: null,
      checkTypes: null,
      opType: null
    },
    // 选择工位模式：-1 = 尚未从后端取到
    roomSelectMode: -1,
    // 当前入座的工位（顶栏显示；未入座为 null）
    currentSeat: null,
    // 【本需求·一人多工位】我占据的全部工位（未入座为空数组）
    mySeats: [],
    // 正在查看的工位的主人姓名（围观提示用）
    viewOwnerName: null,
    // 正在查看的工位现在是否无人操作（主人已离座 → 只提示，不自动接管）
    viewTargetVacant: false
  }),
  getters: {
    // 医生诊室选择
    getIsSetRoom(): boolean {
      return this.isSetRoom
    },
    getRoom(): RoomVO | null {
      return this.room
    },
    /** 当前入座的工位（可能为 null = 未入座） */
    getCurrentSeat(): RoomSeatResp | null {
      return this.currentSeat
    },
    /** 【本需求·一人多工位】我占据的全部工位 */
    getMySeats(): RoomSeatResp[] {
      return this.mySeats || []
    },
    /** 【本需求·一人多工位】我占据的工位数量（顶栏提示"我的工位 N 个"） */
    getMySeatCount(): number {
      return (this.mySeats || []).length
    },
    /**
     * 【主/围观】当前是否**可以操作业务**。
     *
     * 判定（本需求改为"包含"）：
     *   当前查看的工位 ∈ 我的工位列表 ⇒ 可操作（服务端另有一道硬校验：该工位 doc_id 必须是我）。
     * 一键多工位后，我不可能同时只在"一个"工位上，所以不能再用"相等"判断。
     * 兼容：`mySeats` 还没取到（旧接口/旧缓存）时回退到 `currentSeat` 相等判断。
     */
    getCanOperate(): boolean {
      const view = this.room
      if (!view || view.roomId == null || !view.bedNo) {
        return false
      }
      const seats = this.mySeats || []
      if (seats.length > 0) {
        return seats.some(
          (s) => String(s.roomId) === String(view.roomId) && String(s.bedNo) === String(view.bedNo)
        )
      }
      const seat = this.currentSeat
      if (!seat || !seat.seated) {
        return false
      }
      return String(seat.roomId) === String(view.roomId) && String(seat.bedNo) === String(view.bedNo)
    },
    /** 当前是否在**围观别人的工位**（有座但看的不是自己那座，或没座只看别人） */
    getIsViewingOther(): boolean {
      return this.isSetRoom && !this.getCanOperate
    },
    /**
     * 顶栏展示文案：`1号门诊 · A1`；未入座返回空串（由组件显示"未入座"）。
     * 诊室名为空时退化为只显示工位号，避免出现 `undefined · A1`。
     */
    getSeatText(): string {
      const seat = this.currentSeat
      if (!seat || !seat.seated) return ''
      const name = seat.roomName || `诊室${seat.roomId ?? ''}`
      return seat.bedNo ? `${name} · ${seat.bedNo}` : name
    },
    /** 顶栏"当前查看的工位"文案（围观时用它，而不是我自己入座的工位） */
    getViewText(): string {
      const view = this.room
      if (!view || view.roomId == null || !view.bedNo) return ''
      const name = view.roomName || `诊室${view.roomId}`
      return `${name} · ${view.bedNo}`
    }
  },
  actions: {
    // 医生入座
    async setRoomInfoAction(room: RoomVO) {
      // 更新 store
      this.room!.id = room.id
      this.room!.roomId = room.roomId
      this.room!.roomName = room.roomName
      this.room!.bedNo = room.bedNo
      this.room!.status = room.status
      this.room!.docId = room.docId
      this.room!.docName = room.docName
      this.room!.checkTypes = room.checkTypes
      this.room!.opType = room.opType
      this.isSetRoom = true
      // 【主/围观】这条路径都是"我入座的工位"（入座 / 恢复我的工位 / 自动入座 / 选工位页回填），
      // 因此把 currentSeat 一起设上 —— 否则 getCanOperate 会误判为"无座只读"。
      this.currentSeat = {
        seated: true,
        id: room.id ?? null,
        roomId: room.roomId ?? null,
        roomName: room.roomName ?? null,
        bedNo: room.bedNo ?? null,
        ip: room.ip ?? null,
        status: room.status ?? null,
        docId: room.docId ?? null,
        docName: room.docName ?? null,
        checkTypes: room.checkTypes ?? null,
        opType: room.opType ?? null
      } as RoomSeatResp
      this.viewOwnerName = room.docName ?? null
      this.viewTargetVacant = false

      // 【本需求·一人多工位】把该工位并入「我的工位」（已存在则更新，不存在则新增）
      this.upsertMySeat(this.currentSeat)

      // 【修复】写入缓存（sessionStorage）。
      //
      // 原实现是 `const bedInfo = wsCache.get(...); if (bedInfo) { ...; wsCache.set(...) }`
      // —— **只在缓存已存在时才更新，而全项目没有任何地方首次写入**，
      // 于是 ROOM 缓存从未被创建，`room` 只活在内存里：
      //   · 刷新页面 / 新开标签页 / 从会话恢复后，`isSetRoom` 又是初始的 false；
      //   · 而各医生页面（Routine/index/DevInstall）只在 `isSetRoom === true` 时
      //     才启动取数定时器 ⇒ **页面一片空白，看起来像"没加载排队病人"**；
      //   · 角色为 doctor 的用户还会被路由守卫弹回 /roomselect 重新选诊室。
      // 这里改为**无条件写入**；恢复见文件末尾的 setupRoomStorePersistence()。
      wsCache.set(CACHE_KEY.ROOM, {
        isSetRoom: true,
        room: this.room,
        currentSeat: this.currentSeat,
        mySeats: this.mySeats
      })
    },
    /** 【本需求·一人多工位】把一条工位并入 mySeats（按 roomId+bedNo 去重） */
    upsertMySeat(seat: RoomSeatResp | null) {
      if (!seat || seat.roomId == null || !seat.bedNo) return
      const list = (this.mySeats || []).filter(
        (s) => !(String(s.roomId) === String(seat.roomId) && String(s.bedNo) === String(seat.bedNo))
      )
      list.push(seat)
      this.mySeats = list
    },
    /** 【本需求·一人多工位】用后端返回的完整列表替换 mySeats，并同步 currentSeat */
    applyMySeats(seats: RoomSeatResp[]) {
      this.mySeats = Array.isArray(seats) ? seats : []
      if (this.mySeats.length === 0) {
        this.currentSeat = null
        return
      }
      // currentSeat：优先取"当前查看的工位"对应的那条，否则第一条
      const view = this.room
      const matched = this.mySeats.find(
        (s) =>
          null != view &&
          String(s.roomId) === String(view.roomId) &&
          String(s.bedNo) === String(view.bedNo)
      )
      this.currentSeat = matched ?? this.mySeats[0]
    },
    /**
     * 【主/围观】把"我正在看的工位"切到别人（或切回自己）——**不改我的入座工位**。
     *
     * 围观就是靠这个动作实现的：`room`（看谁）与 `currentSeat`（我坐哪）分离，
     * 两者不同时 {@link getCanOperate} 为 false → 界面只读，服务端另有一道硬校验。
     *
     * @param bed       要查看的工位（来自工位列表）
     * @param ownerName 该工位当前主人的姓名（无主时传 null）
     */
    async setViewTargetAction(bed: RoomVO, ownerName?: string | null) {
      this.room!.id = bed.id ?? null
      this.room!.roomId = bed.roomId ?? null
      this.room!.roomName = bed.roomName ?? null
      this.room!.bedNo = bed.bedNo ?? null
      this.room!.ip = bed.ip ?? null
      this.room!.status = bed.status ?? null
      this.room!.docId = bed.docId ?? null
      this.room!.docName = bed.docName ?? null
      this.room!.checkTypes = bed.checkTypes ?? null
      this.room!.opType = bed.opType ?? null
      this.isSetRoom = true
      this.viewOwnerName = ownerName ?? bed.docName ?? null
      this.viewTargetVacant = bed.docId == null
      wsCache.set(CACHE_KEY.ROOM, {
        isSetRoom: true,
        room: this.room,
        currentSeat: this.currentSeat,
        mySeats: this.mySeats
      })
    },
    /**
     * 【主/围观】刷新"我正在看的工位"的最新状态（用于发现主人已离座）。
     *
     * 只更新 docId/docName 与 vacant 标记，不改变"我在看哪个工位"。
     * 按确认口径：主人离座后**只提示、不自动接管**。
     */
    refreshViewTargetState(bed: RoomVO) {
      if (!this.room || String(this.room.roomId) !== String(bed.roomId) || this.room.bedNo !== bed.bedNo) {
        return
      }
      this.room.docId = bed.docId ?? null
      this.room.docName = bed.docName ?? null
      this.viewOwnerName = bed.docName ?? null
      this.viewTargetVacant = bed.docId == null
    },
    // 医生离座
    async clearRoomInfoAction() {
      // 清 store
      this.room.id = null
      this.room.roomId = null
      this.room.roomName = null
      this.room.bedNo = null
      this.room.status = null
      this.room.docId = null
      this.room.docName = null

      this.isSetRoom = false
      // 顶栏标签同步清空（离座后显示"未入座"）
      this.currentSeat = null
      // 【本需求·一人多工位】离座后 mySeats 一并清空
      this.mySeats = []
      this.viewOwnerName = null
      this.viewTargetVacant = false

      // 清缓存（与上面的写入对应，避免下次启动把已离座的诊室恢复出来）
      wsCache.delete(CACHE_KEY.ROOM)
    },
    /**
     * 【修复】应用启动时从 sessionStorage 恢复「医生已选诊室」。
     *
     * 为什么需要：`isSetRoom` 是内存态，刷新即丢；而各医生页面都靠它决定是否取数。
     * 恢复时同时校验诊室信息完整（roomId + bedNo），避免脏缓存指向不存在的工位。
     */
    restoreRoomInfo() {
      if (this.isSetRoom && this.room?.roomId != null) {
        return // 内存里已有，无需恢复
      }
      const cached = wsCache.get(CACHE_KEY.ROOM)
      if (cached?.isSetRoom && cached?.room?.roomId != null && cached?.room?.bedNo != null) {
        this.room = { ...this.room, ...cached.room }
        this.isSetRoom = true
        // 【主/围观】连"我入座的工位"一起恢复：否则刷新后 getCanOperate 会误判为只读
        // 【本需求·一人多工位】优先恢复完整列表；旧缓存没有 mySeats 时用 currentSeat 兜底
        if (Array.isArray(cached?.mySeats) && cached.mySeats.length > 0) {
          this.mySeats = cached.mySeats
        } else if (cached?.currentSeat) {
          this.mySeats = [cached.currentSeat]
        }
        if (cached?.currentSeat) {
          this.currentSeat = cached.currentSeat
          this.viewOwnerName = cached.currentSeat.docName ?? null
          // ⚠️【本次修复】**不把"围观对象"带到下一次打开**：
          // 缓存里的 room 若与我入座的工位不是同一个，说明上次在围观别人。
          // 若照原样恢复，刷新后工作台会一直显示**别人工位的队列**（看着像"患者列表空了"），
          // 而医生以为在看自己的工位 —— 现场反馈的"列表整个是空的"很可能就是这个。
          // 围观是"当前会话里的临时选择"，刷新/重开一律回到我自己的工位。
          const seat = cached.currentSeat
          const cachedIsMine =
            String(cached.room.roomId) === String(seat.roomId) && cached.room.bedNo === seat.bedNo
          if (!cachedIsMine) {
            this.room = {
              ...this.room,
              id: seat.id ?? null,
              roomId: seat.roomId ?? null,
              roomName: seat.roomName ?? null,
              bedNo: seat.bedNo ?? null,
              ip: seat.ip ?? null,
              status: seat.status ?? null,
              docId: seat.docId ?? null,
              docName: seat.docName ?? null,
              checkTypes: seat.checkTypes ?? null,
              opType: seat.opType ?? null
            }
            this.viewOwnerName = seat.docName ?? null
            this.viewTargetVacant = false
            console.info('[room] 上次在围观其他工位，本次打开回到我自己的工位', this.room)
          }
        }
      }
    },

    /* ==================== 选择工位模式（0/1/2/3） ==================== */

    /** 读取「选择工位模式」参数：会话内只取一次；取不到或非法一律按 0（原行为），避免影响存量部署 */
    async loadRoomSelectMode(force = false): Promise<number> {
      if (!force && this.roomSelectMode >= 0) {
        return this.roomSelectMode
      }
      let mode = 0
      try {
        const v = await getConfigKey(ROOM_SELECT_MODE_KEY)
        const n = Number(v)
        if ([0, 1, 2, 3].includes(n)) {
          mode = n
        }
      } catch (e) {
        mode = 0
      }
      this.roomSelectMode = mode
      return mode
    },

    /**
     * 模式 1/3：按本机IP自动匹配并自动入座。
     *
     * 【本次修复】改为**调用后端一个接口**（`POST /clinic/room/auto-seat`）完成
     * 「匹配 → 判定 → 落座」，不再由前端拼 `getIpBed → bindIpToBed → bedDoctorOn` 三步：
     * 原来任一步失败都只能回落"手选工位"，现场表现就是"登录后没有自动入座"且看不出原因。
     * 现在后端直接返回 `reason`（ip_invalid / nomatch / multi / occupied / error）与识别到的 IP。
     *
     * 匹配策略（后端实现，与原前端逻辑一致）：
     * · 已经是我的工位      → 幂等恢复（刷新/重进/上次没正常离座都走这条）；
     * · 空闲候选**恰好 1 个** → 入座（服务端同时保证"一个用户只占一个工位"）；
     * · 空闲候选**多个**     → 不擅自入座（reason='multi'），交人工点选；
     * · 全被他人占用        → reason='occupied' + 占用人姓名（**不挤掉**已在操作的人）。
     */
    async tryAutoSeatByIp(): Promise<AutoSeatResult> {
      try {
        const resp: any = (await RoomApi.autoSeat()) || {}
        const clientIp: string | null = resp.clientIp ?? null
        if (resp.seated) {
          await this.setRoomInfoAction({
            id: resp.id ?? null,
            roomId: resp.roomId ?? null,
            roomName: resp.roomName ?? null,
            bedNo: resp.bedNo ?? null,
            ip: resp.ip ?? null,
            status: resp.status ?? null,
            docId: resp.docId ?? null,
            docName: resp.docName ?? null,
            checkTypes: resp.checkTypes ?? null,
            opType: resp.opType ?? null
          } as RoomVO)
          // 顶栏"当前工位"标签用
          this.currentSeat = resp as RoomSeatResp
          // 【本需求·一人多工位】把该工位并入我的工位列表
          this.upsertMySeat(this.currentSeat)
          console.info('[room] 按IP自动入座成功', resp)
          return { seated: true, clientIp }
        }
        console.info('[room] 按IP自动入座未成功', resp)
        return {
          seated: false,
          clientIp,
          reason: (resp.reason || 'nomatch') as AutoSeatResult['reason'],
          occupiedBy: resp.ownerName ?? resp.docName ?? null,
          // 【本需求】被占用时后端会带回候选工位信息，供"是否接管"确认后直接调用
          roomId: resp.roomId ?? null,
          bedNo: resp.bedNo ?? null,
          roomName: resp.roomName ?? null
        }
      } catch (e) {
        console.error('[tryAutoSeatByIp] 自动入座接口异常', e)
        return { seated: false, clientIp: null, reason: 'error' }
      }
    },

    /**
     * 查询并记录"当前登录人已入座的工位"（系统顶栏显示用）。
     *
     * 场景：刷新页面 / 新开标签页 / 直接进系统，内存里的 `currentSeat` 可能是空的，
     * 但后端知道我是哪个工位的主人 —— 查一次就能让顶栏与各页面口径一致。
     *
     * 【主/围观】注意：**只有在我还没选"要看的工位"、或我看的就是自己工位时**，
     * 才把查看目标也对齐到我的工位；否则会把正在围观的对象覆盖掉（围观就没法用了）。
     */
    async fetchMySeat(): Promise<RoomSeatResp | null> {
      try {
        // 【本需求·一人多工位】优先取"我的全部工位"；后端未升级（404）时回退单值接口
        let seats: RoomSeatResp[] = []
        let fallbackSingle: any = null
        try {
          const list: any = await RoomApi.getMySeats()
          seats = Array.isArray(list) ? (list as RoomSeatResp[]) : []
        } catch (e) {
          console.warn('[fetchMySeat] /my-seats 不可用，回退 /my-seat', e)
          const resp: any = (await RoomApi.getMySeat()) || {}
          if (resp.seated) {
            fallbackSingle = resp
            seats = [resp as RoomSeatResp]
          }
        }

        if (seats.length === 0 && !fallbackSingle) {
          this.mySeats = []
          this.currentSeat = null
          return null
        }

        this.applyMySeats(seats)

        const noViewTarget = !this.isSetRoom || this.room.roomId == null || !this.room.bedNo
        const viewingMine = !noViewTarget && this.getCanOperate
        if (!noViewTarget && !viewingMine) {
          // 正在围观别人 → 只更新"我的工位列表"，不动查看目标
          console.info('[room] 已刷新我的工位列表（当前正在围观他人，不切换查看目标）', seats)
          return this.currentSeat
        }

        // 未选查看目标 / 看的就是自己的某个工位 → 对齐到该工位（优先当前查看的那个）
        const target = this.currentSeat ?? seats[0]
        if (target) {
          await this.setRoomInfoAction({
            id: target.id ?? null,
            roomId: target.roomId ?? null,
            roomName: target.roomName ?? null,
            bedNo: target.bedNo ?? null,
            ip: target.ip ?? null,
            status: target.status ?? null,
            docId: target.docId ?? null,
            docName: target.docName ?? null,
            checkTypes: target.checkTypes ?? null,
            opType: target.opType ?? null
          } as RoomVO)
        }
        console.info('[room] 查询到我的工位列表', seats)
        return this.currentSeat
      } catch (e) {
        console.error('[fetchMySeat] 查询当前工位失败', e)
        return null
      }
    },

    /**
     * 【本需求·接班自助接管】把指定工位从"别人占用"改到我名下，并切换到该工位。
     *
     * @returns 是否接管成功
     */
    async takeOverBed(roomId: number | null, bedNo: string | null): Promise<boolean> {
      if (roomId == null || !bedNo) return false
      try {
        await RoomApi.takeOverBed({ roomId, bedNo })
        // 刷新"我的工位"（此时后端已把该工位 doc_id 设为我）
        await this.fetchMySeat()
        // 切换到该工位（若是刚接管、且不在列表里，则手动补一条并切过去）
        let seat = (this.mySeats || []).find(
          (s) => String(s.roomId) === String(roomId) && String(s.bedNo) === String(bedNo)
        )
        if (!seat) {
          const userStore = useUserStore()
          const curUser: any = userStore.getUser || {}
          seat = {
            seated: true,
            roomId,
            bedNo,
            roomName: this.room?.roomName ?? null,
            docId: curUser.id ?? null,
            docName: curUser.nickname ?? null
          } as RoomSeatResp
          this.mySeats = [...(this.mySeats || []), seat]
        }
        await this.setRoomInfoAction({
          id: seat.id ?? null,
          roomId: seat.roomId ?? null,
          roomName: seat.roomName ?? null,
          bedNo: seat.bedNo ?? null,
          ip: seat.ip ?? null,
          status: seat.status ?? null,
          docId: seat.docId ?? null,
          docName: seat.docName ?? null,
          checkTypes: seat.checkTypes ?? null,
          opType: seat.opType ?? null
        } as RoomVO)
        console.info('[room] 接管工位成功', roomId, bedNo)
        return true
      } catch (e) {
        console.error('[takeOverBed] 接管工位失败', e)
        return false
      }
    },

    /**
     * 入座（bed-doctor-on）+ 写入会话。抽出来给「手动选择」和「按IP自动匹配」共用。
     * @returns 是否入座成功
     */
    async seatRoom(bed: Partial<RoomVO>): Promise<boolean> {
      const userStore = useUserStore()
      const curUser: any = userStore.getUser || {}
      const tempRoomVO: RoomVO = {
        id: bed.id ?? null,
        roomId: bed.roomId ?? null,
        roomName: bed.roomName ?? null,
        bedNo: bed.bedNo ?? null,
        ip: bed.ip ?? null,
        status: bed.status ?? null,
        docId: curUser.id ?? null,
        docName: curUser.nickname ?? null,
        checkTypes: bed.checkTypes ?? null,
        opType: bed.opType ?? null
      }
      const data = await DoctorApi.bedDoctorOn(tempRoomVO)
      if (data !== 0) {
        console.warn('[seatRoom] bedDoctorOn 返回非 0：', data)
        return false
      }
      await this.setRoomInfoAction(tempRoomVO)
      // 【本需求·一人多工位】入座后刷新"我的全部工位"（可能已有多个）
      await this.fetchMySeat()
      return true
    },

    /**
     * 模式 2/3：把本机IP写到指定工位。
     * @returns { code, conflict, msg } —— code=409 表示该IP已绑在别的工位（conflict=true），需确认后带 force 重调
     */
    async bindCurrentIp(bedId: number, force = false): Promise<any> {
      const resp: any = await RoomApi.bindIpToBed(bedId, force)
      return resp || {}
    }
  }
})

export const useRoomStoreWithOut = () => {
  return useRoomStore(store)
}

/**
 * 在应用启动阶段调用一次（见 src/main.ts），把「已选诊室」从 sessionStorage 恢复到 store。
 *
 * 必须早于路由守卫与各医生页面的 onMounted，否则页面会因为 isSetRoom=false 而完全不取数。
 */
export const setupRoomStorePersistence = () => {
  useRoomStoreWithOut().restoreRoomInfo()
}
