<template>
  <div class="workflow-exec">
    <el-card>
      <div slot="header" class="card-header">
        <span>工作流执行监控</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>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="instanceName" label="实例名称" min-width="180" show-overflow-tooltip />
        <el-table-column prop="contactName" label="联系人" width="120" />
        <el-table-column prop="status" label="状态" width="100" 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="150" show-overflow-tooltip />
        <el-table-column label="进度" width="120" align="center">
          <template slot-scope="{ row }">
            {{ row.completedNodes || 0 }}/{{ row.totalNodes || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="170" />
        <el-table-column prop="lastActivityTime" label="最后活动" width="170" />
        <el-table-column label="操作" width="280" fixed="right">
          <template slot-scope="{ row }">
            <el-button type="primary" size="mini" @click="handleViewLogs(row)">日志</el-button>
            <el-button v-if="row.status === 'running'" type="warning" size="mini" @click="handlePause(row)">暂停</el-button>
            <el-button v-if="row.status === 'paused'" type="success" size="mini" @click="handleResume(row)">恢复</el-button>
            <el-button v-if="row.status !== 'completed' && row.status !== 'terminated'" type="danger" size="mini" @click="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 style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px">
              <div>
                <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>
              </div>
              <span v-if="log.durationMs" style="color: #909399; font-size: 12px">{{ log.durationMs }}ms</span>
            </div>
            <div v-if="log.outputContent" style="margin-bottom: 5px">
              <strong>发送内容：</strong>
              <p style="margin: 5px 0; padding: 8px; background: #f5f7fa; border-radius: 4px; white-space: pre-wrap">{{ log.outputContent }}</p>
            </div>
            <div v-if="log.inputContent">
              <strong>接收内容：</strong>
              <p style="margin: 5px 0; padding: 8px; background: #ecf5ff; border-radius: 4px; white-space: pre-wrap">{{ 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" style="text-align: center; color: #909399; padding: 20px">暂无执行日志</div>
    </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: []
    }
  },
  created() {
    this.getWorkflowList()
    this.getList()
  },
  methods: {
    async getWorkflowList() {
      try {
        const res = await listAllWorkflowTemplates()
        this.workflowList = res.data || []
      } catch (e) {
        this.workflowList = []
      }
    },
    async getList() {
      this.loading = true
      try {
        const res = await workflowExecApi.listInstances(this.searchWorkflowId)
        this.tableData = res.data || []
      } catch (error) {
        this.$message.error('获取列表失败')
      } finally {
        this.loading = false
      }
    },
    async handleViewLogs(row) {
      try {
        const res = await workflowExecApi.getNodeLogs(row.id)
        this.nodeLogs = res.data || []
        this.logDialogVisible = true
      } catch (error) {
        this.$message.error('获取日志失败')
      }
    },
    async handlePause(row) {
      try {
        await workflowExecApi.pause(row.id)
        this.$message.success('已暂停')
        this.getList()
      } catch (error) {
        this.$message.error('操作失败')
      }
    },
    async handleResume(row) {
      try {
        await workflowExecApi.resume(row.id)
        this.$message.success('已恢复')
        this.getList()
      } catch (error) {
        this.$message.error('操作失败')
      }
    },
    async handleTerminate(row) {
      try {
        await this.$confirm('确定要终止该工作流实例吗？', '提示', { type: 'warning' })
        await workflowExecApi.terminate(row.id, '手动终止')
        this.$message.success('已终止')
        this.getList()
      } catch (error) {
        if (error !== 'cancel') this.$message.error('操作失败')
      }
    },
    getStatusType(status) {
      const map = { running: 'success', paused: 'warning', completed: 'info', terminated: 'danger', pending: '' }
      return map[status] || ''
    },
    getStatusText(status) {
      const map = { running: '运行中', paused: '已暂停', completed: '已完成', terminated: '已终止', pending: '待启动' }
      return map[status] || status
    },
    getLogTimelineType(status) {
      return status === '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; }
</style>
