<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="租户" prop="tenantId">
        <tenant-select v-model="queryParams.tenantId" @change="handleQuery" />
      </el-form-item>
      <el-form-item label="工作流ID" prop="workflowId">
        <el-input v-model="queryParams.workflowId" placeholder="请输入工作流ID" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="实例状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="运行中" value="running" />
          <el-option label="已暂停" value="paused" />
          <el-option label="已终止" value="terminated" />
          <el-option label="等待人工" value="pending_human" />
          <el-option label="已完成" value="completed" />
        </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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-view" size="mini" @click="handleViewLogs">查看日志</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="mb8">
      <el-col :span="4">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-value">{{ stats.running || 0 }}</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">{{ stats.paused || 0 }}</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">{{ stats.pending_human || 0 }}</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:#67C23A">{{ stats.completed || 0 }}</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:#909399">{{ stats.terminated || 0 }}</div>
            <div class="stat-label">已终止</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table border v-loading="loading" :data="list">
      <el-table-column label="实例ID" align="center" prop="id" width="80" />
      <el-table-column label="租户" align="center" prop="tenant_name" width="140" />
      <el-table-column label="工作流ID" align="center" prop="workflowId" width="80" />
      <el-table-column label="联系人" align="center" prop="contactId" width="100" />
      <el-table-column label="当前节点" align="center" prop="currentNodeName" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status==='running'" type="success">运行中</el-tag>
          <el-tag v-else-if="scope.row.status==='paused'" type="warning">已暂停</el-tag>
          <el-tag v-else-if="scope.row.status==='pending_human'" type="danger">等待人工</el-tag>
          <el-tag v-else-if="scope.row.status==='completed'" type="success">已完成</el-tag>
          <el-tag v-else-if="scope.row.status==='terminated'" type="info">已终止</el-tag>
          <el-tag v-else type="info">{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="控制模式" align="center" prop="controlMode" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.controlMode==='ai'" type="success" size="small">AI接管</el-tag>
          <el-tag v-else-if="scope.row.controlMode==='human'" type="danger" size="small">人工接管</el-tag>
          <el-tag v-else size="small">AI接管</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>
          <el-button v-if="scope.row.status==='running'" size="mini" type="text" icon="el-icon-video-pause" @click="handlePause(scope.row)">暂停</el-button>
          <el-button v-if="scope.row.status==='paused'" size="mini" type="text" icon="el-icon-video-play" @click="handleResume(scope.row)">恢复</el-button>
          <el-button v-if="scope.row.status==='running'||scope.row.status==='paused'" size="mini" type="text" icon="el-icon-switch-button" @click="handleTerminate(scope.row)">终止</el-button>
          <el-button size="mini" type="text" icon="el-icon-sort" @click="handleControlMode(scope.row)">切换控制</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 详情弹窗 -->
    <el-dialog title="实例详情" :visible.sync="detailVisible" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="实例ID">{{ detail.id }}</el-descriptions-item>
        <el-descriptions-item label="工作流ID">{{ detail.workflowId }}</el-descriptions-item>
        <el-descriptions-item label="联系人ID">{{ detail.contactId }}</el-descriptions-item>
        <el-descriptions-item label="当前节点">{{ detail.currentNodeName }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="detail.status==='running'" type="success" size="small">运行中</el-tag>
          <el-tag v-else-if="detail.status==='paused'" type="warning" size="small">已暂停</el-tag>
          <el-tag v-else-if="detail.status==='pending_human'" type="danger" size="small">等待人工</el-tag>
          <el-tag v-else size="small">{{ detail.status }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="控制模式">
          <el-tag v-if="detail.controlMode==='human'" type="danger" size="small">人工接管</el-tag>
          <el-tag v-else type="success" size="small">AI接管</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detail.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detail.updateTime }}</el-descriptions-item>
      </el-descriptions>
      <!-- 节点执行日志 -->
      <el-divider content-position="left">节点执行日志</el-divider>
      <el-table border :data="nodeLogs" size="small" max-height="300">
        <el-table-column label="节点" prop="nodeCode" width="100" />
        <el-table-column label="节点名称" prop="nodeName" />
        <el-table-column label="执行状态" prop="status" width="80">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status==='success'?'success':'danger'" size="mini">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="执行时间" prop="executeTime" width="160" />
        <el-table-column label="耗时(ms)" prop="durationMs" width="80" />
      </el-table>
    </el-dialog>

    <!-- 控制模式切换弹窗 -->
    <el-dialog title="切换控制模式" :visible.sync="controlVisible" width="400px" append-to-body>
      <el-radio-group v-model="controlMode">
        <el-radio label="ai">AI接管（龙虾自动回复）</el-radio>
        <el-radio label="human">人工接管（龙虾暂停AI回复）</el-radio>
      </el-radio-group>
      <div slot="footer">
        <el-button @click="controlVisible=false">取消</el-button>
        <el-button type="primary" @click="submitControlMode">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInstances, getInstance, getNodeLogs, pauseInstance, resumeInstance, terminateInstance, setControlMode } from '@/api/workflow/lobster'
import TenantSelect from '@/components/TenantSelect/index'

export default {
  name: 'LobsterInstance',
  components: { TenantSelect },
  data() {
    return {
      loading: false,
      showSearch: true,
      list: [],
      stats: {},
      detailVisible: false,
      controlVisible: false,
      detail: {},
      nodeLogs: [],
      currentRow: null,
      controlMode: 'ai',
      queryParams: {
        companyId: null,
        pageNum: 1,
        pageSize: 10,
        workflowId: null,
        status: null
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listInstances(this.queryParams).then(res => {
        let data = res.data || {}
        this.list = data.list || res.rows || []
        // 计算统计
        this.stats = { running: 0, paused: 0, pending_human: 0, completed: 0, terminated: 0 }
        this.list.forEach(item => {
          if (this.stats[item.status] !== undefined) this.stats[item.status]++
        })
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleDetail(row) {
      getInstance(row.id).then(res => {
        this.detail = res.data || row
        this.detailVisible = true
        // 获取节点日志
        getNodeLogs(row.id).then(logRes => {
          this.nodeLogs = logRes.data || []
        })
      })
    },
    handlePause(row) {
      this.$confirm('确定暂停该工作流实例吗？', '提示', { type: 'warning' }).then(() => {
        pauseInstance(row.id).then(() => {
          this.$message.success('已暂停')
          this.getList()
        })
      })
    },
    handleResume(row) {
      this.$confirm('确定恢复该工作流实例吗？', '提示', { type: 'warning' }).then(() => {
        resumeInstance(row.id).then(() => {
          this.$message.success('已恢复')
          this.getList()
        })
      })
    },
    handleTerminate(row) {
      this.$confirm('确定终止该工作流实例吗？终止后不可恢复。', '提示', { type: 'warning' }).then(() => {
        terminateInstance(row.id).then(() => {
          this.$message.success('已终止')
          this.getList()
        })
      })
    },
    handleControlMode(row) {
      this.currentRow = row
      this.controlMode = row.controlMode || 'ai'
      this.controlVisible = true
    },
    submitControlMode() {
      setControlMode(this.$withTenant({ id: this.currentRow.id, controlMode: this.controlMode })).then(res => {
        this.$message.success(res.data?.message || '控制模式已切换')
        this.controlVisible = false
        this.getList()
      })
    },
    handleViewLogs() {
      this.$message.info('请点击具体实例查看日志')
    }
  }
}
</script>

<style scoped>
.stat-card { text-align: center; padding: 10px 0; }
.stat-value { font-size: 24px; font-weight: bold; color: #409EFF; }
.stat-label { font-size: 12px; color: #909399; margin-top: 4px; }
</style>