import Vue from "vue";
import { message } from "ant-design-vue";
import { getRpc } from "ycc-api/dist/cmjs/service/Rpc";
const Rpc = getRpc("/yccApi");
export default Vue.extend({
  data() {
    return {
      maxHeight: 0,
      startHeight: 0,
      endHeight: 0,
      Loading: false,
      Timer: 0,
      pages: {
        currentPage: 1,
        pageSize: 20,
        total: 10,
      },
      Blocks: [] as any[],
    };
  },
  computed: {
    ParallelChain(): any {
      return this.$store.getters.isParallelChain;
    },
  },
  activated() {
    this.getLastBlock();
  },
  mounted() {
    this.getLastBlock();
  },
  methods: {
    getLastBlock() {
      if (this.Loading) return;
      this.Loading = true;
      Rpc.getLastHeader().then((data) => {
        if (data.error === null) {
          if (data.result.height !== this.endHeight) {
            this.maxHeight = data.result.height;
            this.pages.total = this.maxHeight;
            this.getBlocks(this.maxHeight);
            return;
          }
          this.Loading = false;
        } else {
          this.Loading = false;
          message.warning({
            // title: this.$t('components.tip'),
            // message: data.error,
            content: data.error as string,
          });
        }
      });
    },
    pageChange(page: number) {
      clearTimeout(this.Timer);
      this.pages.currentPage = page;
      const newHeight =
        this.maxHeight - (this.pages.currentPage - 1) * this.pages.pageSize;
      this.endHeight = 0;
      this.Blocks = [];
      this.getBlocks(newHeight);
    },
    sizeChange(size: number) {
      this.pages.pageSize = size;
      this.pageChange(1);
    },
    getBlocks(endHeight: number) {
      this.Loading = true;
      // 首次更新
      if (this.endHeight === 0) {
        this.endHeight = endHeight;
        this.startHeight =
          this.endHeight - this.pages.pageSize + 1 > 0
            ? this.endHeight - this.pages.pageSize + 1
            : 0; // 尾页判断
      } else {
        // 非首次请求获取更新的区块
        this.startHeight = this.endHeight + 1;
        this.endHeight = this.maxHeight;
      }

      Rpc.getHeaders(this.startHeight, this.endHeight, false).then((data) => {
        if (data.error === null) {
          const info = data.result.items.reverse();
          if (this.pages.currentPage === 1) {
            this.Blocks = [...info, ...this.Blocks];
            this.Blocks.length = this.pages.pageSize;
          } else {
            this.Blocks = info;
          }
          
          this.Loading = false;
        } else {
          this.Loading = false;
          message.warning({
            content: data.error,
          });
          // this.$notify.warning({
          //   title: this.$t('components.tip'),
          //   message: data.error,
          // })
        }
      });
    },
  },
  beforeDestroy() {
    //清除定时器
    clearTimeout(this.Timer);
  },
});
