<script setup>
import { ref, onMounted } from 'vue'
import { invoke } from '@tauri-apps/api/core'

const showSettings = ref(true)
const username = ref('')
const password = ref('')

// 页面加载时尝试从存储中读取配置
onMounted(async () => {
  try {
    const config = await invoke('load_config')
    if (config && config.username) {
      username.value = config.username
      password.value = config.password || ''
    }
  } catch (error) {
    console.log('No saved config found.')
  }
})

// 保存设置并登录
async function saveAndLogin() {
  try {
    await invoke('save_config', { 
      config: { username: username.value, password: password.value } 
    })
    await invoke('start_monitoring') // 开始轮询
    showSettings.value = false // 隐藏设置界面
    await invoke('minimize_to_tray') // 最小化到托盘
  } catch (error) {
    alert('保存失败: ' + error)
  }
}
</script>

<template>
  <div v-if="showSettings" class="settings">
    <h2>登录设置</h2>
    <div>
      <label>用户名:</label>
      <input v-model="username" type="text" />
    </div>
    <div>
      <label>密码:</label>
      <input v-model="password" type="password" />
    </div>
    <button @click="saveAndLogin">登录</button>
  </div>
  <div v-else class="main">
    <h2>正在监控...</h2>
    <p>程序已最小化到系统托盘。</p>
    <button @click="() => showSettings = true">重新打开设置</button>
  </div>
</template>

<style>
.settings, .main {
  padding: 20px;
  font-family: Arial, sans-serif;
}
input {
  margin: 5px 0;
  padding: 8px;
  width: 200px;
}
button {
  margin-top: 10px;
  padding: 10px 20px;
}
</style>