<template>
  <div class="checkin-management-page">
    <van-nav-bar
      title="签到管理"
      left-arrow
      @click-left="onClickLeft"
      fixed
      placeholder
    />

    <div class="activity-info" v-if="activity">
      <h3>{{ activity.title }}</h3>
      <p>时间: {{ formatTime(activity.startTime) }}</p>
    </div>

    <van-tabs v-model:active="activeTab">
      <van-tab title="生成二维码">
        <div class="qr-section">
          <p class="tip">请学生使用APP扫描下方二维码签到</p>
          <div class="qr-container" v-if="qrCodeUrl">
             <!-- In real implementation backend returns URL to image, or content to generate -->
             <!-- We will use a placeholder or assume qrCodeUrl is valid image -->
             <!-- If it is just content, we might need a library like qrcode.js. 
                  For now assuming backend returns a valid image URL or we mock it. 
                  Actually the API returns qrCodeUrl. -->
             <van-image :src="qrCodeUrl" width="250" height="250" />
             <p class="code-text">有效至: {{ formatTime(expiresAt) }}</p>
          </div>
          <van-empty v-else description="点击生成二维码" />
          <div class="actions">
            <van-button type="primary" block @click="generateQr">刷新二维码</van-button>
          </div>
        </div>
      </van-tab>

      <van-tab title="手动签到">
        <div class="manual-section">
          <van-form @submit="onManualCheckin">
            <van-cell-group inset>
              <van-field
                v-model="ticketCode"
                name="ticketCode"
                label="票码"
                placeholder="请输入学电子票码"
                :rules="[{ required: true, message: '请输入票码' }]"
              />
            </van-cell-group>
            <div style="margin: 16px;">
              <van-button round block type="primary" native-type="submit">
                确认签到
              </van-button>
              <van-button round block plain type="primary" style="margin-top: 10px;" @click="showScanner = true">
                扫描入场码
              </van-button>
            </div>
          </van-form>
        </div>
      </van-tab>

      <van-tab title="签到记录">
        <van-list
          v-model:loading="loadingRecords"
          :finished="finishedRecords"
          finished-text="没有更多记录了"
          @load="onLoadRecords"
        >
          <van-cell
            v-for="item in records"
            :key="item.id"
            :title="item.userName"
            :label="`学号: ${item.studentId}`"
            :value="formatTime(item.checkInTime)"
          />
        </van-list>
      </van-tab>
    </van-tabs>

    <!-- Scanner Overlay -->
    <van-popup v-model:show="showScanner" position="bottom" :style="{ height: '100%' }">
       <WebQRScanner 
         v-if="showScanner" 
         @result="handleScanResult" 
         @close="showScanner = false" 
       />
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { getActivityDetail } from '@/services/activity';
import { generateCheckinQr, adminScanTicket, getCheckinRecords } from '@/services/checkin';
import type { Activity } from '@/types/activity';
import type { CheckinResult } from '@/services/checkin';
import { showToast } from 'vant';
import dayjs from 'dayjs';
import WebQRScanner from '@/components/WebQRScanner.vue';

const route = useRoute();
const activityId = Number(route.params.id);

const activity = ref<Activity | null>(null);
const activeTab = ref(0);

// QR Code
const qrCodeUrl = ref('');
const expiresAt = ref('');

// Manual Checkin
const ticketCode = ref('');
const showScanner = ref(false);

// Records
const records = ref<CheckinResult[]>([]);
const loadingRecords = ref(false);
const finishedRecords = ref(false);
const currentPage = ref(1);

onMounted(async () => {
  loadActivity();
  generateQr(); // Auto generate on load
});

const loadActivity = async () => {
  try {
    activity.value = await getActivityDetail(activityId);
  } catch (error) {
    showToast('加载活动信息失败');
  }
};

const onClickLeft = () => history.back();

const generateQr = async () => {
  try {
    const res = await generateCheckinQr(activityId);
    qrCodeUrl.value = res.qrCodeUrl || `https://api.qrserver.com/v1/create-qr-code/?size=250x250&data=${res.qrCodeContent}`;
    expiresAt.value = res.expiresAt;
    showToast('二维码已更新');
  } catch (error) {
     // showToast('生成二维码失败');
  }
};

const onManualCheckin = async () => {
  try {
    await adminScanTicket(activityId, ticketCode.value);
    showToast('签到成功');
    ticketCode.value = '';
    // Refresh records if on that tab
    refreshRecordsIfActive();
  } catch (error) {
    // handled
  }
};

const handleScanResult = async (decodedText: string) => {
  try {
     showToast({ type: 'loading', message: '处理中...', duration: 0 });
     await adminScanTicket(activityId, decodedText);
     showToast({ type: 'success', message: '签到成功' });
     
     // Close scanner after success
     setTimeout(() => {
       showScanner.value = false;
       refreshRecordsIfActive();
     }, 1000);
  } catch (error) {
     showToast('签到失败/无效入场码');
  }
};

const refreshRecordsIfActive = () => {
    // Refresh records if on that tab (usually admins want to see list update)
    // Even if not on tab 2, we might want to refresh next time.
    // For simplicity, just reset and fetch if active.
    // Actually better to just refetch next time tab opens or now.
    // Let's force refresh if we are on tab 2 or want to see it.
    records.value = [];
    currentPage.value = 1;
    finishedRecords.value = false;
    onLoadRecords(); 
};

const onLoadRecords = async () => {
  try {
    const res = await getCheckinRecords(activityId);
    
    // Handle both Page object and Array response
    const list = Array.isArray(res) ? res : (res.records || []);
    const total = Array.isArray(res) ? res.length : (res.total || 0);

    if (currentPage.value === 1) {
      records.value = [];
    }

    records.value.push(...list);
    
    // Use loose comparison for end of list since we might not have reliable totals for array
    if (list.length === 0 || records.value.length >= total) {
        finishedRecords.value = true;
    }
    loadingRecords.value = false;
  } catch (error) {
    loadingRecords.value = false;
    finishedRecords.value = true;
  }
};

const formatTime = (time: string) => {
  return time ? dayjs(time).format('MM-DD HH:mm') : '-';
};
</script>

<style scoped lang="scss">
.checkin-management-page {
  min-height: 100vh;
  background-color: #f7f8fa;

  .activity-info {
    background: #fff;
    padding: 16px;
    
    h3 {
      margin: 0 0 8px;
    }
    p {
      margin: 0;
      color: #666;
      font-size: 14px;
    }
  }

  .qr-section {
    padding: 40px 16px;
    text-align: center;
    background: #fff;
    
    .tip {
      margin-bottom: 20px;
      color: #666;
    }
    
    .qr-container {
      margin-bottom: 20px;
      .code-text {
        color: #999;
        font-size: 12px;
        margin-top: 10px;
      }
    }
  }

  .manual-section {
    padding-top: 20px;
  }
}
</style>
