<template>
  <div class="app-container node-detail-page">
    <!-- 顶部面包屑信息 -->
    <el-card shadow="never" class="header-card">
      <el-row :gutter="20">
        <el-col :span="18">
          <div class="node-title">
            <i :class="getNodeIcon(nodeInfo.nodeType)" :style="{color: getNodeColor(nodeInfo.nodeType)}"></i>
            <span class="node-name">{{ nodeInfo.nodeName || '节点详情' }}</span>
            <el-tag size="small" :type="getStatusTag(nodeInfo.status)" style="margin-left:12px">
              {{ nodeInfo.status || '未知' }}
            </el-tag>
          </div>
          <div class="node-meta">
            <span>实例ID: {{ instanceId }}</span>
            <el-divider direction="vertical" />
            <span>节点编码: {{ nodeInfo.nodeCode }}</span>
            <el-divider direction="vertical" />
            <span>节点类型: {{ getNodeTypeText(nodeInfo.nodeType) }}</span>
          </div>
        </el-col>
        <el-col :span="6" class="actions-col">
          <el-button size="small" icon="el-icon-back" @click="$router.back()">返回</el-button>
          <el-button size="small" icon="el-icon-refresh" @click="fetchDetail">刷新</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-row :gutter="16" style="margin-top:16px">
      <!-- 左侧：节点配置 -->
      <el-col :span="12">
        <el-card shadow="never">
          <div slot="header"><i class="el-icon-setting"></i> 节点配置</div>
          <el-descriptions :column="1" border size="small">
            <el-descriptions-item label="节点名称">{{ nodeInfo.nodeName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="节点编码">{{ nodeInfo.nodeCode || '-' }}</el-descriptions-item>
            <el-descriptions-item label="节点类型">{{ getNodeTypeText(nodeInfo.nodeType) }}</el-descriptions-item>
            <el-descriptions-item label="执行顺序">{{ nodeInfo.execOrder || '-' }}</el-descriptions-item>
            <el-descriptions-item label="超时(秒)">{{ nodeInfo.timeoutSeconds || '-' }}</el-descriptions-item>
            <el-descriptions-item label="重试次数">{{ nodeInfo.maxRetries || '0' }}</el-descriptions-item>
            <el-descriptions-item label="控制模式">{{ nodeInfo.controlMode || 'AI' }}</el-descriptions-item>
            <el-descriptions-item label="Prompt模板">
              {{ nodeInfo.promptName || (nodeInfo.promptId ? 'ID:' + nodeInfo.promptId : '系统默认') }}
            </el-descriptions-item>
            <el-descriptions-item label="模型路由">
              {{ nodeInfo.modelConfig || '默认' }}
            </el-descriptions-item>
          </el-descriptions>

          <!-- nodeJson 格式化展示 -->
          <div style="margin-top:16px" v-if="formattedJson">
            <div class="section-label">完整配置 (nodeJson)</div>
            <pre class="json-viewer">{{ formattedJson }}</pre>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：执行日志 -->
      <el-col :span="12">
        <el-card shadow="never" style="margin-bottom:16px">
          <div slot="header"><i class="el-icon-document"></i> 执行日志</div>
          <div v-if="logs.length === 0" class="empty-block">
            <i class="el-icon-info"></i> 暂无执行日志
          </div>
          <el-timeline v-else>
            <el-timeline-item v-for="(log, idx) in logs" :key="idx"
              :timestamp="log.executeTime || log.createTime"
              :type="log.status === 'error' || log.status === 'FAIL' ? 'danger' : log.status === 'success' || log.status === 'SUCCESS' ? 'success' : 'primary'"
              placement="top">
              <el-card shadow="hover" class="log-card">
                <div class="log-status-row">
                  <el-tag size="mini" :type="log.status === 'error' ? 'danger' : 'success'">
                    {{ log.status || 'running' }}
                  </el-tag>
                  <span class="log-duration" v-if="log.durationMs">{{ log.durationMs }}ms</span>
                </div>
                <div class="log-section" v-if="log.inputData">
                  <span class="log-label">输入:</span>
                  <pre class="log-content">{{ formatLogContent(log.inputData) }}</pre>
                </div>
                <div class="log-section" v-if="log.outputData">
                  <span class="log-label">输出:</span>
                  <pre class="log-content output">{{ formatLogContent(log.outputData) }}</pre>
                </div>
                <div class="log-section error" v-if="log.errorMsg">
                  <span class="log-label">错误:</span>
                  <pre class="log-content error">{{ log.errorMsg }}</pre>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-card>

        <!-- 决策依据 -->
        <el-card shadow="never" style="margin-bottom:16px" v-if="decisionInfo">
          <div slot="header"><i class="el-icon-cpu"></i> 决策依据</div>
          <el-descriptions :column="1" border size="small">
            <el-descriptions-item label="决策类型">{{ decisionInfo.decisionType || '-' }}</el-descriptions-item>
            <el-descriptions-item label="决策结果">{{ decisionInfo.result || '-' }}</el-descriptions-item>
            <el-descriptions-item label="置信度">
              <el-progress :percentage="(decisionInfo.confidence || 0) * 100" :stroke-width="14"
                :color="decisionInfo.confidence > 0.7 ? '#67C23A' : decisionInfo.confidence > 0.4 ? '#E6A23C' : '#F56C6C'" />
            </el-descriptions-item>
            <el-descriptions-item label="推理过程">{{ decisionInfo.reasoning || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 审核记录 -->
        <el-card shadow="never" v-if="auditRecords.length > 0">
          <div slot="header"><i class="el-icon-checked"></i> 审核记录</div>
          <el-timeline>
            <el-timeline-item v-for="(audit, idx) in auditRecords" :key="idx"
              :timestamp="audit.auditTime || audit.createTime"
              :type="audit.auditResult === 'APPROVED' ? 'success' : 'danger'">
              <p><el-tag size="mini" :type="audit.auditResult === 'APPROVED' ? 'success' : 'danger'">{{ audit.auditResult }}</el-tag></p>
              <p v-if="audit.auditRemark" style="color:#909399;font-size:12px">{{ audit.auditRemark }}</p>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getNodeLogs, getInstance } from '@/api/workflow/lobster'
import { getEventAuditDetail } from '@/api/workflow/lobster'

export default {
  name: 'NodeDetail',
  data() {
    return {
      instanceId: null,
      nodeId: null,
      loading: false,
      nodeInfo: {},
      logs: [],
      decisionInfo: null,
      auditRecords: [],
      formattedJson: ''
    }
  },
  created() {
    this.instanceId = this.$route.params.instanceId || this.$route.query.instanceId
    this.nodeId = this.$route.params.nodeId || this.$route.query.nodeId
    this.fetchDetail()
  },
  methods: {
    async fetchDetail() {
      this.loading = true
      try {
        // 加载实例信息
        if (this.instanceId) {
          try {
            const instRes = await getInstance(this.instanceId)
            const inst = instRes.data || instRes || {}
            // 查找对应节点
            const nodes = inst.nodes || inst.nodeList || []
            this.nodeInfo = nodes.find(n => String(n.nodeCode || n.id) === String(this.nodeId)) || {
              nodeName: '节点-' + this.nodeId,
              nodeCode: this.nodeId,
              nodeType: '2',
              status: inst.status || 'unknown'
            }
            this.formattedJson = this.nodeInfo.nodeJson ? JSON.stringify(
              typeof this.nodeInfo.nodeJson === 'string' ? JSON.parse(this.nodeInfo.nodeJson) : this.nodeInfo.nodeJson,
              null, 2
            ) : ''
          } catch (e) {
            this.nodeInfo = { nodeName: '节点-' + this.nodeId, nodeCode: this.nodeId, nodeType: '2' }
          }

          // 加载执行日志
          try {
            const logRes = await getNodeLogs(this.instanceId)
            const allLogs = (logRes.data || logRes || [])
            this.logs = Array.isArray(allLogs)
              ? allLogs.filter(l => String(l.nodeCode || l.nodeId) === String(this.nodeId))
              : []
          } catch (e) { /* 日志加载失败 */ }
        }

        // 加载审核记录
        try {
          const auditRes = await getEventAuditDetail(this.instanceId)
          this.auditRecords = (auditRes.data || []).filter(a =>
            String(a.nodeCode || a.nodeId) === String(this.nodeId)
          )
        } catch (e) { /* 审核记录加载失败 */ }
      } finally {
        this.loading = false
      }
    },

    formatLogContent(data) {
      if (!data) return ''
      if (typeof data === 'string') {
        try { return JSON.stringify(JSON.parse(data), null, 2) } catch (e) { return data }
      }
      return JSON.stringify(data, null, 2)
    },

    getNodeTypeText(type) {
      const map = { 1:'开始', 2:'消息', 3:'判断', 4:'等待', 5:'结束', 6:'API', 7:'购物车', 8:'优惠券', 9:'标签', 10:'赠礼', 11:'文档', 12:'用户', 13:'数据分析', 14:'AI' }
      return map[type] || '未知'
    },
    getNodeIcon(type) {
      const map = { 1:'el-icon-video-play', 2:'el-icon-message', 3:'el-icon-question', 4:'el-icon-time', 5:'el-icon-video-pause', 6:'el-icon-link', 14:'el-icon-magic-stick' }
      return map[type] || 'el-icon-circle-check'
    },
    getNodeColor(type) {
      const map = { 1:'#22c55e', 2:'#3b82f6', 3:'#f59e0b', 4:'#8b5cf6', 5:'#ef4444', 6:'#6366f1', 14:'#ec4899' }
      return map[type] || '#909399'
    },
    getStatusTag(status) {
      if (!status) return 'info'
      const s = String(status).toLowerCase()
      if (s === 'running' || s === 'success') return 'success'
      if (s === 'error' || s === 'failed' || s === 'fail') return 'danger'
      if (s === 'pending' || s === 'waiting') return 'warning'
      return 'info'
    }
  }
}
</script>

<style scoped>
.node-detail-page { padding: 10px; }
.header-card { margin-bottom: 0; }
.node-title { display: flex; align-items: center; font-size: 20px; font-weight: 600; }
.node-title i { font-size: 24px; margin-right: 8px; }
.node-name { margin-right: 4px; }
.node-meta { margin-top: 8px; font-size: 13px; color: #909399; }
.actions-col { display: flex; justify-content: flex-end; align-items: flex-start; gap: 8px; }

.section-label { font-size: 13px; font-weight: 600; color: #606266; margin-bottom: 8px; padding-left: 4px; border-left: 3px solid #409EFF; }
.json-viewer { background: #f5f7fa; padding: 12px; border-radius: 4px; font-size: 12px; line-height: 1.6; overflow-x: auto; max-height: 400px; overflow-y: auto; }

.empty-block { text-align: center; padding: 40px; color: #c0c4cc; }
.empty-block i { font-size: 36px; display: block; margin-bottom: 8px; }

.log-card { margin-bottom: 4px; }
.log-status-row { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
.log-duration { font-size: 11px; color: #909399; }
.log-section { margin-top: 4px; }
.log-label { font-size: 11px; color: #909399; }
.log-content { background: #f5f7fa; padding: 6px 8px; border-radius: 4px; font-size: 11px; margin: 2px 0 0; white-space: pre-wrap; word-break: break-word; max-height: 200px; overflow-y: auto; }
.log-content.output { background: #ecf5ff; }
.log-content.error { background: #fef0f0; color: #F56C6C; }
</style>
