<template>
  <BasicModal type="bottom" v-model:open="getOpen" :isMack="true">
    <view class="select-coupon-modal">
      <!-- 顶部标题栏 -->
      <view class="select-coupon-modal__header">
        <text class="header-title">优惠券</text>
        <view class="header-close" @click="handleClose">
          <image :src="getFileUrl('img/icon/close.png')" mode="aspectFill" class="close-icon"></image>
        </view>
      </view>

      <!-- 优惠券列表：仅查看模式下不展示选中态、点击不触发选择 -->
      <scroll-view class="select-coupon-modal__list" scroll-y v-if="couponList.length > 0">
        <view 
          v-for="(coupon, index) in couponList" 
          :key="coupon.id || index" 
          class="coupon-card"
          :class="{ 'coupon-card--view-only': viewOnly }"
          @click="handleCardClick(coupon, index)"
        >
          <!-- 左侧金额信息：数字大号，“元/折”小号 -->
          <view class="coupon-card__left">
            <view class="amount-row">
              <text class="amount-num">{{ amountNum(coupon) }}</text>
              <text class="amount-unit">{{ amountUnit(coupon) }}</text>
            </view>
            <text class="condition-text">{{ (coupon.minAmount && Number(coupon.minAmount) > 0) ? ('满' + coupon.minAmount + '可用') : '无门槛' }}</text>
          </view>

          <!-- 中间信息 -->
          <view class="coupon-card__center">
            <text class="name-text">{{ coupon.name }}</text>
            <text class="expire-text">{{ formatExpireDate(coupon.expireDate) }}到期</text>
          </view>

          <!-- 右侧单选（仅在选择模式下显示） -->
          <view class="coupon-card__right" v-if="!viewOnly">
            <image :src="getFileUrl('img/icon/sele1.png')" mode="widthFix" class="selected-icon" v-show="!isSelected(coupon)"></image>
            <image :src="getFileUrl('img/icon/sele2.png')" mode="widthFix" class="selected-icon" v-show="isSelected(coupon)"></image>
          </view>
        </view>
      </scroll-view>
      <!-- 无数据时显示 -->
      <view class="select-coupon-modal__empty" v-else>
        <text class="empty-text">您可以去应用市场下载U店在哪APP领取优惠劵</text>
      </view>
    </view>
  </BasicModal>
</template>

<script setup>
import { computed, ref } from 'vue';
import BasicModal from '@/components/Modal/BasicModal.vue';
import { getFileUrl } from '@/utils/file.js';

const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  couponList: {
    type: Array,
    default: () => []
  },
  selectedCouponId: {
    type: [Number, String],
    default: null
  },
  // 仅查看模式：来自左下角优惠券入口，只展示列表，不可选择
  viewOnly: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:open', 'select', 'close']);

const getOpen = computed({
  get: () => props.open,
  set: (val) => emit('update:open', val)
});

// 格式化到期日期
const formatExpireDate = (date) => {
  if (!date) return '';
  // 如果是字符串格式的日期，转换为 YYYY/MM/DD 格式
  if (typeof date === 'string') {
    const d = new Date(date);
    if (!isNaN(d.getTime())) {
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}/${month}/${day}`;
    }
    // 如果已经是 YYYY/MM/DD 格式，直接返回
    if (date.includes('/')) {
      return date;
    }
  }
  return date;
};

// 金额数字部分（用于与“元/折”分开展示，单位用小字号）
const amountNum = (coupon) => {
  const str = coupon.amountDisplay || (coupon.amount + '元');
  return str.length > 0 ? str.slice(0, -1) : '';
};
const amountUnit = (coupon) => {
  const str = coupon.amountDisplay || (coupon.amount + '元');
  return str.length > 0 ? str.slice(-1) : '元';
};

// 判断优惠券是否被选中（统一转字符串比较，避免 number/string 不一致）
const isSelected = (coupon) => {
  if (props.selectedCouponId == null || props.selectedCouponId === '') return false;
  return String(coupon.id) === String(props.selectedCouponId);
};

// 卡片点击：仅查看模式下不触发选择；否则按单选逻辑
const handleCardClick = (coupon, index) => {
  if (props.viewOnly) return;
  const newSelectedId = isSelected(coupon) ? null : coupon.id;
  emit('select', { coupon, index, selectedId: newSelectedId });
};

// 处理关闭
const handleClose = () => {
  getOpen.value = false;
  emit('close');
};
</script>

<style scoped lang="scss">
.select-coupon-modal {
  width: 100%;
  background: #F2F4F8;
  border-radius: 24rpx 24rpx 0 0;
  padding: 0;
  box-sizing: border-box;
  height: 55vh;
  max-height: 88vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  &__header {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 88rpx;
    background: #F2F4F8;

    .header-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #151515;
    }

    .header-close {
      position: absolute;
      right: 30rpx;
      top: 50%;
      transform: translateY(-50%);
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      .close-icon {
        width: 26rpx;
        height: 26rpx;
      }
    }
  }

  &__list {
    flex: 1;
    padding: 24rpx 30rpx;
    padding-bottom: calc(140rpx + env(safe-area-inset-bottom));
    box-sizing: border-box;
    overflow-y: auto;
    min-height: 400rpx;
  }

  &__empty {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 80rpx 30rpx;
    min-height: 400rpx;
    background: transparent;
    margin: 24rpx 30rpx 100rpx 30rpx;
    box-sizing: border-box;

    .empty-text {
      font-size: 30rpx;
      color: #666666;
    }
  }
}

.coupon-card {
  height: 191rpx;
  background: #FFFFFF;
//   border: 1rpx solid #E5E5E5;
  display: flex;
  align-items: center;
  border-radius: 24rpx;
  padding: 28rpx 24rpx;
  margin-bottom: 22rpx;
  box-sizing: border-box;
  transition: all 0.3s;

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

  &:active {
    opacity: 0.8;
  }

  &--view-only:active {
    opacity: 1;
  }

  &__left {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-right: 24rpx;
    min-width: 120rpx;
    text-align: center;

    .amount-row {
      display: flex;
      align-items: baseline;
      justify-content: center;
      margin-bottom: 8rpx;
    }
    .amount-num {
      font-size: 50rpx;
      font-weight: 600;
      color: #F47D1F;
      line-height: 1.2;
    }
    .amount-unit {
      font-size: 28rpx;
      font-weight: 500;
      color: #F47D1F;
      margin-left: 2rpx;
    }

    .condition-text {
      font-size: 24rpx;
      color: #F47D1F;
      line-height: 1.2;
    }
  }

  &__center {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    margin-right: 20rpx;

    .name-text {
      font-size: 28rpx;
      color: #151515;
      font-weight: bold;
      line-height: 1.4;
      margin-bottom: 8rpx;
    }

    .expire-text {
      font-size: 22rpx;
      color: #666666;
      line-height: 1.4;
      margin-top: 20rpx;
    }
  }

  &__right {
    display: flex;
    align-items: center;
    justify-content: center;
    min-width: 60rpx;

    .selected-icon {
      width: 38rpx;
      height: 38rpx;
    }

  }
}
</style>

