// src/stores/state.js
import { defineStore } from 'pinia';
import { sendInstrumentCommand } from '@/api/experiment';
import { message } from '@/utils/message.js'; // 请替换为实际的消息通知库

export const useGlobalStateStore = defineStore('globalState', {
  state: () => ({
    lightStatus: false,
    timer: null // 用于存储 setTimeout 的引用
  }),
  actions: {
    async activateStatus() {
      console.log('Sending command to turn on the LED');
      const response = await sendInstrumentCommand({
        name: 'LED',
        status: 1
      });

      const { code, desc } = response.data;
      if (code === 200) {
        message(desc);
        this.lightStatus = true;
        //console.log('LED turned on, starting timer for 2 minutes');

        this.timer = setTimeout(async () => {
          await this.deactivateStatus();
        }, 2 * 60 * 1000);
      } else {
        message('Failed to turn on the LED');
      }
    },

    async deactivateStatus() {
      console.log('Sending command to turn off the LED');
      const response = await sendInstrumentCommand({
        name: 'LED',
        status: 0
      });

      const { code, desc } = response.data;
      if (code === 200) {
        message(desc);
        this.lightStatus = false;
      } else {
      }

      // 清除计时器
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
      }
    },

    async toggleStatus() {
      if (this.lightStatus) {
        await this.deactivateStatus();
      } else {
        await this.activateStatus();
      }
    }
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'globalState',
        storage: localStorage
      }
    ]
  }
});
