<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="模板ID" prop="templateId">
        <el-input v-model="queryParams.templateId" placeholder="请输入模板ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <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">
      <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="companyUserId" width="100" />
      <el-table-column label="当前节点类型" align="center" prop="currentNodeType" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.currentNodeType" :type="getNodeTypeTag(scope.row.currentNodeType)">{{ getNodeTypeName(scope.row.currentNodeType) }}</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag :type="getWorkflowStatusTag(scope.row.status)">{{ getWorkflowStatusName(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="120">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(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" />

    <!-- 用户SOP详情对话框 -->
    <el-dialog :title="'用户SOP详情 - 工作流' + currentWorkflow.userWorkflowId" :visible.sync="detailOpen" width="1100px" append-to-body @opened="loadUserNodes">
      <div class="workflow-info">
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="工作流ID">{{ currentWorkflow.userWorkflowId }}</el-descriptions-item>
          <el-descriptions-item label="模板ID">{{ currentWorkflow.templateId }}</el-descriptions-item>
          <el-descriptions-item label="企业用户ID">{{ currentWorkflow.companyUserId }}</el-descriptions-item>
          <el-descriptions-item label="当前节点类型">{{ getNodeTypeName(currentWorkflow.currentNodeType) || '-' }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getWorkflowStatusTag(currentWorkflow.status)">{{ getWorkflowStatusName(currentWorkflow.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ currentWorkflow.startTime }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ currentWorkflow.endTime || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="node-panel" style="margin-top: 15px;">
        <h4 style="margin: 0 0 10px 0;">节点列表</h4>
        <el-table :data="userNodes" border row-key="userNodeId">
          <el-table-column label="节点ID" align="center" prop="userNodeId" width="80" />
          <el-table-column label="排序" align="center" prop="sortOrder" width="60" />
          <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)">{{ getNodeTypeName(scope.row.nodeType) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="上一节点" align="center" width="140">
            <template slot-scope="scope">
              <span v-if="scope.row.prevNodeId">{{ getPrevNodeLabel(scope.row.prevNodeId) }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="有效回复" align="center" prop="isValidReply" width="90">
            <template slot-scope="scope">
              <el-tag :type="scope.row.isValidReply === 1 ? 'success' : 'info'">{{ scope.row.isValidReply === 1 ? '是' : '否' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="节点状态" align="center" prop="status" width="120">
            <template slot-scope="scope">
              <el-tag :type="getNodeStatusTag(scope.row.status)">{{ getNodeStatusName(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="开始时间" align="center" prop="startTime" width="160" />
          <el-table-column label="结束时间" align="center" prop="endTime" width="160" />
          <el-table-column label="操作" align="center" width="100">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEditNodeStatus(scope.row)">修改状态</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 修改节点状态对话框 -->
    <el-dialog :title="'修改节点状态 - ' + currentNode.nodeName" :visible.sync="statusDialogOpen" width="450px" append-to-body>
      <el-form ref="statusForm" :model="statusForm" label-width="100px" size="small">
        <el-form-item label="节点状态" prop="status">
          <el-select v-model="statusForm.status" placeholder="请选择节点状态">
            <el-option v-for="dict in nodeStatusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="statusDialogOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitNodeStatus">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUserWorkflow } from '@/api/aiAddwxSop/api'
import { listUserNode, updateUserNode, updateNodeStatus } from '@/api/aiAddwxSop/api'

export default {
  name: 'AiAddwxSopUserSopDetail',
  data() {
    return {
      loading: true,
      showSearch: true,
      total: 0,
      workflowList: [],
      userNodes: [],
      currentWorkflow: {},
      currentNode: {},
      detailOpen: false,
      statusDialogOpen: false,
      nodeTypeOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateId: null,
        status: null
      },
      statusForm: {},
      workflowStatusOptions: [
        { label: '未开始', value: 0 },
        { label: '进行中', value: 1 },
        { label: '已完成', value: 2 },
        { label: '已终止', value: 3 }
      ],
      nodeStatusOptions: [
        { label: '待执行', value: 0 },
        { label: '执行中', value: 1 },
        { label: '已完成', value: 2 },
        { label: '已跳过', value: 3 },
        { label: '执行失败', value: 4 }
      ]
    }
  },
  created() {
    this.getDicts('ai_add_wechat_sop_node').then(response => {
      this.nodeTypeOptions = response.data
    })
    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()
    },
    getWorkflowStatusName(status) {
      const dict = this.workflowStatusOptions.find(d => d.value === status)
      return dict ? dict.label : status
    },
    getWorkflowStatusTag(status) {
      const map = { 0: 'info', 1: 'warning', 2: 'success', 3: 'danger' }
      return map[status] || ''
    },
    getNodeStatusName(status) {
      const dict = this.nodeStatusOptions.find(d => d.value === status)
      return dict ? dict.label : status
    },
    getNodeStatusTag(status) {
      const map = { 0: 'info', 1: 'warning', 2: 'success', 3: '', 4: 'danger' }
      return map[status] || ''
    },
    getNodeTypeName(type) {
      const dict = this.nodeTypeOptions.find(d => d.dictValue === type)
      return dict ? dict.dictLabel : type
    },
    getNodeTypeTag(type) {
      const map = {
        'receive': 'success',
        'medication': 'warning',
        'effect_feedback': 'info',
        'transfer_ai': 'danger'
      }
      return map[type] || ''
    },
    getPrevNodeLabel(prevNodeId) {
      const node = this.userNodes.find(n => n.userNodeId === prevNodeId)
      return node ? node.nodeName + ' (ID:' + node.userNodeId + ')' : 'ID:' + prevNodeId
    },
    handleDetail(row) {
      this.currentWorkflow = row
      this.detailOpen = true
    },
    loadUserNodes() {
      listUserNode(this.currentWorkflow.userWorkflowId).then(response => {
        this.userNodes = response.data || []
      })
    },
    handleEditNodeStatus(row) {
      this.currentNode = row
      this.statusForm = { userNodeId: row.userNodeId, status: row.status }
      this.statusDialogOpen = true
    },
    submitNodeStatus() {
      updateNodeStatus(this.statusForm.userNodeId, this.statusForm.status).then(() => {
        this.msgSuccess('状态修改成功')
        this.statusDialogOpen = false
        this.loadUserNodes()
      })
    }
  }
}
</script>

<style scoped>
.workflow-info {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
}
.node-panel {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  min-height: 200px;
}
</style>
