<template>
  <div class="workflow-exec">
    <!-- 统计卡片 -->
    <el-row :gutter="16" class="mb8">
      <el-col :span="4">
        <el-card shadow="hover"><div class="stat-card">
          <div class="stat-value" style="color:#67C23A">{{ runStats.running }}</div>
          <div class="stat-label">运行中</div>
        </div></el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover"><div class="stat-card">
          <div class="stat-value" style="color:#E6A23C">{{ runStats.paused }}</div>
          <div class="stat-label">已暂停</div>
        </div></el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover"><div class="stat-card">
          <div class="stat-value">{{ runStats.completed }}</div>
          <div class="stat-label">已完成</div>
        </div></el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover"><div class="stat-card">
          <div class="stat-value" style="color:#F56C6C">{{ runStats.terminated }}</div>
          <div class="stat-label">已终止</div>
        </div></el-card>
      </el-col>
    </el-row>

    <!-- 实例列表 -->
    <el-card>
      <div slot="header" class="card-header">
        <span><i class="el-icon-monitor"></i> 工作流实例监控</span>
        <div>
          <el-select v-model="searchWorkflowId" placeholder="选择工作流" clearable
            style="width: 200px; margin-right: 10px" @change="getList">
            <el-option v-for="w in workflowList" :key="w.id" :label="w.templateName" :value="w.id" />
          </el-select>
          <el-button type="primary" @click="getList"><i class="el-icon-search"></i>查询</el-button>
        </div>
      </div>

      <el-table :data="tableData" v-loading="loading" border @row-click="selectInstance">
        <el-table-column type="index" label="#" width="50" align="center" />
        <el-table-column prop="instanceName" label="实例名称" min-width="160" show-overflow-tooltip />
        <el-table-column prop="contactName" label="联系人" width="100" />
        <el-table-column prop="status" label="状态" width="90" align="center">
          <template slot-scope="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currentNodeName" label="当前节点" width="120" show-overflow-tooltip />
        <el-table-column label="进度" width="90" align="center">
          <template slot-scope="{ row }">{{ row.completedNodes || 0 }}/{{ row.totalNodes || 0 }}</template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="160" />
        <el-table-column label="操作" width="320" fixed="right">
          <template slot-scope="{ row }">
            <el-button type="primary" size="mini" @click.stop="handleViewLogs(row)">日志</el-button>
            <el-button type="success" size="mini" @click.stop="openDebug(row)" icon="el-icon-edit">调试</el-button>
            <el-button v-if="row.status==='running'" type="warning" size="mini" @click.stop="handlePause(row)">暂停</el-button>
            <el-button v-if="row.status==='paused'" type="success" size="mini" @click.stop="handleResume(row)">恢复</el-button>
            <el-button v-if="row.status!=='completed'&&row.status!=='terminated'" type="danger" size="mini" @click.stop="handleTerminate(row)">终止</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 日志弹窗 -->
    <el-dialog title="节点执行日志" :visible.sync="logDialogVisible" width="900px">
      <el-timeline>
        <el-timeline-item v-for="log in nodeLogs" :key="log.id" :timestamp="log.createTime"
          :type="getLogTimelineType(log.status)" placement="top">
          <el-card shadow="hover">
            <div class="log-header-row">
              <span><el-tag size="small">{{ log.nodeName }}</el-tag>
                <el-tag size="small" type="info" style="margin-left:5px">{{ log.nodeType }}</el-tag>
                <el-tag size="small" :type="log.status==='sent'?'success':'primary'" style="margin-left:5px">
                  {{ log.status === 'sent' ? '发送' : '接收' }}</el-tag>
              </span>
              <span v-if="log.durationMs" style="color:#909399;font-size:12px">{{ log.durationMs }}ms</span>
            </div>
            <div v-if="log.outputContent" class="log-section"><strong>发送:</strong>
              <p class="log-box">{{ log.outputContent }}</p></div>
            <div v-if="log.inputContent" class="log-section"><strong>接收:</strong>
              <p class="log-box input">{{ log.inputContent }}</p></div>
            <div v-if="log.errorMessage" style="color:#f56c6c;margin-top:5px"><strong>错误:</strong>{{ log.errorMessage }}</div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
      <div v-if="!nodeLogs.length" class="empty-tip">暂无执行日志</div>
    </el-dialog>

    <!-- 逐节点调试弹窗 -->
    <el-dialog title="逐节点调试测试" :visible.sync="debugVisible" width="950px" append-to-body>
      <template v-if="debugInstance">
        <el-alert :title="'当前调试实例: ' + (debugInstance.instanceName || debugInstance.id)" type="info" :closable="false" show-icon />

        <el-row :gutter="16" style="margin-top: 12px">
          <!-- 左侧节点图 -->
          <el-col :span="12">
            <el-card shadow="never">
              <div slot="header"><span><i class="el-icon-share"></i> 节点流转 ({{ debugNodeLogs.length }}个)</span></div>
              <el-steps direction="vertical" :active="debugCurrentStep" finish-status="success" process-status="process">
                <el-step v-for="(n, idx) in debugNodeLogs" :key="idx"
                  :title="n.nodeName"
                  :description="'状态: ' + (n.status || 'pending') + (n.duration ? ' (' + n.duration + 'ms)' : '')" />
              </el-steps>
              <el-empty v-if="debugNodeLogs.length === 0" description="加载节点日志中..." />
            </el-card>
          </el-col>

          <!-- 右侧调试面板 -->
          <el-col :span="12">
            <el-card shadow="never" style="margin-bottom: 12px">
              <div slot="header"><span><i class="el-icon-edit-outline"></i> 发送模拟消息</span></div>
              <el-input v-model="debugInput" type="textarea" :rows="3"
                placeholder="输入模拟客户回复消息，点击执行下一步..." />
              <div style="margin-top: 8px; display: flex; gap: 8px">
                <el-button type="primary" size="small" @click="executeDebugStep" :loading="debugStepLoading">
                  <i class="el-icon-d-arrow-right"></i> 执行下一步
                </el-button>
                <el-button size="small" @click="refreshDebugLogs">
                  <i class="el-icon-refresh"></i> 刷新日志
                </el-button>
              </div>
            </el-card>

            <el-card shadow="never">
              <div slot="header"><span><i class="el-icon-info"></i> 执行结果</span></div>
              <div v-if="debugOutput" class="debug-output">
                <div class="debug-label">AI响应:</div>
                <div class="debug-content">{{ debugOutput }}</div>
              </div>
              <div v-if="debugError" class="debug-error">{{ debugError }}</div>
              <el-empty v-if="!debugOutput && !debugError" description="点击执行下一步查看结果" :image-size="60" />
            </el-card>
          </el-col>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { workflowExecApi } from '@/api/company/workflowExec'
import { listAllWorkflowTemplates } from '@/api/company/workflowLobster'

export default {
  name: 'WorkflowExecMonitor',
  data() {
    return {
      loading: false, tableData: [], searchWorkflowId: null, workflowList: [],
      logDialogVisible: false, nodeLogs: [],
      runStats: { running: 0, paused: 0, completed: 0, terminated: 0 },
      // 逐节点调试
      debugVisible: false, debugInstance: null, debugNodeLogs: [],
      debugCurrentStep: 0, debugInput: '', debugOutput: '', debugError: '',
      debugStepLoading: false
    }
  },
  created() { this.getWorkflowList(); this.getList() },
  methods: {
    async getWorkflowList() {
      try { const r = await listAllWorkflowTemplates(); this.workflowList = r.data || [] } catch (e) { this.workflowList = [] }
    },
    async getList() {
      this.loading = true
      try {
        const res = await workflowExecApi.listInstances(this.searchWorkflowId)
        this.tableData = res.data || []
        this.computeStats()
      } catch (e) { this.$message.error('获取列表失败') }
      finally { this.loading = false }
    },
    computeStats() {
      this.runStats = { running: 0, paused: 0, completed: 0, terminated: 0 }
      this.tableData.forEach(r => {
        if (r.status === 'running') this.runStats.running++
        else if (r.status === 'paused') this.runStats.paused++
        else if (r.status === 'completed') this.runStats.completed++
        else if (r.status === 'terminated') this.runStats.terminated++
      })
    },
    selectInstance(row) {},
    async handleViewLogs(row) {
      try { const r = await workflowExecApi.getNodeLogs(row.id); this.nodeLogs = r.data || []; this.logDialogVisible = true }
      catch (e) { this.$message.error('获取日志失败') }
    },
    async handlePause(row) {
      try { await workflowExecApi.pause(row.id); this.$message.success('已暂停'); this.getList() }
      catch (e) { this.$message.error('操作失败') }
    },
    async handleResume(row) {
      try { await workflowExecApi.resume(row.id); this.$message.success('已恢复'); this.getList() }
      catch (e) { this.$message.error('操作失败') }
    },
    async handleTerminate(row) {
      try {
        await this.$confirm('确定终止该实例？', '提示', { type: 'warning' })
        await workflowExecApi.terminate(row.id, '手动终止')
        this.$message.success('已终止'); this.getList()
      } catch (e) { if (e !== 'cancel') this.$message.error('操作失败') }
    },

    // ====== 逐节点调试 ======
    async openDebug(row) {
      this.debugInstance = row
      this.debugVisible = true
      this.debugCurrentStep = row.completedNodes || 0
      this.debugOutput = ''
      this.debugError = ''
      this.debugInput = ''
      await this.refreshDebugLogs()
    },
    async refreshDebugLogs() {
      if (!this.debugInstance) return
      try {
        const r = await workflowExecApi.getNodeLogs(this.debugInstance.id)
        this.debugNodeLogs = r.data || []
        this.debugCurrentStep = (this.debugInstance.completedNodes || 0)
      } catch (e) { this.debugNodeLogs = [] }
    },
    async executeDebugStep() {
      if (!this.debugInstance) return
      this.debugStepLoading = true
      this.debugOutput = ''
      this.debugError = ''
      try {
        const res = await workflowExecApi.executeNextNode(this.debugInstance.id, this.debugInput || null)
        const data = res.data || res
        this.debugOutput = typeof data === 'string' ? data : (data.reply || data.output || JSON.stringify(data))
        this.$message.success('节点执行完成')
        await this.refreshDebugLogs()
        // 更新实例状态
        try {
          const stateRes = await workflowExecApi.getInstanceState(this.debugInstance.id)
          if (stateRes.data) {
            this.debugInstance = { ...this.debugInstance, ...stateRes.data }
          }
        } catch (e) { /* 静默 */ }
      } catch (e) {
        this.debugError = '执行失败: ' + (e.message || '未知错误')
        this.$message.error(this.debugError)
      } finally { this.debugStepLoading = false }
    },

    getStatusType(s) {
      const m = { running: 'success', paused: 'warning', completed: 'info', terminated: 'danger', pending: '' }
      return m[s] || ''
    },
    getStatusText(s) {
      const m = { running: '运行中', paused: '已暂停', completed: '已完成', terminated: '已终止', pending: '待启动' }
      return m[s] || s
    },
    getLogTimelineType(s) { return s === 'sent' ? 'success' : 'primary' }
  }
}
</script>

<style scoped>
.card-header { display: flex; justify-content: space-between; align-items: center; }
.card-header div { display: flex; gap: 10px; align-items: center; }
.stat-card { text-align: center; padding: 6px 0; }
.stat-value { font-size: 22px; font-weight: bold; color: #409EFF; }
.stat-label { font-size: 11px; color: #909399; margin-top: 2px; }
.log-header-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; }
.log-section { margin-bottom: 4px; }
.log-box { margin: 4px 0; padding: 8px; background: #f5f7fa; border-radius: 4px; white-space: pre-wrap; font-size: 12px; }
.log-box.input { background: #ecf5ff; }
.empty-tip { text-align: center; color: #909399; padding: 20px; }
.debug-output { margin-top: 8px; }
.debug-label { font-size: 12px; color: #909399; margin-bottom: 4px; }
.debug-content { padding: 10px; background: #ecf5ff; border-radius: 6px; white-space: pre-wrap; font-size: 13px; }
.debug-error { padding: 10px; color: #F56C6C; background: #fef0f0; border-radius: 6px; margin-top: 6px; font-size: 12px; }
</style>
