import { store } from '@/store'
import { defineStore } from 'pinia'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import {RoomVO} from "@/api/ecg/room";

const { wsCache } = useCache("sessionStorage")

interface RoomInfoVO {
  // 医生诊室选择
  isSetRoom: boolean
  room: RoomVO
}

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
    }
  }),
  getters: {
    // 医生诊室选择
    getIsSetRoom(): boolean {
      return this.isSetRoom
    },
    getRoom(): RoomVO | null {
      return this.room
    }
  },
  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

      // 【修复】写入缓存（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 })
    },
    // 医生离座
    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

      // 清缓存（与上面的写入对应，避免下次启动把已离座的诊室恢复出来）
      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
      }
    },
  }
})

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

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