<template>
  <div class="system-settings">
    <a-page-header
      title="系统设置"
      sub-title="系统配置与权限管理"
    />

    <!-- 标签页 -->
    <a-tabs v-model:activeKey="activeTab" type="card">
      <!-- 权限设置标签页 -->
      <a-tab-pane key="permissions" tab="权限设置">
        <PermissionManagement />
      </a-tab-pane>

      <!-- 角色权限管理标签页 -->
      <a-tab-pane key="role-permissions" tab="角色权限管理">
        <RolePermissionManagement />
      </a-tab-pane>

      <!-- 操作日志标签页 -->
      <a-tab-pane key="logs" tab="操作日志">
        <div>
          <!-- 统计卡片 -->
          <a-row :gutter="16" style="margin-bottom: 16px">
            <a-col :span="6">
              <a-card size="small">
                <a-statistic
                  title="今日操作"
                  :value="logStats.todayCount || 0"
                  :value-style="{ color: '#3f8600' }"
                />
              </a-card>
            </a-col>
            <a-col :span="6">
              <a-card size="small">
                <a-statistic
                  title="本周操作"
                  :value="logStats.weekCount || 0"
                  :value-style="{ color: '#1890ff' }"
                />
              </a-card>
            </a-col>
            <a-col :span="6">
              <a-card size="small">
                <a-statistic
                  title="本月操作"
                  :value="logStats.monthCount || 0"
                  :value-style="{ color: '#722ed1' }"
                />
              </a-card>
            </a-col>
            <a-col :span="6">
              <a-card size="small">
                <a-statistic
                  title="总操作数"
                  :value="logStats.totalCount || 0"
                  :value-style="{ color: '#cf1322' }"
                />
              </a-card>
            </a-col>
          </a-row>

          <!-- 搜索表单 -->
          <a-card style="margin-bottom: 16px">
            <a-form layout="inline" :model="logFilters">
              <a-form-item label="用户名">
                <a-input
                  v-model:value="logFilters.username"
                  placeholder="请输入用户名"
                  style="width: 150px"
                />
              </a-form-item>
              <a-form-item label="操作类型">
                <a-select
                  v-model:value="logFilters.action"
                  placeholder="请选择操作类型"
                  style="width: 150px"
                  allow-clear
                >
                  <a-select-option value="login">登录</a-select-option>
                  <a-select-option value="logout">登出</a-select-option>
                  <a-select-option value="create">创建</a-select-option>
                  <a-select-option value="update">更新</a-select-option>
                  <a-select-option value="delete">删除</a-select-option>
                  <a-select-option value="view">查看</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="时间范围">
                <a-range-picker
                  v-model:value="logFilters.dateRange"
                  style="width: 250px"
                />
              </a-form-item>
              <a-form-item>
                <a-space>
                  <a-button @click="handleExportLogs">
                    <DownloadOutlined />
                    导出Excel
                  </a-button>
                  <a-button type="primary" @click="searchLogs">
                    <SearchOutlined />
                    搜索
                  </a-button>
                  <a-button @click="resetLogFilters">
                    重置
                  </a-button>
                </a-space>
              </a-form-item>
            </a-form>
          </a-card>

          <!-- 操作日志表格 -->
          <a-card>
            <a-table
              :columns="logColumns"
              :data-source="logList"
              :loading="logLoading"
              :pagination="logPagination"
              @change="handleLogTableChange"
              row-key="id"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'action'">
                  <a-tag :color="getActionColor(record.action)">
                    {{ getActionText(record.action) }}
                  </a-tag>
                </template>
                <template v-if="column.key === 'operation'">
                  <a-button type="link" @click="showLogDetail(record)">
                    查看详情
                  </a-button>
                </template>
              </template>
            </a-table>
          </a-card>

          <!-- 日志详情模态框 -->
          <a-modal
            v-model:open="logDetailVisible"
            title="操作日志详情"
            :footer="null"
            width="800px"
          >
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="用户名">
                {{ selectedLog.username }}
              </a-descriptions-item>
              <a-descriptions-item label="操作类型">
                <a-tag :color="getActionColor(selectedLog.action)">
                  {{ getActionText(selectedLog.action) }}
                </a-tag>
              </a-descriptions-item>
              <a-descriptions-item label="操作时间">
                {{ dayjs(selectedLog.created_at).format('YYYY-MM-DD HH:mm:ss') }}
              </a-descriptions-item>
              <a-descriptions-item label="IP地址">
                {{ selectedLog.ip_address }}
              </a-descriptions-item>
              <a-descriptions-item label="用户代理" :span="2">
                {{ selectedLog.user_agent }}
              </a-descriptions-item>
              <a-descriptions-item label="操作描述" :span="2">
                {{ selectedLog.description }}
              </a-descriptions-item>
              <a-descriptions-item label="请求详情" :span="2">
                <pre style="white-space: pre-wrap; word-break: break-all;">{{ selectedLog.details }}</pre>
              </a-descriptions-item>
            </a-descriptions>
          </a-modal>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { SearchOutlined, DownloadOutlined } from '@ant-design/icons-vue'
import { operationLogAPI } from '@/utils/api'
import dayjs from 'dayjs'
import PermissionManagement from '@/components/PermissionManagement.vue'
import RolePermissionManagement from '@/components/RolePermissionManagement.vue'

// 标签页状态
const activeTab = ref('permissions')

// 操作日志相关数据
const logLoading = ref(false)
const logList = ref([])
const logStats = reactive({
  todayCount: 0,
  weekCount: 0,
  monthCount: 0,
  totalCount: 0
})

const logFilters = reactive({
  username: '',
  action: undefined,
  dateRange: undefined
})

const logPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
})

const logDetailVisible = ref(false)
const selectedLog = ref({})

// 表格列定义
const logColumns = [
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
    width: 120
  },
  {
    title: '操作类型',
    dataIndex: 'action',
    key: 'action',
    width: 100
  },
  {
    title: '操作描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  },
  {
    title: 'IP地址',
    dataIndex: 'ip_address',
    key: 'ip_address',
    width: 140
  },
  {
    title: '操作时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 180,
    customRender: ({ text }) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
  },
  {
    title: '操作',
    key: 'operation',
    width: 100
  }
]

// 获取操作类型颜色
const getActionColor = (action) => {
  const colors = {
    login: 'green',
    logout: 'blue',
    create: 'cyan',
    update: 'orange',
    delete: 'red',
    view: 'purple'
  }
  return colors[action] || 'default'
}

// 获取操作类型文本
const getActionText = (action) => {
  const texts = {
    login: '登录',
    logout: '登出',
    create: '创建',
    update: '更新',
    delete: '删除',
    view: '查看'
  }
  return texts[action] || action
}

// 获取操作日志统计
const getLogStats = async () => {
  try {
    const response = await operationLogAPI.getStats()
    if (response.code === 200) {
      Object.assign(logStats, response.data)
    }
  } catch (error) {
    console.error('获取日志统计失败:', error)
  }
}

// 获取操作日志列表
const getLogList = async () => {
  logLoading.value = true
  try {
    const params = {
      page: logPagination.current,
      pageSize: logPagination.pageSize,
      ...logFilters
    }
    
    if (logFilters.dateRange && logFilters.dateRange.length === 2) {
      params.startDate = dayjs(logFilters.dateRange[0]).format('YYYY-MM-DD')
      params.endDate = dayjs(logFilters.dateRange[1]).format('YYYY-MM-DD')
    }
    
    const response = await operationLogAPI.getList(params)
    if (response.code === 200) {
      logList.value = response.data.list
      logPagination.total = response.data.total
    }
  } catch (error) {
    message.error('获取操作日志失败')
    console.error('获取操作日志失败:', error)
  } finally {
    logLoading.value = false
  }
}

// 搜索日志
const searchLogs = () => {
  logPagination.current = 1
  getLogList()
}

// 重置搜索条件
const resetLogFilters = () => {
  Object.assign(logFilters, {
    username: '',
    action: undefined,
    dateRange: undefined
  })
  searchLogs()
}

const handleExportLogs = async () => {
  try {
    logLoading.value = true
    const params = {
      username: logFilters.username || undefined,
      action: logFilters.action || undefined
    }
    
    // 处理日期范围
    if (logFilters.dateRange && logFilters.dateRange.length === 2) {
      params.startDate = dayjs(logFilters.dateRange[0]).format('YYYY-MM-DD')
      params.endDate = dayjs(logFilters.dateRange[1]).format('YYYY-MM-DD')
    }
    
    // 过滤掉undefined值
    Object.keys(params).forEach(key => {
      if (params[key] === undefined) {
        delete params[key]
      }
    })
    
      const response = await operationLogAPI.export(params)
      
      // 创建下载链接
      const url = window.URL.createObjectURL(response.data)
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `操作日志_${new Date().getTime()}.xlsx`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    message.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    message.error('导出失败，请稍后重试')
  } finally {
    logLoading.value = false
  }
}

// 表格变化处理
const handleLogTableChange = (pagination) => {
  logPagination.current = pagination.current
  logPagination.pageSize = pagination.pageSize
  getLogList()
}

// 显示日志详情
const showLogDetail = (record) => {
  selectedLog.value = record
  logDetailVisible.value = true
}

// 页面加载时获取数据
onMounted(() => {
  getLogStats()
  getLogList()
})
</script>

<style scoped>
.system-settings {
  padding: 24px;
}

.ant-statistic-content {
  font-size: 20px;
  font-weight: bold;
}

.ant-descriptions-item-label {
  font-weight: bold;
}

pre {
  background-color: #f5f5f5;
  padding: 8px;
  border-radius: 4px;
  font-size: 12px;
}
</style>