<template>
  <uni-popup type='bottom' ref='popupRef' :is-mask-click='false'>
    <view class='popup-content c-flex-column'>
      <view class='c-flex-row'>
        <text>优惠券</text>
        <text @click.stop='confirm'>确定</text>
      </view>

      <scroll-view scroll-y>
        <coupon-item v-for='(item,index) in coupons' :item='item' :key='index' @confirm='confirmItem(index)' />
      </scroll-view>
    </view>
  </uni-popup>
</template>

<script lang='ts' setup>
import CouponItem from '../components/coupon-item.vue';
import { getCompanyId } from '@/utils';
import { getCouponList } from '@/api/user';
import { CouponBean } from '@/api/user/types';
import { useUserStore } from '@/store';

const popupRef = ref();

const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);

const props = defineProps({
  orderPrice: {
    type: Number,
    default: 0
  }
});
const emits = defineEmits(['confirm']);
const coupons = ref<CouponBean[]>([]);

const fetchData = async (status: number) => {
  const { list } = await getCouponList({
    companyId: getCompanyId(),
    memberId: userInfo.value?.id,
    status: status,
    pageNum: 1,
    pageSize: 100
  });
  list.filter((item: CouponBean) => item.status = (props.orderPrice >= item.threshold) ? 0 : 1);
  coupons.value = list;
};

const show = () => {
  popupRef.value.open();
  fetchData(0);
};

const confirmItem = (index: number) => {
  coupons.value.forEach(item => {
    item.checked = false;
  });
  coupons.value[index].checked = !coupons.value[index].checked;
};


const confirm = () => {
  close();
  emits('confirm', coupons.value.filter(item => item.checked)[0]);
};

const close = () => {
  popupRef.value.close();
};

defineExpose({
  show
});
</script>

<style lang='scss' scoped>
.popup-content {
  background: #FFFFFF;
  border-radius: 20rpx 20rpx 0 0;
  padding: 38rpx 45rpx 10rpx 45rpx;

  view:nth-of-type(1) {
    display: flex;
    margin-bottom: 70rpx;
    position: relative;

    text:nth-of-type(1) {
      font-weight: bold;
      font-size: 30rpx;
      color: #333333;
      position: absolute;
      left: 0;
      right: 0;
      text-align: center;
    }

    text:nth-of-type(2) {
      font-weight: bold;
      font-size: 30rpx;
      color: #F32B2B;
      position: absolute;
      right: 0;
    }
  }

  scroll-view {
    max-height: 600rpx;
  }

}
</style>
