<script setup lang="ts">
import { ref, computed } from 'vue'
import {
  exportStatistics,
  getMemberStatistics,
  getBookingStatistics,
  getSignInStatistics,
  getMemberSignInDetails,
  type MemberStatistics,
  type BookingStatistics,
  type SignInStatistics,
  type MemberSignInDetail,
} from '@/api/datacount'
import AppLayout from '@/components/AppLayout.vue'

const periodType = ref('ALL')
const showDatePicker = ref(false)
const startDate = ref('')
const endDate = ref('')
const exporting = ref(false)
const loading = ref(false)

const reportType = ref('summary')

const memberStats = ref<MemberStatistics | null>(null)
const bookingStats = ref<BookingStatistics | null>(null)
const signInStats = ref<SignInStatistics | null>(null)
const memberDetails = ref<MemberSignInDetail[]>([])
const detailTotal = ref(0)

const periodOptions = [
  { label: '今日', value: 'DAY' },
  { label: '本周', value: 'WEEK' },
  { label: '本月', value: 'MONTH' },
  { label: '本年', value: 'YEAR' },
  { label: '总计', value: 'ALL' },
  { label: '自定义', value: 'CUSTOM' },
]

const reportOptions = [
  { label: '综合统计', value: 'summary', icon: 'fa-chart-pie' },
  { label: '会员统计', value: 'member', icon: 'fa-users' },
  { label: '预约统计', value: 'booking', icon: 'fa-calendar-check' },
  { label: '签到统计', value: 'signin', icon: 'fa-clipboard-check' },
]

function formatDateTime(dateStr: string, isEnd: boolean): string {
  if (!dateStr) return ''
  return isEnd ? dateStr + 'T23:59:59' : dateStr + 'T00:00:00'
}

function buildParams(): Record<string, string> {
  const params: Record<string, string> = {}
  if (periodType.value === 'CUSTOM') {
    if (startDate.value) params.startTime = formatDateTime(startDate.value, false)
    if (endDate.value) params.endTime = formatDateTime(endDate.value, true)
  } else {
    params.periodType = periodType.value
  }
  return params
}

async function handlePreview() {
  loading.value = true
  try {
    const params = buildParams()
    if (reportType.value === 'summary' || reportType.value === 'member') {
      memberStats.value = await getMemberStatistics(params)
    }
    if (reportType.value === 'summary' || reportType.value === 'booking') {
      bookingStats.value = await getBookingStatistics(params)
    }
    if (reportType.value === 'summary' || reportType.value === 'signin') {
      signInStats.value = await getSignInStatistics(params)
    }
    if (reportType.value === 'signin') {
      const detailParams = { ...params, page: 1, size: 100 }
      const result = await getMemberSignInDetails(detailParams)
      memberDetails.value = result.list || []
      detailTotal.value = result.total || 0
    }
  } catch {
    memberStats.value = null
    bookingStats.value = null
    signInStats.value = null
  } finally {
    loading.value = false
  }
}

async function handleExport() {
  exporting.value = true
  try {
    const params: Record<string, string> = { ...buildParams() }
    params.statType = reportType.value
    const blob = await exportStatistics(params)
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    const now = new Date()
    const reportLabel = reportOptions.find((r) => r.value === reportType.value)?.label || '报表'
    const filename = `${reportLabel}_${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}.xlsx`
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  } catch {
    // 导出失败
  } finally {
    exporting.value = false
  }
}

function changePeriod(value: string) {
  periodType.value = value
  showDatePicker.value = value === 'CUSTOM'
  if (value !== 'CUSTOM') {
    handlePreview()
  }
}

function switchReportType(value: string) {
  reportType.value = value
  handlePreview()
}

function today(): string {
  return new Date().toISOString().slice(0, 10)
}

const hasData = computed(() => {
  return memberStats.value || bookingStats.value || signInStats.value
})
</script>

<template>
  <AppLayout>
    <div class="report-toolbar">
      <div class="period-selector">
        <button
          v-for="opt in periodOptions"
          :key="opt.value"
          class="period-btn"
          :class="{ active: periodType === opt.value }"
          @click="changePeriod(opt.value)"
        >
          {{ opt.label }}
        </button>
      </div>

      <transition name="fade">
        <div v-if="showDatePicker" class="date-range">
          <label>开始日期</label>
          <input v-model="startDate" type="date" :max="endDate || today()" />
          <label>结束日期</label>
          <input v-model="endDate" type="date" :min="startDate" :max="today()" />
        </div>
      </transition>
    </div>

    <section class="report-type-bar">
      <div class="report-type-selector">
        <button
          v-for="opt in reportOptions"
          :key="opt.value"
          class="report-type-btn"
          :class="{ active: reportType === opt.value }"
          @click="switchReportType(opt.value)"
        >
          <i :class="'fas ' + opt.icon"></i>
          <span>{{ opt.label }}</span>
        </button>
      </div>
    </section>

    <div class="action-bar">
      <button class="btn btn-outline" :disabled="loading" @click="handlePreview">
        <i class="fas fa-eye"></i> 预览数据
      </button>
      <button class="btn btn-export" :disabled="exporting" @click="handleExport">
        <i class="fas fa-file-excel"></i>
        {{ exporting ? '导出中...' : '导出Excel' }}
      </button>
    </div>

    <section v-if="loading" class="preview-section">
      <div class="sk-table">
        <div class="sk-row" v-for="i in 5" :key="'sk-' + i">
          <div class="sk-cell skeleton" style="width: 30%"></div>
          <div class="sk-cell skeleton" style="width: 20%"></div>
          <div class="sk-cell skeleton" style="width: 20%"></div>
          <div class="sk-cell skeleton" style="width: 30%"></div>
        </div>
      </div>
    </section>

    <section v-else-if="hasData" class="preview-section">
      <div class="card">
        <div class="card-header">
          <h3>
            <i :class="'fas ' + (reportOptions.find(r => r.value === reportType)?.icon || 'fa-chart-pie')" style="margin-right: 8px; color: #4f7cff"></i>
            {{ reportOptions.find(r => r.value === reportType)?.label || '统计' }}预览
          </h3>
        </div>

        <!-- 会员统计 -->
        <div v-if="(reportType === 'summary' || reportType === 'member') && memberStats" class="stats-table">
          <table>
            <thead>
              <tr>
                <th>统计项</th>
                <th>数值</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>统计日期</td>
                <td>{{ memberStats.statDate }}</td>
              </tr>
              <tr>
                <td>新增会员数</td>
                <td class="highlight">{{ memberStats.newMembers }}</td>
              </tr>
              <tr>
                <td>活跃会员数</td>
                <td class="highlight">{{ memberStats.activeMembers }}</td>
              </tr>
              <tr>
                <td>累计会员总数</td>
                <td class="highlight">{{ memberStats.totalMembers }}</td>
              </tr>
              <tr>
                <td>签到会员数</td>
                <td>{{ memberStats.signInMembers }}</td>
              </tr>
              <tr>
                <td>预约会员数</td>
                <td>{{ memberStats.bookingMembers }}</td>
              </tr>
              <tr>
                <td>取消预约会员数</td>
                <td>{{ memberStats.cancelMembers }}</td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 预约统计 -->
        <div v-if="(reportType === 'summary' || reportType === 'booking') && bookingStats" class="stats-table">
          <table>
            <thead>
              <tr>
                <th>统计项</th>
                <th>数值</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>统计日期</td>
                <td>{{ bookingStats.statDate }}</td>
              </tr>
              <tr>
                <td>新增预约数</td>
                <td class="highlight">{{ bookingStats.newBookings }}</td>
              </tr>
              <tr>
                <td>取消预约数</td>
                <td>{{ bookingStats.cancelBookings }}</td>
              </tr>
              <tr>
                <td>出席预约数</td>
                <td class="highlight">{{ bookingStats.attendBookings }}</td>
              </tr>
              <tr>
                <td>缺席预约数</td>
                <td>{{ bookingStats.absentBookings }}</td>
              </tr>
              <tr>
                <td>预约出席率</td>
                <td class="highlight">{{ bookingStats.attendanceRate }}%</td>
              </tr>
              <tr>
                <td>取消率</td>
                <td>{{ bookingStats.cancelRate }}%</td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 签到统计 -->
        <div v-if="(reportType === 'summary' || reportType === 'signin') && signInStats" class="stats-table">
          <table>
            <thead>
              <tr>
                <th>统计项</th>
                <th>数值</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>统计日期</td>
                <td>{{ signInStats.statDate }}</td>
              </tr>
              <tr>
                <td>签到总次数</td>
                <td class="highlight">{{ signInStats.totalSignIns }}</td>
              </tr>
              <tr>
                <td>成功签到次数</td>
                <td class="highlight">{{ signInStats.successSignIns }}</td>
              </tr>
              <tr>
                <td>失败签到次数</td>
                <td>{{ signInStats.failSignIns }}</td>
              </tr>
              <tr>
                <td>签到成功率</td>
                <td class="highlight">{{ signInStats.successRate }}%</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </section>

    <section v-else class="empty-section">
      <div class="empty-state">
        <i class="fas fa-chart-bar empty-icon"></i>
        <p>点击"预览数据"查看报表内容</p>
      </div>
    </section>
  </AppLayout>
</template>

<style scoped>
/* ---- toolbar ---- */
.report-toolbar {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
  margin-bottom: 16px;
}

.period-selector {
  display: flex;
  gap: 8px;
}

.period-btn {
  padding: 8px 20px;
  border-radius: 20px;
  border: 1px solid #e2e8f0;
  background: white;
  font-size: 13px;
  font-weight: 500;
  color: #3e4e62;
  cursor: pointer;
  transition: 0.15s;
  white-space: nowrap;
}

.period-btn.active {
  background: #4f7cff;
  border-color: #4f7cff;
  color: white;
}

.period-btn:hover:not(.active) {
  background: #f0f5ff;
}

/* ---- date range ---- */
.date-range {
  display: flex;
  align-items: center;
  gap: 8px;
  background: white;
  padding: 8px 14px;
  border-radius: 16px;
  border: 1px solid #edf2f9;
  animation: fadeIn 0.25s ease;
}

.date-range label {
  font-size: 13px;
  color: #6b7d94;
  font-weight: 500;
}

.date-range input {
  padding: 6px 10px;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  font-size: 13px;
  color: #1e293b;
  outline: none;
}

/* ---- report type ---- */
.report-type-bar {
  margin-bottom: 20px;
}

.report-type-selector {
  display: flex;
  gap: 8px;
}

.report-type-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  border-radius: 14px;
  border: 1px solid #e2e8f0;
  background: white;
  font-size: 14px;
  font-weight: 500;
  color: #3e4e62;
  cursor: pointer;
  transition: 0.15s;
}

.report-type-btn i {
  font-size: 16px;
}

.report-type-btn.active {
  background: #4f7cff;
  border-color: #4f7cff;
  color: white;
}

.report-type-btn:hover:not(.active) {
  background: #f0f5ff;
}

/* ---- action bar ---- */
.action-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
}

.btn {
  padding: 9px 20px;
  border-radius: 20px;
  border: 1px solid #e2e8f0;
  background: white;
  font-weight: 500;
  font-size: 13px;
  color: #1e293b;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  transition: 0.15s;
}

.btn-outline:hover {
  background: #f0f5ff;
  border-color: #4f7cff;
  color: #4f7cff;
}

.btn-export {
  background: #10b981;
  border-color: #10b981;
  color: white;
}

.btn-export:hover { background: #059669; }
.btn:disabled { opacity: 0.6; cursor: not-allowed; }

/* ---- preview ---- */
.preview-section {
  animation: fadeIn 0.35s ease;
}

.card {
  background: white;
  border-radius: 20px;
  border: 1px solid #edf2f9;
  padding: 20px 24px;
  margin-bottom: 16px;
}

.card-header {
  margin-bottom: 16px;
}

.card-header h3 {
  font-weight: 600;
  font-size: 16px;
  color: #0b1a33;
}

.stats-table {
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

thead th {
  text-align: left;
  padding: 10px 14px;
  font-size: 12px;
  font-weight: 600;
  color: #6b7d94;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  border-bottom: 1px solid #edf2f9;
}

tbody td {
  padding: 10px 14px;
  font-size: 14px;
  color: #1e293b;
  border-bottom: 1px solid #f1f5fa;
}

tbody tr:last-child td {
  border-bottom: none;
}

td.highlight {
  font-weight: 600;
  color: #4f7cff;
}

/* ---- empty ---- */
.empty-section {
  display: flex;
  justify-content: center;
  padding: 60px 0;
}

.empty-state {
  text-align: center;
  color: #8b9ab0;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  display: block;
}

.empty-state p {
  font-size: 14px;
}

/* ---- skeleton ---- */
.skeleton {
  background: linear-gradient(90deg, #eef2f8 25%, #e0e7f0 50%, #eef2f8 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  border-radius: 8px;
}

.sk-table {
  background: white;
  border-radius: 20px;
  border: 1px solid #edf2f9;
  padding: 20px 24px;
}

.sk-row {
  display: flex;
  gap: 16px;
  padding: 12px 0;
  border-bottom: 1px solid #f1f5fa;
}

.sk-row:last-child { border-bottom: none; }

.sk-cell {
  height: 16px;
}

/* ---- animations ---- */
@keyframes shimmer {
  0% { background-position: -200% 0; }
  100% { background-position: 200% 0; }
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(6px); }
  to { opacity: 1; transform: translateY(0); }
}

.fade-enter-active { animation: fadeIn 0.25s ease; }
.fade-leave-active { animation: fadeIn 0.15s ease reverse; }
</style>
