<template>
  <div class="gift">
    <view class="gift-nav">
      <view
        v-for="(item, index) in navList"
        :key="index"
        class="gift-nav-item"
        :class="{ current: currentTab === index }"
        @click="handleTabChange(index)"
      >
        {{ item.total ? `${item.title} (${item.total})` : item.title }}
      </view>
    </view>

    <swiper :current="currentTab" class="gift-swiper" duration="300" @change="changeTab">
      <swiper-item v-for="(item, index) in navList" :key="index">
        <view class="gift-swiper-item">
          <scroll-view
            class="gift-list"
            scroll-y
            :show-scrollbar="false"
            :scroll-top="tabScrollTop"
            lower-threshold="50"
            @scrolltolower="pageScroll"
          >
            <template v-if="item.list">
              <template v-for="(listItem, idx) in item.list">
                <gift-card
                  :key="idx"
                  :card-item="listItem"
                  :be-overdue="index === 1"
                  @bind-record-click="onRecordClick"
                />
              </template>
              <uni-load-more v-if="item.list.length" :status="item.loading" />
            </template>
            <empty
              v-if="item.loading === 'noMore' && !item.list.length"
              back-color="transparent"
              text="暂无礼品卡～"
            />
          </scroll-view>
        </view>
      </swiper-item>
    </swiper>
    <uni-popup ref="recordListDialog" type="dialog">
      <uni-popup-dialog title="消费记录" :before-close="true" confirm-txt="知道了" hide-cancel-btn>
        <scroll-view class="expense" scroll-y>
          <view v-for="(item, index) in recordList" :key="index" class="consum-li">
            <view class="li-top flex">
              <view class="li-top-order">
                <text class="order-label"
                  >{{ item.ioType == 6 ? "退款" : "订单" }}:{{ item.orderNo }}</text
                >
                <text class="order-copy" @click="copyOrderNo(item.orderNo)">复制</text>
              </view>
              <template v-if="item.ioType == 1 || item.ioType == 4">
                <text class="order-price-red">-{{ item.usedAmount }}</text>
              </template>
              <template v-else>
                <text class="order-price-green">+{{ item.usedAmount }}</text>
              </template>
            </view>
            <view class="li-bottom flex">
              <text class="order-time">{{ item.createdAt }}</text>
              <text class="order-surplus">余{{ item.remainAmount }}</text>
            </view>
          </view>
        </scroll-view>
      </uni-popup-dialog>
    </uni-popup>
  </div>
</template>
<script>
import { getGiftCardList } from "@/api/coupon.api.js";
import uniPopup from "@/components/uni-popup/uni-popup";
import uniPopupDialog from "@/components/uni-popup/uni-popup-dialog";
import giftCard from "@/components/giftCard.vue";
import empty from "@/components/empty";
import { getConsumptions } from "@/api/member.api";
import { debounce } from "@/utils";
const commonParams = {
  loading: false,
  finished: false,
  total: 0,
  page: 1,
  pageSize: 50,
  list: []
};
export default {
  name: "GiftCardList",
  components: {
    giftCard,
    empty,
    uniPopup,
    uniPopupDialog
  },
  data() {
    return {
      recordList: [],
      consumptionList: [],
      sharePicData: {},
      currentTab: 0,
      navList: [
        {
          status: 2,
          title: "可使用",
          ...JSON.parse(JSON.stringify(commonParams))
        },
        {
          status: 1,
          title: "不可用",
          ...JSON.parse(JSON.stringify(commonParams))
        }
      ],
      currentOrder: {}
    };
  },
  onLoad({ status }) {
    status && (this.currentTab = Number(status));
    this.getList();
  },
  methods: {
    // 复制
    copyOrderNo(orderNo) {
      uni.setClipboardData({
        data: orderNo,
        success: () => {
          /* #ifdef MP-ALIPAY */
          uni.showToast({
            title: "复制成功",
            icon: "none"
          });
          /* #endif */
        }
      });
    },
    handleTabChange(index) {
      this.currentTab = index;
      this.changeTab();
    },
    pageScroll() {
      if (!this.navList[this.currentTab].finished) {
        this.getList();
      }
    },

    changeTab: debounce(function(e) {
      if (e) {
        const index = e.detail.current;
        this.currentTab = index;
      }
      this.getList();
    }, 100),

    setNavListData(key, val) {
      this.$set(this.navList[this.currentTab], key, val);
    },
    async onRecordClick(item) {
      if (!item || !item.id) {
        uni.showToast({
          title: "暂无此卡消费记录！",
          icon: "none"
        });
      }
      const params = {
        pageNo: 1,
        pageSize: 300,
        userCardId: item.id
      };
      const [res] = await getConsumptions(params);
      this.recordList = res.dataList || [];
      if (this.recordList?.length) {
        this.$refs.recordListDialog.open();
      } else {
        uni.showToast({
          title: "暂无此卡消费记录！",
          icon: "none"
        });
      }
    },
    async getList() {
      let { finished, page, pageSize, list, status } = this.navList[this.currentTab];
      if (finished) return;
      this.setNavListData("loading", "loading");
      const [res] = await getGiftCardList({
        pageNo: page,
        pageSize,
        queryStatus: status
      });
      if (res) {
        list = [...list, ...(res.currentStatusData.dataList || [])];
        this.setNavListData("list", list);
        this.setNavListData("total", res.currentStatusData.totalCount);
        this.$set(this.navList[this.currentTab === 0 ? 1 : 0], "total", res.mutexStautsCount);
        if (!res.currentStatusData.hasNext) {
          this.setNavListData("finished", true);
          this.setNavListData("loading", "noMore");
        } else {
          page++;
          this.setNavListData("loading", "more");
          this.setNavListData("page", page);
        }
        return;
      }
      this.setNavListData("loading", "noMore");
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/style/var.scss";
.gift {
  background: $page-color-base;
  height: 100vh;
  &-swiper {
    height: calc(100% - 80rpx);
    &-item {
      height: 100%;
      padding-top: 10rpx;
      box-sizing: border-box;
      ::v-deep .gift-card {
        margin: 0 20rpx 20rpx;
      }
    }
  }

  .gift-list {
    height: 100%;
    padding: 0 $padding-md;
  }
  &-nav {
    display: flex;
    height: 80rpx;
    &-item {
      position: relative;
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
      font-size: 26rpx;
      color: #333333;
      &.current {
        color: #ec1500;
        font-weight: bold;
        &:after {
          content: "";
          position: absolute;
          left: 50%;
          bottom: 0;
          transform: translateX(-50%);
          width: 80rpx;
          height: 0;
          border-bottom: 6rpx solid #ec1500;
          border-radius: 3rpx;
        }
      }
    }
  }
}
.flex {
  display: flex;
  justify-content: space-between;
}
.expense {
  overflow-y: auto;
  width: 622rpx;
  height: 624rpx;
  margin-top: 26rpx;
  .consum-li {
    margin-bottom: 24rpx;
    @include text-size(28);
    .li-bottom {
      color: $gray-4;
      padding-top: 20rpx;
    }
    .order-copy {
      @include text-size(22);
      display: inline-block;
      width: 62rpx;
      height: 32rpx;
      line-height: 32rpx;
      text-align: center;
      background: #f7f8fa;
      border-radius: 12rpx;
      margin-left: 4rpx;
    }
    .order-label {
      color: #323233;
    }
    .order-price-red {
      color: $red;
    }
    .order-price-green {
      color: #07c160;
    }
  }
}
</style>
