<template>
  <div class="page-container">
    <!-- 顶部操作栏 -->
    <div class="header-actions">
      <a-space>
        <a-button type="primary" status="warning" @click="handleGenerate" :loading="generating">
          <template #icon><icon-robot /></template>
          立即生成AI分析
        </a-button>
        <a-button @click="openSettings">
          <template #icon><icon-settings /></template>
          设置
        </a-button>
      </a-space>
      <div class="alert-info" v-if="alertCount > 0">
        当前实时告警: <span :class="{ 'red-text': alertCount > threshold }">{{ alertCount }}</span> 条
      </div>
    </div>

    <!-- 搜索栏 -->
    <a-card class="search-card" :bordered="false">
      <a-form layout="inline" :model="searchForm" @submit="fetchReports">
        <a-form-item label="报表标题">
          <a-input v-model="searchForm.keyword" placeholder="输入标题搜索" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">查询</a-button>
          <a-button @click="resetSearch" style="margin-left: 10px">重置</a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 报表列表 -->
    <a-card :bordered="false" style="margin-top: 16px">
      <a-table :data="reports" :loading="loading" :pagination="pagination" @page-change="onPageChange">
        <template #columns>
          <a-table-column title="生成时间" data-index="created_at">
            <template #cell="{ record }">{{ new Date(record.created_at).toLocaleString() }}</template>
          </a-table-column>
          <a-table-column title="标题" data-index="title" />
          <a-table-column title="触发告警数" data-index="alert_count" />
          <a-table-column title="状态" data-index="status">
            <template #cell="{ record }">
              <a-tag :color="record.status === 'COMPLETED' ? 'green' : record.status === 'GENERATING' ? 'blue' : 'red'">
                {{ record.status === 'COMPLETED' ? '已完成' : '生成中' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="操作" width="200">
            <template #cell="{ record }">
              <a-space>
                <a-button size="small" type="text" @click="viewReport(record)">查看</a-button>
                <a-button size="small" type="text" @click="downloadReport(record)">下载</a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 设置弹窗 -->
    <a-modal v-model:visible="settingsVisible" title="AI分析设置" @ok="saveSettings">
      <a-form :model="settingsForm" layout="vertical">
        <a-form-item label="AI API地址" field="ai_api_url" required>
          <a-input v-model="settingsForm.ai_api_url" placeholder="https://api.openai.com/v1/chat/completions" />
        </a-form-item>
        <a-form-item label="API Key" field="ai_api_key" required>
          <a-input-password v-model="settingsForm.ai_api_key" placeholder="sk-..." />
        </a-form-item>
        <a-form-item label="模型名称" field="ai_model" required>
          <div style="display: flex; width: 100%;">
              <a-select 
                v-model="settingsForm.ai_model" 
                allow-create 
                placeholder="选择或输入模型名称"
                :loading="loadingModels"
                style="flex: 1; margin-right: 8px;"
              >
                 <a-option v-for="m in availableModels" :key="m" :value="m">{{ m }}</a-option>
                 <!-- Fallback options if fetch fails or user hasn't fetched -->
                 <a-option v-if="availableModels.length === 0">gpt-3.5-turbo</a-option>
                 <a-option v-if="availableModels.length === 0">gpt-4</a-option>
              </a-select>
              <a-button @click="fetchModels" :loading="loadingModels">
                  <template #icon><icon-refresh /></template>
                  获取模型
              </a-button>
          </div>
        </a-form-item>
        <a-form-item label="AI自动确认告警阈值" field="ai_alert_threshold">
          <a-input-number v-model="settingsForm.ai_alert_threshold" />
          <template #extra>当实时告警超过此数量时，系统将自动确认前300条告警并生成AI分析报表。</template>
        </a-form-item>
        <a-form-item label="开启自动确认" field="ai_auto_ack">
          <a-switch v-model="settingsForm.ai_auto_ack" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button @click="testConnection" :loading="testingConnection" style="float: left">测试连接</a-button>
        <a-button @click="settingsVisible = false">取消</a-button>
        <a-button type="primary" @click="saveSettings">确定</a-button>
      </template>
    </a-modal>

    <!-- 报表详情弹窗 -->
    <a-modal v-model:visible="reportVisible" title="分析报告详情" width="800px" :footer="false">
      <div v-if="currentReport">
        <h3>{{ currentReport.title }}</h3>
        <a-divider />
        <MarkdownViewer :content="currentReport.content || '内容生成中（或生成失败）...'" />
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import { IconRobot, IconSettings, IconRefresh } from '@arco-design/web-vue/es/icon';
import { getAIConfig, updateAIConfig, generateAIReport, getAIReports, testAIConnection, getRemoteModels, type AIReport } from '../../api/ai';
import { getAlarms } from '../../api/monitor';
import MarkdownViewer from '../../components/MarkdownViewer.vue';

const loading = ref(false);
const generating = ref(false);
const testingConnection = ref(false);
const loadingModels = ref(false);
const reports = ref<AIReport[]>([]);
const alertCount = ref(0);
const threshold = ref(200);
const availableModels = ref<string[]>([]);

// 搜索与分页
const searchForm = reactive({ keyword: '' });
const pagination = reactive({ current: 1, pageSize: 10, total: 0 });

// 设置相关
const settingsVisible = ref(false);
const settingsForm = reactive({
  ai_api_url: '',
  ai_api_key: '',
  ai_model: 'gpt-3.5-turbo',
  ai_alert_threshold: 200,
  ai_auto_ack: false
});

// 报表详情相关
const reportVisible = ref(false);
const currentReport = ref<AIReport | null>(null);

const fetchReports = async () => {
  loading.value = true;
  try {
    const res: any = await getAIReports({
      page: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword
    });
    reports.value = res.data;
    pagination.total = res.total;
  } finally {
    loading.value = false;
  }
};

const fetchAlertCount = async () => {
  try {
    const alarms = await getAlarms('ACTIVE');
    alertCount.value = alarms.length;
  } catch (e) { console.error(e); }
};

const onPageChange = (page: number) => {
  pagination.current = page;
  fetchReports();
};

const resetSearch = () => {
  searchForm.keyword = '';
  pagination.current = 1;
  fetchReports();
};

// 设置逻辑
const openSettings = async () => {
  const res: any = await getAIConfig();
  // 手动赋值以确保类型正确
  settingsForm.ai_api_url = res.ai_api_url;
  settingsForm.ai_api_key = res.ai_api_key;
  settingsForm.ai_model = res.ai_model || 'gpt-3.5-turbo';
  settingsForm.ai_alert_threshold = Number(res.ai_alert_threshold) || 200;
  settingsForm.ai_auto_ack = res.ai_auto_ack === 'true'; // 转为 boolean
  
  settingsVisible.value = true;
};

const fetchModels = async () => {
    if (!settingsForm.ai_api_url || !settingsForm.ai_api_key) {
        Message.warning('请先填写API地址和Key');
        return;
    }
    loadingModels.value = true;
    try {
        const res: any = await getRemoteModels({
            ai_api_url: settingsForm.ai_api_url,
            ai_api_key: settingsForm.ai_api_key
        });
        if (res.models && Array.isArray(res.models)) {
            availableModels.value = res.models;
            Message.success(`获取成功，共找到 ${res.models.length} 个模型`);
        } else {
            Message.warning('未能获取到模型列表，请手动输入');
        }
    } catch (err: any) {
        console.error(err);
        Message.error('获取模型列表失败: ' + (err.response?.data?.error || err.message));
    } finally {
        loadingModels.value = false;
    }
};

const saveSettings = async () => {
  if (!settingsForm.ai_api_url || !settingsForm.ai_api_key) {
      Message.warning('请填写API地址和Key');
      return;
  }
  try {
    await updateAIConfig({
      ...settingsForm,
      ai_alert_threshold: String(settingsForm.ai_alert_threshold),
      ai_auto_ack: String(settingsForm.ai_auto_ack) // 转为 string
    });
    Message.success('配置已保存');
    threshold.value = Number(settingsForm.ai_alert_threshold);
    settingsVisible.value = false;
  } catch (e) {
    Message.error('保存失败');
  }
};

const testConnection = async () => {
    if (!settingsForm.ai_api_url || !settingsForm.ai_api_key) {
        Message.warning('请先填写API地址和Key');
        return;
    }
    testingConnection.value = true;
    try {
        await testAIConnection({
            ai_api_url: settingsForm.ai_api_url,
            ai_api_key: settingsForm.ai_api_key,
            ai_model: settingsForm.ai_model
        });
        Message.success('连接成功');
    } catch (err: any) {
        console.error(err);
        Modal.error({
            title: '连接失败',
            content: err.response?.data?.error || err.message || '未知错误'
        });
    } finally {
        testingConnection.value = false;
    }
}

// 生成报表逻辑
const handleGenerate = async () => {
  generating.value = true;
  try {
    await generateAIReport();
    Message.success('分析任务已提交，请稍候查看结果');
    fetchReports();
  } catch (e: any) {
    if (e.response && e.response.status === 400 && e.response.data.error.includes('AI接口未配置')) {
         Modal.confirm({
             title: '未配置AI接口',
             content: '系统检测到您尚未配置AI接口信息，是否立即前往配置？',
             onOk: () => {
                 openSettings();
             }
         });
    } else {
        Message.error(e.response?.data?.error || '任务提交失败');
    }
  } finally {
    generating.value = false;
  }
};

// 查看与下载
const viewReport = (report: AIReport) => {
  currentReport.value = report;
  reportVisible.value = true;
};

const downloadReport = (report: AIReport) => {
  const blob = new Blob([report.content], { type: 'text/plain;charset=utf-8' });
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = `${report.title}.md`;
  link.click();
  window.URL.revokeObjectURL(url);
};

onMounted(() => {
  fetchReports();
  fetchAlertCount();
  // 获取初始阈值
  getAIConfig().then((res: any) => {
      if(res.ai_alert_threshold) threshold.value = Number(res.ai_alert_threshold);
  });
});
</script>

<style scoped>
.page-container { padding: 20px; }
.header-actions { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.alert-info { font-size: 16px; font-weight: bold; }
.red-text { color: #f53f3f; }
</style>
