<template>
  <div class="intent-rule-page">
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">意图规则管理</h1>
          <p class="page-desc">配置意图识别规则，让特定问题走固定回复或话术流程。[AC-IDSMETA-16]</p>
        </div>
        <div class="header-actions">
          <el-select v-model="filterResponseType" placeholder="按响应类型筛选" clearable style="width: 150px;">
            <el-option v-for="opt in RESPONSE_TYPE_OPTIONS" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>
            新建规则
          </el-button>
        </div>
      </div>
    </div>

    <el-card shadow="hover" class="rule-card" v-loading="loading">
      <el-table :data="rules" stripe style="width: 100%">
        <el-table-column prop="name" label="意图名称" min-width="150" />
        <el-table-column prop="keywords" label="关键词" min-width="180">
          <template #default="{ row }">
            <div class="keyword-tags">
              <el-tag
                v-for="(kw, idx) in row.keywords?.slice(0, 3)"
                :key="idx"
                size="small"
                type="info"
                style="margin-right: 4px; margin-bottom: 4px;"
              >
                {{ kw }}
              </el-tag>
              <span v-if="row.keywords?.length > 3" class="more-tag">
                +{{ row.keywords.length - 3 }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="response_type" label="响应类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getResponseTagType(row.response_type)" size="small">
              {{ getResponseLabel(row.response_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="80" sortable />
        <el-table-column prop="hit_count" label="命中次数" width="100" sortable />
        <el-table-column label="元数据" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.metadata && Object.keys(row.metadata).length > 0" size="small" type="info">
              {{ Object.keys(row.metadata).length }} 个字段
            </el-tag>
            <span v-else class="no-metadata">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="is_enabled" label="状态" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.is_enabled"
              @change="handleToggleEnabled(row)"
              active-color="#67C23A"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleTest(row)">
              <el-icon><Aim /></el-icon>
              测试
            </el-button>
            <el-button type="primary" link size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑规则' : '新建规则'"
      width="800px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="意图名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入意图名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-input-number v-model="formData.priority" :min="1" :max="100" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="关键词">
          <keyword-input :model-value="formData.keywords || []" @update:model-value="formData.keywords = $event" placeholder="输入关键词后按回车添加" />
        </el-form-item>

        <el-form-item label="正则表达式">
          <pattern-input :model-value="formData.patterns || []" @update:model-value="formData.patterns = $event" placeholder="输入正则表达式后按回车添加" />
        </el-form-item>

        <el-form-item label="响应类型" prop="response_type">
          <el-radio-group v-model="formData.response_type" @change="handleResponseTypeChange">
            <el-radio-button
              v-for="opt in RESPONSE_TYPE_OPTIONS"
              :key="opt.value"
              :value="opt.value"
            >
              {{ opt.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>

        <transition name="slide-fade" mode="out-in">
          <div v-if="formData.response_type === 'fixed'" key="fixed">
            <el-form-item label="固定回复" prop="fixed_reply">
              <el-input
                v-model="formData.fixed_reply"
                type="textarea"
                :rows="4"
                placeholder="请输入固定回复内容"
              />
            </el-form-item>
          </div>
          <div v-else-if="formData.response_type === 'rag'" key="rag">
            <el-form-item label="知识库" prop="target_kb_ids">
              <el-select
                v-model="formData.target_kb_ids"
                multiple
                placeholder="请选择知识库"
                style="width: 100%;"
              >
                <el-option
                  v-for="kb in knowledgeBases"
                  :key="kb.id"
                  :label="kb.name"
                  :value="kb.id"
                />
              </el-select>
            </el-form-item>
          </div>
          <div v-else-if="formData.response_type === 'flow'" key="flow">
            <el-form-item label="话术流程" prop="flow_id">
              <el-select v-model="formData.flow_id" placeholder="请选择话术流程" style="width: 100%;">
                <el-option
                  v-for="flow in scriptFlows"
                  :key="flow.id"
                  :label="flow.name"
                  :value="flow.id"
                />
              </el-select>
            </el-form-item>
          </div>
          <div v-else-if="formData.response_type === 'transfer'" key="transfer">
            <el-form-item label="转人工话术" prop="transfer_message">
              <el-input
                v-model="formData.transfer_message"
                type="textarea"
                :rows="3"
                placeholder="请输入转人工时的提示话术"
              />
            </el-form-item>
          </div>
        </transition>

        <el-divider content-position="left">元数据配置 [AC-IDSMETA-16]</el-divider>

        <MetadataForm
          ref="metadataFormRef"
          scope="intent_rule"
          v-model="formData.metadata"
          :is-new-object="!isEdit"
          :col-span="12"
        />
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ isEdit ? '保存' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <TestDialog
      v-model:visible="testDialogVisible"
      :rule-id="testRuleId"
      :rule-name="testRuleName"
      :rule-priority="testRulePriority"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Aim } from '@element-plus/icons-vue'
import {
  listIntentRules,
  createIntentRule,
  updateIntentRule,
  deleteIntentRule
} from '@/api/intent-rule'
import { listKnowledgeBases } from '@/api/knowledge-base'
import { listScriptFlows } from '@/api/script-flow'
import { MetadataForm } from '@/components/metadata'
import { RESPONSE_TYPE_OPTIONS, RESPONSE_TYPE_MAP } from '@/types/intent-rule'
import type { IntentRule, IntentRuleCreate, IntentRuleUpdate } from '@/types/intent-rule'
import type { KnowledgeBase } from '@/types/knowledge-base'
import type { ScriptFlow } from '@/types/script-flow'
import type { MetadataPayload } from '@/types/metadata'
import KeywordInput from './components/KeywordInput.vue'
import PatternInput from './components/PatternInput.vue'
import TestDialog from './components/TestDialog.vue'

const loading = ref(false)
const rules = ref<IntentRule[]>([])
const knowledgeBases = ref<KnowledgeBase[]>([])
const scriptFlows = ref<ScriptFlow[]>([])
const filterResponseType = ref('')
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const formRef = ref()
const metadataFormRef = ref()
const currentEditId = ref('')
const testDialogVisible = ref(false)
const testRuleId = ref('')
const testRuleName = ref('')
const testRulePriority = ref(0)

const defaultFormData = (): IntentRuleCreate => ({
  name: '',
  keywords: [],
  patterns: [],
  response_type: 'fixed',
  priority: 50,
  fixed_reply: '',
  target_kb_ids: [],
  flow_id: '',
  transfer_message: '',
  is_enabled: true,
  metadata: {}
})

const formData = ref<IntentRuleCreate>(defaultFormData())

const formRules = {
  name: [{ required: true, message: '请输入意图名称', trigger: 'blur' }],
  response_type: [{ required: true, message: '请选择响应类型', trigger: 'change' }],
  priority: [{ required: true, message: '请设置优先级', trigger: 'blur' }]
}

const getResponseLabel = (type: string) => {
  return RESPONSE_TYPE_MAP[type]?.label || type
}

const getResponseTagType = (type: string): '' | 'success' | 'warning' | 'danger' | 'info' => {
  const colorMap: Record<string, '' | 'success' | 'warning' | 'danger' | 'info'> = {
    fixed: '',
    rag: 'success',
    flow: 'warning',
    transfer: 'danger'
  }
  return colorMap[type] || ''
}

const loadRules = async () => {
  loading.value = true
  try {
    const res = await listIntentRules({
      response_type: filterResponseType.value || undefined
    })
    rules.value = res.data || []
  } catch (error) {
    ElMessage.error('加载规则列表失败')
  } finally {
    loading.value = false
  }
}

const loadKnowledgeBases = async () => {
  try {
    const res = await listKnowledgeBases({ is_enabled: true })
    knowledgeBases.value = res.data || []
  } catch (error) {
    console.error('加载知识库列表失败', error)
  }
}

const loadScriptFlows = async () => {
  try {
    const res = await listScriptFlows({ is_enabled: true })
    scriptFlows.value = res.data || []
  } catch (error) {
    console.error('加载话术流程列表失败', error)
  }
}

const handleCreate = () => {
  isEdit.value = false
  currentEditId.value = ''
  formData.value = defaultFormData()
  dialogVisible.value = true
}

const handleEdit = (row: IntentRule) => {
  isEdit.value = true
  currentEditId.value = row.id
  formData.value = {
    name: row.name,
    keywords: row.keywords || [],
    patterns: row.patterns || [],
    response_type: row.response_type,
    priority: row.priority,
    fixed_reply: row.fixed_reply || '',
    target_kb_ids: row.target_kb_ids || [],
    flow_id: row.flow_id || '',
    transfer_message: row.transfer_message || '',
    is_enabled: row.is_enabled,
    metadata: row.metadata || {}
  }
  dialogVisible.value = true
}

const handleDelete = async (row: IntentRule) => {
  try {
    await ElMessageBox.confirm('确定要删除该规则吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteIntentRule(row.id)
    ElMessage.success('删除成功')
    loadRules()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleTest = (row: IntentRule) => {
  testRuleId.value = row.id
  testRuleName.value = row.name
  testRulePriority.value = row.priority
  testDialogVisible.value = true
}

const handleToggleEnabled = async (row: IntentRule) => {
  try {
    await updateIntentRule(row.id, { is_enabled: row.is_enabled })
    ElMessage.success(row.is_enabled ? '已启用' : '已禁用')
  } catch (error) {
    row.is_enabled = !row.is_enabled
    ElMessage.error('操作失败')
  }
}

const handleResponseTypeChange = () => {
  formData.value.fixed_reply = ''
  formData.value.target_kb_ids = []
  formData.value.flow_id = ''
  formData.value.transfer_message = ''
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
  } catch {
    return
  }

  if (metadataFormRef.value) {
    const validation = await metadataFormRef.value.validate()
    if (!validation.valid) {
      ElMessage.warning('请完善必填的元数据字段')
      return
    }
  }

  submitting.value = true
  try {
    if (isEdit.value) {
      const updateData: IntentRuleUpdate = {
        name: formData.value.name,
        keywords: formData.value.keywords,
        patterns: formData.value.patterns,
        response_type: formData.value.response_type,
        priority: formData.value.priority,
        is_enabled: formData.value.is_enabled,
        metadata: formData.value.metadata
      }
      if (formData.value.response_type === 'fixed') {
        updateData.fixed_reply = formData.value.fixed_reply
      } else if (formData.value.response_type === 'rag') {
        updateData.target_kb_ids = formData.value.target_kb_ids
      } else if (formData.value.response_type === 'flow') {
        updateData.flow_id = formData.value.flow_id
      } else if (formData.value.response_type === 'transfer') {
        updateData.transfer_message = formData.value.transfer_message
      }
      await updateIntentRule(currentEditId.value, updateData)
      ElMessage.success('保存成功')
    } else {
      await createIntentRule(formData.value)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    loadRules()
  } catch (error) {
    ElMessage.error(isEdit.value ? '保存失败' : '创建失败')
  } finally {
    submitting.value = false
  }
}

watch(filterResponseType, () => {
  loadRules()
})

onMounted(() => {
  loadRules()
  loadKnowledgeBases()
  loadScriptFlows()
})
</script>

<style scoped>
.intent-rule-page {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
  flex-wrap: wrap;
}

.title-section {
  flex: 1;
  min-width: 300px;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 700;
  color: var(--el-text-color-primary);
}

.page-desc {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.rule-card {
  border-radius: 8px;
}

.keyword-tags {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.more-tag {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-left: 4px;
}

.no-metadata {
  color: var(--el-text-color-placeholder);
}

.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.2s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateX(20px);
  opacity: 0;
}
</style>
