<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    title="测试意图规则"
    width="800px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <div class="test-dialog-content">
      <div class="rule-info">
        <el-tag type="info">规则名称：{{ ruleName }}</el-tag>
        <el-tag type="warning">优先级：{{ rulePriority }}</el-tag>
      </div>

      <el-form @submit.prevent="handleTest">
        <el-form-item label="测试消息">
          <el-input
            v-model="testMessage"
            type="textarea"
            :rows="3"
            placeholder="请输入测试消息，模拟用户输入"
          />
        </el-form-item>
        <el-button type="primary" :loading="testing" @click="handleTest">
          执行测试
        </el-button>
      </el-form>

      <div v-if="testResult" class="test-result">
        <el-divider>测试结果</el-divider>

        <div class="result-summary">
          <el-statistic title="匹配状态" :value="testResult.results[0]?.matched ? '匹配成功' : '未匹配'">
            <template #suffix>
              <el-icon :class="testResult.results[0]?.matched ? 'success-icon' : 'error-icon'">
                <component :is="testResult.results[0]?.matched ? 'CircleCheckFilled' : 'CircleCloseFilled'" />
              </el-icon>
            </template>
          </el-statistic>
          <el-statistic title="匹配类型" :value="testResult.results[0]?.matchType || '-'" />
          <el-statistic title="优先级排名" :value="`第 ${testResult.results[0]?.priorityRank || '-'} 位`" />
        </div>

        <div v-if="testResult.results[0]?.matched" class="match-details">
          <div v-if="testResult.results[0]?.matchedKeywords?.length" class="detail-section">
            <h4>匹配关键词</h4>
            <div class="tag-list">
              <el-tag
                v-for="(kw, idx) in testResult.results[0].matchedKeywords"
                :key="idx"
                type="success"
                size="small"
              >
                {{ kw }}
              </el-tag>
            </div>
          </div>

          <div v-if="testResult.results[0]?.matchedPatterns?.length" class="detail-section">
            <h4>匹配正则</h4>
            <div class="tag-list">
              <el-tag
                v-for="(pattern, idx) in testResult.results[0].matchedPatterns"
                :key="idx"
                type="warning"
                size="small"
              >
                {{ pattern }}
              </el-tag>
            </div>
          </div>
        </div>

        <div v-if="testResult.results[0]?.conflictRules?.length" class="conflict-section">
          <el-alert
            title="检测到优先级冲突"
            type="warning"
            :closable="false"
            show-icon
          >
            <template #default>
              <p>以下规则也会匹配此消息，请检查优先级设置：</p>
              <ul class="conflict-list">
                <li v-for="conflict in testResult.results[0].conflictRules" :key="conflict.ruleId">
                  <strong>{{ conflict.ruleName }}</strong>（优先级：{{ conflict.priority }}）- {{ conflict.reason }}
                </li>
              </ul>
            </template>
          </el-alert>
        </div>

        <div v-if="!testResult.results[0]?.matched && testResult.results[0]?.reason" class="reason-section">
          <el-alert
            title="未匹配原因"
            type="info"
            :closable="false"
          >
            {{ testResult.results[0].reason }}
          </el-alert>
        </div>
      </div>
    </div>

    <template #footer>
      <el-button @click="$emit('update:visible', false)">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { CircleCheckFilled, CircleCloseFilled } from '@element-plus/icons-vue'
import { testIntentRule, type IntentRuleTestResult } from '@/api/monitoring'

const props = defineProps<{
  visible: boolean
  ruleId: string
  ruleName: string
  rulePriority: number
}>()

const emit = defineEmits<{
  'update:visible': [value: boolean]
}>()

const testMessage = ref('')
const testing = ref(false)
const testResult = ref<IntentRuleTestResult | null>(null)

watch(() => props.visible, (val) => {
  if (val) {
    testMessage.value = ''
    testResult.value = null
  }
})

const handleTest = async () => {
  if (!testMessage.value.trim()) {
    ElMessage.warning('请输入测试消息')
    return
  }

  testing.value = true
  try {
    testResult.value = await testIntentRule(props.ruleId, {
      message: testMessage.value
    })
    ElMessage.success('测试完成')
  } catch (error) {
    ElMessage.error('测试失败')
    testResult.value = null
  } finally {
    testing.value = false
  }
}
</script>

<style scoped>
.test-dialog-content {
  padding: 0 12px;
}

.rule-info {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.test-result {
  margin-top: 20px;
}

.result-summary {
  display: flex;
  gap: 40px;
  margin-bottom: 24px;
  padding: 16px;
  background: var(--el-fill-color-light);
  border-radius: 8px;
}

.success-icon {
  color: var(--el-color-success);
  font-size: 24px;
}

.error-icon {
  color: var(--el-color-danger);
  font-size: 24px;
}

.match-details {
  margin-bottom: 20px;
}

.detail-section {
  margin-bottom: 16px;
}

.detail-section h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.conflict-section {
  margin-top: 20px;
}

.conflict-list {
  margin: 8px 0 0 0;
  padding-left: 20px;
}

.conflict-list li {
  margin-bottom: 4px;
}

.reason-section {
  margin-top: 20px;
}
</style>
