<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="工作流状态" clearable>
          <el-option v-for="dict in workflowStatusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @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-plus" @click="handleCreateDialog">从模板创建</el-button> -->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="workflowList">
      <el-table-column label="工作流ID" align="center" prop="userWorkflowId" width="100" />
      <el-table-column label="模板ID" align="center" prop="templateId" width="80" />
      <!-- <el-table-column label="业务ID" align="center" prop="businessKey" width="80" /> -->
      <el-table-column label="当前节点" align="center" prop="currentNodeKey" show-overflow-tooltip />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusName(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180" />
      <el-table-column label="结束时间" align="center" prop="endTime" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-s-promotion" @click="handleAdvance(scope.row)" :disabled="scope.row.status !== 1">推进</el-button>
          <el-button size="mini" type="text" icon="el-icon-document" @click="handleViewLog(scope.row)">日志</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 从模板创建对话框 -->
    <el-dialog title="从模板创建工作流" :visible.sync="createDialogOpen" width="500px" append-to-body>
      <el-form ref="createForm" :model="createForm" label-width="100px">
        <el-form-item label="选择模板" prop="templateId">
          <el-select v-model="createForm.templateId" placeholder="请选择模板" style="width: 100%">
            <el-option v-for="t in templateOptions" :key="t.templateId" :label="t.templateName" :value="t.templateId" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="业务ID" prop="businessKey">
          <el-input v-model="createForm.businessKey" placeholder="请输入关联业务ID" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="createDialogOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitCreate">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 工作流详情对话框 -->
    <el-dialog :title="'工作流详情 - ' + detailWorkflow.userWorkflowId" :visible.sync="detailOpen" width="900px" append-to-body>
      <div class="workflow-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工作流ID">{{ detailWorkflow.userWorkflowId }}</el-descriptions-item>
          <el-descriptions-item label="模板ID">{{ detailWorkflow.templateId }}</el-descriptions-item>
          <!-- <el-descriptions-item label="业务ID">{{ detailWorkflow.businessKey }}</el-descriptions-item> -->
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTag(detailWorkflow.status)">{{ getStatusName(detailWorkflow.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="当前节点">{{ detailWorkflow.currentNodeKey }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ detailWorkflow.startTime }}</el-descriptions-item>
        </el-descriptions>

        <h4 style="margin-top: 20px;">节点流程</h4>
        <div class="node-flow">
          <div v-for="(node, index) in detailNodes" :key="node.userNodeId" class="flow-item">
            <div class="flow-node" :class="getNodeStatusClass(node)">
              <div class="node-header">
                <el-tag :type="getNodeTypeTag(node.nodeType)" size="mini">{{ getNodeTypeName(node.nodeType) }}</el-tag>
                <span class="node-name">{{ node.nodeName }}</span>
                <el-tag :type="getNodeStatusTag(node.status)" size="mini">{{ getNodeStatusName(node.status) }}</el-tag>
              </div>
              <div class="node-body">
                <div v-if="node.prompt" class="node-field">
                  <label>提示词：</label>
                  <span>{{ node.prompt }}</span>
                </div>
                <div v-if="node.nextCondition" class="node-field">
                  <label>进入下一节点条件：</label>
                  <span>{{ node.nextCondition }}</span>
                </div>
                <div class="node-field">
                  <label>上一节点ID：</label>
                  <span>{{ node.prevNodeId || '无' }}</span>
                </div>
                <div class="node-field">
                  <label>下一节点ID：</label>
                  <span>{{ node.nextNodeId || '无' }}</span>
                </div>
                <div v-if="node.childNodes" class="node-field">
                  <label>子节点：</label>
                  <span>{{ node.childNodes }}</span>
                </div>
              </div>
              <div class="node-actions">
                <el-button size="mini" type="primary" @click="handleEditNode(node)">编辑</el-button>
              </div>
            </div>
            <div v-if="index < detailNodes.length - 1" class="flow-arrow">
              <i class="el-icon-bottom"></i>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑节点对话框 -->
    <el-dialog :title="'编辑节点 - ' + editNodeForm.nodeName" :visible.sync="editNodeOpen" width="600px" append-to-body>
      <el-form ref="editNodeFormRef" :model="editNodeForm" label-width="140px">
        <el-form-item label="节点名称">
          <el-input v-model="editNodeForm.nodeName" />
        </el-form-item>
        <el-form-item label="提示词">
          <el-input v-model="editNodeForm.prompt" type="textarea" :rows="4" placeholder="请输入提示词" />
        </el-form-item>
        <el-form-item label="进入下一节点条件">
          <el-input v-model="editNodeForm.nextCondition" type="textarea" :rows="2" placeholder='JSON格式，如 {"type":"timeout","value":86400}' />
        </el-form-item>
        <el-form-item label="子节点">
          <el-input v-model="editNodeForm.childNodes" placeholder='JSON数组，如 [101,102,103]' />
        </el-form-item>
        <el-form-item label="节点配置">
          <el-input v-model="editNodeForm.nodeConfig" type="textarea" :rows="3" placeholder="JSON格式扩展配置" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editNodeOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitEditNode">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 执行日志对话框 -->
    <el-dialog title="执行日志" :visible.sync="logOpen" width="1000px" append-to-body>
      <el-table :data="execLogs" v-loading="logLoading">
        <el-table-column label="日志ID" align="center" prop="logId" width="80" />
        <el-table-column label="节点名称" align="center" prop="nodeName" />
        <el-table-column label="节点类型" align="center" prop="nodeType" width="120">
          <template slot-scope="scope">
            <el-tag :type="getNodeTypeTag(scope.row.nodeType)" size="mini">{{ getNodeTypeName(scope.row.nodeType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template slot-scope="scope">
            <el-tag :type="getExecStatusTag(scope.row.status)">{{ getExecStatusName(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" prop="startTime" width="180" />
        <el-table-column label="结束时间" align="center" prop="endTime" width="180" />
        <el-table-column label="耗时(ms)" align="center" prop="duration" width="100" />
        <el-table-column label="错误信息" align="center" prop="errorMessage" show-overflow-tooltip />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listUserWorkflow, getUserWorkflow, createUserWorkflowFromTemplate, advanceWorkflow, delUserWorkflow } from '../../api/aiAddwxSop/api'
import { listUserNode, updateUserNode } from '../../api/aiAddwxSop/api'
import { listExecLogByWorkflow } from '../../api/aiAddwxSop/api'
import { listTemplate } from '../../api/aiAddwxSop/api'

export default {
  name: 'AiAddwxSopUserWorkflow',
  data() {
    return {
      loading: true,
      showSearch: true,
      total: 0,
      workflowList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: null
      },
      // 创建对话框
      createDialogOpen: false,
      createForm: {},
      templateOptions: [],
      // 详情对话框
      detailOpen: false,
      detailWorkflow: {},
      detailNodes: [],
      // 编辑节点
      editNodeOpen: false,
      editNodeForm: {},
      // 日志对话框
      logOpen: false,
      logLoading: false,
      execLogs: [],
      // 状态选项
      workflowStatusOptions: [
        { label: '未开始', value: 0 },
        { label: '进行中', value: 1 },
        { label: '已完成', value: 2 },
        { label: '已终止', value: 3 }
      ]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listUserWorkflow(this.queryParams).then(response => {
        this.workflowList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleCreateDialog() {
      this.createForm = {}
      listTemplate({ status: 1 }).then(response => {
        this.templateOptions = response.rows || []
      })
      this.createDialogOpen = true
    },
    submitCreate() {
      createUserWorkflowFromTemplate(this.createForm.templateId, this.createForm.businessKey).then(() => {
        this.msgSuccess('创建工作流成功')
        this.createDialogOpen = false
        this.getList()
      })
    },
    handleDetail(row) {
      getUserWorkflow(row.userWorkflowId).then(response => {
        this.detailWorkflow = response.data
        this.detailNodes = response.nodes || []
        this.detailOpen = true
      })
    },
    handleAdvance(row) {
      this.$confirm('确认推进到下一节点吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return advanceWorkflow(row.userWorkflowId, row.currentNodeId)
      }).then(() => {
        this.msgSuccess('推进成功')
        this.getList()
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该工作流吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delUserWorkflow(row.userWorkflowId)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    handleEditNode(node) {
      this.editNodeForm = { ...node }
      this.editNodeOpen = true
    },
    submitEditNode() {
      updateUserNode(this.editNodeForm).then(() => {
        this.msgSuccess('保存成功')
        this.editNodeOpen = false
        this.handleDetail({ userWorkflowId: this.editNodeForm.userWorkflowId })
      })
    },
    handleViewLog(row) {
      this.logOpen = true
      this.logLoading = true
      listExecLogByWorkflow(row.userWorkflowId).then(response => {
        this.execLogs = response.data || []
        this.logLoading = false
      })
    },
    // 工具方法
    getStatusName(status) {
      const map = { 0: '未开始', 1: '进行中', 2: '已完成', 3: '已终止' }
      return map[status] || '未知'
    },
    getStatusTag(status) {
      const map = { 0: 'info', 1: 'warning', 2: 'success', 3: 'danger' }
      return map[status] || ''
    },
    getNodeTypeName(type) {
      const map = { 'receive': '收货节点', 'medication': '用药节点', 'effect_feedback': '效果反馈节点', 'transfer_ai': '转AI节点' }
      return map[type] || type
    },
    getNodeTypeTag(type) {
      const map = { 'receive': 'success', 'medication': 'warning', 'effect_feedback': 'info', 'transfer_ai': 'danger' }
      return map[type] || ''
    },
    getNodeStatusName(status) {
      const map = { 0: '待执行', 1: '执行中', 2: '已完成', 3: '已跳过', 4: '执行失败' }
      return map[status] || '未知'
    },
    getNodeStatusTag(status) {
      const map = { 0: 'info', 1: 'warning', 2: 'success', 3: '', 4: 'danger' }
      return map[status] || ''
    },
    getNodeStatusClass(node) {
      if (node.status === 1) return 'flow-node-active'
      if (node.status === 2) return 'flow-node-done'
      if (node.status === 4) return 'flow-node-error'
      return ''
    },
    getExecStatusName(status) {
      const map = { 0: '待执行', 1: '执行中', 2: '成功', 3: '失败', 4: '跳过' }
      return map[status] || '未知'
    },
    getExecStatusTag(status) {
      const map = { 0: 'info', 1: 'warning', 2: 'success', 3: 'danger', 4: '' }
      return map[status] || ''
    }
  }
}
</script>

<style scoped>
.workflow-detail {
  padding: 10px;
}
.node-flow {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}
.flow-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}
.flow-node {
  border: 2px solid #dcdfe6;
  border-radius: 8px;
  padding: 12px 16px;
  width: 80%;
  background: #fff;
  transition: all 0.3s;
}
.flow-node-active {
  border-color: #409eff;
  background: #ecf5ff;
}
.flow-node-done {
  border-color: #67c23a;
  background: #f0f9eb;
}
.flow-node-error {
  border-color: #f56c6c;
  background: #fef0f0;
}
.node-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}
.node-name {
  font-weight: bold;
  font-size: 14px;
}
.node-body {
  font-size: 12px;
  color: #606266;
}
.node-field {
  margin: 4px 0;
}
.node-field label {
  color: #909399;
}
.node-actions {
  margin-top: 8px;
  text-align: right;
}
.flow-arrow {
  padding: 8px 0;
  color: #c0c4cc;
  font-size: 20px;
}
</style>
