<template>
  <div class="settings-container">
    <!-- 头部 -->
    <header class="header">
      <div class="logo">
        <el-icon><Setting /></el-icon>
        个人设置
      </div>
      <el-button @click="goBack" type="primary" size="small">
        返回下载器
      </el-button>
    </header>

    <!-- 主要内容 -->
    <div class="main-content">
      <el-card class="settings-card">
        <template #header>
          <div class="card-header">
            <span>用户信息</span>
          </div>
        </template>
        
        <el-form :model="userInfo" label-width="120px">
          <el-form-item label="用户名">
            <el-input v-model="userInfo.userName" disabled />
          </el-form-item>
          
          <el-form-item label="邮箱">
            <el-input v-model="userInfo.email" disabled />
          </el-form-item>
          
          <el-form-item label="注册时间">
            <el-input v-model="userInfo.createdAt" disabled />
          </el-form-item>
          
          <el-form-item label="最后登录">
            <el-input v-model="userInfo.lastLoginAt" disabled />
          </el-form-item>
        </el-form>
      </el-card>

      <el-card class="settings-card">
        <template #header>
          <div class="card-header">
            <span>下载设置</span>
          </div>
        </template>
        
        <el-form :model="downloadSettings" label-width="120px">
          <el-form-item label="最大并发数">
            <el-input-number 
              v-model="downloadSettings.maxConcurrentDownloads" 
              :min="1" 
              :max="10"
              @change="saveSettings"
            />
            <span class="form-tip">同时下载的最大文件数量</span>
          </el-form-item>
          
          <el-form-item label="文件名前缀">
            <el-input 
              v-model="downloadSettings.fileNamePrefix" 
              placeholder="例如: vue-downloader"
              @input="saveSettings"
            />
            <span class="form-tip">为所有下载文件添加前缀</span>
          </el-form-item>
          
          <el-form-item label="下载通知">
            <el-switch 
              v-model="downloadSettings.enableNotifications"
              @change="saveSettings"
            />
            <span class="form-tip">下载完成后显示通知</span>
          </el-form-item>
        </el-form>
      </el-card>

      <el-card class="settings-card">
        <template #header>
          <div class="card-header">
            <span>数据管理</span>
          </div>
        </template>
        
        <div class="data-management">
          <div class="data-item">
            <div class="data-info">
              <h4>下载历史</h4>
              <p>清除所有下载历史记录</p>
            </div>
            <el-button @click="clearHistory" type="danger" size="small">
              清除历史
            </el-button>
          </div>
          
          <div class="data-item">
            <div class="data-info">
              <h4>用户数据</h4>
              <p>删除当前用户的所有数据</p>
            </div>
            <el-button @click="deleteUserData" type="danger" size="small">
              删除数据
            </el-button>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Setting } from '@element-plus/icons-vue'
import { useAuthStore } from '../stores/auth'
import http from '@/utils/request.js';
import config from '@/api/api.js';

const router = useRouter()
const authStore = useAuthStore()

// 用户信息
const userInfo = reactive({
  userName: '',
  email: '',
  createdAt: '',
  lastLoginAt: ''
})

// 下载设置
const downloadSettings = reactive({
  maxConcurrentDownloads: 3,
  fileNamePrefix: '',
  enableNotifications: true
})

// 初始化数据
const initializeData = () => {
  const user = authStore.user
  if (user) {
    userInfo.userName = user.userName
    userInfo.email = user.email || '未设置'
    userInfo.createdAt = new Date(user.createdAt).toLocaleString()
    userInfo.lastLoginAt = user.lastLoginAt ? new Date(user.lastLoginAt).toLocaleString() : '从未登录'
    
    // 加载用户设置
    const settings = authStore.getUserSettings()
    Object.assign(downloadSettings, settings)
  }
}

// 保存设置
const saveSettings = () => {
  try {
    authStore.updateUserSettings(downloadSettings)
    ElMessage.success('设置已保存')
  } catch (error) {
    ElMessage.error('保存设置失败')
  }
}

// 清除历史记录
const clearHistory = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清除所有下载历史记录吗？此操作不可恢复。',
      '确认清除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    authStore.clearDownloadHistory()
    ElMessage.success('历史记录已清除')
    http.post(config.uploadDetailDeleteAll, {
      type: 1
    }).then(res => {
      if (res.code === 200) {
      } else {
      }
    })
  } catch {
    // 用户取消
  }
}

// 删除用户数据
const deleteUserData = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要删除当前用户的所有数据吗？包括设置、历史记录等，此操作不可恢复。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 清除历史记录
    authStore.clearDownloadHistory()
    
    // 重置用户设置
    const defaultSettings = {
      maxConcurrentDownloads: 3,
      fileNamePrefix: '',
      enableNotifications: true
    }
    authStore.updateUserSettings(defaultSettings)
    Object.assign(downloadSettings, defaultSettings)
    
    ElMessage.success('用户数据已删除')
    http.post(config.uploadDetailDeleteAll, {
      type: 2
    }).then(res => {
      if (res.code === 200) {
      } else {
      }
    })
  } catch {
    // 用户取消
  }
}

// 返回下载器
const goBack = () => {
  router.push('/downloader')
}

// 组件挂载时初始化
onMounted(() => {
  initializeData()
  userInfo.userName = sessionStorage.getItem("userName") || ''
})
</script>

<style scoped>
.settings-container {
  min-height: 100vh;
  background: #f5f5f5;
}

.header {
  background: white;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.logo {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.main-content {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 20px;
}

.settings-card {
  margin-bottom: 20px;
}

.card-header {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.form-tip {
  margin-left: 10px;
  color: #666;
  font-size: 12px;
}

.data-management {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.data-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.data-info h4 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 14px;
}

.data-info p {
  margin: 0;
  color: #666;
  font-size: 12px;
}

@media (max-width: 768px) {
  .main-content {
    padding: 0 10px;
  }
  
  .data-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>
