<template>
  <div>
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <!-- Tab1: 产量修正日志 -->
      <el-tab-pane label="产量修正日志" name="adjustment">
        <el-form :inline="true" class="mb-16">
          <el-form-item label="时间范围">
            <el-date-picker v-model="adjQuery.dateRange" type="daterange" value-format="YYYY-MM-DD" clearable />
          </el-form-item>
          <el-form-item label="目标表">
            <el-select v-model="adjQuery.targetTable" clearable placeholder="全部">
              <el-option label="日产量" value="daily_production" />
              <el-option label="员工日汇总" value="worker_daily_summary" />
            </el-select>
          </el-form-item>
          <el-form-item label="关键字">
            <el-input v-model="adjQuery.keyword" placeholder="原因/操作IP" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadAdjustment">查询</el-button>
            <el-button @click="resetAdjQuery">重置</el-button>
            <el-button type="success" @click="exportAdjustment">导出</el-button>
          </el-form-item>
        </el-form>

        <el-table :data="adjList" border stripe v-loading="adjLoading">
          <el-table-column prop="createdAt" label="修正时间" sortable align="center" />
          <el-table-column prop="targetTable" label="目标表" show-overflow-tooltip>
            <template #default="{ row }">
              {{ targetTableLabel(row.targetTable) }}
            </template>
          </el-table-column>
          <el-table-column prop="targetId" label="目标ID" align="center" />
          <el-table-column prop="oldValue" label="修正前" align="center" />
          <el-table-column prop="newValue" label="修正后" align="center" />
          <el-table-column prop="reason" label="修正原因" show-overflow-tooltip />
          <el-table-column prop="operatorIp" label="操作IP" align="center" />
        </el-table>

        <el-empty v-if="!adjLoading && adjList.length === 0" description="暂无产量修正记录" />

        <el-pagination
          v-if="adjPage.total > 0"
          v-model:current-page="adjPage.page"
          v-model:page-size="adjPage.pageSize"
          :page-sizes="[20, 50, 100]"
          :total="adjPage.total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          style="margin-top:16px"
        />
      </el-tab-pane>

      <!-- Tab2: 系统运行日志 -->
      <el-tab-pane label="系统运行日志" name="system">
        <el-form :inline="true" class="mb-16">
          <el-form-item label="日志级别">
            <el-select v-model="sysQuery.logLevel" clearable placeholder="全部">
              <el-option label="ERROR" value="ERROR" />
              <el-option label="WARN" value="WARN" />
              <el-option label="INFO" value="INFO" />
              <el-option label="DEBUG" value="DEBUG" />
            </el-select>
          </el-form-item>
          <el-form-item label="来源">
            <el-select v-model="sysQuery.source" clearable placeholder="全部">
              <el-option label="CncCollector" value="CncCollector" />
              <el-option label="WebApi" value="WebApi" />
              <el-option label="Scheduler" value="Scheduler" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker v-model="sysQuery.dateRange" type="daterange" value-format="YYYY-MM-DD" clearable />
          </el-form-item>
          <el-form-item label="关键字">
            <el-input v-model="sysQuery.keyword" placeholder="消息内容" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadSystem">查询</el-button>
            <el-button @click="resetSysQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table :data="sysList" border stripe v-loading="sysLoading">
          <el-table-column prop="createdAt" label="时间" sortable align="center" />
          <el-table-column label="级别" align="center">
            <template #default="{ row }">
              <el-tag :type="logLevelTag(row.logLevel)" size="small">{{ row.logLevel }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="source" label="来源" show-overflow-tooltip />
          <el-table-column label="消息" show-overflow-tooltip>
            <template #default="{ row }">
              <span>{{ row.message }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right" align="center">
            <template #default="{ row }">
              <div style="white-space:nowrap">
                <el-button link type="primary" @click="viewSysDetail(row)">查看详情</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <el-empty v-if="!sysLoading && sysList.length === 0" description="暂无系统日志" />

        <el-pagination
          v-if="sysPage.total > 0"
          v-model:current-page="sysPage.page"
          v-model:page-size="sysPage.pageSize"
          :page-sizes="[20, 50, 100]"
          :total="sysPage.total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          style="margin-top:16px"
        />

        <!-- 系统日志详情弹窗 -->
        <el-dialog v-model="sysDetailVisible" title="日志详情" width="700px" destroy-on-close>
          <el-descriptions :column="1" border size="small">
            <el-descriptions-item label="时间">{{ sysDetailRow.createdAt }}</el-descriptions-item>
            <el-descriptions-item label="级别">
              <el-tag :type="logLevelTag(sysDetailRow.logLevel)" size="small">{{ sysDetailRow.logLevel }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="来源">{{ sysDetailRow.source }}</el-descriptions-item>
            <el-descriptions-item label="消息">
              <div style="white-space:pre-wrap;word-break:break-all">{{ sysDetailRow.message }}</div>
            </el-descriptions-item>
            <el-descriptions-item label="堆栈信息">
              <div v-if="sysDetailRow.stackTrace" style="white-space:pre-wrap;word-break:break-all;background:#f5f7fa;padding:8px;border-radius:4px;font-family:monospace;font-size:12px">{{ sysDetailRow.stackTrace }}</div>
              <span v-else style="color:#c0c4cc">无</span>
            </el-descriptions-item>
            <el-descriptions-item label="附加数据">
              <div v-if="sysDetailRow.extraData" style="white-space:pre-wrap;word-break:break-all;background:#f5f7fa;padding:8px;border-radius:4px;font-family:monospace;font-size:12px">{{ formatJson(sysDetailRow.extraData) }}</div>
              <span v-else style="color:#c0c4cc">无</span>
            </el-descriptions-item>
          </el-descriptions>
          <template #footer><el-button @click="sysDetailVisible = false">关闭</el-button></template>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import type { ApiResponse, OperationLog } from '@/types'

const activeTab = ref('adjustment')

// ===== Tab1: 产量修正日志 =====
const adjLoading = ref(false)
const adjList = ref<OperationLog[]>([])
const adjQuery = reactive({
  dateRange: null as string[] | null,
  targetTable: '',
  keyword: '',
})
const adjPage = reactive({ page: 1, pageSize: 20, total: 0 })

function targetTableLabel(table: string): string {
  const map: Record<string, string> = {
    daily_production: '日产量',
    worker_daily_summary: '员工日汇总',
  }
  return map[table] || table
}

async function loadAdjustment() {
  adjLoading.value = true
  try {
    const params: Record<string, string | number> = { page: adjPage.page, pageSize: adjPage.pageSize }
    if (adjQuery.dateRange?.length === 2) { params.startDate = adjQuery.dateRange[0]; params.endDate = adjQuery.dateRange[1] }
    if (adjQuery.targetTable) params.targetTable = adjQuery.targetTable
    if (adjQuery.keyword) params.keyword = adjQuery.keyword
    const r = await request.get<{ items: OperationLog[]; total: number }>('/admin/log/adjustment', { params })
    adjList.value = r.data?.items || []
    adjPage.total = r.data?.total || 0
  } finally { adjLoading.value = false }
}

function resetAdjQuery() {
  Object.assign(adjQuery, { dateRange: null, targetTable: '', keyword: '' })
  adjPage.page = 1
  loadAdjustment()
}

async function exportAdjustment() {
  try {
    const params: Record<string, string> = {}
    if (adjQuery.dateRange?.length === 2) { params.startDate = adjQuery.dateRange[0]; params.endDate = adjQuery.dateRange[1] }
    if (adjQuery.targetTable) params.targetTable = adjQuery.targetTable
    if (adjQuery.keyword) params.keyword = adjQuery.keyword
    // 导出Excel：直接打开新窗口下载
    const qs = new URLSearchParams(params).toString()
    const isMock = window.location.pathname.startsWith('/mock')
    const base = isMock ? '/mock-api' : '/api'
    window.open(`${base}/admin/log/adjustment/export?${qs}`, '_blank')
    ElMessage.success('正在导出...')
  } catch { ElMessage.error('导出失败') }
}

// ===== Tab2: 系统运行日志 =====
const sysLoading = ref(false)
const sysList = ref<OperationLog[]>([])
const sysQuery = reactive({
  logLevel: '',
  source: '',
  dateRange: null as string[] | null,
  keyword: '',
})
const sysPage = reactive({ page: 1, pageSize: 20, total: 0 })
const sysDetailVisible = ref(false)
const sysDetailRow = ref<OperationLog>({} as OperationLog)

function logLevelTag(level: string): string {
  const map: Record<string, string> = { ERROR: 'danger', WARN: 'warning', INFO: 'success', DEBUG: 'info' }
  return map[level] || 'info'
}

async function loadSystem() {
  sysLoading.value = true
  try {
    const params: Record<string, string | number> = { page: sysPage.page, pageSize: sysPage.pageSize }
    if (sysQuery.logLevel) params.logLevel = sysQuery.logLevel
    if (sysQuery.source) params.source = sysQuery.source
    if (sysQuery.dateRange?.length === 2) { params.startDate = sysQuery.dateRange[0]; params.endDate = sysQuery.dateRange[1] }
    if (sysQuery.keyword) params.keyword = sysQuery.keyword
    const r = await request.get<{ items: OperationLog[]; total: number }>('/admin/log/system', { params })
    sysList.value = r.data?.items || []
    sysPage.total = r.data?.total || 0
  } finally { sysLoading.value = false }
}

function resetSysQuery() {
  Object.assign(sysQuery, { logLevel: '', source: '', dateRange: null, keyword: '' })
  sysPage.page = 1
  loadSystem()
}

function viewSysDetail(row: OperationLog) {
  sysDetailRow.value = row
  sysDetailVisible.value = true
}

function formatJson(str: string): string {
  try { return JSON.stringify(JSON.parse(str), null, 2) } catch { return str }
}

function handleTabChange(tab: string) {
  if (tab === 'adjustment' && adjList.value.length === 0) loadAdjustment()
  if (tab === 'system' && sysList.value.length === 0) loadSystem()
}

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