<template>
  <div>
    <search v-model="query"></search>
    <pass-list-table
        class="list-table"
        :pass-list="passList"
        @nextPage="nextPage"
        @update="updateSinglePass" />
  </div>
</template>

<script>
import Search from "../newProductList/Search";
import PassListTable from "./PassListTable";
import {GO_URLS} from "../../config/URLS";

export default {
  name: "PassList.vue",
  data() {
    return {
      query: {
        // 查询通证列表的查询条件
        type: 0,
        identifier: '',
        amount_sort: 0
      },
      page: 1,
      page_size: 50,
      passList: [], // 查询到的通证列表
      total: 0
    }
  },
  components: {
    Search,
    PassListTable
  },
  mounted() {
    this.getList(true);
  },
  watch: {
    query: {
      handler() {
        this.getList(true);
      },
      deep: true
    }
  },
  methods: {
    /**
     * @param refresh 当查询条件改变时传入整个列表刷新，否则查询数据添加到 passList
     */
    async getList(refresh) {
      if (refresh) {
        this.page = 1;
      }
      const params = Object.assign(
          {},
          this.query,
          {
            page: this.page,
            page_size: this.page_size
          }
      )
      if (params.identifier === '') delete params.identifier;
      const res = await this.$ajax({
        type: "get",
        url: GO_URLS.passList,
        params
      });
      this.total = res.data.total;
      if (refresh) {
        this.passList = res.data.results || [];
      } else {
        this.passList = this.passList.concat(res.data.results);
      }
    },
    /**
     * 滚动加载通证列表
     */
    async nextPage() {
      if (this.total > this.page * this.page_size) {
        this.page += 1;
        await this.getList(false);
      }
    },
    async updateSinglePass(id, balance) {
      let times = 5;
      let i = setInterval(async () => {
        times -= 1;
        const res = await this.$ajax({
          type: 'get',
          url: GO_URLS.pass,
          params: {
            id
          }
        })
        if (res.data.balance !== balance || times <= 0) {
          this.passList.forEach((item, index) => {
            if (item.id === id) {
              this.$set(this.passList[index], 'balance', res.data.balance);
            }
          })
          clearInterval(i);
        }
      }, 1000 * 5)
    }
  },


}
</script>

<style scoped lang="less">
.list-table {
  margin-top: 21px;
}

</style>
