<template>
  <div class="funnel-page">
    <el-card shadow="never" class="filter-card">
      <el-form inline>
        <el-form-item label="统计周期">
          <el-radio-group v-model="range" @change="fetchAll" size="small">
            <el-radio-button value="7d">近7天</el-radio-button>
            <el-radio-button value="30d">近30天</el-radio-button>
            <el-radio-button value="3m">近3个月</el-radio-button>
            <el-radio-button value="1y">近1年</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="fetchAll">刷新</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 转化漏斗 -->
    <el-card shadow="never" title="转化漏斗" class="mt16">
      <div v-if="funnel.steps && funnel.steps.length" class="funnel-bars">
        <div class="funnel-step" v-for="(s, i) in funnel.steps" :key="s.key">
          <div class="funnel-row">
            <div class="funnel-name">{{ s.name }}</div>
            <div class="funnel-bar-wrap">
              <div class="funnel-bar" :style="{ width: (s.value ? Math.max(4, (s.value / (funnel.steps[0].value||1) ) * 100) : 0) + '%', background: i===0 ? '#409eff' : (i===4?'#f56c6c':'#67c23a') }"></div>
            </div>
            <div class="funnel-val">{{ s.value }}</div>
            <el-tag size="small" :type="s.stepRate>=10?'success':(s.stepRate>=1?'warning':'danger')" v-if="i>0">{{ s.stepRate }}%</el-tag>
          </div>
          <div class="funnel-sub" v-if="i>0">上一步→本步 转化率 {{ s.stepRate }}% · 相对访问 {{ s.rate }}%</div>
        </div>
      </div>
      <el-empty v-else description="暂无漏斗数据（需用户访问产生埋点）" />
    </el-card>

    <!-- RFM 客户分层 -->
    <el-card shadow="never" title="RFM 客户价值分层" class="mt16">
      <el-row :gutter="12" class="tier-cards" v-if="rfm.tierCount">
        <el-col :span="4" v-for="(cnt, name) in rfm.tierCount" :key="name">
          <el-card shadow="hover" class="tier-card">
            <div class="tier-name">{{ name }}</div>
            <div class="tier-val">{{ cnt }}</div>
          </el-card>
        </el-col>
      </el-row>
      <el-table :data="rfm.list || []" border v-loading="rfmLoad" style="width:100%;margin-top:12px">
        <el-table-column label="用户" min-width="140"><template #default="{row}">{{ row.nickname||'-' }}<br><span style="font-size:12px;color:#999">{{ row.phone||'-' }}</span></template></el-table-column>
        <el-table-column label="R 最近消费" width="110" align="center"><template #default="{row}">{{ row.R }} 天前</template></el-table-column>
        <el-table-column label="F 频次" width="80" align="center"><template #default="{row}">{{ row.F }} 单</template></el-table-column>
        <el-table-column label="M 金额" width="110" align="center"><template #default="{row}">¥{{ formatMoney(row.M) }}</template></el-table-column>
        <el-table-column label="R/F/M 评分" width="130" align="center"><template #default="{row}"><el-tag size="small" type="info">{{ row.rScore }}/{{ row.fScore }}/{{ row.mScore }}</el-tag></template></el-table-column>
        <el-table-column label="分层" min-width="120" align="center"><template #default="{row}"><el-tag :type="tierType(row.tier)" size="small">{{ row.tier }}</el-tag></template></el-table-column>
      </el-table>
      <el-empty v-if="!rfm.list || !rfm.list.length" description="暂无购买用户" />
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
const API = axios.create({ baseURL: '/api/admin' })
API.interceptors.request.use(c => { c.headers.Authorization = 'Bearer ' + localStorage.getItem('admin_token'); return c })

const range = ref('30d')
const funnel = ref({ steps: [] })
const rfm = ref({ list: [], tierCount: {} })
const rfmLoad = ref(false)

const RANGE = { '7d': [-7, '日'], '30d': [-30, '月'], '3m': [-90, '季'], '1y': [-365, '年'] }

function formatMoney(n) { return Number(n||0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) }
function tierType(t) {
  if (t==='重要价值客户') return 'danger'
  if (t==='重要发展客户') return 'success'
  if (t==='重要保持客户') return 'warning'
  if (t==='重要挽留客户') return 'primary'
  return 'info'
}

async function fetchFunnel() {
  try { const r = await API.get('/funnel/funnel', { params: { range: range.value } }); funnel.value = r.data.data || { steps: [] } }
  catch { funnel.value = { steps: [] } }
}
async function fetchRfm() {
  rfmLoad.value = true
  try { const r = await API.get('/funnel/rfm', { params: { range: range.value } }); rfm.value = r.data.data || { list: [], tierCount: {} } }
  catch { rfm.value = { list: [], tierCount: {} } }
  finally { rfmLoad.value = false }
}
function fetchAll() { fetchFunnel(); fetchRfm() }
onMounted(fetchAll)
</script>

<style scoped>
.funnel-page { max-width: 1200px; }
.filter-card { margin-bottom: 12px; }
.mt16 { margin-top: 12px; }
.funnel-bars { padding: 4px 0; }
.funnel-step { margin-bottom: 14px; }
.funnel-row { display: flex; align-items: center; gap: 10px; }
.funnel-name { width: 70px; font-size: 13px; color: #666; flex-shrink: 0; }
.funnel-bar-wrap { flex: 1; background: #f5f7fa; border-radius: 6px; height: 26px; overflow: hidden; }
.funnel-bar { height: 100%; border-radius: 6px; transition: width .4s; }
.funnel-val { width: 50px; text-align: right; font-weight: 700; font-size: 14px; }
.funnel-sub { font-size: 12px; color: #999; padding-left: 80px; }
.tier-cards { margin-bottom: 12px; }
.tier-card { text-align: center; }
.tier-name { font-size: 12px; color: #666; }
.tier-val { font-size: 26px; font-weight: 700; color: #409eff; }
</style>
