<template>
  <div class="settings-container">
    <a-page-header title="系统设置" sub-title="管理系统配置和参数" />
    
    <a-tabs default-active-key="1" class="settings-tabs">
      <a-tab-pane key="1" tab="基本设置">
        <a-card title="系统参数配置" class="settings-card">
          <a-form :model="basicSettings" layout="vertical">
            <a-form-item label="系统名称">
              <a-input v-model:value="basicSettings.systemName" placeholder="请输入系统名称" />
            </a-form-item>
            
            <a-form-item label="系统描述">
              <a-textarea v-model:value="basicSettings.systemDescription" placeholder="请输入系统描述" :rows="4" />
            </a-form-item>
            
            <a-form-item label="管理员邮箱">
              <a-input v-model:value="basicSettings.adminEmail" placeholder="请输入管理员邮箱" />
            </a-form-item>
            
            <a-form-item label="系统维护模式">
              <a-switch v-model:checked="basicSettings.maintenanceMode" />
              <span class="setting-description">启用后，除管理员外的用户将无法登录系统</span>
            </a-form-item>
            
            <a-form-item>
              <a-button type="primary" @click="saveBasicSettings">保存设置</a-button>
              <a-button style="margin-left: 10px" @click="resetBasicSettings">重置</a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-tab-pane>
      
      <a-tab-pane key="2" tab="安全设置">
        <a-card title="密码策略" class="settings-card">
          <a-form :model="securitySettings" layout="vertical">
            <a-form-item label="密码最小长度">
              <a-input-number v-model:value="securitySettings.minPasswordLength" :min="6" :max="20" />
              <span class="setting-description">密码最小长度要求（6-20个字符）</span>
            </a-form-item>
            
            <a-form-item label="密码复杂度要求">
              <a-checkbox-group v-model:value="securitySettings.passwordComplexity">
                <a-checkbox value="uppercase">必须包含大写字母</a-checkbox>
                <a-checkbox value="lowercase">必须包含小写字母</a-checkbox>
                <a-checkbox value="numbers">必须包含数字</a-checkbox>
                <a-checkbox value="special">必须包含特殊字符</a-checkbox>
              </a-checkbox-group>
            </a-form-item>
            
            <a-form-item label="密码过期时间">
              <a-select v-model:value="securitySettings.passwordExpiry">
                <a-select-option value="30">30天</a-select-option>
                <a-select-option value="60">60天</a-select-option>
                <a-select-option value="90">90天</a-select-option>
                <a-select-option value="180">180天</a-select-option>
                <a-select-option value="365">365天</a-select-option>
                <a-select-option value="0">永不过期</a-select-option>
              </a-select>
            </a-form-item>
            
            <a-form-item label="登录失败锁定">
              <a-input-number v-model:value="securitySettings.loginAttempts" :min="3" :max="10" />
              <span class="setting-description">连续失败次数后锁定账户</span>
            </a-form-item>
            
            <a-form-item label="锁定时间">
              <a-select v-model:value="securitySettings.lockDuration">
                <a-select-option value="15">15分钟</a-select-option>
                <a-select-option value="30">30分钟</a-select-option>
                <a-select-option value="60">1小时</a-select-option>
                <a-select-option value="1440">24小时</a-select-option>
                <a-select-option value="-1">需管理员手动解锁</a-select-option>
              </a-select>
            </a-form-item>
            
            <a-form-item>
              <a-button type="primary" @click="saveSecuritySettings">保存设置</a-button>
              <a-button style="margin-left: 10px" @click="resetSecuritySettings">重置</a-button>
            </a-form-item>
          </a-form>
        </a-card>
        
        <a-card title="双因素认证" class="settings-card">
          <a-form :model="twoFactorSettings" layout="vertical">
            <a-form-item label="启用双因素认证">
              <a-switch v-model:checked="twoFactorSettings.enabled" />
              <span class="setting-description">要求用户使用双因素认证登录系统</span>
            </a-form-item>
            
            <a-form-item label="适用角色">
              <a-checkbox-group v-model:value="twoFactorSettings.roles">
                <a-checkbox value="admin">管理员</a-checkbox>
                <a-checkbox value="manager">经理</a-checkbox>
                <a-checkbox value="teller">柜员</a-checkbox>
                <a-checkbox value="user">普通用户</a-checkbox>
              </a-checkbox-group>
            </a-form-item>
            
            <a-form-item>
              <a-button type="primary" @click="saveTwoFactorSettings">保存设置</a-button>
              <a-button style="margin-left: 10px" @click="resetTwoFactorSettings">重置</a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-tab-pane>
      
      <a-tab-pane key="3" tab="系统日志">
        <a-card title="日志查询" class="settings-card">
          <a-form layout="inline" class="log-search-form">
            <a-form-item label="日志类型">
              <a-select v-model:value="logQuery.type" style="width: 150px">
                <a-select-option value="all">全部</a-select-option>
                <a-select-option value="login">登录日志</a-select-option>
                <a-select-option value="operation">操作日志</a-select-option>
                <a-select-option value="system">系统日志</a-select-option>
                <a-select-option value="error">错误日志</a-select-option>
              </a-select>
            </a-form-item>
            
            <a-form-item label="日期范围">
              <a-range-picker v-model:value="logQuery.dateRange" />
            </a-form-item>
            
            <a-form-item label="用户">
              <a-input v-model:value="logQuery.user" placeholder="用户名" style="width: 150px" />
            </a-form-item>
            
            <a-form-item>
              <a-button type="primary" @click="searchLogs">查询</a-button>
              <a-button style="margin-left: 10px" @click="resetLogQuery">重置</a-button>
            </a-form-item>
          </a-form>
          
          <a-table
            :columns="logColumns"
            :data-source="logs"
            :loading="logsLoading"
            :pagination="logPagination"
            @change="handleLogTableChange"
            class="log-table"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'level'">
                <a-tag :color="getLogLevelColor(record.level)">{{ record.level }}</a-tag>
              </template>
              <template v-if="column.key === 'action'">
                <a @click="viewLogDetail(record)">查看详情</a>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>
      
      <a-tab-pane key="4" tab="备份与恢复">
        <a-card title="数据备份" class="settings-card">
          <a-form layout="vertical">
            <a-form-item label="自动备份">
              <a-switch v-model:checked="backupSettings.autoBackup" />
              <span class="setting-description">启用系统自动备份功能</span>
            </a-form-item>
            
            <a-form-item label="备份频率">
              <a-select v-model:value="backupSettings.frequency" style="width: 200px">
                <a-select-option value="daily">每天</a-select-option>
                <a-select-option value="weekly">每周</a-select-option>
                <a-select-option value="monthly">每月</a-select-option>
              </a-select>
            </a-form-item>
            
            <a-form-item label="保留备份数量">
              <a-input-number v-model:value="backupSettings.keepCount" :min="1" :max="30" />
              <span class="setting-description">系统将保留最近的备份数量</span>
            </a-form-item>
            
            <a-form-item>
              <a-button type="primary" @click="saveBackupSettings">保存设置</a-button>
              <a-button style="margin-left: 10px" @click="resetBackupSettings">重置</a-button>
              <a-button type="primary" danger style="margin-left: 10px" @click="createManualBackup">立即备份</a-button>
            </a-form-item>
          </a-form>
          
          <a-divider />
          
          <h3>备份历史</h3>
          <a-table
            :columns="backupColumns"
            :data-source="backups"
            :loading="backupsLoading"
            :pagination="{ pageSize: 5 }"
            class="backup-table"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <a-button type="link" @click="downloadBackup(record)">下载</a-button>
                <a-button type="link" danger @click="confirmRestoreBackup(record)">恢复</a-button>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>
    </a-tabs>
    
    <!-- 日志详情弹窗 -->
    <a-modal
      v-model:visible="logDetailVisible"
      title="日志详情"
      width="700px"
      :footer="null"
    >
      <a-descriptions bordered :column="1">
        <a-descriptions-item label="ID">{{ selectedLog.id }}</a-descriptions-item>
        <a-descriptions-item label="时间">{{ selectedLog.timestamp }}</a-descriptions-item>
        <a-descriptions-item label="类型">{{ selectedLog.type }}</a-descriptions-item>
        <a-descriptions-item label="级别">
          <a-tag :color="getLogLevelColor(selectedLog.level)">{{ selectedLog.level }}</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="用户">{{ selectedLog.user }}</a-descriptions-item>
        <a-descriptions-item label="IP地址">{{ selectedLog.ip }}</a-descriptions-item>
        <a-descriptions-item label="操作">{{ selectedLog.action }}</a-descriptions-item>
        <a-descriptions-item label="详细信息">
          <div class="log-detail-content">{{ selectedLog.message }}</div>
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
    
    <!-- 恢复备份确认弹窗 -->
    <a-modal
      v-model:visible="restoreConfirmVisible"
      title="恢复备份"
      @ok="restoreBackup"
      okText="确认恢复"
      cancelText="取消"
      :okButtonProps="{ danger: true }"
    >
      <p>您确定要恢复到 {{ selectedBackup.created_at }} 的备份吗？</p>
      <p><strong>警告：</strong> 此操作将覆盖当前系统数据，且不可撤销！</p>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'

// 基本设置
const basicSettings = reactive({
  systemName: '宁夏银行管理系统',
  systemDescription: '专业的银行业务管理解决方案，提供全面的账户管理、交易处理和报表分析功能。',
  adminEmail: 'admin@example.com',
  maintenanceMode: false
})

// 安全设置
const securitySettings = reactive({
  minPasswordLength: 8,
  passwordComplexity: ['uppercase', 'lowercase', 'numbers'],
  passwordExpiry: '90',
  loginAttempts: 5,
  lockDuration: '60'
})

// 双因素认证设置
const twoFactorSettings = reactive({
  enabled: false,
  roles: ['admin', 'manager']
})

// 备份设置
const backupSettings = reactive({
  autoBackup: true,
  frequency: 'daily',
  keepCount: 7
})

// 日志查询参数
const logQuery = reactive({
  type: 'all',
  dateRange: null,
  user: ''
})

// 日志表格列定义
const logColumns = [
  { title: 'ID', dataIndex: 'id', key: 'id' },
  { title: '时间', dataIndex: 'timestamp', key: 'timestamp', sorter: true },
  { title: '类型', dataIndex: 'type', key: 'type', filters: [
    { text: '登录日志', value: 'login' },
    { text: '操作日志', value: 'operation' },
    { text: '系统日志', value: 'system' },
    { text: '错误日志', value: 'error' }
  ] },
  { title: '级别', dataIndex: 'level', key: 'level' },
  { title: '用户', dataIndex: 'user', key: 'user' },
  { title: '操作', dataIndex: 'action', key: 'action' },
  { title: '消息', dataIndex: 'message', key: 'message', ellipsis: true },
  { title: '操作', key: 'action', width: 100 }
]

// 备份表格列定义
const backupColumns = [
  { title: 'ID', dataIndex: 'id', key: 'id' },
  { title: '创建时间', dataIndex: 'created_at', key: 'created_at' },
  { title: '大小', dataIndex: 'size', key: 'size' },
  { title: '类型', dataIndex: 'type', key: 'type' },
  { title: '创建者', dataIndex: 'created_by', key: 'created_by' },
  { title: '操作', key: 'action', width: 150 }
]

// 日志数据
const logs = ref([])
const logsLoading = ref(false)
const logPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 备份数据
const backups = ref([])
const backupsLoading = ref(false)

// 日志详情弹窗
const logDetailVisible = ref(false)
const selectedLog = ref({})

// 恢复备份确认弹窗
const restoreConfirmVisible = ref(false)
const selectedBackup = ref({})

// 页面加载时获取数据
onMounted(() => {
  fetchSettings()
  fetchLogs()
  fetchBackups()
})

// 获取系统设置
const fetchSettings = async () => {
  try {
    // 这里应该调用API获取系统设置
    // 模拟API调用
    setTimeout(() => {
      // 设置已经在上面初始化了
    }, 500)
  } catch (error) {
    message.error('获取系统设置失败')
    console.error('获取系统设置失败:', error)
  }
}

// 获取日志数据
const fetchLogs = async () => {
  logsLoading.value = true
  try {
    // 这里应该调用API获取日志数据
    // 模拟API调用
    setTimeout(() => {
      logs.value = [
        {
          id: '1001',
          timestamp: '2025-09-17 14:30:25',
          type: 'login',
          level: 'info',
          user: 'admin',
          ip: '192.168.1.100',
          action: '用户登录',
          message: '管理员成功登录系统'
        },
        {
          id: '1002',
          timestamp: '2025-09-17 14:35:12',
          type: 'operation',
          level: 'warning',
          user: 'admin',
          ip: '192.168.1.100',
          action: '修改用户权限',
          message: '修改用户 user001 的权限'
        },
        {
          id: '1003',
          timestamp: '2025-09-17 14:40:05',
          type: 'system',
          level: 'error',
          user: 'system',
          ip: '127.0.0.1',
          action: '系统错误',
          message: '数据库连接失败: Connection timeout'
        }
      ]
      logPagination.total = 100
      logsLoading.value = false
    }, 500)
  } catch (error) {
    message.error('获取日志数据失败')
    console.error('获取日志数据失败:', error)
    logsLoading.value = false
  }
}

// 获取备份数据
const fetchBackups = async () => {
  backupsLoading.value = true
  try {
    // 这里应该调用API获取备份数据
    // 模拟API调用
    setTimeout(() => {
      backups.value = [
        {
          id: '1',
          created_at: '2025-09-17 00:00:00',
          size: '125.4 MB',
          type: '自动备份',
          created_by: 'system'
        },
        {
          id: '2',
          created_at: '2025-09-16 00:00:00',
          size: '124.8 MB',
          type: '自动备份',
          created_by: 'system'
        },
        {
          id: '3',
          created_at: '2025-09-15 14:30:00',
          size: '126.2 MB',
          type: '手动备份',
          created_by: 'admin'
        }
      ]
      backupsLoading.value = false
    }, 500)
  } catch (error) {
    message.error('获取备份数据失败')
    console.error('获取备份数据失败:', error)
    backupsLoading.value = false
  }
}

// 保存基本设置
const saveBasicSettings = () => {
  // 这里应该调用API保存基本设置
  message.success('基本设置保存成功')
}

// 重置基本设置
const resetBasicSettings = () => {
  // 重置为初始值或从服务器重新获取
  fetchSettings()
  message.info('基本设置已重置')
}

// 保存安全设置
const saveSecuritySettings = () => {
  // 这里应该调用API保存安全设置
  message.success('安全设置保存成功')
}

// 重置安全设置
const resetSecuritySettings = () => {
  // 重置为初始值或从服务器重新获取
  fetchSettings()
  message.info('安全设置已重置')
}

// 保存双因素认证设置
const saveTwoFactorSettings = () => {
  // 这里应该调用API保存双因素认证设置
  message.success('双因素认证设置保存成功')
}

// 重置双因素认证设置
const resetTwoFactorSettings = () => {
  // 重置为初始值或从服务器重新获取
  fetchSettings()
  message.info('双因素认证设置已重置')
}

// 保存备份设置
const saveBackupSettings = () => {
  // 这里应该调用API保存备份设置
  message.success('备份设置保存成功')
}

// 重置备份设置
const resetBackupSettings = () => {
  // 重置为初始值或从服务器重新获取
  fetchSettings()
  message.info('备份设置已重置')
}

// 创建手动备份
const createManualBackup = () => {
  // 这里应该调用API创建手动备份
  message.loading({ content: '正在创建备份...', key: 'backupLoading' })
  
  // 模拟API调用
  setTimeout(() => {
    message.success({ content: '备份创建成功', key: 'backupLoading' })
    fetchBackups() // 刷新备份列表
  }, 2000)
}

// 搜索日志
const searchLogs = () => {
  // 重置分页到第一页
  logPagination.current = 1
  fetchLogs()
}

// 重置日志查询条件
const resetLogQuery = () => {
  logQuery.type = 'all'
  logQuery.dateRange = null
  logQuery.user = ''
  searchLogs()
}

// 处理日志表格变化（排序、筛选、分页）
const handleLogTableChange = (pagination, filters, sorter) => {
  logPagination.current = pagination.current
  // 这里可以根据sorter和filters更新查询参数
  fetchLogs()
}

// 查看日志详情
const viewLogDetail = (record) => {
  selectedLog.value = record
  logDetailVisible.value = true
}

// 下载备份
const downloadBackup = (record) => {
  // 这里应该调用API下载备份
  message.success(`开始下载备份 ${record.id}`)
}

// 确认恢复备份
const confirmRestoreBackup = (record) => {
  selectedBackup.value = record
  restoreConfirmVisible.value = true
}

// 恢复备份
const restoreBackup = () => {
  // 这里应该调用API恢复备份
  message.loading({ content: '正在恢复备份...', key: 'restoreLoading' })
  
  // 模拟API调用
  setTimeout(() => {
    message.success({ content: '备份恢复成功，系统将在5秒后刷新', key: 'restoreLoading' })
    restoreConfirmVisible.value = false
    
    // 模拟系统刷新
    setTimeout(() => {
      window.location.reload()
    }, 5000)
  }, 2000)
}

// 获取日志级别对应的颜色
const getLogLevelColor = (level) => {
  const colors = {
    info: 'blue',
    warning: 'orange',
    error: 'red',
    debug: 'green'
  }
  return colors[level] || 'default'
}
</script>

<style scoped>
.settings-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 64px);
}

.settings-tabs {
  background-color: #fff;
  padding: 24px;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

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

.setting-description {
  color: #8c8c8c;
  margin-left: 8px;
  font-size: 12px;
}

.log-search-form {
  margin-bottom: 24px;
}

.log-table, .backup-table {
  margin-top: 16px;
}

.log-detail-content {
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 300px;
  overflow-y: auto;
  padding: 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-family: monospace;
}
</style>
