<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <!-- 操作日志 -->
      <el-tab-pane label="操作日志" name="operlog">
        <!-- 搜索栏 -->
        <el-form :model="operlogParams" :inline="true" class="search-form">
          <el-form-item label="系统模块">
            <el-input v-model="operlogParams.title" placeholder="请输入系统模块" clearable @keyup.enter="getOperlogList" />
          </el-form-item>
          <el-form-item label="操作人员">
            <el-input v-model="operlogParams.operName" placeholder="请输入操作人员" clearable @keyup.enter="getOperlogList" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="operlogParams.status" placeholder="操作状态" clearable>
              <el-option label="成功" :value="0" />
              <el-option label="失败" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getOperlogList">搜索</el-button>
            <el-button @click="resetOperlog">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 操作栏 -->
        <el-row :gutter="10" class="mb10">
          <el-col :span="1.5">
            <el-button type="danger" plain :disabled="!operlogSelectedIds.length" @click="handleDeleteOperlog">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain @click="handleCleanOperlog">清空</el-button>
          </el-col>
        </el-row>

        <!-- 表格 -->
        <el-table v-loading="operlogLoading" :data="operlogList" @selection-change="handleOperlogSelection">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="日志编号" prop="oper_id" width="100" />
          <el-table-column label="系统模块" prop="title" width="150" show-overflow-tooltip />
          <el-table-column label="操作类型" prop="business_type" width="100">
            <template #default="{ row }">
              {{ businessTypeMap[row.business_type] || '其他' }}
            </template>
          </el-table-column>
          <el-table-column label="请求方式" prop="request_method" width="100" />
          <el-table-column label="操作人员" prop="oper_name" width="120" />
          <el-table-column label="操作地址" prop="oper_ip" width="130" />
          <el-table-column label="操作状态" prop="status" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 0 ? 'success' : 'danger'">
                {{ row.status === 0 ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作时间" prop="oper_time" width="160" />
          <el-table-column label="耗时" prop="cost_time" width="80">
            <template #default="{ row }">
              {{ row.cost_time }}ms
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-model:current-page="operlogParams.pageNum"
          v-model:page-size="operlogParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="operlogTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="getOperlogList"
          @current-change="getOperlogList"
          style="margin-top: 15px; justify-content: flex-end"
        />
      </el-tab-pane>

      <!-- 登录日志 -->
      <el-tab-pane label="登录日志" name="logininfor">
        <!-- 搜索栏 -->
        <el-form :model="loginParams" :inline="true" class="search-form">
          <el-form-item label="登录地址">
            <el-input v-model="loginParams.ipaddr" placeholder="请输入登录地址" clearable @keyup.enter="getLogininforList" />
          </el-form-item>
          <el-form-item label="用户名称">
            <el-input v-model="loginParams.userName" placeholder="请输入用户名称" clearable @keyup.enter="getLogininforList" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="loginParams.status" placeholder="登录状态" clearable>
              <el-option label="成功" value="0" />
              <el-option label="失败" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getLogininforList">搜索</el-button>
            <el-button @click="resetLogininfor">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 操作栏 -->
        <el-row :gutter="10" class="mb10">
          <el-col :span="1.5">
            <el-button type="danger" plain :disabled="!loginSelectedIds.length" @click="handleDeleteLogininfor">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain @click="handleCleanLogininfor">清空</el-button>
          </el-col>
        </el-row>

        <!-- 表格 -->
        <el-table v-loading="loginLoading" :data="logininforList" @selection-change="handleLoginSelection">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="访问编号" prop="info_id" width="100" />
          <el-table-column label="用户名称" prop="user_name" width="150" />
          <el-table-column label="登录地址" prop="ipaddr" width="140" />
          <el-table-column label="登录地点" prop="login_location" width="150" show-overflow-tooltip />
          <el-table-column label="浏览器" prop="browser" width="120" />
          <el-table-column label="操作系统" prop="os" width="120" />
          <el-table-column label="登录状态" prop="status" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === '0' ? 'success' : 'danger'">
                {{ row.status === '0' ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作信息" prop="msg" width="200" show-overflow-tooltip />
          <el-table-column label="登录时间" prop="login_time" width="160" />
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-model:current-page="loginParams.pageNum"
          v-model:page-size="loginParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="loginTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="getLogininforList"
          @current-change="getLogininforList"
          style="margin-top: 15px; justify-content: flex-end"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
/**
 * 日志管理页面
 * @author 湖北新华业务中台研发团队
 */
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'

const activeTab = ref('operlog')

// 操作类型映射
const businessTypeMap = {
  0: '其他',
  1: '新增',
  2: '修改',
  3: '删除',
  4: '授权',
  5: '导出',
  6: '导入',
  7: '强退',
  8: '生成代码',
  9: '清空数据'
}

// 操作日志
const operlogParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: '',
  operName: '',
  status: null
})
const operlogLoading = ref(false)
const operlogList = ref([])
const operlogTotal = ref(0)
const operlogSelectedIds = ref([])

// 登录日志
const loginParams = reactive({
  pageNum: 1,
  pageSize: 10,
  ipaddr: '',
  userName: '',
  status: ''
})
const loginLoading = ref(false)
const logininforList = ref([])
const loginTotal = ref(0)
const loginSelectedIds = ref([])

// Tab切换
const handleTabChange = (tab) => {
  if (tab === 'operlog') {
    getOperlogList()
  } else {
    getLogininforList()
  }
}

// ==================== 操作日志 ====================
const getOperlogList = async () => {
  operlogLoading.value = true
  try {
    const res = await request.get('/api/system/log/operlog/list', { params: operlogParams })
    operlogList.value = res.rows || []
    operlogTotal.value = res.total || 0
  } catch (error) {
    console.error('获取操作日志失败:', error)
  } finally {
    operlogLoading.value = false
  }
}

const resetOperlog = () => {
  operlogParams.title = ''
  operlogParams.operName = ''
  operlogParams.status = null
  operlogParams.pageNum = 1
  getOperlogList()
}

const handleOperlogSelection = (selection) => {
  operlogSelectedIds.value = selection.map(item => item.oper_id)
}

const handleDeleteOperlog = async () => {
  if (!operlogSelectedIds.value.length) return
  await ElMessageBox.confirm('确认删除选中的操作日志?', '提示', { type: 'warning' })
  try {
    await request.delete(`/api/system/log/operlog/${operlogSelectedIds.value.join(',')}`)
    ElMessage.success('删除成功')
    getOperlogList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

const handleCleanOperlog = async () => {
  await ElMessageBox.confirm('确认清空全部操作日志?', '提示', { type: 'warning' })
  try {
    await request.delete('/api/system/log/operlog/clean')
    ElMessage.success('清空成功')
    getOperlogList()
  } catch (error) {
    ElMessage.error('清空失败')
  }
}

// ==================== 登录日志 ====================
const getLogininforList = async () => {
  loginLoading.value = true
  try {
    const res = await request.get('/api/system/log/logininfor/list', { params: loginParams })
    logininforList.value = res.rows || []
    loginTotal.value = res.total || 0
  } catch (error) {
    console.error('获取登录日志失败:', error)
  } finally {
    loginLoading.value = false
  }
}

const resetLogininfor = () => {
  loginParams.ipaddr = ''
  loginParams.userName = ''
  loginParams.status = ''
  loginParams.pageNum = 1
  getLogininforList()
}

const handleLoginSelection = (selection) => {
  loginSelectedIds.value = selection.map(item => item.info_id)
}

const handleDeleteLogininfor = async () => {
  if (!loginSelectedIds.value.length) return
  await ElMessageBox.confirm('确认删除选中的登录日志?', '提示', { type: 'warning' })
  try {
    await request.delete(`/api/system/log/logininfor/${loginSelectedIds.value.join(',')}`)
    ElMessage.success('删除成功')
    getLogininforList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

const handleCleanLogininfor = async () => {
  await ElMessageBox.confirm('确认清空全部登录日志?', '提示', { type: 'warning' })
  try {
    await request.delete('/api/system/log/logininfor/clean')
    ElMessage.success('清空成功')
    getLogininforList()
  } catch (error) {
    ElMessage.error('清空失败')
  }
}

onMounted(() => {
  getOperlogList()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 15px;
}
.mb10 {
  margin-bottom: 10px;
}
</style>
