<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" class="search-form">
      <el-form-item label="错误类型" prop="errorType">
        <el-select v-model="queryParams.errorType" placeholder="请选择" clearable style="width: 120px">
          <el-option label="系统错误" value="SYSTEM" />
          <el-option label="业务错误" value="BUSINESS" />
          <el-option label="API错误" value="API" />
          <el-option label="SQL错误" value="SQL" />
          <el-option label="认证错误" value="AUTH" />
        </el-select>
      </el-form-item>
      <el-form-item label="错误级别" prop="errorLevel">
        <el-select v-model="queryParams.errorLevel" placeholder="请选择" clearable style="width: 100px">
          <el-option label="ERROR" value="ERROR" />
          <el-option label="WARN" value="WARN" />
          <el-option label="FATAL" value="FATAL" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width: 100px">
          <el-option label="未处理" value="0" />
          <el-option label="已处理" value="1" />
          <el-option label="已忽略" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="错误信息" prop="errorMessage">
        <el-input v-model="queryParams.errorMessage" placeholder="请输入" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="发生时间" style="width: 308px;">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="Check" :disabled="multiple" @click="handleBatchResolve('1')" v-hasPermi="['monitor:errorLog:resolve']">
          批量处理
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Close" :disabled="multiple" @click="handleBatchResolve('2')" v-hasPermi="['monitor:errorLog:resolve']">
          批量忽略
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['monitor:errorLog:remove']">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" @click="handleClean" v-hasPermi="['monitor:errorLog:clean']">
          清空
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="errorList" @selection-change="handleSelectionChange" row-key="errorId">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="错误类型" prop="errorType" width="100" align="center">
        <template #default="scope">
          <el-tag :type="getErrorTypeTag(scope.row.errorType)" size="small">{{ scope.row.errorType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="级别" prop="errorLevel" width="80" align="center">
        <template #default="scope">
          <el-tag :type="getErrorLevelTag(scope.row.errorLevel)" size="small">{{ scope.row.errorLevel }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="错误信息" prop="errorMessage" min-width="250" show-overflow-tooltip />
      <el-table-column label="请求URL" prop="requestUrl" width="200" show-overflow-tooltip />
      <el-table-column label="操作人" prop="userName" width="100" align="center" />
      <el-table-column label="次数" prop="occurCount" width="70" align="center">
        <template #default="scope">
          <el-badge :value="scope.row.occurCount" :max="99" :type="scope.row.occurCount > 10 ? 'danger' : 'primary'" />
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="80" align="center">
        <template #default="scope">
          <el-tag :type="getStatusTag(scope.row.status)" size="small">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发生时间" prop="createTime" width="160" align="center" />
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)">详情</el-button>
          <el-button link type="success" icon="Check" @click="handleResolve(scope.row, '1')" v-if="scope.row.status === '0'" v-hasPermi="['monitor:errorLog:resolve']">处理</el-button>
          <el-button link type="warning" icon="Close" @click="handleResolve(scope.row, '2')" v-if="scope.row.status === '0'" v-hasPermi="['monitor:errorLog:resolve']">忽略</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 详情对话框 -->
    <el-dialog title="错误详情" v-model="detailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border label-width="100px">
        <el-descriptions-item label="错误ID">{{ detail.errorId }}</el-descriptions-item>
        <el-descriptions-item label="错误代码">{{ detail.errorCode }}</el-descriptions-item>
        <el-descriptions-item label="错误类型">
          <el-tag :type="getErrorTypeTag(detail.errorType)" size="small">{{ detail.errorType }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="错误级别">
          <el-tag :type="getErrorLevelTag(detail.errorLevel)" size="small">{{ detail.errorLevel }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="请求URL" :span="2">{{ detail.requestUrl }}</el-descriptions-item>
        <el-descriptions-item label="请求方法">{{ detail.requestMethod }}</el-descriptions-item>
        <el-descriptions-item label="请求IP">{{ detail.requestIp }}</el-descriptions-item>
        <el-descriptions-item label="请求参数" :span="2" v-if="detail.requestParams">{{ detail.requestParams }}</el-descriptions-item>
        <el-descriptions-item label="操作人">{{ detail.userName }}</el-descriptions-item>
        <el-descriptions-item label="发生次数">{{ detail.occurCount }}</el-descriptions-item>
        <el-descriptions-item label="首次时间">{{ detail.firstTime }}</el-descriptions-item>
        <el-descriptions-item label="最近时间">{{ detail.lastTime }}</el-descriptions-item>
        <el-descriptions-item label="来源类" :span="2">{{ detail.sourceClass }}</el-descriptions-item>
        <el-descriptions-item label="来源方法">{{ detail.sourceMethod }}</el-descriptions-item>
        <el-descriptions-item label="行号">{{ detail.sourceLine }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTag(detail.status)" size="small">{{ getStatusText(detail.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="处理人">{{ detail.resolveBy || '-' }}</el-descriptions-item>
        <el-descriptions-item label="处理时间" :span="2">{{ detail.resolveTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="处理备注" :span="2">{{ detail.resolveRemark || '-' }}</el-descriptions-item>
        <el-descriptions-item label="错误消息" :span="2">{{ detail.errorMessage }}</el-descriptions-item>
      </el-descriptions>
      
      <el-divider content-position="left">堆栈信息</el-divider>
      <el-input
        v-model="detail.errorDetail"
        type="textarea"
        :rows="12"
        readonly
        class="stack-trace"
      />
      
      <template #footer v-if="detail.status === '0'">
        <el-button @click="detailOpen = false">关闭</el-button>
        <el-button type="warning" @click="handleResolveFromDetail('2')">忽略</el-button>
        <el-button type="success" @click="handleResolveFromDetail('1')">标记已处理</el-button>
      </template>
    </el-dialog>

    <!-- 处理备注对话框 -->
    <el-dialog title="处理备注" v-model="resolveOpen" width="500px" append-to-body>
      <el-form ref="resolveRef" :model="resolveForm" label-width="80px">
        <el-form-item label="处理备注">
          <el-input v-model="resolveForm.remark" type="textarea" :rows="3" placeholder="请输入处理备注（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resolveOpen = false">取消</el-button>
        <el-button type="primary" @click="submitResolve">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ErrorLog">
import { listErrorLog, getErrorLog, resolveError, batchResolve, delErrorLog, cleanErrorLog } from '@/api/monitor/errorLog'

const { proxy } = getCurrentInstance()

const loading = ref(true)
const showSearch = ref(true)
const errorList = ref([])
const ids = ref([])
const multiple = ref(true)
const total = ref(0)
const dateRange = ref([])
const detailOpen = ref(false)
const detail = ref({})
const resolveOpen = ref(false)
const resolveForm = ref({})

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  errorType: null,
  errorLevel: null,
  errorMessage: null,
  status: null
})

function getList() {
  loading.value = true
  listErrorLog(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    errorList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  dateRange.value = []
  proxy.resetForm('queryRef')
  handleQuery()
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.errorId)
  multiple.value = !selection.length
}

function handleView(row) {
  getErrorLog(row.errorId).then(response => {
    detail.value = response.data
    detailOpen.value = true
  })
}

function handleResolve(row, status) {
  resolveForm.value = {
    errorId: row.errorId,
    errorIds: null,
    status: status,
    remark: ''
  }
  resolveOpen.value = true
}

function handleResolveFromDetail(status) {
  resolveForm.value = {
    errorId: detail.value.errorId,
    errorIds: null,
    status: status,
    remark: ''
  }
  resolveOpen.value = true
}

function handleBatchResolve(status) {
  resolveForm.value = {
    errorId: null,
    errorIds: ids.value,
    status: status,
    remark: ''
  }
  resolveOpen.value = true
}

function submitResolve() {
  if (resolveForm.value.errorIds) {
    // 批量处理
    batchResolve({
      errorIds: resolveForm.value.errorIds,
      status: resolveForm.value.status,
      remark: resolveForm.value.remark
    }).then(() => {
      proxy.$modal.msgSuccess('处理成功')
      resolveOpen.value = false
      detailOpen.value = false
      getList()
    })
  } else {
    // 单个处理
    resolveError({
      errorId: resolveForm.value.errorId,
      status: resolveForm.value.status,
      remark: resolveForm.value.remark
    }).then(() => {
      proxy.$modal.msgSuccess('处理成功')
      resolveOpen.value = false
      detailOpen.value = false
      getList()
    })
  }
}

function handleDelete() {
  proxy.$modal.confirm('确认删除选中的错误日志吗？').then(() => {
    return delErrorLog(ids.value)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(() => {})
}

function handleClean() {
  proxy.$modal.confirm('确认清空所有错误日志吗？此操作不可恢复！').then(() => {
    return cleanErrorLog()
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('清空成功')
  }).catch(() => {})
}

function getErrorTypeTag(type) {
  const map = { SYSTEM: 'danger', BUSINESS: 'warning', API: 'info', SQL: 'danger', AUTH: 'warning' }
  return map[type] || 'info'
}

function getErrorLevelTag(level) {
  const map = { FATAL: 'danger', ERROR: 'danger', WARN: 'warning' }
  return map[level] || 'info'
}

function getStatusTag(status) {
  const map = { '0': 'danger', '1': 'success', '2': 'info' }
  return map[status] || 'info'
}

function getStatusText(status) {
  const map = { '0': '未处理', '1': '已处理', '2': '已忽略' }
  return map[status] || '未知'
}

getList()
</script>

<style scoped>
.search-form {
  background: #fff;
  padding: 20px 20px 0;
  border-radius: 4px;
  margin-bottom: 16px;
}

.stack-trace {
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 12px;
}

:deep(.stack-trace .el-textarea__inner) {
  background: #1e1e1e;
  color: #d4d4d4;
  font-family: 'Consolas', 'Monaco', monospace;
}
</style>
