<template>
  <div class="app-container">
    <!-- ===== 统计卡片 ===== -->
    <el-row :gutter="16" class="mb16">
      <el-col :span="6" v-for="card in statCards" :key="card.label">
        <el-card shadow="hover" class="stat-card">
          <div class="card-inner">
            <div class="card-icon" :style="{ background: card.bg }">
              <i :class="card.icon"></i>
            </div>
            <div class="card-info">
              <span class="card-value">{{ card.value }}</span>
              <span class="card-label">{{ card.label }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- ===== 筛选 ===== -->
    <el-card shadow="never" class="mb16 filter-card">
      <el-form :inline="true" size="small">
        <el-form-item label="租户名称">
          <el-select
            v-model="queryParams.companyId"
            placeholder="选择租户"
            clearable
            filterable
            size="small"
            style="width: 200px"
          >
            <el-option
              v-for="item in companyList"
              :key="item.companyId"
              :label="item.companyName"
              :value="item.companyId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择" clearable size="small">
            <el-option label="运行中" value="running" />
            <el-option label="已暂停" value="paused" />
            <el-option label="已完成" value="completed" />
            <el-option label="已终止" value="terminated" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- ===== 实例列表 ===== -->
    <el-table border v-loading="loading" :data="instanceList">
      <el-table-column label="实例ID" prop="instanceId" width="120" align="center" />
      <el-table-column label="租户" align="center" prop="tenant_name" width="140" />
      <el-table-column label="工作流名称" prop="workflowName" show-overflow-tooltip />
      <el-table-column label="当前节点" prop="currentNode" show-overflow-tooltip />
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="s">
          <el-tag :type="statusTag(s.row.status)" size="small">{{ statusName(s.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="启动时间" align="center" prop="startTime" width="160" />
      <el-table-column label="操作" align="center" width="180">
        <template slot-scope="s">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(s.row)">详情</el-button>
          <el-button v-if="s.row.status==='running'||s.row.status==='paused'" size="mini" type="text" icon="el-icon-video-pause" style="color:#E6A23C" @click="handleTerminate(s.row)">终止</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- ===== 详情弹窗 ===== -->
    <el-dialog title="实例详情" :visible.sync="detailVisible" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="实例ID">{{ detail.instanceId }}</el-descriptions-item>
        <el-descriptions-item label="租户ID">{{ detail.companyId }}</el-descriptions-item>
        <el-descriptions-item label="工作流">{{ detail.workflowName }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="statusTag(detail.status)" size="small">{{ statusName(detail.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="启动时间">{{ detail.startTime }}</el-descriptions-item>
        <el-descriptions-item label="当前节点">{{ detail.currentNode }}</el-descriptions-item>
      </el-descriptions>
      <el-divider>节点执行日志</el-divider>
      <el-table :data="nodeLogs" border size="small" max-height="300">
        <el-table-column label="节点" prop="nodeName" />
        <el-table-column label="类型" prop="nodeType" width="80" />
        <el-table-column label="状态" prop="status" width="80" />
        <el-table-column label="耗时" prop="duration" width="80" />
        <el-table-column label="时间" prop="timestamp" width="160" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listAllInstances, getInstanceDetail, getInstanceNodeLogs, getInstanceStats, forceTerminateInstance } from '@/api/admin/lobster'
import { listAllCompanies } from '@/api/admin/sysCompany'

export default {
  name: 'LobsterInstanceMonitor',
  data() {
    return {
      loading: false,
      instanceList: [],
      total: 0,
      companyList: [],
      queryParams: { pageNum: 1, pageSize: 10, companyId: null, status: null },
      statCards: [
        { label: '运行中', value: 0, icon: 'el-icon-video-play', bg: '#e6f7ff' },
        { label: '已暂停', value: 0, icon: 'el-icon-video-pause', bg: '#fff7e6' },
        { label: '死信队列', value: 0, icon: 'el-icon-warning', bg: '#f9f0ff' },
        { label: '今日Token消耗', value: '0', icon: 'el-icon-coin', bg: '#f6ffed' }
      ],
      detailVisible: false,
      detail: {},
      nodeLogs: []
    }
  },
  created() { this.getCompanyList(); this.getList(); this.loadStats() },
  methods: {
    getCompanyList() {
      listAllCompanies({ pageSize: 9999 }).then(response => {
        this.companyList = response.rows || []
      })
    },
    getList() {
      this.loading = true
      listAllInstances(this.queryParams).then(r => {
        this.instanceList = r.rows || r.data || []
        this.total = r.total || 0
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    loadStats() {
      getInstanceStats().then(r => {
        const d = r.data || {}
        this.statCards[0].value = d.running || 0
        this.statCards[1].value = d.paused || 0
        this.statCards[2].value = d.deadLetters || 0
        this.statCards[3].value = d.todayTokens || '0'
      }).catch(() => {})
    },
    handleQuery() { this.queryParams.pageNum = 1; this.getList() },
    resetQuery() { this.queryParams = { pageNum: 1, pageSize: 10, companyId: null, status: null }; this.getList() },
    handleDetail(row) {
      getInstanceDetail(row.instanceId).then(r => {
        this.detail = r.data || {}
        this.detailVisible = true
      })
      getInstanceNodeLogs(row.instanceId).then(r => {
        this.nodeLogs = r.data || []
      })
    },
    handleTerminate(row) {
      this.$confirm(`确认强制终止实例 ${row.instanceId}？`, '警告', { type: 'warning' }).then(() => {
        forceTerminateInstance(row.instanceId, '管理员强制终止').then(() => {
          this.$message.success('已终止')
          this.getList()
        })
      })
    },
    statusTag(s) {
      return { running: 'primary', paused: 'warning', completed: 'success', terminated: 'danger' }[s] || 'info'
    },
    statusName(s) {
      return { running: '运行中', paused: '已暂停', completed: '已完成', terminated: '已终止' }[s] || s
    }
  }
}
</script>

<style scoped>
.stat-card { cursor: default; }
.card-inner { display: flex; align-items: center; }
.card-icon { width: 46px; height: 46px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin-right: 14px; font-size: 22px; color: #fff; }
.card-value { font-size: 22px; font-weight: bold; color: #333; display: block; }
.card-label { font-size: 12px; color: #999; }
.filter-card { padding-bottom: 0; }
.mb16 { margin-bottom: 16px; }
</style>