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

      // 更新 cache
      const bedInfo = wsCache.get(CACHE_KEY.ROOM)
      if (bedInfo) {
        bedInfo.room = room
        bedInfo.isSetRoom = true
        wsCache.set(CACHE_KEY.ROOM, bedInfo)
      }
    },
    // 医生离座
    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

      // 更新 cache
      const roomInfo = wsCache.get(CACHE_KEY.ROOM)
      if (roomInfo) {
        roomInfo.room = null
        roomInfo.isSetRoom = false
        wsCache.set(CACHE_KEY.ROOM, roomInfo)
      }
    },
  }
})

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