<template>
  <view class="coupon-center">
    <view class="tabs">
      <view
        v-for="tab in tabs"
        :key="tab.value"
        class="tab-item"
        :class="{ active: currentTab === tab.value }"
        @tap="switchTab(tab.value)"
      >
        {{ tab.label }}
      </view>
    </view>

    <view class="coupon-list">
      <view v-if="loading" class="loading">加载中...</view>
      <view v-else-if="list.length === 0" class="empty">暂无优惠券</view>
      <view v-else>
        <view
          v-for="item in list"
          :key="item.id"
          class="coupon-item"
          :class="{ disabled: item.remainCount === 0 }"
        >
          <view class="coupon-left">
            <view class="amount">
              <text class="symbol">¥</text>
              <text class="value">{{ formatAmount(item) }}</text>
            </view>
            <view class="condition">{{ formatCondition(item) }}</view>
          </view>
          <view class="coupon-right">
            <view class="name">{{ item.name }}</view>
            <view class="date">{{ item.startDate }} ~ {{ item.endDate }}</view>
            <view class="scope">{{ formatScope(item) }}</view>
            <view class="stock">剩余 {{ item.remainCount }}</view>
            <button
              class="claim-btn"
              :disabled="item.remainCount === 0"
              @tap="handleClaim(item.id)"
            >
              {{ item.remainCount === 0 ? '已抢光' : '立即领取' }}
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getAvailableCoupons, claimCoupon } from '@/api/coupon';

const tabs = [
  { label: '全部', value: 'all' },
  { label: '满减券', value: 'fixed' },
  { label: '折扣券', value: 'percent' },
];

const currentTab = ref('all');
const list = ref<any[]>([]);
const loading = ref(false);

onMounted(() => {
  fetchList();
});

const switchTab = (tab: string) => {
  currentTab.value = tab;
  fetchList();
};

const fetchList = async () => {
  loading.value = true;
  try {
    const res: any = await getAvailableCoupons();
    console.log('优惠券中心原始数据:', res);
    // 处理响应结构：res.data.list 是真正的数据数组
    let data = res.data?.list || [];
    console.log('解析后的数据:', data);

    if (currentTab.value !== 'all') {
      data = data.filter((item: any) => item.type === currentTab.value);
    }

    list.value = data;
    console.log('最终显示的数据:', list.value);
  } catch (e: any) {
    console.error('加载失败:', e);
    uni.showToast({ title: e.message || '加载失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

const formatAmount = (item: any) => {
  if (item.type === 'fixed') {
    return item.value;
  }
  return `${item.value / 10}折`;
};

const formatCondition = (item: any) => {
  if (item.minAmount > 0) {
    return `满${item.minAmount}元可用`;
  }
  return '无门槛';
};

const formatScope = (item: any) => {
  const scopeMap: Record<string, string> = {
    platform: '平台通用',
    merchant: '指定商家',
    room: '指定房源',
  };
  return scopeMap[item.scope] || item.scope;
};

const handleClaim = async (couponId: number) => {
  try {
    await claimCoupon(couponId);
    uni.showToast({ title: '领取成功', icon: 'success' });
    fetchList();
  } catch (e: any) {
    uni.showToast({ title: e.message || '领取失败', icon: 'none' });
  }
};
</script>

<style scoped lang="scss">
.coupon-center {
  min-height: 100vh;
  background: #f5f5f5;
}

.tabs {
  display: flex;
  background: #fff;
  padding: 0 32rpx;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 32rpx 0;
  font-size: 28rpx;
  color: #666;
  position: relative;

  &.active {
    color: #1890ff;
    font-weight: bold;

    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 60rpx;
      height: 4rpx;
      background: #1890ff;
      border-radius: 2rpx;
    }
  }
}

.coupon-list {
  padding: 24rpx 32rpx;
}

.loading,
.empty {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
  font-size: 28rpx;
}

.coupon-item {
  display: flex;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  overflow: hidden;
  position: relative;

  &.disabled {
    opacity: 0.5;
  }
}

.coupon-left {
  width: 200rpx;
  padding: 32rpx 24rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #fff;
  border-right: 2rpx dashed rgba(255, 255, 255, 0.3);
}

.amount {
  display: flex;
  align-items: baseline;
  margin-bottom: 8rpx;
}

.symbol {
  font-size: 32rpx;
  font-weight: bold;
}

.value {
  font-size: 56rpx;
  font-weight: bold;
}

.condition {
  font-size: 24rpx;
  opacity: 0.9;
}

.coupon-right {
  flex: 1;
  padding: 24rpx;
  color: #fff;
  position: relative;
}

.name {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 12rpx;
}

.date,
.scope,
.stock {
  font-size: 24rpx;
  opacity: 0.9;
  margin-bottom: 8rpx;
}

.claim-btn {
  position: absolute;
  right: 24rpx;
  bottom: 24rpx;
  padding: 12rpx 32rpx;
  background: rgba(255, 255, 255, 0.9);
  color: #667eea;
  border-radius: 32rpx;
  font-size: 24rpx;
  font-weight: bold;
  border: none;

  &:disabled {
    background: rgba(255, 255, 255, 0.5);
    color: #999;
  }
}
</style>
