<template>
    <view class="scroll-container theme-light">
        <view class="bt-page">
            <PageHeader title="签到记录" subtitle="" :show-back="true" />
            <view class="mi-mod-tabs">
                <view
                    v-for="tab in tabs"
                    :key="tab.key"
                    class="bt-tab"
                    :class="{ 'bt-tab--active': activeFilter === tab.key }"
                    hover-class="mi-tap-tab--hover"
                    :hover-stay-time="150"
                    @tap="activeFilter = tab.key"
                >
                    <text class="bt-tab__text">{{ tab.label }}</text>
                </view>
            </view>
            <view class="bt-page__body">
                <view class="bt-card">
                    <text class="bt-card__title" v-if="filteredList.length > 0">共 {{ filteredList.length }} 条记录</text>
                    <view
                        v-for="item in filteredList"
                        :key="item.id"
                        class="mi-mod-checkin-row"
                        hover-class="mi-tap-row--hover"
                        :hover-stay-time="150"
                        @tap="showDetail(item)"
                    >
                        <view class="mi-mod-checkin-row__icon" :class="'mi-mod-checkin-row__icon--' + item.tagTheme">
                            <image class="mi-mod-checkin-row__icon-img" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/usercheck.png" mode="aspectFit" />
                        </view>
                        <view class="mi-mod-checkin-row__info">
                            <text class="mi-mod-checkin-row__title">{{ item.title }}</text>
                            <text class="mi-mod-checkin-row__time">{{ item.time }} · {{ item.location }}</text>
                        </view>
                        <view class="mi-mod-checkin-row__tag" :class="'mi-mod-checkin-row__tag--' + item.tagTheme">
                            <text class="mi-mod-checkin-row__tag-text">{{ item.tag }}</text>
                        </view>
                    </view>
                    <view v-if="filteredList.length === 0 && !loading" class="bt-empty">
                        <text class="bt-empty__text">暂无签到记录</text>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import PageHeader from '@/components/index/PageHeader.vue'
import { getCheckInRecords } from '@/api/main.js'

const tabs = ref([
    { key: 'all', label: '全部' },
    { key: 'signin', label: '签到' }
])
const activeFilter = ref('all')
const list = ref([])
const loading = ref(false)

const filteredList = computed(() => {
    if (activeFilter.value === 'all') return list.value
    // "签到" tab: 筛选普通签到记录（非团课/私教类）
    if (activeFilter.value === 'signin') {
        return list.value.filter((i) => i.tagTheme === 'default')
    }
    return list.value.filter((i) => i.tagTheme === activeFilter.value)
})

async function fetchCheckInHistory() {
    if (loading.value) return
    loading.value = true
    console.log('[checkInHistory] 开始获取签到记录')
    try {
        const res = await getCheckInRecords({ page: 0, size: 50 })
        console.log('[checkInHistory] getCheckInRecords 返回:', JSON.stringify(res, null, 2))
        const records = res?.data?.content || res?.content || []
        if (Array.isArray(records) && records.length > 0) {
            list.value = records.map((record) => ({
                id: record.id,
                title: record.courseName || record.name || '签到',
                time: formatCheckInTime(record.checkInTime || record.createTime),
                location: record.location || record.address || '',
                tag: record.courseType || record.type || '签到',
                tagTheme: getTagTheme(record.courseType || record.type)
            }))
        } else {
            list.value = []
        }
    } catch (e) {
        console.error('[checkInHistory] 获取签到记录失败:', e)
        list.value = []
    } finally {
        loading.value = false
    }
}

function formatCheckInTime(timeStr) {
    if (!timeStr) return ''
    try {
        const d = new Date(timeStr)
        const month = d.getMonth() + 1
        const day = d.getDate()
        const hour = d.getHours().toString().padStart(2, '0')
        const minute = d.getMinutes().toString().padStart(2, '0')
        return `${month}月${day}日 ${hour}:${minute}`
    } catch {
        return timeStr
    }
}

function getTagTheme(type) {
    if (!type) return 'default'
    const t = type.toLowerCase()
    if (t.includes('团课') || t.includes('group')) return 'primary'
    if (t.includes('私教') || t.includes('personal')) return 'accent'
    if (t.includes('线上') || t.includes('online')) return 'info'
    return 'default'
}

function showDetail(item) {
    uni.showModal({
        title: item.title,
        content: `${item.time}\n${item.location ? '地点：' + item.location + '\n' : ''}类型：${item.tag}`,
        showCancel: false
    })
}

onMounted(() => {
    fetchCheckInHistory()
})
</script>

<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@import '@/common/style/memberInfo/member-info-component-reset.css';
@import '@/common/style/memberInfo/member-info-tap.css';
@import '@/common/style/memberInfo/pages/body-test-common.css';
@import '@/common/style/memberInfo/pages/module-pages-common.css';
</style>
