<script setup lang="ts">
import { storeToRefs } from "pinia";
import { ref } from "vue";
import { useMonitorStore } from "@/stores/monitor";

const store = useMonitorStore();
const { loginMode, isMonitoring, username, password, tokenSessionId, rememberPassword } = storeToRefs(store);
/** 表单操作加载状态 */
const isLoading = ref(false);

async function handleSaveSettings() {
  isLoading.value = true;
  await store.saveSettings();
  isLoading.value = false;
}

async function handleStartMonitoring() {
  isLoading.value = true;
  await store.startMonitoring();
  isLoading.value = false;
}

async function handleStopMonitoring() {
  isLoading.value = true;
  store.stopMonitoring();
  isLoading.value = false;
}
</script>

<template>
  <a-form layout="vertical">
    <a-form-item>
      <a-radio-group v-model:value="loginMode" :disabled="isMonitoring">
        <a-radio-button value="password"> 账号密码登录 </a-radio-button>
        <a-radio-button value="token"> Token 登录 </a-radio-button>
      </a-radio-group>
    </a-form-item>

    <template v-if="loginMode === 'password'">
      <a-form-item label="用户名">
        <a-input v-model:value="username" placeholder="请输入用户名" :disabled="isLoading" />
      </a-form-item>
      <a-form-item label="密码">
        <a-input-password v-model:value="password" placeholder="请输入密码" :disabled="isLoading" />
      </a-form-item>
    </template>

    <template v-else>
      <a-form-item label="ASP.NET_SessionId">
        <a-input
          v-model:value="tokenSessionId"
          placeholder="请输入 ASP.NET_SessionId"
          :disabled="isLoading"
          allow-clear
        />
      </a-form-item>
      <a-typography-text type="secondary" style="font-size: 12px; display: block; margin-bottom: 12px">
        从浏览器开发者工具 (F12) → Application → Cookies 中复制 ASP.NET_SessionId 的值
      </a-typography-text>
    </template>

    <a-form-item>
      <a-checkbox v-model:checked="rememberPassword">
        记住{{ loginMode === "password" ? "密码" : "Token" }}
      </a-checkbox>
    </a-form-item>
    <a-form-item>
      <a-space>
        <a-button type="primary" :loading="isLoading" @click="handleSaveSettings()"> 保存设置 </a-button>
        <a-button
          type="primary"
          :loading="isLoading"
          :disabled="isMonitoring"
          style="background: #52c41a; border-color: #52c41a"
          @click="handleStartMonitoring()"
        >
          开始监测
        </a-button>
        <a-button danger :disabled="isLoading || !isMonitoring" @click="handleStopMonitoring()"> 停止监测 </a-button>
      </a-space>
    </a-form-item>
  </a-form>
</template>
