<template>
  <!-- 优惠券页面 -->
  <view class="page">

    <!-- 主 Tab + 右侧「全部」类型筛选 -->
    <view class="tabs-wrap">
      <view class="tabs-row">
        <view class="tabs-main">
          <view
            v-for="(tab, index) in tabs"
            :key="index"
            :class="['tab-item', { 'tab-item--active': currentTab === index }]"
            @click="handleTabChange(index)"
          >
            {{ tab }}
          </view>
        </view>
        <view class="tabs-trigger-gap" />
        <view class="tabs-trigger" @click="toggleTypePanel">
          <text
            :class="[
              'tabs-trigger__text',
              {
                'tabs-trigger__text--open': typePanelOpen,
                'tabs-trigger__text--filtered': !typePanelOpen && typeFilter !== 'all'
              }
            ]"
          >{{ typeTriggerLabel }}</text>
          <view
            :class="['tabs-trigger__chevron', { 'tabs-trigger__chevron--open': typePanelOpen }]"
          />
        </view>
      </view>
      <view v-if="typePanelOpen" class="type-filter-row">
        <view
          v-for="opt in typeFilterOptions"
          :key="opt.value"
          :class="['type-pill', { 'type-pill--active': typeFilter === opt.value }]"
          @click="selectTypeFilter(opt.value)"
        >
          {{ opt.label }}
        </view>
      </view>
    </view>

    <!-- 列表区域：展开类型筛选时盖半透明遮罩，点击关闭 -->
    <view class="page-body">
      <view v-if="typePanelOpen" class="type-mask" @tap="closeTypePanel" />
      <scroll-view class="content" scroll-y :class="{ 'content--dimmed': typePanelOpen }">
      <view class="coupon-list" v-if="filteredCoupons.length > 0">
        <view v-for="(coupon, index) in filteredCoupons" :key="coupon.id || index"
          :class="['coupon-card', getCouponCardClass(coupon)]">
          <image :src="getFileUrl('img/personal/coupon.png')" mode="widthFix" class="coupon-card-bg"></image>
          <image :src="getFileUrl('img/personal/couponLeft.png')" mode="heightFix" class="coupon-card-bgLeft"></image>
          <view class="coupon-card-content">
            <!-- 左侧金额区域 -->
            <view class="coupon-card__left">
              <view class="amount-wrapper">
                <text class="amount-number">{{ coupon.amount }}</text>
                <text class="amount-unit">{{ coupon.amountUnit || '元' }}</text>
              </view>
              <text class="condition-text">{{ coupon.conditionText || (coupon.minAmount > 0 ? '满' + coupon.minAmount + '可用' : '无门槛') }}</text>
            </view>

            <!-- 右侧信息区域 -->
            <view class="coupon-card__right">
              <view class="coupon-info">
                <text class="coupon-name">{{ coupon.name }}</text>
                <view class="coupon-rules" @click="handleShowRules(coupon)">
                  使用规则
                  <text class="arrow">›</text>
                </view>
                <text class="coupon-expire">{{ coupon.expireDate ? coupon.expireDate + '到期' : '' }}</text>
              </view>
            </view>
          </view>

        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-else>
        <image :src="getFileUrl('img/icon/noCoupon.png')" mode="widthFix" class="empty-icon"></image>
        <text class="empty-text">暂无优惠券</text>
      </view>
      </scroll-view>
    </view>

    <!-- 使用规则弹窗 -->
    <RulesModal v-model:open="showRulesModal" :couponData="selectedCoupon" />
  </view>
</template>

<script setup>
import { onShow } from "@dcloudio/uni-app";
import { ref, computed } from "vue";
import { getFileUrl } from "@/utils/file.js";
import RulesModal from "./components/RulesModal.vue";
import * as diningApi from "@/api/dining.js";

// 标签页：0未使用 1即将过期 2已使用 3已过期
const tabs = ['未使用', '即将过期', '已使用', '已过期'];
const currentTab = ref(0);

/** 右侧：展开折扣券 / 满减券筛选（couponType 1 满减 2 折扣） */
const typePanelOpen = ref(false);
const typeFilter = ref('all');
const typeFilterOptions = [
  { value: 'all', label: '全部' },
  { value: 'discount', label: '折扣券' },
  { value: 'reduction', label: '满减券' }
];

/** 右上角文案与当前选中的券类型一致 */
const typeTriggerLabel = computed(() => {
  const hit = typeFilterOptions.find((o) => o.value === typeFilter.value);
  return hit?.label ?? '全部';
});

function toggleTypePanel() {
  typePanelOpen.value = !typePanelOpen.value;
}

function closeTypePanel() {
  typePanelOpen.value = false;
}

function selectTypeFilter(value) {
  typeFilter.value = value;
  // 仅在「切换券类型」流程中展示选项，选完后收起
  typePanelOpen.value = false;
}

// 弹窗控制
const showRulesModal = ref(false);
const selectedCoupon = ref({
  amount: 0,
  amountUnit: '元',
  minAmount: 0,
  name: '',
  expireDate: '',
  specifiedDay: '',
  supplementaryInstruction: '',
  conditionText: '',
  qrCodeUrl: '',
  verificationCode: ''
});

// 优惠券数据（接口返回）
const couponList = ref([]);
const loading = ref(false);

// 规范化接口返回的优惠券项
function normalizeCouponItem(raw) {
  if (!raw || typeof raw !== 'object') return null;
  const couponType = Number(raw.couponType) ?? 1;
  const nominalValue = Number(raw.nominalValue ?? raw.amount ?? 0) || 0;
  const discountRate = ((Number(raw.discountRate ?? 0) || 0) / 10) || 0;
  const minAmount = Number(raw.minimumSpendingAmount ?? raw.minAmount ?? 0) || 0;
  let amount = nominalValue;
  let amountUnit = '元';
  let conditionText = minAmount > 0 ? `满${minAmount}可用` : '无门槛';
  if (couponType === 2 && discountRate > 0) {
    amount = discountRate;
    amountUnit = '折';
    conditionText = minAmount > 0 ? `满${minAmount}可用` : '无门槛';
  }
  return {
    id: raw.id ?? raw.userCouponId ?? raw.couponId ?? '',
    amount,
    amountUnit,
    minAmount,
    name: raw.name ?? raw.title ?? raw.couponName ?? '',
    expireDate: raw.expirationTime ?? raw.endGetDate ?? raw.expireDate ?? '',
    status: currentTab.value,
    couponType,
    nominalValue,
    discountRate,
    conditionText,
    specifiedDay: raw.specifiedDay ?? raw.validDays ?? '',
    supplementaryInstruction: raw.supplementaryInstruction ?? raw.description ?? '',
    qrCodeUrl: raw.qrCodeUrl ?? raw.qrcodeUrl ?? raw.qrUrl ?? '',
    verificationCode:
      raw.verificationCode ?? raw.verifyCode ?? raw.couponCode ?? raw.pickUpCode ?? ''
  };
}

// 列表：主 Tab 数据 + 类型筛选（全部 / 折扣券 / 满减券）
const filteredCoupons = computed(() => {
  const list = couponList.value;
  const t = typeFilter.value;
  if (t === 'discount') return list.filter((c) => Number(c.couponType) === 2);
  if (t === 'reduction') return list.filter((c) => Number(c.couponType) === 1);
  return list;
});

// 切换标签页
const handleTabChange = (index) => {
  currentTab.value = index;
  typePanelOpen.value = false;
  fetchCouponList();
};

// 拉取优惠券列表（coupon/getUserCouponList）
const fetchCouponList = async () => {
  loading.value = true;
  try {
    const storeId = uni.getStorageSync('currentStoreId') || '';
    const res = await diningApi.GetUserCouponList({ storeId, tabType: currentTab.value, page: 1, size: 20 });
    const list = Array.isArray(res) ? res : (res?.data ?? res?.records ?? res?.list ?? []);
    const arr = Array.isArray(list) ? list : [];
    couponList.value = arr.map(normalizeCouponItem).filter(Boolean);
  } catch (err) {
    console.error('获取优惠券列表失败:', err);
    uni.showToast({ title: '加载失败', icon: 'none' });
    couponList.value = [];
  } finally {
    loading.value = false;
  }
};

// 获取优惠券卡片样式类
const getCouponCardClass = (coupon) => {
  if (coupon?.status === 2) return 'coupon-card--used';
  if (coupon?.status === 3) return 'coupon-card--expired';
  return '';
};

// 查看使用规则
const handleShowRules = (coupon) => {
  selectedCoupon.value = { ...coupon };
  showRulesModal.value = true;
};

// 使用 onShow 拉取数据（onLoad 在 uni-app Vue3 组合式 API 下可能不触发，onShow 更可靠）
onShow(() => {
  fetchCouponList();
});
</script>

<style lang="scss" scoped>
.page {
  height: 100vh;
  min-height: 100vh;
  background: #F5F5F5;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.header {
  background: #FFFFFF;
  padding: 20rpx 30rpx;
  padding-top: calc(20rpx + env(safe-area-inset-top));

  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #151515;
    text-align: center;
  }
}

.tabs-wrap {
  flex-shrink: 0;
  background: #ffffff;
  position: relative;
  z-index: 20;
}

.page-body {
  flex: 1;
  min-height: 0;
  position: relative;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.type-mask {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 10;
  background: rgba(0, 0, 0, 0.45);
}

.tabs-row {
  display: flex;
  flex-direction: row;
  align-items: flex-end;
  padding: 0 24rpx 0 20rpx;
  box-sizing: border-box;
}

.tabs-main {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: row;
  align-items: flex-end;
}

.tabs-trigger-gap {
  flex-shrink: 0;
  width: 24rpx;
}

.tabs-trigger {
  flex-shrink: 0;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-end;
  padding: 28rpx 0 24rpx 8rpx;
  box-sizing: border-box;
}

.tabs-trigger__text {
  font-size: 26rpx;
  color: #151515;
  line-height: 1;
}

.tabs-trigger__text--open {
  color: #f47d1f;
}

/* 已选折扣券/满减券且面板收起时，右上角保持主题色提示当前筛选 */
.tabs-trigger__text--filtered {
  color: #f47d1f;
}

.tabs-trigger__chevron {
  width: 0;
  height: 0;
  margin-left: 8rpx;
  border-left: 8rpx solid transparent;
  border-right: 8rpx solid transparent;
  border-top: 10rpx solid #999999;
  transform: translateY(2rpx);
}

.tabs-trigger__chevron--open {
  border-top: none;
  border-bottom: 10rpx solid #f47d1f;
  border-left: 8rpx solid transparent;
  border-right: 8rpx solid transparent;
  transform: translateY(-2rpx);
}

.type-filter-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  flex-wrap: wrap;
  gap: 16rpx;
  padding: 8rpx 30rpx 20rpx;
  box-sizing: border-box;
  background: #ffffff;
}

.type-pill {
  padding: 14rpx 32rpx;
  border-radius: 999rpx;
  font-size: 24rpx;
  color: #333333;
  background: #f2f3f5;
  line-height: 1.2;
}

.type-pill--active {
  background: #fff4e6;
  color: #f47d1f;
  font-weight: 500;
}

.tab-item {
  flex: 1;
  min-width: 0;
  text-align: center;
  font-size: 26rpx;
  color: #666666;
  padding: 28rpx 4rpx 24rpx;
  position: relative;
  transition: color 0.2s;
  box-sizing: border-box;

  &--active {
    color: #151515;
    font-weight: bold;

    &::after {
      content: '';
      position: absolute;
      bottom: 16rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 48rpx;
      height: 6rpx;
      background: linear-gradient(90deg, #ff8a57 0%, #f47d1f 100%);
      border-radius: 3rpx;
    }
  }
}

.content {
  flex: 1;
  min-height: 0;
  position: relative;
  z-index: 1;
  padding: 24rpx 30rpx;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  box-sizing: border-box;
}

.content--dimmed {
  pointer-events: none;
}

.coupon-list {
  position: relative;

  .coupon-card-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1;
  }

  .coupon-card-bgLeft {
    position: absolute;
    top: 0;
    left: 0;
    width: auto;
    height: 190rpx;
    z-index: 1;
  }

  .coupon-card-content {
    position: relative;
    z-index: 3;
    display: flex;
    align-items: center;
  }

  .coupon-card {
    display: flex;
    align-items: center;
    margin-bottom: 24rpx;
    overflow: hidden;
    position: relative;
    box-sizing: border-box;
    position: relative;
    z-index: 3;

    &:last-child {
      margin-bottom: 0;
    }

    &__left {
      width: 200rpx;
      padding: 32rpx 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

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

        .amount-number {
          font-size: 64rpx;
          font-weight: bold;
          color: #F47D1F;
          line-height: 1;
        }

        .amount-unit {
          font-size: 28rpx;
          color: #F47D1F;
          margin-left: 4rpx;
        }
      }

      .condition-text {
        font-size: 22rpx;
        color: #F47D1F;
      }
    }

    &__divider {
      width: 2rpx;
      height: 100%;
      position: relative;

      .dash-line {
        width: 2rpx;
        height: 100%;
        // background-image: linear-gradient(to bottom, #FFD9C2 0%, #FFD9C2 50%, transparent 50%, transparent 100%);
        background-size: 2rpx 12rpx;
        background-repeat: repeat-y;
      }
    }

    &__right {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 32rpx 24rpx;

      .coupon-info {
        flex: 1;
        display: flex;
        flex-direction: column;

        .coupon-name {
          font-size: 28rpx;
          font-weight: bold;
          color: #151515;
          margin-bottom: 12rpx;
        }

        .coupon-rules {
          font-size: 22rpx;
          color: #999999;
          margin-bottom: 12rpx;
          display: flex;
          align-items: center;

          .arrow {
            font-size: 28rpx;
            margin-left: 4rpx;
          }
        }

        .coupon-expire {
          font-size: 22rpx;
          color: #999999;
        }
      }

    }

    // 已使用状态
    &--used {
      background: #F8F8F8;

      .coupon-card__left {

        .amount-number,
        .amount-unit,
        .condition-text {
          color: #CCCCCC;
        }
      }

      .coupon-card__right {
        .coupon-info {

          .coupon-name,
          .coupon-rules,
          .coupon-expire {
            color: #CCCCCC;
          }
        }
      }
    }

    // 已过期状态
    &--expired {
      background: #F8F8F8;

      .coupon-card__left {

        .amount-number,
        .amount-unit,
        .condition-text {
          color: #CCCCCC;
        }
      }

      .coupon-card__right {
        .coupon-info {

          .coupon-name,
          .coupon-rules,
          .coupon-expire {
            color: #CCCCCC;
          }
        }
      }
    }
  }
}

.hover-active {
  opacity: 0.8;
  transform: scale(0.98);
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 200rpx;

  .empty-icon {
    width: 300rpx;
    height: 280rpx;
    margin-bottom: 40rpx;
  }

  .empty-text {
    font-size: 28rpx;
    color: #AAAAAA;
  }
}
</style>
