<template>
  <view class="container">
    <Header title="我的券"></Header>
    <view class="tab">
      <view
        :class="currentTab == index ? 'tab-select' : 'tab-item'"
        @click="changeTab(index)"
        v-for="(item, index) in tabList"
        :key="index"
      >
        {{ item }}
      </view>
    </view>
    <view class="content">
      <view class="card">
        <text class="text">已领取优惠金额（元）</text>
        <text class="price">{{ discountAmount }}</text>
      </view>

      <!-- 优惠券状态 -->
      <view class="status">
        <view
          :class="currenStatus == index ? 'status-select' : 'status-item'"
          @click="changeStatus(index)"
          v-for="(item, index) in statusList"
          :key="index"
        >
          {{ item }}
        </view>
      </view>

      <!-- 优惠券列表 -->
      <view class="ticket-list" v-if="couponData.length">
        <view class="ticket-item" v-for="(item, index) in couponData" :key="index">
          <view class="ticket-box">
            <view class="ticket-left" :class="item.status == 0 ? 'past' : 'normal'">
              <view class="ticket-box">
                <view class="ticket-price">
                  <text class="price">￥</text>
                  <text class="num">{{ item.reduceAmount }}</text>
                </view>
                <view class="ticket-desc">
                  <text class="desc">满{{ item.cashCondition }}元可用</text>
                  <!-- <text class="desc">数量：{{ item.maxNum }}</text> -->
                </view>
              </view>
            </view>

            <view class="ticket-right">
              <image
                class="img"
                :src="iconUrl[item.status]"
                v-if="item.status == 0 || item.status == 2"
              ></image>
              <view class="head">
                <text class="title">{{ item.couponName }}</text>
                <view class="headbox">
                  <text class="time">
                    使用时间：{{ item.userStartTime.slice(0, 10) }}-{{
                      item.userEndTime.slice(0, 10)
                    }}
                  </text>
                  <view class="btn" @tap="toShop(item.shopId)" v-if="item.status == 3">使用</view>
                </view>
              </view>
              <view class="foot">
                <view class="line"></view>
                <view class="footbox" @click="handleChangeDetail(index)">
                  <text class="desc">详细信息</text>
                  <wd-icon
                    :name="item.showDetail ? 'chevron-down' : 'chevron-right'"
                    size="15px"
                    color="#9d9d9d"
                  ></wd-icon>
                </view>
              </view>
            </view>
          </view>

          <view class="detail" v-if="item.showDetail">
            <view class="line"></view>
            <view class="detail-box">
              <view class="rowbox">
                <text>使用时间</text>
                <text class="desc">
                  {{ item.userStartTime.slice(0, 10) }}-{{ item.userEndTime.slice(0, 10) }}
                </text>
              </view>
              <view class="rowbox">
                <text>使用条件</text>
                <text class="desc">满{{ item.cashCondition }}元可用</text>
              </view>
              <view class="rowbox">
                <text>使用说明</text>
                <text class="desc">
                  {{ item.couponExplain }}
                </text>
              </view>
            </view>
          </view>
        </view>
        <!-- <wd-loadmore :state="state" @reload="getCouponList" /> -->
        <view
          style="
            width: 100%;
            text-align: center;
            font-size: 24rpx;
            margin-top: 10rpx;
            color: #888989;
          "
          v-if="isEnd"
        >
          没有更多啦~
        </view>
      </view>
      <wd-status-tip image="content" tip="暂无优惠券" v-else />
    </view>
  </view>
</template>

<script setup>
import { myCouponListApi, userCouponStatisticsApi } from '@/api/ticket';
import Header from '@/pages/order/components/Header/index.vue';

const fileDomain = import.meta.env.VITE_APP_IMG_URL;

// 优惠券状态 0:失效 2:已使用,3-未使用
const iconUrl = ref({
  0: '@/static/ticket/past-icon.png',
  2: '@/static/ticket/used-icon.png',
});

// 主状态
const tabList = ['有效优惠券', '无效优惠券'];
const currentTab = ref(0);

const changeTab = (index) => {
  if (currentTab.value !== index) {
    currentTab.value = parseInt(index);
    initCouponList().then(() => {
      getStatistics();
      getCouponList();
    });
  }
};

// 子状态
const statusList = ['全部', '已使用', '未使用'];
const currenStatus = ref(0);

const changeStatus = (index) => {
  if (currenStatus.value !== index) {
    currenStatus.value = index;
    initCouponList().then(() => {
      getStatistics();
      getCouponList();
    });
  }
};

/**
 * 获取用户统计列表
 */
const discountAmount = ref(0.0);
const getStatistics = async () => {
  const params = {
    statuMain: currentTab.value,
    statuSon: currenStatus.value,
  };
  const res = await userCouponStatisticsApi(params);
  if (res.code === 0) {
    discountAmount.value = res.data;
  }
};
getStatistics();

/**
 * 获取用户优惠券列表
 */
const isEnd = ref(false);
const state = ref('loading');
const total = ref(0);
const couponData = ref([]);
const catalog = reactive({
  current: 0,
  size: 10,
  statuMain: 0,
  statuSon: 0,
});
const getCouponList = async () => {
  // if (isEnd.value) return;
  catalog.current++;
  state.value = 'loading';
  catalog.statuMain = currentTab.value;
  catalog.statuSon = currenStatus.value;
  console.log(catalog);
  xma.showLoading({
    title: '加载中...',
    mask: true,
  });
  const res = await myCouponListApi(catalog);
  if (res.data.records.length < catalog.size) {
    isEnd.value = true;
  }
  if (res.data.records.length > 0) {
    res.data.records.forEach((item) => {
      item.showDetail = false;
    });
    couponData.value.push(...res.data.records);
    total.value = res.data.total;
  }
  // state.value = 'finished';
  xma.hideLoading();
};
getCouponList();

// 下拉刷新
onPullDownRefresh(() => {
  getStatistics();
  initCouponList().then(() => {
    getCouponList();
    xma.stopPullDownRefresh();
  });
});

// 触底函数
onReachBottom(() => {
  if (couponData.value.length >= total.value) {
    isEnd.value = true;
    // state.value = 'finished';
  } else {
    getCouponList();
  }
});

const initCouponList = () => {
  return new Promise((resolve, reject) => {
    couponData.value = [];
    total.value = 0;
    catalog.current = 0;
    resolve();
  });
};

/**
 * 修改优惠券详情显示状态
 */
const handleChangeDetail = (idx) => {
  couponData.value[idx].showDetail = !couponData.value[idx].showDetail;
};

const toShop = (idx) => {
  xma.navigateTo({
    url: `/pages/shop/shop?shopId=${idx}`,
  });
};
</script>

<style scoped lang="scss">
page {
  background: #f3f3f3;
}

.container {
  width: 375 * 2rpx;
  margin: 0 auto;

  // 标签栏
  .tab {
    display: flex;
    align-items: center;
    justify-content: space-around;
    height: 88rpx;
    background: #fff;
    width: 100%;
    position: fixed;
    top: 88rpx;
    z-index: 999;

    .tab-item {
      font-family: PingFang SC;
      font-weight: bold;
      font-size: 32rpx;
      color: #999;
    }

    .tab-select {
      font-family: PingFang SC;
      font-weight: bold;
      font-size: 32rpx;
      color: #333;
      position: relative;

      &::after {
        content: '';
        width: 36rpx;
        height: 16rpx;
        background: url('../../static/ticket/tab.png') no-repeat;
        background-size: 100% 100%;
        position: absolute;
        bottom: -16rpx;
        left: 50%;
        transform: translate(-50%);
      }
    }
  }

  .content {
    display: flex;
    flex-direction: column;
    padding: 202rpx 26rpx 26rpx;
    gap: 36rpx;

    .card {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 38rpx;
      width: 100%;
      height: 216rpx;
      border-radius: 16rpx;
      background: linear-gradient(270deg, #fc7859 0%, #f22424 100%);

      .text {
        padding-top: 26rpx;
        font-family: PingFang SC;
        font-size: 24rpx;
        color: #ffffff;
      }

      .price {
        font-family: PingFang SC;
        font-weight: bold;
        font-size: 36rpx;
        color: #ffffff;
      }
    }

    .status {
      display: flex;
      flex-direction: row;
      align-items: center;
      gap: 18rpx;

      .status-item {
        width: 132rpx;
        height: 56rpx;
        background-color: #fff;
        border-radius: 28rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-family: PingFang SC;
        font-weight: bold;
        font-size: 24rpx;
        color: #666;
      }

      .status-select {
        width: 132rpx;
        height: 56rpx;
        background-color: #fff;
        border-radius: 28rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-family: PingFang SC;
        font-weight: bold;
        font-size: 24rpx;
        color: #f12a2a;
      }
    }

    .ticket-list {
      display: flex;
      flex-direction: column;
      gap: 36rpx;

      .ticket-item {
        width: 100%;
        background-color: #fff;
        border-radius: 16rpx;
        display: flex;
        flex-direction: column;

        .ticket-box {
          display: flex;

          .normal {
            background: url('../../static/ticket/ticket-normal.png') no-repeat;
            background-size: 100% 100%;
          }

          .past {
            background: url('../../static/ticket/ticket-past.png') no-repeat;
            background-size: 100% 100%;
          }

          .ticket-left {
            width: 200rpx;
            height: 200rpx;

            .ticket-box {
              width: 94%;
              height: 100%;
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              gap: 30rpx;

              .ticket-price {
                display: flex;
                align-items: last baseline;

                text {
                  font-size: 24rpx;
                  line-height: 24rpx;
                  font-family: PingFang SC;
                  color: #fff;
                }

                .num {
                  font-size: 52rpx;
                }
              }

              .ticket-desc {
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 24rpx;

                .desc {
                  font-size: 24rpx;
                  line-height: 24rpx;
                  font-family: PingFang SC;
                  color: #fff;
                }
              }
            }
          }

          .ticket-right {
            display: flex;
            flex-direction: column;
            width: 504rpx;
            position: relative;

            .img {
              width: 126rpx;
              height: 94rpx;
              position: absolute;
              right: 28rpx;
              top: 26rpx;
            }

            .head {
              display: flex;
              flex-direction: column;
              padding: 30rpx 22rpx 26rpx 32rpx;
              gap: 4rpx;

              .title {
                font-family: PingFang SC Heavy-Regular;
                font-size: 32rpx;
                color: #333333;
                line-height: 32rpx;
              }

              .headbox {
                display: flex;
                justify-content: space-between;
                align-items: end;
                height: 50rpx;

                .time {
                  font-family: PingFang SC Heavy-Regular;
                  font-size: 20rpx;
                  color: #999999;
                  line-height: 20rpx;
                }

                .btn {
                  width: 102rpx;
                  height: 50rpx;
                  box-sizing: border-box;
                  border-radius: 26rpx;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  background: linear-gradient(90deg, #ff7051 0%, #ff382e 100%);
                  color: #fff;
                  font-size: 24rpx;
                  line-height: 24rpx;
                }
              }
            }

            .foot {
              display: flex;
              flex-direction: column;
              padding: 0 22rpx 14rpx 32rpx;
              gap: 14rpx;

              .line {
                border-top: 2rpx solid #f2f2f2;
              }

              .footbox {
                display: flex;
                align-items: center;
                justify-content: space-between;

                .desc {
                  font-family: PingFang SC Heavy-Regular;
                  font-size: 20rpx;
                  color: #999999;
                  line-height: 20rpx;
                }
              }
            }
          }
        }

        .detail {
          display: flex;
          flex-direction: column;
          padding: 24rpx 0rpx 56rpx 0rpx;
          gap: 30rpx;

          .line {
            border-top: 2rpx solid #e7e7e7;
          }

          .detail-box {
            display: flex;
            flex-direction: column;
            gap: 40rpx;
            padding: 0 40rpx 0 22rpx;

            .rowbox {
              display: flex;
              flex-direction: row;
              gap: 48rpx;

              text {
                font-family: PingFang SC Regular;
                font-size: 28rpx;
                color: #666666;
                line-height: 28rpx;
              }

              .desc {
                width: 476rpx;
              }
            }
          }
        }
      }

      .coupon-tips {
        width: 100%;
        background-color: #fff;
        border-radius: 16rpx;
        display: flex;
        flex-direction: column;
        padding: 40rpx 46rpx 40rpx;
        // min-height: 436rpx;
        box-sizing: border-box;
        gap: 38rpx;

        .tips {
          font-family: PingFang SC Bold-Regular;
          font-size: 32rpx;
          color: #333333;
          line-height: 32rpx;
          text-align: center;
        }

        .desc {
          white-space: pre-line;
          /* 将空格和换行符保留在文本中 */
          font-family: PingFang SC Regular;
          font-size: 24rpx;
          color: #333333;
          line-height: 36rpx;
          text-align: left;
        }
      }
    }
  }
}
</style>
