<template>
  <div>
    <h2 style="margin-bottom: 24px">漏斗分析</h2>

    <!-- App selector bar -->
    <div class="app-selector-bar">
      <span class="selector-label">选择应用</span>
      <el-select
        :model-value="appKey"
        placeholder="请选择应用"
        style="width:220px"
        :loading="loadingApps"
        @change="setApp"
      >
        <el-option v-for="a in apps" :key="a.appKey" :label="a.name" :value="a.appKey" />
      </el-select>
    </div>
    <el-empty v-if="gateStatus === 'no-app'" description="请选择一个应用" style="margin-top:80px" />
    <div v-else-if="gateStatus === 'loading'" v-loading="true" style="min-height:200px" />
    <div v-else-if="gateStatus === 'not-enabled'" style="margin-top:60px;text-align:center">
      <el-empty description="当前应用未开通崩溃收集服务">
        <el-button type="primary" @click="applyDialogVisible = true">申请开通</el-button>
      </el-empty>
    </div>
    <template v-else>

    <el-card style="margin-bottom: 16px">
      <template #header>配置漏斗步骤</template>
      <div class="funnel-builder">
        <div v-for="(step, idx) in steps" :key="idx" class="funnel-step-row">
          <span class="step-index">步骤 {{ idx + 1 }}</span>
          <el-input v-model="steps[idx]" placeholder="事件名" style="width: 280px" />
          <el-button v-if="steps.length > 1" type="danger" text @click="removeStep(idx)">删除</el-button>
        </div>
        <div style="margin-top: 12px; display: flex; gap: 12px">
          <el-button @click="addStep">添加步骤</el-button>
          <el-button type="primary" :loading="loading" @click="analyze">分析</el-button>
        </div>
      </div>
    </el-card>

    <el-card v-if="funnelData.length">
      <template #header>漏斗结果</template>
      <div class="funnel-charts">
        <div ref="funnelChartRef" class="funnel-chart"></div>
        <div class="funnel-detail">
          <div v-for="(step, idx) in funnelData" :key="idx" class="funnel-item">
            <div class="funnel-step-info">
              <span class="funnel-step-index">{{ idx + 1 }}</span>
              <span class="funnel-step-name">{{ step.eventName }}</span>
              <span class="funnel-step-count">{{ step.count }} 人</span>
              <el-tag :type="step.conversionRate >= 80 ? 'success' : step.conversionRate >= 50 ? 'warning' : 'danger'" size="small">
                {{ step.conversionRate.toFixed(1) }}%
              </el-tag>
            </div>
            <el-progress
              :percentage="step.conversionRate"
              :stroke-width="16"
              :color="funnelColor(idx)"
              :show-text="false"
            />
          </div>
        </div>
      </div>
    </el-card>
    </template>
    <el-dialog v-model="applyDialogVisible" title="申请开通崩溃收集" width="400px" :close-on-click-modal="false">
      <el-input v-model="applyReason" type="textarea" placeholder="请说明申请原因（选填）" :rows="3" />
      <template #footer>
        <el-button @click="applyDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="applyLoading" @click="submitActivation">提交申请</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
import { bugCollectApi, type BugCollectFunnelStep } from '@/api/bugcollect'
import { useBugCollectApp } from '@/composables/useBugCollectApp'
import * as echarts from 'echarts'

const { apps, loadingApps, appKey, setApp, gateStatus, applyDialogVisible, applyReason, applyLoading, submitActivation } = useBugCollectApp()

const steps = ref(['', ''])
const funnelData = ref<BugCollectFunnelStep[]>([])
const loading = ref(false)

const funnelChartRef = ref<HTMLElement | null>(null)
let funnelChart: echarts.ECharts | null = null

const FUNNEL_COLORS = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#b37feb', '#36cfc9']

function addStep() {
  steps.value.push('')
}

function removeStep(idx: number) {
  steps.value.splice(idx, 1)
}

function funnelColor(idx: number) {
  return FUNNEL_COLORS[idx % FUNNEL_COLORS.length]
}

async function analyze() {
  const validSteps = steps.value.filter((s) => s.trim())
  if (validSteps.length < 2 || !appKey.value) return
  loading.value = true
  try {
    const res = await bugCollectApi.funnel(appKey.value, validSteps)
    funnelData.value = res.data.data ?? []
    await nextTick()
    renderChart()
  } catch {
    funnelData.value = []
  } finally {
    loading.value = false
  }
}

function renderChart() {
  if (!funnelChartRef.value || funnelData.value.length === 0) return
  if (!funnelChart) funnelChart = echarts.init(funnelChartRef.value)

  funnelChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} 人 ({d}%)',
    },
    series: [{
      type: 'funnel',
      left: '10%',
      top: 20,
      bottom: 20,
      width: '80%',
      min: 0,
      max: funnelData.value[0]?.count ?? 100,
      minSize: '0%',
      maxSize: '100%',
      sort: 'descending',
      gap: 4,
      label: {
        show: true,
        position: 'inside',
        formatter: '{b}\n{c} 人',
      },
      labelLine: { show: false },
      emphasis: {
        label: { fontSize: 16 },
      },
      data: funnelData.value.map((d, i) => ({
        name: d.eventName,
        value: d.count,
        itemStyle: { color: FUNNEL_COLORS[i % FUNNEL_COLORS.length] },
      })),
    }],
  })
}

function handleChartResize() {
  funnelChart?.resize()
}

watch(gateStatus, (s) => { if (s === 'enabled') { /* ready */ } })
onMounted(() => {
  window.addEventListener('resize', handleChartResize)
})
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleChartResize)
  funnelChart?.dispose()
})
</script>

<style scoped>
.app-selector-bar { display:flex; align-items:center; gap:12px; margin-bottom:20px; }
.selector-label { font-size:14px; color:#606266; }
.funnel-builder {
  display: flex;
  flex-direction: column;
}
.funnel-step-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}
.step-index {
  width: 60px;
  font-size: 13px;
  color: #666;
  flex-shrink: 0;
}
.funnel-charts {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  min-height: 300px;
}
.funnel-chart {
  width: 100%;
  height: 300px;
}
.funnel-detail {
  display: flex;
  flex-direction: column;
  gap: 16px;
  justify-content: center;
}
.funnel-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
}
.funnel-step-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}
.funnel-step-index {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #409EFF;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 600;
  flex-shrink: 0;
}
.funnel-step-name {
  flex: 1;
  font-weight: 600;
}
.funnel-step-count {
  color: #666;
  font-size: 13px;
}
</style>
