import { defineStore } from 'pinia';
import { ref } from 'vue';
import { useUserStore } from '@/stores/modules/user';

export const useLockScreenStore = defineStore(
  'lockScreen',
  () => {
    const isLocked = ref(false);
    const lockTime = ref<string | null>(null);

    /**
     * 锁屏（保存当前时间）
     */
    function lock() {
      isLocked.value = true;
      lockTime.value = new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    }

    /**
     * 尝试解锁（验证密码）
     * 使用原生 fetch 绕过 hook-fetch 拦截器，避免 body 流消费问题
     */
    async function unlock(password: string): Promise<boolean> {
      try {
        const userStore = useUserStore();
        const resp = await fetch(`${import.meta.env.VITE_API_URL}/auth/verifyPassword`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${userStore.token}`,
            'ClientID': import.meta.env.VITE_CLIENT_ID,
            ...(userStore.userInfo?.tenantId ? { 'tenant-id': userStore.userInfo.tenantId } : {}),
          },
          body: JSON.stringify({ password }),
        });
        const data = await resp.json();
        console.log('解锁响应:', data);
        if (data?.code === 200 && data?.data === true) {
          isLocked.value = false;
          lockTime.value = null;
          return true;
        }
        return false;
      }
      catch (e) {
        console.error('解锁请求异常:', e);
        return false;
      }
    }

    /**
     * 解锁（不调用接口，直接解锁）
     */
    function unlockDirect() {
      isLocked.value = false;
      lockTime.value = null;
    }

    return {
      isLocked,
      lockTime,
      lock,
      unlock,
      unlockDirect,
    };
  },
  {
    persist: {
      storage: sessionStorage, // 使用 sessionStorage，浏览器关闭后自动清除
      pick: ['isLocked', 'lockTime'],
    },
  },
);
