<template>
  <div>
    <!-- 统计 -->
    <el-tag
      class="com-table__tip"
      v-if="vaildData(tableOption.tip, config.tip) && tableOption.selection"
    >
      <span class="com-table__tip-name">
        {{ '当前表格已选择' }}
        <span class="com-table__tip-count">{{ selectLen }}</span>
        {{ '项' }}
      </span>
      <el-button
        type="text"
        size="small"
        @click="clearSelection"
        v-if="vaildData(tableOption.selectClearBtn, config.selectClearBtn) && tableOption.selection"
      >
        {{ '清 空' }}
      </el-button>
    </el-tag>
    <!-- 表格主体 -->
    <el-table
      :key="reload"
      :data="list"
      :row-key="vaildData(tableOption.rowKey, config.rowKey)"
      @current-change="currentRowChange"
      @row-click="rowClick"
      :height="tableHeight"
      ref="table"
      v-loading="tableLoading"
      @selection-change="selectionChange"
      @select="select"
      @select-all="selectAll"
    >
      <template slot="empty">
        <slot name="empty" v-if="$slots.empty"></slot>
        <el-empty
          v-else
          :image-size="100"
          :description="tableOption.emptyText || '暂无数据'"
        ></el-empty>
      </template>
      <column :columnOption="columnOption">
        <column-default ref="columnDefault" slot="header">
          <template slot-scope="{ row, index }" slot="expand">
            <slot :row="row" :index="index" name="expand"></slot>
          </template>
        </column-default>
        <template v-for="item in mainSlot" slot-scope="scope" :slot="item">
          <slot v-bind="scope" :name="item"></slot>
        </template>
        <column-menu slot="footer">
          <template slot="menu" slot-scope="scope">
            <slot name="menu" v-bind="scope"></slot>
          </template>
        </column-menu>
      </column>
    </el-table>
    <!-- 分页 -->
    <table-page ref="tablePage"></table-page>
  </div>
</template>
<script>
import init from '../../utils/init.js';
import tablePage from './table-page';
import column from './column';
import columnMenu from './column-menu';
import columnDefault from './column-default';
import config from './config.js';
import { getColumn } from '../../utils/util.js';
import sortable from 'sortablejs';

export default {
  name: 'comTable',
  mixins: [init()],
  provide() {
    return {
      comTable: this,
    };
  },
  components: {
    column, // 数据列
    columnDefault, // 其它列,
    columnMenu, // 操作栏，
    tablePage, // 分页
  },
  data() {
    return {
      reload: Math.random(),
      config: config,
      list: [],
      listError: {},
      tableHeight: undefined,
      tableIndex: -1,
      tableSelect: [],
      sumsList: {},
      btnDisabledList: {},
      btnDisabled: false,
      default: {},
    };
  },
  created() {},
  mounted() {
    this.dataInit();
    // this.getTableHeight();
    this.refreshTable();
  },
  computed: {
    rowKey() {
      return this.tableOption.rowKey;
    },
    tableColumnName() {
      return 'elTableColumn';
    },
    isRowSort() {
      return this.tableOption.rowSort;
    },
    isAutoHeight() {
      return this.tableOption.height === 'auto';
    },
    mainSlot() {
      let result = [];

      this.propOption.forEach(item => {
        if (this.$scopedSlots[item.prop]) result.push(item.prop);
      });

      return result;
    },
    calcHeight() {
      return this.tableOption.calcHeight || 0;
    },
    propOption() {
      let result = [];
      function findProp(list = []) {
        if (!Array.isArray(list)) return;
        list.forEach(ele => {
          if (Array.isArray(ele.children)) findProp(ele.children);
          else result.push(ele);
        });
      }
      findProp(this.columnOption);
      return result;
    },
    columnOption() {
      let tableOption = this.deepClone(this.tableOption);
      return getColumn(tableOption.column);
    },
    selectLen() {
      return this.tableSelect ? this.tableSelect.length : 0;
    },
  },
  watch: {
    data: {
      handler() {
        this.dataInit();
      },
      deep: true,
    },
  },
  props: {
    value: {
      type: Object,
      default: () => {
        return {};
      },
    },
    page: {
      type: Object,
      default() {
        return {};
      },
    },
    tableLoading: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Array,
      required: true,
      default: () => {
        return [];
      },
    },
  },
  methods: {
    // 计算表格高度
    getTableHeight() {
      if (this.isAutoHeight) {
        this.$nextTick(() => {
          const tableRef = this.$refs.table;
          const tablePageRef = this.$refs.tablePage;
          if (!tableRef) return;
          const tableStyle = tableRef.$el;
          const pageStyle = tablePageRef.$el.offsetHeight || 20;
          this.tableHeight =
            document.documentElement.clientHeight -
            tableStyle.offsetTop -
            pageStyle -
            this.calcHeight;
        });
      } else {
        this.tableHeight = this.tableOption.height;
      }
    },
    // 刷新表格
    refreshTable(callback) {
      console.log('refreshTable');
      this.reload = Math.random();
      this.$nextTick(() => {
        callback && callback();
      });
    },
    // 清除多选
    clearSelection() {
      console.log('clearSelection');
      this.$emit('selection-clear', this.deepClone(this.tableSelect));
      this.$refs.table.clearSelection();
    },
    // 初始化
    dataInit() {
      console.log('dataInit');
      this.list = this.data;
      this.list.forEach((ele, index) => {
        this.$set(ele, '$index', index);
      });
    },
    //设置单选
    currentRowChange(currentRow, oldCurrentRow) {
      console.log('currentRowChange');
      this.$emit('current-row-change', currentRow, oldCurrentRow);
    },
    // 选择回调
    selectionChange(val) {
      console.log('selectionChange');
      this.tableSelect = val;
      this.$emit('selection-change', this.tableSelect);
    },
    // 单个选择回调
    select(selection, row) {
      console.log('select');
      this.$emit('select', selection, row);
    },
    // 点击勾选全选 Checkbox
    selectAll(selection) {
      console.log('selectAll');
      this.$emit('select-all', selection);
    },
    // 行点击
    rowClick(row, event, column) {
      console.log('rowClick');
      this.$emit('row-click', row, event, column);
    },
    // 编辑
    rowEdit(row, index) {
      console.log('rowEdit', row, index);
      this.$emit('row-edit', row, index, () => {});
    },
    // 删除
    rowDel(row, index) {
      console.log('rowDel', row, index);
      this.$emit('row-del', row, index, () => {});
    },
    // 拖拽
    tableDrop(type, el, callback) {
      console.log('tableDrop');
      if (this.isSortable !== true) {
        if (type == 'row' && !this.isRowSort) {
          return;
        }
      }
      sortable &&
        sortable.create(el, {
          animation: 500,
          delay: 0,
          onEnd: evt => callback(evt),
        });
    },
  },
};
</script>
