<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-row :gutter="8" type="flex" justify="space-between" style="margin-bottom:12px">
        <el-col :span="14">
          <el-input v-model="query.keyword" placeholder="场景名" size="small" style="width:240px" clearable @keyup.enter.native="load" />
          <el-select v-model="query.enabled" placeholder="启用状态" size="small" clearable style="width:120px;margin-left:8px">
            <el-option label="启用" :value="1" /><el-option label="停用" :value="0" />
          </el-select>
          <el-button type="primary" size="small" icon="el-icon-search" @click="load" style="margin-left:8px">查询</el-button>
        </el-col>
        <el-col :span="10" style="text-align:right">
          <el-button type="success" size="small" icon="el-icon-video-play" @click="runAll">跑全部启用</el-button>
          <el-button type="primary" size="small" icon="el-icon-plus" @click="openAdd">新增场景</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="list" border size="small">
        <el-table-column label="ID" prop="id" width="70" />
        <el-table-column label="场景名" prop="scenario_name" />
        <el-table-column label="模板ID" prop="template_id" width="100" />
        <el-table-column label="业务描述" prop="business_desc" show-overflow-tooltip />
        <el-table-column label="最低分" prop="min_score" width="80" />
        <el-table-column label="启用" prop="enabled" width="80">
          <template slot-scope="s"><el-tag :type="s.row.enabled === 1 ? 'success' : 'info'">{{ s.row.enabled === 1 ? '是' : '否' }}</el-tag></template>
        </el-table-column>
        <el-table-column label="最近运行" prop="last_run_status" width="100">
          <template slot-scope="s"><el-tag v-if="s.row.last_run_status" :type="s.row.last_run_status === 'SUCCESS' ? 'success' : 'danger'" size="mini">{{ s.row.last_run_status }}</el-tag></template>
        </el-table-column>
        <el-table-column label="最近时间" prop="last_run_time" width="160" />
        <el-table-column label="操作" width="240" fixed="right">
          <template slot-scope="s">
            <el-button type="text" size="mini" @click="runOne(s.row)">立即运行</el-button>
            <el-button type="text" size="mini" @click="openEdit(s.row)">编辑</el-button>
            <el-button type="text" size="mini" style="color:#F56C6C" @click="del(s.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination background layout="prev, pager, next, total" :total="total" :page-size="query.pageSize" :current-page.sync="query.pageNum" @current-change="load" style="margin-top:12px;text-align:right" />
    </el-card>

    <el-dialog :title="form.id ? '编辑场景' : '新增场景'" :visible.sync="dlg" width="640px">
      <el-form :model="form" label-width="100px" size="small">
        <el-form-item label="场景名" required><el-input v-model="form.scenarioName" /></el-form-item>
        <el-form-item label="模板ID"><el-input-number v-model="form.templateId" :min="0" style="width:100%" /></el-form-item>
        <el-form-item label="业务描述"><el-input type="textarea" v-model="form.businessDesc" :rows="2" /></el-form-item>
        <el-form-item label="用户输入" required>
          <el-input type="textarea" v-model="form.userInputsText" :rows="6" placeholder="每行一条用户消息" />
        </el-form-item>
        <el-form-item label="最低通过分"><el-input-number v-model="form.minScore" :min="0" :max="100" /></el-form-item>
        <el-form-item label="启用"><el-switch v-model="form.enabled" :active-value="1" :inactive-value="0" /></el-form-item>
      </el-form>
      <div slot="footer"><el-button @click="dlg=false">取消</el-button><el-button type="primary" @click="save">保存</el-button></div>
    </el-dialog>
  </div>
</template>

<script>
import { listScenarios, saveScenario, deleteScenario, runScenarioNow, runAllScenarios } from '@/api/workflow/lobster-e2e'
export default {
  data() {
    return {
      loading: false, list: [], total: 0,
      query: { pageNum: 1, pageSize: 20, keyword: '', enabled: null },
      dlg: false,
      form: { id: null, scenarioName: '', templateId: null, businessDesc: '', userInputsText: '', minScore: 60, enabled: 1 }
    }
  },
  created() { this.load() },
  methods: {
    async load() {
      this.loading = true
      try {
        const res = await listScenarios(this.query)
        this.list = res.data || res || []
        this.total = this.list.length
      } finally { this.loading = false }
    },
    openAdd() { this.form = { id: null, scenarioName: '', templateId: null, businessDesc: '', userInputsText: '', minScore: 60, enabled: 1 }; this.dlg = true },
    openEdit(row) {
      let inputs = []
      try { inputs = row.user_inputs_json ? JSON.parse(row.user_inputs_json) : [] } catch (e) {}
      this.form = {
        id: row.id, scenarioName: row.scenario_name, templateId: row.template_id,
        businessDesc: row.business_desc, userInputsText: inputs.join('\n'),
        minScore: row.min_score, enabled: row.enabled
      }
      this.dlg = true
    },
    async save() {
      const userInputs = (this.form.userInputsText || '').split('\n').map(x => x.trim()).filter(x => x)
      const body = { ...this.form, userInputs }
      delete body.userInputsText
      await saveScenario(body)
      this.$message.success('已保存')
      this.dlg = false; this.load()
    },
    async runOne(row) {
      const res = await runScenarioNow(row.id)
      this.$message.success('已触发，runId=' + (res.data?.runId || ''))
      this.load()
    },
    async runAll() {
      const res = await runAllScenarios()
      this.$message.success('已触发 ' + (res.data?.triggered || 0) + ' 个场景')
      this.load()
    },
    async del(row) {
      await this.$confirm('确认删除该场景？', '提示', { type: 'warning' })
      await deleteScenario(row.id)
      this.$message.success('已删除'); this.load()
    }
  }
}
</script>
