<template>
  <div class="workflow-lobster app-container">
    <el-card shadow="never" class="ai-generate-card">
      <div slot="header" class="card-header">
        <span><i class="el-icon-s-opportunity" /> AI智能生成工作流</span>
      </div>

      <el-input
        v-model="userRequirement"
        type="textarea"
        :rows="5"
        placeholder="请输入业务需求，点击生成工作流方案"
      />

      <div v-if="availableApis.length" class="api-select-section">
        <div class="api-select-label">配合的接口</div>
        <el-checkbox-group v-model="selectedApiIds">
          <el-checkbox
            v-for="api in availableApis"
            :key="api.id"
            :label="api.id"
            :disabled="true"
            border
            size="small"
            class="api-item"
          >
            {{ api.apiName }}（{{ api.apiType }}）
          </el-checkbox>
        </el-checkbox-group>
      </div>

      <div class="generate-actions">
        <el-button type="primary" size="medium" :loading="generating" @click="handleGenerate">生成工作流方案</el-button>
        <el-button size="medium" @click="clearRequirement">清空</el-button>
      </div>

      <div v-if="generationResult" class="generation-result">
        <workflow-solution-editor
          v-model="generationResult"
          :readonly="false"
          divider-title="AI生成结果"
        />

        <div class="confirm-actions">
          <el-button type="success" :loading="saving" @click="handleConfirmSave">确认并保存方案</el-button>
        </div>
      </div>
    </el-card>

    <el-card shadow="never" class="template-list-card">
      <div slot="header" class="card-header">
        <span>已保存工作流模板</span>
      </div>
      <el-table v-loading="loading" :data="tableData" border>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="templateName" label="模板名称" min-width="180" />
        <el-table-column prop="templateCode" label="模板编码" min-width="140" />
        <el-table-column prop="industryType" label="行业类型" width="110" />
        <el-table-column prop="status" label="状态" width="90">
          <template slot-scope="scope">
            <el-tag size="mini" :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '已发布' : '未发布' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="220" fixed="right">
          <template slot-scope="scope">
            <div class="table-action-group">
              <el-button class="action-btn" type="text" @click="handlePreview(scope.row)">预览</el-button>
              <el-button v-if="scope.row.status !== 1" class="action-btn" type="text" @click="handleEditTemplate(scope.row)">编辑</el-button>
              <el-button class="action-btn" type="text" @click="handleVisual(scope.row)">流程图</el-button>
              <el-button
                v-if="scope.row.status !== 1"
                class="action-btn danger-btn"
                type="text"
                @click="handleDeleteTemplate(scope.row)"
              >删除</el-button>
              <el-button
                v-if="scope.row.status !== 1"
                class="action-btn"
                type="text"
                :loading="statusChangingId === scope.row.id"
                @click="handlePublish(scope.row)"
              >发布</el-button>
              <el-button
                v-else
                class="action-btn"
                type="text"
                :loading="statusChangingId === scope.row.id"
                @click="handleUnpublish(scope.row)"
              >取消发布</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog :title="templateDialogMode === 'preview' ? '模板预览' : '模板编辑'" :visible.sync="templateDialogVisible" width="1000px">
      <workflow-solution-editor
        v-model="templateForm"
        :readonly="templateDialogMode === 'preview'"
        :compact="true"
      />

      <div slot="footer">
        <el-button @click="templateDialogVisible = false">关闭</el-button>
        <el-button v-if="templateDialogMode === 'edit'" type="primary" :loading="templateSaving" @click="submitTemplateEdit">保存修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import WorkflowSolutionEditor from './WorkflowSolutionEditor.vue'
import {
  getActiveExternalApis,
  listWorkflowTemplate,
  getWorkflowTemplateDetail,
  updateWorkflowTemplate,
  updateWorkflowTemplateStatus,
  deleteWorkflowTemplate,
  aiGenerateWorkflow,
  getGenerateResultDetail,
  confirmGenerateResultEdited
} from '@/api/company/workflowLobster'

export default {
  name: 'WorkflowLobster',
  components: { WorkflowSolutionEditor },
  data() {
    return {
      loading: false,
      generating: false,
      saving: false,
      userRequirement: '',
      availableApis: [],
      selectedApiIds: [],
      generationResult: null,
      currentRecordId: null,
      tableData: [],
      templateDialogVisible: false,
      templateDialogMode: 'preview',
      templateSaving: false,
      statusChangingId: null,
      page: {
        current: 1,
        size: 10,
        total: 0
      },
      templateForm: {
        id: null,
        templateName: '',
        industryType: '',
        description: '',
        variables: [],
        nodes: [],
        templateCode: '',
      }
    }
  },
  created() {
    this.loadAvailableApis()
    this.loadTemplateList()
  },
  methods: {
    async loadAvailableApis() {
      try {
        const res = await getActiveExternalApis()
        const data = this.extractListData(res)
        this.availableApis = data || []
        this.selectedApiIds = this.availableApis.map(item => item.id)
      } catch (e) {
        this.availableApis = []
        this.selectedApiIds = []
      }
    },
    extractListData(res) {
      if (!res) return []
      if (Array.isArray(res.data)) return res.data
      if (res.data && Array.isArray(res.data.records)) return res.data.records
      if (Array.isArray(res.rows)) return res.rows
      return []
    },
    clearRequirement() {
      this.userRequirement = ''
    },
    async loadTemplateList() {
      this.loading = true
      try {
        const res = await listWorkflowTemplate({ page: this.page.current, size: this.page.size })
        if (Array.isArray(res.data)) {
          this.tableData = res.data
          this.page.total = res.data.length
          return
        }
        if (res.data && Array.isArray(res.data.rows)) {
          this.tableData = res.data.rows
          this.page.total = res.data.total || 0
          return
        }
        if (res.rows) {
          this.tableData = res.rows
          this.page.total = res.total || 0
          return
        }
        this.tableData = []
        this.page.total = 0
      } finally {
        this.loading = false
      }
    },
    handleSizeChange(size) {
      this.page.size = size
      this.page.current = 1
      this.loadTemplateList()
    },
    handleCurrentChange(current) {
      this.page.current = current
      this.loadTemplateList()
    },
    async handleGenerate() {
      if (!this.userRequirement.trim()) {
        this.$message.warning('请输入业务需求描述')
        return
      }
      this.generating = true
      try {
        const res = await aiGenerateWorkflow({
          requirement: this.userRequirement,
          selectedApiIds: this.selectedApiIds.length ? this.selectedApiIds : undefined
        })
        const recordId = res.data && res.data.recordId
        if (!recordId) throw new Error('未返回生成记录ID')
        this.currentRecordId = recordId
        await this.pollGenerationResult(recordId)
      } catch (e) {
        this.$message.error(e.message || '生成失败')
      } finally {
        this.generating = false
      }
    },
    async pollGenerationResult(recordId) {
      const maxAttempts = 420
      let attempts = 0
      while (attempts < maxAttempts) {
        const res = await getGenerateResultDetail(recordId)
        const result = res.data || {}
        if (result.status === 1) {
          this.generationResult = {
            templateName: result.templateName || '',
            industryType: result.industryType || 'general',
            description: result.description || '',
            variables: result.variables || [],
            nodes: result.nodes || [],
            edges: result.edges || [] // 添加edges数据
          }
          this.$message.success('工作流方案生成成功，可拖拽和编辑节点后再保存')
          return
        }
        if (result.status === 2) {
          throw new Error(result.errorMsg || '生成失败')
        }
        await this.waitOneSecond()
        attempts += 1
      }
      throw new Error('生成超时，请稍后重试')
    },
    waitOneSecond() {
      return new Promise(resolve => {
        setTimeout(resolve, 1000)
      })
    },
    async handleConfirmSave() {
      if (!this.currentRecordId) {
        this.$message.warning('请先生成工作流')
        return
      }
      this.saving = true
      try {
        const payload = {
          templateName: this.generationResult.templateName,
          industryType: this.generationResult.industryType,
          description: this.generationResult.description,
          variables: this.generationResult.variables || [],
          nodes: this.generationResult.nodes || [],
          edges: this.generationResult.edges || [] // 添加edges数据
        }
        const hasEdited = true
        if (hasEdited) {
          await confirmGenerateResultEdited(this.currentRecordId, payload)
        } else {
          await confirmGenerateResult(this.currentRecordId)
        }
        this.$message.success('方案已确认保存')
        this.generationResult = null
        this.currentRecordId = null
        this.userRequirement = ''
        this.selectedApiIds = this.availableApis.map(item => item.id)
        this.loadTemplateList()
      } catch (e) {
        this.$message.error(e.message || '保存失败')
      } finally {
        this.saving = false
      }
    },
    async handlePreview(row) {
      await this.openTemplateDialog(row, 'preview')
    },
    async handleEditTemplate(row) {
      await this.openTemplateDialog(row, 'edit')
    },
    handleVisual(row) {
      this.$router.push({
        path: '/workflow/visual/' + row.id,
      })
    },
    async openTemplateDialog(row, mode) {
      this.templateDialogMode = mode
      this.templateDialogVisible = true

      try {
        const res = await getWorkflowTemplateDetail(row.id)
        const data = (res && res.data) ? res.data : row
        this.fillTemplateForm(data, row,row.templateCode )
      } catch (e) {
        this.fillTemplateForm(row, row,row.templateCode )
      }
    },
    fillTemplateForm(data, fallbackRow,templateCode) {
      const safe = data || fallbackRow || {}
      this.templateForm = {
        id: safe.id || fallbackRow.id,
        templateName: safe.templateName || '',
        industryType: safe.industryType || '',
        description: safe.description || '',
        variables: Array.isArray(safe.variables) ? JSON.parse(JSON.stringify(safe.variables)) : [],
        nodes: Array.isArray(safe.nodes) ? JSON.parse(JSON.stringify(safe.nodes)) : []
      }
      console.log(this.templateForm)
    },
    async submitTemplateEdit() {
      this.templateSaving = true
      
      try {
        const payload = {
          templateName: this.templateForm.templateName,
          industryType: this.templateForm.industryType,
          description: this.templateForm.description,
          variables: this.templateForm.variables || [],
          nodes: this.templateForm.nodes || []
        }
        
        await updateWorkflowTemplate(this.templateForm.id, payload)
        this.$message.success('模板修改成功')
        this.templateDialogVisible = false
        await this.loadTemplateList()
      } catch (e) {
        this.$message.error(e.message || '修改失败')
      } finally {
        this.templateSaving = false
      }
    },
    async handleDeleteTemplate(row) {
      try {
        await this.$confirm('确认删除该模板吗？', '提示', { type: 'warning' })
        await deleteWorkflowTemplate(row.id)
        this.$message.success('删除成功')
        await this.loadTemplateList()
      } catch (e) {
        if (e !== 'cancel') {
          this.$message.error(e.message || '删除失败')
        }
      }
    },
    async handlePublish(row) {
      await this.changeTemplateStatus(row, 1)
    },
    async handleUnpublish(row) {
      await this.changeTemplateStatus(row, 0)
    },
    async changeTemplateStatus(row, status) {
      const actionText = status === 1 ? '发布' : '取消发布'
      try {
        await this.$confirm(`确认${actionText}该模板吗？`, '提示', { type: 'warning' })
        this.statusChangingId = row.id
        await updateWorkflowTemplateStatus(row.id, status)
        this.$message.success(`${actionText}成功`)
        await this.loadTemplateList()
      } catch (e) {
        if (e !== 'cancel') {
          this.$message.error(e.message || `${actionText}失败`)
        }
      } finally {
        this.statusChangingId = null
      }
    }
  }
}
</script>

<style scoped lang="scss">
.workflow-lobster {
  .ai-generate-card {
    margin-bottom: 16px;
  }
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
  }
  .api-select-section {
    margin-top: 12px;
    background: #f5f7fa;
    border-radius: 6px;
    padding: 10px;
  }
  .api-select-label {
    font-size: 13px;
    color: #606266;
    margin-bottom: 8px;
  }
  .api-item {
    margin-bottom: 8px;
  }
  .generate-actions {
    margin-top: 12px;
  }
  .generation-result {
    margin-top: 12px;
  }
  .confirm-actions {
    margin-top: 16px;
    text-align: center;
  }
  .pagination {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }

  .table-action-group {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 2px 10px;
  }

  ::v-deep .table-action-group .action-btn {
    margin: 0;
    min-width: 44px;
    text-align: center;
    padding: 2px 0;
  }

  ::v-deep .table-action-group .danger-btn {
    color: #f56c6c;
  }
}
</style>
