﻿<template>
    <view class="member-card-section">
        <view class="member-card-section__inner">
            <!-- 标题栏 -->
            <view class="member-card-section__head">
                <view class="member-card-section__head-inner">
                    <text class="member-card-section__title">我的会员卡</text>
                    <view class="member-card-section__count" v-if="activeCount > 0">
                        <text class="member-card-section__count-num">{{ activeCount }}</text>
                        <text class="member-card-section__count-text">张有效</text>
                    </view>
                </view>
            </view>

            <!-- 三张卡展示 -->
            <view class="card-three-row">
                <!-- 储值卡 -->
                <view
                    class="card-three-item"
                    :class="{ 'card-three-item--inactive': !storedCard.hasCard }"
                    hover-class="mi-tap-card--hover"
                    :hover-stay-time="150"
                    @tap="$emit('stored-card-tap')"
                >
                    <view class="card-three-item__icon-wrap card-three-item__icon-wrap--stored">
                        <uni-icons type="wallet" size="28rpx" :color="storedCard.hasCard ? '#667eea' : '#B0BEC5'" />
                    </view>
                    <text class="card-three-item__label">储值卡</text>
                    <text class="card-three-item__value" v-if="storedCard.hasCard">¥{{ storedCard.balance }}</text>
                    <text class="card-three-item__value card-three-item__value--empty" v-else>未购买</text>
                    <text class="card-three-item__sub" v-if="storedCard.hasCard">余额</text>
                </view>

                <!-- 次数卡 -->
                <view
                    class="card-three-item"
                    :class="{ 'card-three-item--inactive': !countCard.hasCard }"
                >
                    <view class="card-three-item__icon-wrap card-three-item__icon-wrap--count">
                        <uni-icons type="loop" size="28rpx" :color="countCard.hasCard ? '#4CAF50' : '#B0BEC5'" />
                    </view>
                    <text class="card-three-item__label">次数卡</text>
                    <text class="card-three-item__value" v-if="countCard.hasCard">{{ countCard.remainingTimes }}次</text>
                    <text class="card-three-item__value card-three-item__value--empty" v-else>未购买</text>
                    <text class="card-three-item__sub" v-if="countCard.hasCard">剩余</text>
                </view>

                <!-- 时长卡 -->
                <view
                    class="card-three-item"
                    :class="{ 'card-three-item--inactive': !timeCard.hasCard }"
                >
                    <view class="card-three-item__icon-wrap card-three-item__icon-wrap--time">
                        <uni-icons type="calendar" size="28rpx" :color="timeCard.hasCard ? '#FF6B35' : '#B0BEC5'" />
                    </view>
                    <text class="card-three-item__label">时长卡</text>
                    <text class="card-three-item__value" v-if="timeCard.hasCard">{{ timeCard.remainingDays }}天</text>
                    <text class="card-three-item__value card-three-item__value--empty" v-else>未购买</text>
                    <text class="card-three-item__sub" v-if="timeCard.hasCard">剩余</text>
                </view>
            </view>

            <!-- 操作按钮 -->
            <view class="card-actions">
                <view
                    class="card-actions__btn card-actions__btn--primary"
                    hover-class="mi-tap-btn--hover"
                    :hover-stay-time="150"
                    @tap="$emit('view-all')"
                >
                    <text class="card-actions__btn-text">查看卡片</text>
                </view>
                <view
                    class="card-actions__btn card-actions__btn--ghost"
                    hover-class="mi-tap-btn--hover"
                    :hover-stay-time="150"
                    @tap.stop="$emit('purchase')"
                >
                    <text class="card-actions__btn-text card-actions__btn-text--ghost">购买新卡</text>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { getStoredCardInfo, getMyMemberCardsWithStatus } from '@/api/main.js'
import { getMemberId } from '@/utils/request.js'

defineEmits(['view-all', 'purchase', 'stored-card-tap'])

const storedCard = reactive({ hasCard: false, balance: 0 })
const countCard = reactive({ hasCard: false, remainingTimes: 0 })
const timeCard = reactive({ hasCard: false, remainingDays: 0 })
const activeCount = ref(0)
let isLoading = false

async function loadMemberCard() {
    if (isLoading) return
    isLoading = true
    try {
        const memberId = getMemberId()
        if (!memberId) return

        // 并行获取储值卡和所有有效卡
        const [storedRes, activeCardsRes] = await Promise.all([
            getStoredCardInfo(memberId).catch(() => null),
            getMyMemberCardsWithStatus(memberId, 'active').catch(() => null)
        ])

        // 解析储值卡
        if (storedRes) {
            const data = storedRes.data || storedRes.value || storedRes
            if (data && (data.balance > 0 || data.totalAmount > 0 || data.id)) {
                storedCard.hasCard = true
                storedCard.balance = data.balance || data.totalAmount || 0
            }
        }

        // 解析有效卡列表（排除储值卡）
        let allActive = []
        if (activeCardsRes?.value) {
            allActive = activeCardsRes.value
        } else if (Array.isArray(activeCardsRes)) {
            allActive = activeCardsRes
        } else if (activeCardsRes?.data) {
            allActive = Array.isArray(activeCardsRes.data) ? activeCardsRes.data : (activeCardsRes.data.value || [])
        }
        allActive = allActive.filter(card => card.memberCardType !== 'STORED_VALUE_CARD')
        activeCount.value = allActive.length

        // 查找次数卡
        const countCardData = allActive.find(c => c.memberCardType === 'COUNT_CARD')
        if (countCardData) {
            countCard.hasCard = true
            countCard.remainingTimes = countCardData.remainingTimes || countCardData.remainingAmount || 0
        }

        // 查找时长卡（优先找有效期最长的）
        const timeCards = allActive.filter(c => c.memberCardType === 'TIME_CARD')
        if (timeCards.length > 0) {
            timeCard.hasCard = true
            // 计算剩余天数
            let maxDays = 0
            timeCards.forEach(c => {
                if (c.expireTime) {
                    const now = new Date()
                    const expire = new Date(c.expireTime)
                    const days = Math.max(0, Math.ceil((expire - now) / (1000 * 60 * 60 * 24)))
                    if (days > maxDays) maxDays = days
                }
            })
            timeCard.remainingDays = maxDays
        }
    } catch (e) {
        console.error('[MemberInfoMemberCard] 加载失败:', e)
    } finally {
        isLoading = false
    }
}

onMounted(() => {
    loadMemberCard()
})

defineExpose({ loadMemberCard })
</script>

<style lang="scss" scoped>
@import '@/common/style/memberInfo/member-info-component-reset.css';
@import '@/common/style/memberInfo/member-info-tap.css';

// ========== 容器 ==========
.member-card-section {
    width: 100%;
    flex-shrink: 0;
}

.member-card-section__inner {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    width: 100%;
}

// ========== 标题栏 ==========
.member-card-section__head {
    width: 100%;
}

.member-card-section__head-inner {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    width: 100%;
}

.member-card-section__title {
    font-size: var(--font-size-md);
    font-weight: 700;
    color: var(--text-dark);
}

.member-card-section__count {
    display: inline-flex;
    flex-direction: row;
    align-items: center;
    gap: 4rpx;
    padding: 4rpx 14rpx;
    border-radius: 20rpx;
    background: rgba(255, 107, 53, 0.1);
    flex-shrink: 0;
}

.member-card-section__count-num {
    font-size: 26rpx;
    font-weight: 700;
    color: #FF6B35;
    line-height: 1;
}

.member-card-section__count-text {
    font-size: 22rpx;
    font-weight: 400;
    color: #FF6B35;
    line-height: 1;
}

// ========== 三张卡片行 ==========
.card-three-row {
    display: flex;
    gap: 16rpx;
    width: 100%;
}

.card-three-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8rpx;
    padding: 24rpx 12rpx;
    border-radius: 16rpx;
    background: #FFFFFF;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
    transition: all 0.2s;
}

.card-three-item--inactive {
    opacity: 0.55;
    background: #F5F7FA;
    box-shadow: none;
}

.card-three-item__icon-wrap {
    width: 56rpx;
    height: 56rpx;
    border-radius: 28rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.card-three-item__icon-wrap--stored {
    background: rgba(102, 126, 234, 0.1);
}

.card-three-item__icon-wrap--count {
    background: rgba(76, 175, 80, 0.1);
}

.card-three-item__icon-wrap--time {
    background: rgba(255, 107, 53, 0.1);
}

.card-three-item--inactive .card-three-item__icon-wrap {
    background: rgba(0, 0, 0, 0.04);
}

.card-three-item__label {
    font-size: 24rpx;
    font-weight: 500;
    color: #5E6F8D;
}

.card-three-item__value {
    font-size: 26rpx;
    font-weight: 700;
    color: #1E2A3A;
    line-height: 1;
}

.card-three-item__value--empty {
    font-size: 24rpx;
    font-weight: 400;
    color: #B0BEC5;
}

.card-three-item__sub {
    font-size: 20rpx;
    color: #A0AEC0;
}

// ========== 操作按钮 ==========
.card-actions {
    display: flex;
    gap: 16rpx;
    width: 100%;
}

.card-actions__btn {
    flex: 1;
    height: 72rpx;
    border-radius: 36rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.card-actions__btn--primary {
    background: linear-gradient(135deg, #FF6B35, #FF8C5A);
    box-shadow: 0 4rpx 12rpx rgba(255, 107, 53, 0.3);
}

.card-actions__btn--ghost {
    background: #FFFFFF;
    border: 2rpx solid #FF6B35;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

.card-actions__btn-text {
    font-size: 28rpx;
    font-weight: 600;
    color: #FFFFFF;
}

.card-actions__btn-text--ghost {
    color: #FF6B35;
}
</style>
