<template>
  <div class="app-container">
    <el-card shadow="hover" class="ai-generate-card">
      <div slot="header">
        <span><i class="el-icon-magic-stick"></i> AI智能生成工作流</span>
      </div>

      <div class="ai-input-section">
        <el-input
          v-model="userRequirement"
          type="textarea"
          :rows="5"
          placeholder="请描述您的业务需求，例如：&#10;• 我是做旅游行业的，需要每天早上给客户发个性化问候，然后根据客户的回复进行智能跟进&#10;• 我是做教育的，需要每隔一天给潜在客户发送课程资讯，并自动回答常见问题&#10;• 我是做医美的，需要在客户生日时发送祝福，并推荐适合的护理项目"
        />

        <div class="api-select-section" v-if="availableApis.length > 0">
          <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" border size="small">
              <span>{{ api.apiName }}</span>
              <el-tag size="small" type="info" style="margin-left:4px">{{ api.apiType }}</el-tag>
              <span v-if="api.apiDescription" class="api-desc">{{ api.apiDescription }}</span>
            </el-checkbox>
          </el-checkbox-group>
        </div>

        <div class="generate-actions">
          <el-button type="primary" size="medium" @click="handleGenerate" :loading="generating" v-hasPermi="['workflow:lobster:edit']">
            <i class="el-icon-magic-stick"></i>
            {{ generating ? 'AI生成中...' : '生成工作流方案' }}
          </el-button>
          <el-button size="medium" @click="clearRequirement">
            <i class="el-icon-delete"></i> 清空
          </el-button>
        </div>
      </div>

      <div v-if="generationResult" class="generation-result">
        <el-divider></el-divider>
        <div class="result-header">
          <h3>AI生成的落地方案</h3>
          <div>
            <el-button type="primary" size="small" @click="editingResult = !editingResult">
              <i class="el-icon-edit"></i> {{ editingResult ? '完成编辑' : '编辑方案' }}
            </el-button>
          </div>
        </div>

        <div class="result-info-section">
          <el-form label-width="100px" size="small">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="方案名称">
                  <el-input v-if="editingResult" v-model="generationResult.templateName" placeholder="方案名称" />
                  <span v-else>{{ generationResult.templateName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="行业类型">
                  <el-select v-if="editingResult" v-model="generationResult.industryType" placeholder="行业类型" style="width:100%">
                    <el-option label="旅游" value="travel" />
                    <el-option label="教育" value="education" />
                    <el-option label="医疗" value="medical" />
                    <el-option label="医美" value="medical_beauty" />
                    <el-option label="装修" value="decoration" />
                    <el-option label="零售" value="retail" />
                    <el-option label="通用" value="general" />
                  </el-select>
                  <span v-else>{{ getIndustryText(generationResult.industryType) }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="方案描述">
              <el-input v-if="editingResult" v-model="generationResult.description" type="textarea" :rows="3" placeholder="方案描述" />
              <div v-else style="white-space:pre-wrap">{{ generationResult.description }}</div>
            </el-form-item>
          </el-form>
        </div>

        <h4 class="nodes-title">工作流节点（{{ generationResult.nodes.length }}个）</h4>
        <el-timeline>
          <el-timeline-item
            v-for="(node, index) in generationResult.nodes"
            :key="index"
            :type="getNodeTypeColor(node.nodeType)"
          >
            <el-card class="node-card" shadow="hover">
              <div class="node-header">
                <span class="node-name">{{ node.nodeName }}</span>
                <el-tag size="small" :type="getNodeTypeColor(node.nodeType)">
                  {{ getNodeTypeText(node.nodeType) }}
                </el-tag>
              </div>
              <div class="node-content" v-if="node.messageTemplate">
                <div class="message-preview">{{ node.messageTemplate }}</div>
              </div>
              <div class="node-content" v-if="node.nodeType === 3 && node.conditionExpr">
                <el-tag size="small" type="warning">条件分支</el-tag>
                <span style="margin-left:8px;font-size:12px;color:#909399">{{ node.conditionExpr }}</span>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>

        <div class="result-actions">
          <el-button type="primary" @click="handleConfirmSave" :loading="saving">
            <i class="el-icon-check"></i> 确认保存为模板
          </el-button>
          <el-button type="success" v-if="savedWorkflowId" @click="$router.push({path:'/lobster/production-workflow/canvas',query:{workflowId:savedWorkflowId}})">
            <i class="el-icon-edit"></i> 进入画布编辑
          </el-button>
          <el-button @click="handleRegenerate">
            <i class="el-icon-refresh"></i> 重新生成
          </el-button>
          <el-button @click="generationResult = null; editingResult = false; savedWorkflowId = null">
            取消
          </el-button>
        </div>
      </div>
    </el-card>

    <el-dialog title="重新生成" :visible.sync="regenerateDialogVisible" width="500px" append-to-body>
      <el-form :model="regenerateForm" label-width="80px">
        <el-form-item label="修改意见">
          <el-input v-model="regenerateForm.feedback" type="textarea" :rows="4" placeholder="请输入修改意见，AI将根据您的反馈重新生成" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="regenerateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRegenerate" :loading="regenerating">重新生成</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listApiRegistry, getAvailableChannels, aiGenerate, getGenerateResult, confirmGenerate, confirmGenerateEdited, regenerateWorkflow } from '@/api/workflow/lobster'

export default {
  name: 'LobsterGenerate',
  data() {
    return {
      userRequirement: '',
      availableApis: [],
      selectedApiIds: [],
      generating: false,
      saving: false,
      editingResult: false,
      generationResult: null,
      savedWorkflowId: null,
      currentRecordId: null,
      regenerateDialogVisible: false,
      regenerating: false,
      regenerateForm: { feedback: '' }
    }
  },
  created() {
    this.loadAvailableApis()
  },
  methods: {
    loadAvailableApis() {
      listApiRegistry().then(res => {
        this.availableApis = (res.data || []).filter(a => a.enabled === 1)
      }).catch(() => {})
    },
    handleGenerate() {
      if (!this.userRequirement.trim()) {
        this.$message.warning('请输入业务需求描述')
        return
      }
      this.generating = true
      aiGenerate({
        requirement: this.userRequirement,
        selectedApiIds: this.selectedApiIds.length > 0 ? this.selectedApiIds : undefined
      }).then(res => {
        if (res.code === 200) {
          this.currentRecordId = res.data.recordId
          this.pollGenerationResult(res.data.recordId)
        } else {
          this.$message.error(res.msg || '生成失败')
          this.generating = false
        }
      }).catch(err => {
        this.$message.error('生成请求失败：' + (err.message || ''))
        this.generating = false
      })
    },
    pollGenerationResult(recordId) {
      let attempts = 0
      const maxAttempts = 420
      const poll = () => {
        if (attempts >= maxAttempts) {
          this.$message.error('生成超时，请稍后在模板库中查看')
          this.generating = false
          return
        }
        getGenerateResult(recordId).then(res => {
          if (res.code === 200) {
            const result = res.data
            if (result.status === 1) {
              this.generationResult = {
                templateName: result.templateName,
                industryType: result.industryType,
                description: result.description,
                variables: result.variables || [],
                nodes: result.nodes || []
              }
              this.generating = false
              this.$message.success('AI工作流方案生成成功！')
            } else if (result.status === 2) {
              this.$message.error(result.errorMsg || '生成失败')
              this.generating = false
            } else {
              attempts++
              setTimeout(poll, 2000)
            }
          }
        }).catch(() => {
          attempts++
          setTimeout(poll, 2000)
        })
      }
      poll()
    },
    handleConfirmSave() {
      this.saving = true
      const solutionData = {
        templateName: this.generationResult.templateName,
        industryType: this.generationResult.industryType,
        description: this.generationResult.description,
        variables: this.generationResult.variables || [],
        nodes: this.generationResult.nodes || []
      }
      const apiCall = this.editingResult
        ? confirmGenerateEdited(this.currentRecordId, solutionData)
        : confirmGenerate(this.currentRecordId, solutionData)
      apiCall.then(res => {
        if (res.code === 200) {
          const savedWorkflowId = (res.data && res.data.workflowId) || (res.data && res.data.id)
          const msg = savedWorkflowId
            ? '方案保存成功！'
            : '方案保存成功，可在模板库中查看和编辑'
          this.$message({ message: msg, type: 'success', duration: 4000,
            showClose: true,
            onClose: () => { if (savedWorkflowId) this.$router.push({ path: '/lobster/production-workflow/canvas', query: { workflowId: savedWorkflowId } }) }
          })
          // 同时展示进入画布按钮
          if (savedWorkflowId) {
            this.savedWorkflowId = savedWorkflowId
          } else {
            this.generationResult = null
          }
          this.editingResult = false
          this.userRequirement = ''
          this.selectedApiIds = []
        } else {
          this.$message.error(res.msg || '保存失败')
        }
      }).catch(err => {
        this.$message.error('保存失败：' + (err.message || ''))
      }).finally(() => {
        this.saving = false
      })
    },
    handleRegenerate() {
      this.regenerateForm.feedback = ''
      this.regenerateDialogVisible = true
    },
    submitRegenerate() {
      if (!this.regenerateForm.feedback.trim()) {
        this.$message.warning('请输入修改意见')
        return
      }
      this.regenerating = true
      regenerateWorkflow(this.currentRecordId, {
        feedback: this.regenerateForm.feedback
      }).then(res => {
        if (res.code === 200) {
          this.currentRecordId = res.data.recordId
          this.pollGenerationResult(res.data.recordId)
          this.regenerateDialogVisible = false
        } else {
          this.$message.error(res.msg || '重新生成失败')
        }
      }).catch(err => {
        this.$message.error('重新生成失败：' + (err.message || ''))
      }).finally(() => {
        this.regenerating = false
      })
    },
    clearRequirement() {
      this.userRequirement = ''
      this.selectedApiIds = []
      this.generationResult = null
      this.editingResult = false
    },
    getIndustryText(type) {
      const map = { travel: '旅游', education: '教育', medical: '医疗', medical_beauty: '医美', decoration: '装修', retail: '零售', general: '通用' }
      return map[type] || type || '通用'
    },
    getNodeTypeText(type) {
      const map = { 1: '开始节点', 2: '消息节点', 3: '判断节点', 4: '等待节点', 5: '结束节点', 6: 'API调用节点' }
      return map[type] || '未知节点'
    },
    getNodeTypeColor(type) {
      const map = { 1: 'success', 2: '', 3: 'warning', 4: 'info', 5: 'danger', 6: '' }
      return map[type] || ''
    }
  }
}
</script>

<style scoped>
.ai-generate-card { margin-bottom: 16px; }
.ai-input-section { max-width: 800px; }
.api-select-section { margin-top: 16px; }
.api-select-label { font-size: 14px; color: #606266; margin-bottom: 8px; }
.api-desc { font-size: 12px; color: #909399; margin-left: 4px; }
.generate-actions { margin-top: 16px; }
.generation-result { margin-top: 16px; }
.result-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
.result-header h3 { margin: 0; }
.result-actions { margin-top: 20px; text-align: center; }
.nodes-title { margin: 16px 0 12px; font-size: 14px; color: #606266; }
.node-card { margin-bottom: 8px; }
.node-header { display: flex; justify-content: space-between; align-items: center; }
.node-name { font-weight: bold; }
.node-content { margin-top: 8px; }
.message-preview { white-space: pre-wrap; font-size: 13px; color: #606266; background: #f5f7fa; padding: 8px; border-radius: 4px; }
</style>
