<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    title="流程模拟执行"
    width="900px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <div class="simulate-dialog">
      <div class="input-section">
        <div class="section-title">用户输入</div>
        <div class="input-hint">每行一条用户输入，按顺序模拟流程执行</div>
        <el-input
          v-model="userInputsText"
          type="textarea"
          :rows="5"
          placeholder="请输入用户回复，每行一条&#10;例如：&#10;12345678901234&#10;质量问题&#10;是的"
        />
        <div class="input-actions">
          <el-button type="primary" :loading="simulating" @click="handleSimulate">
            <el-icon><VideoPlay /></el-icon>
            开始模拟
          </el-button>
        </div>
      </div>

      <div v-if="simulationResult" class="result-section">
        <el-divider content-position="left">模拟结果</el-divider>
        
        <div class="result-summary">
          <el-row :gutter="16">
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-value">{{ simulationResult.result.totalSteps }}</div>
                <div class="summary-label">总步骤数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-value">{{ simulationResult.coverage.coveredSteps }}</div>
                <div class="summary-label">已覆盖步骤</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-value" :class="coverageClass">
                  {{ (simulationResult.coverage.coverageRate * 100).toFixed(0) }}%
                </div>
                <div class="summary-label">覆盖率</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-value">{{ simulationResult.result.totalDurationMs }}ms</div>
                <div class="summary-label">总耗时</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <div v-if="simulationResult.issues.length > 0" class="issues-section">
          <el-alert
            v-for="(issue, index) in simulationResult.issues"
            :key="index"
            :title="issue"
            type="warning"
            :closable="false"
            show-icon
            style="margin-bottom: 8px;"
          />
        </div>

        <div class="timeline-section">
          <div class="section-title">执行时间线</div>
          <el-timeline>
            <el-timeline-item
              v-for="(step, index) in simulationResult.simulation"
              :key="index"
              :type="step.matchedCondition ? 'success' : 'info'"
              :hollow="true"
            >
              <div class="timeline-step">
                <div class="step-header">
                  <el-tag size="small" type="primary">步骤 {{ step.stepNo }}</el-tag>
                  <span class="step-duration">{{ step.durationMs }}ms</span>
                </div>
                <div class="step-bot-message">
                  <span class="label">机器人：</span>
                  {{ step.botMessage }}
                </div>
                <div class="step-user-input">
                  <span class="label">用户：</span>
                  {{ step.userInput }}
                </div>
                <div v-if="step.matchedCondition" class="step-condition">
                  <span class="label">匹配条件：</span>
                  <el-tag size="small" :type="getConditionType(step.matchedCondition.type)">
                    {{ step.matchedCondition.type }}
                  </el-tag>
                  <span v-if="step.matchedCondition.keywords" class="condition-detail">
                    关键词: {{ step.matchedCondition.keywords.join(', ') }}
                  </span>
                  <span v-if="step.matchedCondition.pattern" class="condition-detail">
                    正则: {{ step.matchedCondition.pattern }}
                  </span>
                  <span class="condition-goto">→ 步骤 {{ step.matchedCondition.gotoStep }}</span>
                </div>
                <div v-else class="step-condition">
                  <span class="label">匹配条件：</span>
                  <el-tag size="small" type="info">无匹配</el-tag>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>

        <div v-if="simulationResult.coverage.uncoveredSteps.length > 0" class="uncovered-section">
          <div class="section-title">未覆盖步骤</div>
          <div class="uncovered-steps">
            <el-tag
              v-for="stepNo in simulationResult.coverage.uncoveredSteps"
              :key="stepNo"
              type="warning"
              style="margin-right: 8px;"
            >
              步骤 {{ stepNo }}
            </el-tag>
          </div>
        </div>
      </div>
    </div>

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

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { VideoPlay } from '@element-plus/icons-vue'
import { simulateScriptFlow, type FlowSimulateResponse } from '@/api/script-flow'

const props = defineProps<{
  visible: boolean
  flowId: string
  flowName: string
}>()

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
}>()

const userInputsText = ref('')
const simulating = ref(false)
const simulationResult = ref<FlowSimulateResponse | null>(null)

const coverageClass = computed(() => {
  if (!simulationResult.value) return ''
  const rate = simulationResult.value.coverage.coverageRate
  if (rate >= 0.8) return 'coverage-good'
  if (rate >= 0.5) return 'coverage-medium'
  return 'coverage-low'
})

const getConditionType = (type: string) => {
  switch (type) {
    case 'keyword':
      return 'success'
    case 'pattern':
      return 'warning'
    case 'default':
      return 'info'
    default:
      return ''
  }
}

const handleSimulate = async () => {
  const inputs = userInputsText.value
    .split('\n')
    .map(line => line.trim())
    .filter(line => line.length > 0)

  if (inputs.length === 0) {
    ElMessage.warning('请输入至少一条用户回复')
    return
  }

  simulating.value = true
  try {
    const result = await simulateScriptFlow(props.flowId, { userInputs: inputs })
    simulationResult.value = result
    ElMessage.success('模拟执行完成')
  } catch (error) {
    ElMessage.error('模拟执行失败')
  } finally {
    simulating.value = false
  }
}
</script>

<style scoped>
.simulate-dialog {
  max-height: 70vh;
  overflow-y: auto;
}

.input-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
}

.input-hint {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-bottom: 8px;
}

.input-actions {
  margin-top: 12px;
}

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

.result-summary {
  margin-bottom: 16px;
}

.summary-item {
  text-align: center;
  padding: 12px;
  background-color: var(--el-fill-color-light);
  border-radius: 6px;
}

.summary-value {
  font-size: 24px;
  font-weight: 700;
  color: var(--el-text-color-primary);
}

.summary-value.coverage-good {
  color: var(--el-color-success);
}

.summary-value.coverage-medium {
  color: var(--el-color-warning);
}

.summary-value.coverage-low {
  color: var(--el-color-danger);
}

.summary-label {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
}

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

.timeline-section {
  margin-top: 16px;
}

.timeline-step {
  padding: 8px 0;
}

.step-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.step-duration {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.step-bot-message,
.step-user-input {
  font-size: 13px;
  margin-bottom: 4px;
}

.step-bot-message .label,
.step-user-input .label {
  color: var(--el-text-color-secondary);
  margin-right: 4px;
}

.step-condition {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 8px;
}

.step-condition .label {
  margin-right: 4px;
}

.condition-detail {
  margin-left: 8px;
  font-family: monospace;
  font-size: 11px;
}

.condition-goto {
  margin-left: 8px;
  color: var(--el-color-primary);
}

.uncovered-section {
  margin-top: 16px;
}

.uncovered-steps {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
</style>
