<template>
  <div class="alert-page">
    <el-page-header title="告警与工单" content="风险告警规则与工单处置" />

    <el-tabs v-model="activeTab" class="mt-4">
      <el-tab-pane label="告警记录" name="records">
        <el-row :gutter="16" class="mb-4">
          <el-col :span="6">
            <el-select v-model="recordFilter.status" placeholder="状态" clearable @change="fetchRecords">
              <el-option label="待处理" value="pending" />
              <el-option label="已确认" value="confirmed" />
              <el-option label="已关闭" value="closed" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="checkAlerts">执行检测</el-button>
            <el-button @click="initRules">初始化规则</el-button>
          </el-col>
        </el-row>

        <el-table :data="records" v-loading="loadingRecords" border>
          <el-table-column prop="id" label="ID" width="60" />
          <el-table-column prop="title" label="标题" />
          <el-table-column prop="severity" label="严重级别" width="100">
            <template #default="scope">
              <el-tag :type="severityType(scope.row.severity)" size="small">{{ scope.row.severity }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="statusType(scope.row.status)" size="small">{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="触发时间" width="160" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button size="small" @click="viewDetail(scope.row)">详情</el-button>
              <el-button size="small" type="primary" @click="openCreateWO(scope.row)">创建工单</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="recordPage.page" :page-size="recordPage.page_size" :total="recordPage.total" layout="prev, pager, next" @current-change="fetchRecords" class="mt-4" />
      </el-tab-pane>

      <el-tab-pane label="工单管理" name="workorders">
        <el-row :gutter="16" class="mb-4">
          <el-col :span="6">
            <el-select v-model="woFilter.status" placeholder="状态" clearable @change="fetchWorkOrders">
              <el-option label="待处理" value="pending" />
              <el-option label="处理中" value="in_progress" />
              <el-option label="已关闭" value="closed" />
            </el-select>
          </el-col>
        </el-row>
        <el-table :data="workOrders" v-loading="loadingWO" border>
          <el-table-column prop="id" label="ID" width="60" />
          <el-table-column prop="title" label="标题" />
          <el-table-column prop="assignee_name" label="负责人" width="120" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="woStatusType(scope.row.status)" size="small">{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="160" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-select v-model="scope.row._newStatus" placeholder="更新状态" size="small" style="width:100px" @change="updateWO(scope.row, scope.row._newStatus)">
                <el-option label="处理中" value="in_progress" />
                <el-option label="已关闭" value="closed" />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="woPage.page" :page-size="woPage.page_size" :total="woPage.total" layout="prev, pager, next" @current-change="fetchWorkOrders" class="mt-4" />
      </el-tab-pane>
    </el-tabs>

    <el-dialog v-model="detailVisible" title="告警详情" width="600px">
      <p><strong>规则：</strong>{{ detail.rule_id }}</p>
      <p><strong>标题：</strong>{{ detail.title }}</p>
      <p><strong>内容：</strong>{{ detail.content }}</p>
      <p><strong>严重级别：</strong>{{ detail.severity }}</p>
      <p><strong>状态：</strong>{{ detail.status }}</p>
      <p><strong>触发时间：</strong>{{ detail.created_at }}</p>
    </el-dialog>

    <el-dialog v-model="woVisible" title="创建工单" width="500px">
      <el-form :model="woForm" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="woForm.title" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="woForm.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="woVisible = false">取消</el-button>
        <el-button type="primary" @click="submitWO">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import request from '@/api/request';

const activeTab = ref('records');
const records = ref([]);
const workOrders = ref([]);
const loadingRecords = ref(false);
const loadingWO = ref(false);
const recordPage = reactive({ page: 1, page_size: 20, total: 0 });
const woPage = reactive({ page: 1, page_size: 20, total: 0 });
const recordFilter = reactive({ status: '' });
const woFilter = reactive({ status: '' });

const detailVisible = ref(false);
const detail = reactive<any>({});
const woVisible = ref(false);
const woForm = reactive({ alert_id: 0, title: '', description: '' });

const severityType = (s: string) => {
  if (s === 'critical') return 'danger';
  if (s === 'high') return 'warning';
  if (s === 'medium') return '';
  return 'info';
};
const statusType = (s: string) => {
  if (s === 'pending') return 'danger';
  if (s === 'confirmed') return 'warning';
  return 'info';
};
const woStatusType = (s: string) => {
  if (s === 'pending') return 'danger';
  if (s === 'in_progress') return 'warning';
  return 'success';
};

const fetchRecords = async () => {
  loadingRecords.value = true;
  const res: any = await request.get('/alerts/records', {
    params: { status: recordFilter.status, page: recordPage.page, page_size: recordPage.page_size },
  });
  records.value = res.data || [];
  recordPage.total = res.total || 0;
  loadingRecords.value = false;
};
const fetchWorkOrders = async () => {
  loadingWO.value = true;
  const res: any = await request.get('/alerts/work-orders', {
    params: { status: woFilter.status, page: woPage.page, page_size: woPage.page_size },
  });
  workOrders.value = res.data || [];
  woPage.total = res.total || 0;
  loadingWO.value = false;
};

const checkAlerts = async () => {
  await request.post('/alerts/check');
  ElMessage.success('检测完成');
  fetchRecords();
};
const initRules = async () => {
  await request.post('/alerts/init-rules');
  ElMessage.success('规则初始化完成');
};

const viewDetail = (row: any) => {
  Object.assign(detail, row);
  detailVisible.value = true;
};
const openCreateWO = (row: any) => {
  woForm.alert_id = row.id;
  woForm.title = row.title;
  woForm.description = row.content || '';
  woVisible.value = true;
};
const submitWO = async () => {
  await request.post('/alerts/work-orders', null, {
    params: { alert_id: woForm.alert_id, title: woForm.title, description: woForm.description },
  });
  ElMessage.success('工单创建成功');
  woVisible.value = false;
  activeTab.value = 'workorders';
  fetchWorkOrders();
};
const updateWO = async (row: any, status: string) => {
  if (!status) return;
  await request.post(`/alerts/work-orders/${row.id}/status`, null, { params: { status } });
  ElMessage.success('状态更新成功');
  fetchWorkOrders();
};

onMounted(() => { fetchRecords(); fetchWorkOrders(); });
</script>
