<script setup lang="ts">
import { ref, onMounted } from 'vue'
import {
  getMemberSignInDetails,
  getMemberMonthlySignIns,
  getMemberDailySignIns,
  type MemberSignInDetail,
  type MemberMonthlySignIn,
  type MemberDailySignIn,
} from '@/api/datacount'
import AppLayout from '@/components/AppLayout.vue'
import { useToast } from '@/composables/useToast'

const toast = useToast()

const loading = ref(true)
const periodType = ref('DAY')
const showDatePicker = ref(false)
const startDate = ref('')
const endDate = ref('')

const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const list = ref<MemberSignInDetail[]>([])

// 月度弹窗
const showMonthly = ref(false)
const monthlyLoading = ref(false)
const monthlyData = ref<MemberMonthlySignIn[]>([])
const selectedMember = ref<MemberSignInDetail | null>(null)

// 月份展开状态：{ [month]: MemberDailySignIn[] | null }
const expandedMonth = ref('')
const dailyLoading = ref(false)
const dailyData = ref<MemberDailySignIn[]>([])

const signInTypeLabel: Record<string, string> = {
  QR_CODE: '扫码签到',
  MANUAL: '手动签到',
  FACE: '人脸签到',
}

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

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

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

function totalPages(): number {
  return Math.max(1, Math.ceil(total.value / pageSize.value))
}

async function fetchData() {
  loading.value = true
  try {
    const params: Record<string, string | number> = {}
    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
    }
    params.page = currentPage.value
    params.size = pageSize.value

    const res = await getMemberSignInDetails(params)
    total.value = res.total
    list.value = res.list
  } catch (e: any) {
    toast.error(e?.response?.data?.error || e?.message || '获取签到明细失败')
    total.value = 0
    list.value = []
  } finally {
    loading.value = false
  }
}

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

function handleCustomQuery() {
  if (!startDate.value && !endDate.value) return
  currentPage.value = 1
  fetchData()
}

async function viewMonthly(item: MemberSignInDetail) {
  selectedMember.value = item
  showMonthly.value = true
  monthlyLoading.value = true
  monthlyData.value = []
  try {
    monthlyData.value = await getMemberMonthlySignIns(item.memberId)
  } catch (e: any) {
    toast.error(e?.response?.data?.error || e?.message || '获取月度数据失败')
  } finally {
    monthlyLoading.value = false
  }
}

function closeMonthly() {
  showMonthly.value = false
  selectedMember.value = null
  monthlyData.value = []
  expandedMonth.value = ''
  dailyData.value = []
}

async function toggleMonth(month: string) {
  if (expandedMonth.value === month) {
    // 收起
    expandedMonth.value = ''
    dailyData.value = []
  } else {
    // 展开
    expandedMonth.value = month
    dailyLoading.value = true
    dailyData.value = []
    try {
      dailyData.value = await getMemberDailySignIns(selectedMember.value!.memberId, month)
    } catch (e: any) {
      toast.error(e?.response?.data?.error || e?.message || '获取每日数据失败')
    } finally {
      dailyLoading.value = false
    }
  }
}

function goPage(page: number) {
  if (page < 1 || page > totalPages()) return
  currentPage.value = page
  fetchData()
}

onMounted(fetchData)
</script>

<template>
  <AppLayout>
    <div class="period-bar">
      <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()" />
          <button class="btn btn-primary" @click="handleCustomQuery">
            <i class="fas fa-search"></i> 查询
          </button>
        </div>
      </transition>
    </div>

    <div class="page-header">
      <h2>会员签到明细</h2>
      <span class="total-info">共 {{ total }} 人</span>
    </div>

    <div class="card">
      <template v-if="loading">
        <div class="skeleton-table">
          <div v-for="i in 5" :key="'sk-' + i" class="sk-row">
            <div class="sk-cell skeleton" style="width:60px"></div>
            <div class="sk-cell skeleton" style="width:80px"></div>
            <div class="sk-cell skeleton" style="width:120px"></div>
            <div class="sk-cell skeleton" style="width:60px"></div>
            <div class="sk-cell skeleton" style="width:60px"></div>
            <div class="sk-cell skeleton" style="width:60px"></div>
            <div class="sk-cell skeleton" style="width:140px"></div>
          </div>
        </div>
      </template>

      <template v-else-if="list.length > 0">
        <div class="table-wrap">
          <table>
            <thead>
              <tr>
                <th>会员ID</th>
                <th>昵称</th>
                <th>手机号</th>
                <th>签到总次数</th>
                <th>成功</th>
                <th>失败</th>
                <th>最近签到时间</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in list" :key="item.memberId" class="clickable-row" @click="viewMonthly(item)">
                <td>{{ item.memberId }}</td>
                <td>{{ item.memberName }}</td>
                <td>{{ item.memberPhone }}</td>
                <td>
                  <span class="badge badge-blue">{{ item.totalSignIns }}</span>
                </td>
                <td>
                  <span class="badge badge-green">{{ item.successSignIns }}</span>
                </td>
                <td>
                  <span class="badge badge-red">{{ item.failedSignIns }}</span>
                </td>
                <td class="time-cell">{{ item.lastSignInTime }}</td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="pagination" v-if="totalPages() > 1">
          <button class="page-btn" :disabled="currentPage <= 1" @click="goPage(currentPage - 1)">
            <i class="fas fa-chevron-left"></i>
          </button>
          <span class="page-info">{{ currentPage }} / {{ totalPages() }}</span>
          <button class="page-btn" :disabled="currentPage >= totalPages()" @click="goPage(currentPage + 1)">
            <i class="fas fa-chevron-right"></i>
          </button>
        </div>
      </template>

      <div v-else class="empty-state">暂无签到数据</div>
    </div>

    <!-- 月度签到弹窗 -->
    <Teleport to="body">
      <transition name="modal">
        <div v-if="showMonthly" class="modal-overlay" @click.self="closeMonthly">
          <div class="modal-panel">
            <div class="modal-header">
              <h3>
                <i class="fas fa-calendar-alt" style="margin-right: 8px; color: #ec4899"></i>
                {{ selectedMember?.memberName }} 的月度签到记录
              </h3>
              <button class="modal-close" @click="closeMonthly">
                <i class="fas fa-times"></i>
              </button>
            </div>
            <div class="modal-body">
              <template v-if="monthlyLoading">
                <div class="sk-row" v-for="i in 5" :key="'skm-' + i">
                  <div class="sk-cell skeleton" style="width:80px"></div>
                  <div class="sk-cell skeleton" style="width:60px"></div>
                  <div class="sk-cell skeleton" style="width:60px"></div>
                  <div class="sk-cell skeleton" style="width:60px"></div>
                </div>
              </template>
              <template v-else-if="monthlyData.length > 0">
                <div class="monthly-list">
                  <template v-for="m in monthlyData" :key="m.month">
                    <div
                      class="month-row"
                      :class="{ expanded: expandedMonth === m.month }"
                      @click="toggleMonth(m.month)"
                    >
                      <div class="month-main">
                        <span class="month-badge">{{ m.month }}</span>
                        <div class="month-stats">
                          <span class="stat-item">
                            <span class="stat-val">{{ m.totalSignIns }}</span>
                            <span class="stat-sub">次</span>
                          </span>
                          <span class="stat-sep"></span>
                          <span class="stat-item success">
                            <span class="stat-val">{{ m.successSignIns }}</span>
                            <span class="stat-sub">成功</span>
                          </span>
                          <span class="stat-sep"></span>
                          <span class="stat-item fail">
                            <span class="stat-val">{{ m.failedSignIns }}</span>
                            <span class="stat-sub">失败</span>
                          </span>
                        </div>
                        <i
                          class="fas fa-chevron-down expand-icon"
                          :class="{ rotated: expandedMonth === m.month }"
                        ></i>
                      </div>

                      <!-- 展开：每日明细 -->
                      <transition name="expand">
                        <div v-if="expandedMonth === m.month" class="daily-panel">
                          <div v-if="dailyLoading" class="daily-loading">
                            <div class="sk-cell skeleton" style="width:100%;height:16px" v-for="i in 3" :key="'ds-' + i"></div>
                          </div>
                          <template v-else-if="dailyData.length > 0">
                            <div
                              v-for="d in dailyData"
                              :key="d.signInTime"
                              class="daily-row"
                              :class="{ failed: d.signInStatus === 'FAILED' }"
                            >
                              <span class="daily-time">
                                <i class="fas" :class="d.signInStatus === 'SUCCESS' ? 'fa-check-circle' : 'fa-times-circle'"></i>
                                {{ d.signInTime }}
                              </span>
                              <span class="daily-type">{{ signInTypeLabel[d.signInType] || d.signInType }}</span>
                              <span v-if="d.signInStatus === 'FAILED' && d.failReason" class="daily-reason">{{ d.failReason }}</span>
                            </div>
                          </template>
                          <div v-else class="daily-empty">该月无签到记录</div>
                        </div>
                      </transition>
                    </div>
                  </template>
                </div>
              </template>
              <div v-else class="empty-state">该会员暂无签到记录</div>
            </div>
          </div>
        </div>
      </transition>
    </Teleport>
  </AppLayout>
</template>

<style scoped>
.period-bar {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
  margin-bottom: 24px;
}

.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 {
  display: flex;
  align-items: center;
  gap: 8px;
  background: white;
  padding: 8px 14px;
  border-radius: 16px;
  border: 1px solid #edf2f9;
}

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

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

.btn {
  padding: 8px 16px;
  border-radius: 8px;
  border: none;
  font-size: 13px;
  cursor: pointer;
  font-weight: 500;
  transition: 0.15s;
}

.btn-primary {
  background: #4f7cff;
  color: white;
}

.btn-primary:hover {
  background: #3b5fd9;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.page-header h2 {
  font-size: 18px;
  font-weight: 600;
  color: #0b1a33;
}

.total-info {
  font-size: 13px;
  color: #8b9ab0;
  background: #f0f3f8;
  padding: 4px 12px;
  border-radius: 12px;
}

.card {
  background: white;
  border-radius: 12px;
  border: 1px solid #edf2f9;
  overflow: hidden;
}

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

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

thead {
  background: #f8fafd;
}

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

td {
  padding: 12px 16px;
  font-size: 14px;
  color: #3e4e62;
  border-bottom: 1px solid #f0f3f8;
}

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

tr:hover td {
  background: #f8fafd;
}

.clickable-row {
  cursor: pointer;
  transition: background 0.15s;
}

.clickable-row:hover td {
  background: #fdf2f8;
}

.time-cell {
  font-size: 13px;
  color: #8b9ab0;
  white-space: nowrap;
}

.badge {
  display: inline-block;
  padding: 2px 10px;
  border-radius: 10px;
  font-size: 13px;
  font-weight: 600;
}

.badge-blue {
  background: #f0f5ff;
  color: #4f7cff;
}

.badge-green {
  background: #ecfdf5;
  color: #10b981;
}

.badge-red {
  background: #fef2f2;
  color: #ef4444;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 16px;
  border-top: 1px solid #edf2f9;
}

.page-btn {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  background: white;
  color: #6b7d94;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: 0.15s;
}

.page-btn:hover:not(:disabled) {
  background: #f0f5ff;
  color: #4f7cff;
  border-color: #4f7cff;
}

.page-btn:disabled {
  opacity: 0.4;
  cursor: not-allowed;
}

.page-info {
  font-size: 13px;
  color: #6b7d94;
  font-weight: 500;
}

.empty-state {
  color: #8b9ab0;
  text-align: center;
  padding: 48px 16px;
  font-size: 14px;
}

/* ---- modal ---- */
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(11, 26, 51, 0.45);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.modal-panel {
  background: white;
  border-radius: 16px;
  width: 520px;
  max-width: 90vw;
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  border-bottom: 1px solid #edf2f9;
}

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

.modal-close {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  border: none;
  background: #f0f3f8;
  color: #8b9ab0;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: 0.15s;
}

.modal-close:hover {
  background: #fef2f2;
  color: #ef4444;
}

.modal-body {
  padding: 16px 24px 24px;
  overflow-y: auto;
}

/* ---- monthly list ---- */
.monthly-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.month-row {
  border: 1px solid #edf2f9;
  border-radius: 12px;
  overflow: hidden;
  transition: border-color 0.2s;
}

.month-row:hover {
  border-color: #d0d8e8;
}

.month-row.expanded {
  border-color: #c4d4f5;
}

.month-main {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 12px 16px;
  cursor: pointer;
  user-select: none;
}

.month-badge {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 8px;
  font-size: 13px;
  font-weight: 600;
  background: #fdf2f8;
  color: #ec4899;
  flex-shrink: 0;
}

.month-stats {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.stat-item {
  display: flex;
  align-items: baseline;
  gap: 3px;
}

.stat-val {
  font-size: 16px;
  font-weight: 700;
  color: #3e4e62;
}

.stat-item.success .stat-val {
  color: #10b981;
}

.stat-item.fail .stat-val {
  color: #ef4444;
}

.stat-sub {
  font-size: 11px;
  color: #8b9ab0;
}

.stat-sep {
  width: 1px;
  height: 14px;
  background: #edf2f9;
}

.expand-icon {
  color: #8b9ab0;
  font-size: 12px;
  transition: transform 0.25s ease;
  flex-shrink: 0;
}

.expand-icon.rotated {
  transform: rotate(180deg);
}

/* ---- daily panel ---- */
.daily-panel {
  border-top: 1px solid #edf2f9;
  background: #fafbfc;
  padding: 12px 16px;
}

.daily-loading {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.daily-row {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f3f8;
}

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

.daily-row.failed {
  background: #fef2f2;
  margin: 0 -8px;
  padding: 8px;
  border-radius: 6px;
}

.daily-time {
  font-size: 13px;
  color: #3e4e62;
  display: flex;
  align-items: center;
  gap: 6px;
  flex-shrink: 0;
}

.daily-time .fa-check-circle {
  color: #10b981;
  font-size: 14px;
}

.daily-time .fa-times-circle {
  color: #ef4444;
  font-size: 14px;
}

.daily-type {
  font-size: 12px;
  color: #6b7d94;
  background: #f0f3f8;
  padding: 2px 8px;
  border-radius: 6px;
}

.daily-reason {
  font-size: 12px;
  color: #ef4444;
  flex: 1;
  text-align: right;
}

.daily-empty {
  font-size: 13px;
  color: #8b9ab0;
  text-align: center;
  padding: 12px 0;
}

/* ---- expand transition ---- */
.expand-enter-active,
.expand-leave-active {
  transition: all 0.25s ease;
  overflow: hidden;
}

.expand-enter-from,
.expand-leave-to {
  opacity: 0;
  max-height: 0;
}

.expand-enter-to,
.expand-leave-from {
  opacity: 1;
  max-height: 600px;
}

/* ---- modal animation ---- */
.modal-enter-active {
  transition: opacity 0.25s ease;
}

.modal-enter-active .modal-panel {
  transition: transform 0.25s ease;
}

.modal-leave-active {
  transition: opacity 0.2s ease;
}

.modal-leave-active .modal-panel {
  transition: transform 0.2s ease;
}

.modal-enter-from {
  opacity: 0;
}

.modal-enter-from .modal-panel {
  transform: scale(0.95) translateY(10px);
}

.modal-leave-to {
  opacity: 0;
}

.modal-leave-to .modal-panel {
  transform: scale(0.95) translateY(10px);
}

.skeleton-table {
  padding: 16px;
}

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

.sk-cell {
  height: 16px;
  border-radius: 4px;
}

.skeleton {
  background: linear-gradient(90deg, #edf2f9 25%, #f8fafd 50%, #edf2f9 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

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

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
