<template>
  <div class="x-tabs-list" v-loading="loading">
    <Tabs :value="defaultTab" class="x-tabs-list__tabs" @tab-click="handleTabClick">
      <TabPane v-for="(tab,index) in tabs" v-bind="tab" :key="tab.name||index"></TabPane>
    </Tabs>
    <div class="x-tabs-list__toolbar">
      <slot name="toolbar"></slot>
    </div>
    <div class="x-tabs-list__content" :class="{'is-fixed':fixed}">
      <slot></slot>
    </div>
    <Pagination v-if="pager"
                class="x-tabs-list__pager"
                @current-change="handlePageChange"
                @size-change="handleSizeChange"
                :page-sizes="[10,20,50,100]"
                layout="total, sizes,->, prev, pager, next, jumper"
                background
                v-bind="pager"></Pagination>
  </div>
</template>

<script>
/**
 * 选项卡列表
 * @module XTabsList
 */
import {Tabs, TabPane, Pagination} from 'element-ui';

/**
 * 插槽
 * @member slots
 * @property {string} default 定义列表内容
 * @property {string} toolbar 定义工具栏
 */

export default {
  name: 'XTabsList',
  inheritAttrs: false,
  inject: ['$system'],
  components: {
    Tabs,
    TabPane,
    Pagination
  },
  /**
   * 属性参数
   * @member props
   * @property {array} [tabs] 选项卡数据 [{label,name,lazy, disabled,closable}]
   * @property {string} [defaultTab] 初始显示的选项卡名称
   * @property {object} [pager] 分页配置，参考 el-pagination 组件参数设置，不需要分页设置为null
   * @property {function} [loader] 加载数据回调函数，参数：{tab, page, size}
   */
  props: {
    // [{label,name,lazy, disabled,closable}]
    tabs: {
      type: Array
    },
    defaultTab: {
      type: String
    },
    pager: {
      type: Object
    },
    loader: Function
  },
  data() {
    return {
      tab: null,
      page: 1,
      size: 10,
      loading: false
    };
  },
  computed: {
    fixed() {
      return this.$system?.fixed;
    }
  },
  watch: {
    defaultTab: {
      immediate: true,
      handler(v) {
        this.tab = v || '0';
      }
    },
    pager: {
      immediate: true,
      handler(o) {
        this.page = o.currentPage || 1;
        this.size = o.pageSize || 10;
      }
    }
  },
  methods: {
    handleTabClick(tab) {
      this.tab = tab.name || tab.index;
      this.$emit('change', this.tab, this.page, this.size);
      this.load();
    },
    handlePageChange(page) {
      this.page = page;
      this.$emit('change', this.tab, this.page, this.size);
      this.load();
    },
    handleSizeChange(size) {
      this.size = size;
      this.$emit('change', this.tab, this.page, this.size);
      this.load();
    },
    /**
     * 调用数据加载方法
     * @method load
     */
    load() {
      const {tab, page, size} = this;
      if (this.loader) {
        const promise = this.loader({tab, page, size});
        // 为了兼容
        if (promise.finally) {
          this.loading = true;
          promise.finally(_ => {
            this.loading = false;
          });
        }
      }
    }
  },
  created() {
    this.load();
  }
};
</script>
