<template>
  <u-popup v-model="visible" mode="center" :border-radius="16" @close="onClose">
    <view class="coupon-popup">
      <view class="popup-header">
        <text class="title">选择要核销的券</text>
        <u-icon name="close" size="40" @click="close"></u-icon>
      </view>
      <scroll-view scroll-y class="coupon-list" :style="{ maxHeight: '500rpx' }">
        <view
          v-for="(item, index) in itemList"
          :key="index"
          class="coupon-item"
          :class="{ active: selectedIndex === index }"
          @click="onSelect(index)"
        >
          <view class="coupon-title">{{ item.skuTitle || '卡券' }}</view>
          <view v-if="item.vip" class="coupon-vip">{{ item.vip.name }}</view>
        </view>
      </scroll-view>
      <view class="popup-footer">
        <u-button type="primary" @click="onConfirm" :disabled="selectedIndex < 0">
          确定核销
        </u-button>
      </view>
    </view>
  </u-popup>
</template>

<script>
/**
 * 券码选择弹窗
 * 当核销准备接口返回多个券时，让用户选择要核销的券
 */
export default {
  name: 'CouponSelectPopup',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    itemList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      visible: false,
      selectedIndex: -1
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.visible = !!val
        if (val) {
          this.selectedIndex = this.itemList.length === 1 ? 0 : -1
        }
      }
    },
    visible(val) {
      this.$emit('input', val)
    },
    itemList: {
      immediate: true,
      handler(list) {
        if (list && list.length === 1 && this.visible) {
          this.selectedIndex = 0
        }
      }
    }
  },
  methods: {
    close() {
      this.visible = false
    },
    onClose() {
      this.$emit('close')
    },
    onSelect(index) {
      this.selectedIndex = index
    },
    onConfirm() {
      if (this.selectedIndex < 0 || !this.itemList[this.selectedIndex]) {
        this.$u.toast('请选择要核销的券')
        return
      }
      this.$emit('confirm', this.itemList[this.selectedIndex])
      this.close()
    }
  }
}
</script>

<style lang="scss" scoped>
.coupon-popup {
  width: 600rpx;
  padding: 30rpx;
  background: #fff;
  border-radius: 16rpx;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;

  .title {
    font-size: 34rpx;
    font-weight: 600;
    color: #333;
  }
}

.coupon-list {
  margin-bottom: 30rpx;
}

.coupon-item {
  padding: 24rpx;
  margin-bottom: 16rpx;
  background: #f7f8fa;
  border-radius: 12rpx;
  border: 2rpx solid transparent;

  &.active {
    border-color: #3996FD;
    background: #e8f4ff;
  }

  .coupon-title {
    font-size: 30rpx;
    color: #333;
    font-weight: 500;
  }

  .coupon-vip {
    font-size: 24rpx;
    color: #999;
    margin-top: 8rpx;
  }
}

.popup-footer {
  .u-btn {
    width: 100%;
  }
}
</style>
