<!-- 优惠券中心  -->
<template>
  <s-layout title="我的商品券" :bgStyle="{ color: '#f2f2f2' }">
    <su-sticky bgColor="#fff">
      <su-tabs
        :list="tabMaps"
        :scrollable="false"
        @change="onTabsChange"
        :current="state.currentTab"
      ></su-tabs>
    </su-sticky>
    <s-empty
      v-if="state.pagination.total === 0"
      icon="/static/coupon-empty.png"
      text="暂无优惠券"
    ></s-empty>
    <view v-for="item in state.pagination.data" :key="item.id">
        <s-coupon-list
          :data="item"
          type="user"
          @tap="
            sheep.$router.go('/pages/coupon/detail', {
              id: item.coupon_id,
              user_coupon_id: item.id,
            })
          "
        >
          <template #default>
            <button
              class="ss-reset-button card-btn ss-flex ss-row-center ss-col-center"
              v-if="item.status !== 'expired'"
              :class="
                item.status == 'can_get' || item.status == 'can_use'
                  ? ''
                  : item.status == 'used' || item.status == 'expired'
                  ? 'disabled-btn'
                  : 'border-btn'
              "
              :disabled="item.status != 'can_get' && item.status != 'can_use'"
              @click.stop="
                sheep.$router.go('/pages/coupon/detail', {
                  id: item.coupon_id,
                  user_coupon_id: item.id,
                })
              "
            >
              {{ item.status_text }}
            </button>
            <image src="/static/expired.png" v-else class="expired-image"/>
          </template>
        </s-coupon-list>
      </view>

    <uni-load-more
      v-if="state.pagination.total > 0"
      :status="state.loadStatus"
      :content-text="{
        contentdown: '上拉加载更多',
      }"
      @tap="loadmore"
    />
    <s-coupon-choose :show="state.show" :dataList="state.dataList" :level="state.level" @get="getProgramIds"></s-coupon-choose>
  </s-layout>
</template>

<script setup>
  import sheep from '@/sheep';
  import { onLoad, onReachBottom } from '@dcloudio/uni-app';
  import { computed, reactive } from 'vue';
  import _ from 'lodash';

  // 数据
  const pagination = {
    data: [],
    current_page: 1,
    total: 1,
    last_page: 1,
  };

  const state = reactive({
    currentTab: 0,
    pagination: {
      data: [],
      current_page: 1,
      total: 1,
      last_page: 1,
    },
    loadStatus: '',
    type: '',
    dataList: [{
      type: '方案一',
      key: 'programme_1',
      typeList: []
    }, {
      type: '方案二',
      key: 'programme_2',
      typeList: []
    }],
    show: false,
    level: '',
  });
  const tabMaps = [   
    {
      name: '已领取',
      value: 'geted',
    },
    {
      name: '已使用',
      value: 'used',
    },
    {
      name: '已失效',
      value: 'expired',
    },
  ];
  function onTabsChange(e) {
    state.pagination = pagination;
    state.currentTab = e.index;
    state.type = e.value;
    getCoupon();
  }
  async function getData(page = 1, list_rows = 5) {
    state.loadStatus = 'loading';
    const res = await sheep.$api.coupon.list({ list_rows, page });
    if (res.code === 1) {
      let couponlist = _.concat(state.pagination.data, res.data.data);
      state.pagination = {
        ...res.data,
        data: couponlist,
      };
      if (state.pagination.current_page < state.pagination.last_page) {
        state.loadStatus = 'more';
      } else {
        state.loadStatus = 'noMore';
      }
    }
  }
  async function getCoupon(page = 1, list_rows = 5) {
    state.loadStatus = 'loading';
    let res = await sheep.$api.coupon.userCoupon({
      type: state.type,
      list_rows,
      page,
    });
    if (res.code === 1) {
      let couponlist = _.concat(state.pagination.data, res.data.data);
      state.pagination = {
        ...res.data,
        data: couponlist,
      };
      if (state.pagination.current_page < state.pagination.last_page) {
        state.loadStatus = 'more';
      } else {
        state.loadStatus = 'noMore';
      }
    }
  }
  async function getBuy(id) {
    const { code, msg } = await sheep.$api.coupon.get(id);
    if (code === 1) {
      uni.showToast({
        title: msg,
      });
      setTimeout(() => {
        state.pagination = pagination;
        getData();
      }, 1000);
    }
  }
  async function commissionCouponList() {
    const { code, data, msg } = await sheep.$api.coupon.commissionCouponList();
    if (code === 1 && data && `${data.is_get}` === '0' && `${data.level}` !== '1') {
      state.dataList.forEach((item) => {
        item.typeList = data[item.key].map(val => ({ name: val.name, time: `${val.get_start_time}~${val.get_end_time}`, id: val.id }))
      });
      state.show = true;
      state.level = data.level_name;
    } else {
      getCoupon();
    }
  }
  // 加载更多
  function loadmore() {
    if (state.loadStatus !== 'noMore') {
      if (state.currentTab == 0) {
        getData(state.pagination.current_page + 1);
      } else {
        getCoupon(state.pagination.current_page + 1);
      }
    }
  }
  async function getProgramIds(key) {
    const { typeList } = state.dataList.find((val) => val.key === key);
    const { code, data, msg } = await sheep.$api.coupon.getIds(typeList.map(val => (val.id)).join());
    state.show = false;
    if (code !== 1) {
      sheep.$helper.toast(msg);
    }
    setTimeout(() => {
      getCoupon();
    }, 500)
  }
  onLoad((Option) => {
    state.type = Option.type;
    Option.type === 'geted'
        ? (state.currentTab = 0)
        : Option.type === 'used'
        ? (state.currentTab = 1)
        : (state.currentTab = 2);
    commissionCouponList();
  });
  onReachBottom(() => {
    loadmore();
  });
</script>
<style lang="scss" scoped>
  .card-btn {
    // width: 144rpx;
    padding: 0 16rpx;
    height: 50rpx;
    border-radius: 40rpx;
    background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main));
    color: #ffffff;
    font-size: 24rpx;
    font-weight: 400;
  }
  .border-btn {
    background: linear-gradient(90deg, var(--ui-BG-Main-opacity-4), var(--ui-BG-Main-light));
    color: #fff !important;
  }
  .disabled-btn {
    background: #cccccc;
    background-color: #cccccc !important;
    color: #fff !important;
  }
  .expired-image {
   width: 84rpx;
   height: 84rpx; 
   margin-top: -10rpx;
   margin-left: -120rpx;
  }
</style>
