<template>
  <div class="flow-monitoring-page">
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">话术流程监控</h1>
          <p class="page-desc">查看话术流程的激活统计、完成率和流失点分析。</p>
        </div>
        <div class="filter-section">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="loadStats"
          />
        </div>
      </div>
    </div>

    <el-row :gutter="16" class="summary-cards">
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="summary-card">
            <div class="summary-icon" style="background-color: var(--el-color-primary-light-9);">
              <el-icon :size="24" color="var(--el-color-primary)"><DataLine /></el-icon>
            </div>
            <div class="summary-content">
              <div class="summary-value">{{ stats.totalActivations }}</div>
              <div class="summary-label">总激活次数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="summary-card">
            <div class="summary-icon" style="background-color: var(--el-color-success-light-9);">
              <el-icon :size="24" color="var(--el-color-success)"><CircleCheck /></el-icon>
            </div>
            <div class="summary-content">
              <div class="summary-value">{{ stats.totalCompletions }}</div>
              <div class="summary-label">总完成次数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="summary-card">
            <div class="summary-icon" style="background-color: var(--el-color-warning-light-9);">
              <el-icon :size="24" color="var(--el-color-warning)"><TrendCharts /></el-icon>
            </div>
            <div class="summary-content">
              <div class="summary-value">{{ (stats.completionRate * 100).toFixed(1) }}%</div>
              <div class="summary-label">整体完成率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="hover" class="flow-table-card" v-loading="loading">
      <template #header>
        <span>流程统计列表</span>
      </template>
      <el-table :data="stats.flows" stripe style="width: 100%">
        <el-table-column prop="flowName" label="流程名称" min-width="150" />
        <el-table-column prop="activationCount" label="激活次数" width="100" sortable />
        <el-table-column prop="completionCount" label="完成次数" width="100" sortable />
        <el-table-column label="完成率" width="120" sortable :sort-method="(a: FlowStatItem, b: FlowStatItem) => a.completionRate - b.completionRate">
          <template #default="{ row }">
            <el-progress
              :percentage="row.completionRate * 100"
              :color="getProgressColor(row.completionRate)"
              :stroke-width="10"
              :show-text="false"
            />
            <span class="progress-text">{{ (row.completionRate * 100).toFixed(1) }}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="avgDuration" label="平均耗时(秒)" width="120" sortable>
          <template #default="{ row }">
            {{ row.avgDuration.toFixed(1) }}
          </template>
        </el-table-column>
        <el-table-column prop="avgStepsCompleted" label="平均完成步骤" width="120" sortable>
          <template #default="{ row }">
            {{ row.avgStepsCompleted.toFixed(1) }}
          </template>
        </el-table-column>
        <el-table-column label="流失点" min-width="200">
          <template #default="{ row }">
            <div v-if="row.dropOffPoints && row.dropOffPoints.length > 0" class="dropoff-tags">
              <el-tag
                v-for="point in row.dropOffPoints.slice(0, 3)"
                :key="point.stepNo"
                type="warning"
                size="small"
                style="margin-right: 4px;"
              >
                步骤{{ point.stepNo }}: {{ point.dropOffCount }}次
              </el-tag>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="lastActivatedAt" label="最近激活" width="160">
          <template #default="{ row }">
            {{ formatDate(row.lastActivatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="showExecutions(row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="executionsDialogVisible"
      :title="`${currentFlowName} - 执行记录`"
      width="800px"
      destroy-on-close
    >
      <el-table :data="executions" v-loading="executionsLoading" stripe>
        <el-table-column prop="sessionId" label="会话ID" min-width="200" />
        <el-table-column label="进度" width="120">
          <template #default="{ row }">
            {{ row.currentStep }} / {{ row.totalSteps }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startedAt" label="开始时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.startedAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="completedAt" label="完成时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.completedAt) || '-' }}
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="executionsPage"
          :page-size="20"
          :total="executionsTotal"
          layout="total, prev, pager, next"
          @current-change="loadExecutions"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { DataLine, CircleCheck, TrendCharts } from '@element-plus/icons-vue'
import { getFlowStats, getFlowExecutions, type FlowStatsResponse, type FlowExecutionRecord, type FlowStatItem } from '@/api/monitoring'

const loading = ref(false)
const dateRange = ref<[string, string] | null>(null)
const stats = ref<FlowStatsResponse>({
  totalActivations: 0,
  totalCompletions: 0,
  completionRate: 0,
  flows: []
})

const executionsDialogVisible = ref(false)
const executionsLoading = ref(false)
const currentFlowId = ref('')
const currentFlowName = ref('')
const executions = ref<FlowExecutionRecord[]>([])
const executionsPage = ref(1)
const executionsTotal = ref(0)

const formatDate = (dateStr: string | null) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getProgressColor = (rate: number) => {
  if (rate >= 0.8) return '#67C23A'
  if (rate >= 0.5) return '#E6A23C'
  return '#F56C6C'
}

const getStatusType = (status: string) => {
  switch (status) {
    case 'completed':
      return 'success'
    case 'active':
      return 'primary'
    case 'timeout':
      return 'warning'
    case 'cancelled':
      return 'info'
    default:
      return ''
  }
}

const getStatusLabel = (status: string) => {
  const labels: Record<string, string> = {
    completed: '已完成',
    active: '进行中',
    timeout: '超时',
    cancelled: '已取消'
  }
  return labels[status] || status
}

const loadStats = async () => {
  loading.value = true
  try {
    const params: Record<string, string> = {}
    if (dateRange.value) {
      params.startDate = dateRange.value[0]
      params.endDate = dateRange.value[1]
    }
    stats.value = await getFlowStats(params)
  } catch (error) {
    ElMessage.error('加载统计数据失败')
  } finally {
    loading.value = false
  }
}

const showExecutions = (flow: FlowStatsResponse['flows'][0]) => {
  currentFlowId.value = flow.flowId
  currentFlowName.value = flow.flowName
  executionsPage.value = 1
  executionsDialogVisible.value = true
  loadExecutions()
}

const loadExecutions = async () => {
  executionsLoading.value = true
  try {
    const res = await getFlowExecutions(currentFlowId.value, {
      page: executionsPage.value,
      pageSize: 20
    })
    executions.value = res.data
    executionsTotal.value = res.total
  } catch (error) {
    ElMessage.error('加载执行记录失败')
  } finally {
    executionsLoading.value = false
  }
}

onMounted(() => {
  loadStats()
})
</script>

<style scoped>
.flow-monitoring-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);
}

.summary-cards {
  margin-bottom: 24px;
}

.summary-card {
  display: flex;
  align-items: center;
  gap: 16px;
}

.summary-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.summary-content {
  flex: 1;
}

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

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

.flow-table-card {
  border-radius: 8px;
}

.progress-text {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-left: 8px;
}

.dropoff-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.pagination-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>
