<template>
  <Loading :loading="loading">
    <div :class="_class">
      <div
        :class="_fixedClass"
        v-if="fixed"
      >
        <div
          :class="_fixedHeaderClass"
          ref="theadCenter"
          :style="{marginBottom: - scrollWidth +'px'}"
        >
          <THead
            :columns="columns"
            :indeterminate="indeterminate"
            :all-value="allValue"
            :selector="selector"
            :scroll-width="scrollWidth"
            :width="dataNow.length != 0 ? width : 0"
            :fixed="fixed"
          />
        </div>
        <div
          :class="_fixedBodyClass"
          ref="tbodyCenter"
          :style="{height:height + 'px'}"
          @mousemove="moveScroll('tbodyCenter')"
          @scroll="onScrollCol"
          @mousewheel="onScrollCol"
        >
          <TBody
            :columns="columns"
            :scroll-width="scrollWidth"
            :width="width"
            :data-now="dataNow"
            :expand-index="expandIndex"
            :select-value-list="selectValueList"
            :selector="selector"
            :empty-text="emptyText"
            :row-key="rowKey"
            ref="tbody"
          />
        </div>
        <div
          v-if="dataNow != 0"
          :class="[_fixedLeftClass,{ 'hive-table-fixed-left-shabow' : leftShabow }]"
          ref="theadLeft"
        >
          <div
            :class="_fixedHeaderClass"
            :style="{marginBottom: - scrollWidth +'px',marginRight: - scrollWidth +'px'}"
          >
            <THead
              :columns="fixedLeftHead"
              :indeterminate="indeterminate"
              :all-value="allValue"
              :selector="selector"
              :scroll-width="scrollWidth"
              :fixed="fixed"
            />
          </div>
          <div
            :class="_fixedBodyClass"
            ref="tbodyLeft"
            @mousemove="moveScroll('tbodyLeft')"
            @scroll="onScrollCol"
            @mousewheel="onScrollCol"
            :style="{paddingBottom: scrollWidth +'px',marginBottom: - scrollWidth +'px',marginRight:height ? - scrollWidth +'px' : 'auto',height:height + 'px'}"
          >
            <TBody
              :columns="fixedLeftHead"
              :scroll-width="scrollWidth"
              :data-now="dataNow"
              :expand-index="expandIndex"
              :select-value-list="selectValueList"
              :selector="selector"
              :empty-text="emptyText"
              :row-key="rowKey"
            />
          </div>
        </div>
        <div
          v-if="dataNow.length != 0"
          :class="[_fixedRightClass,{ 'hive-table-fixed-right-shabow' : rightShabow }]"
          ref="theadRight"
        >
          <div
            :class="_fixedHeaderClass"
            :style="{marginBottom: - scrollWidth +'px',marginRight: - scrollWidth +'px'}"
          >
            <THead
              :columns="fixedRightHead"
              :indeterminate="indeterminate"
              :all-value="allValue"
              :selector="selector"
              :scroll-width="scrollWidth"
              :fixed="fixed"
            />
          </div>
          <div
            :class="_fixedBodyClass"
            ref="tbodyRight"
            @mousemove="moveScroll('tbodyRight')"
            @scroll="onScrollCol"
            @mousewheel="onScrollCol"
            :style="{marginBottom: - scrollWidth +'px',paddingBottom: scrollWidth +'px',height:height + 'px'}"
          >
            <TBody
              :columns="fixedRightHead"
              :scroll-width="scrollWidth"
              :data-now="dataNow"
              :expand-index="expandIndex"
              :select-value-list="selectValueList"
              :selector="selector"
              :empty-text="emptyText"
              :row-key="rowKey"
            />
          </div>
        </div>
      </div>
      <div v-else>
        <THead
          :columns="columns"
          :indeterminate="indeterminate"
          :all-value="allValue"
          :selector="selector"
          :scroll-width="scrollWidth"
          :width="width"
          ref="thead"
          @onChange="checkAll"
          @click="sortColumn"
          :item-width="itemWidth"
          :fixed="fixed"
        />
        <TBody
          :columns="columns"
          :scroll-width="scrollWidth"
          :width="width"
          :data-now="dataNow"
          :expand-index="expandIndex"
          :select-value-list="selectValueList"
          :selector="selector"
          :empty-text="emptyText"
          :indeterminate="indeterminate"
          :all-value="allValue"
          @onChange="selectRow"
          @itemWidth="setWidth"
          :row-key="rowKey"
          ref="tbody"
        />
      </div>
      <div
        :class="_pageClass"
        v-if="pagination"
      >
        <Pagination
          v-bind="pagination"
          @change="changePage"
          @pageSizeChange="changePageSize"
        />
      </div>
    </div>
  </Loading>
</template>

<script>
/*
 * import RenderCell from '../render-cell';
 * import ExpandCell from './expand-cell';
 */
import Pagination from '../pagination';
/*
 * import Icon from '../icon';
 * import Checkbox from '../checkbox';
 */
import Loading from '../loading';

import THead from './table-head';
import TBody from './table-body';

const name = 'hive-table';

export default {
  name,
  components: {
    /*
     * RenderCell,
     * ExpandCell,
     */
    Pagination,
    /*
     * Icon,
     * Checkbox,
     */
    Loading,
    THead,
    TBody
  },
  props: {
    /**
     * 列信息配置
     */
    columns: {
      type: Array,
      default() {
        return [];
      }
    },
    /**
     * 数据列表
     */
    data: {
      type: Array,
      default() {
        return [];
      }
    },
    /**
     * 无数据提醒
     */
    emptyText: {
      type: String,
      default: '暂无数据'
    },
    /**
     * 可选择
     *
     */
    selector: Array,
    /**
     * 分页设置
     */
    pagination: {
      type: [Boolean, Object],
      default() {
        return {
          total: this.data.length,
          pageSizeOption: [10, 20, 30]
        };
      }
    },
    /**
     * 是否启用固定表头以及固定列功能，固定列需要设置表格宽度
     */
    fixed: Boolean,
    /**
     * 表格的行 key 参数名
     */
    rowKey: {
      type: String,
      default: 'id'
    },
    /**
     * 表格宽度
     */
    width: Number,
    /**
     * 表格高度
     */
    height: Number,
    /**
     *是否加载中
     */
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dataNow: [],
      pageSize: this.pagination
        ? this.pagination.pageSizeOption[0]
        : this.data.length,
      pageNow: 1,
      toSorter: '',
      dataValue: this.data,
      sortType: [],
      // 折叠展开的行
      expandIndex: [],
      // 当前折叠状态，true：折叠
      expandTypeValue: true,
      indeterminate: false,
      // 可选择时是否全选
      allValue: false,
      // 可选择时当前页状态
      selectValueList: [],
      // 可选择时所有数据状态
      selectValueAll: [],
      // 可选择时选中项
      selectList: this.selector ? this.selector : '',
      onChangeSelect: this.selector ? this.selector.onChange : '',
      // 左浮动列
      fixedLeftHead: this.columns.filter(item => item.fixed === 'left'),
      // 右浮动列
      fixedRightHead: this.columns.filter(item => item.fixed === 'right'),
      // 横向滚动条
      scrollLeftCol: 0,
      // 纵向滚动条
      scrollTopRow: 0,
      // 滚动条宽度
      scrollWidth: 0,
      // 右边阴影
      rightShabow: true,
      // 左边阴影
      leftShabow: false,
      // 每列宽度
      itemWidth: [],
      // 固定左侧列宽度
      widthLeft: -1,
      // 固定右侧列宽
      widthRight: -1,
      bodyScroll: {},
      leftScroll: {},
      rightScroll: {},
      // 当前滚动操作的部分
      scrollName: ''
    };
  },
  computed: {
    _class() {
      return [name];
    },
    _pageClass() {
      return `${name}_page`;
    },
    _fixedClass() {
      return `${name}-fixed`;
    },
    _fixedHeaderClass() {
      return `${name}-fixed-head`;
    },
    _fixedBodyClass() {
      return `${name}-fixed-body`;
    },
    _fixedLeftClass() {
      return `${name}-fixed-left`;
    },
    _fixedRightClass() {
      return `${name}-fixed-right`;
    }
  },
  watch: {
    pageSize(value) {
      this.changePage(this.pageNow);
      this.seTable();
    },
    dataValue() {
      this.changePage(this.pageNow);
    },
    selector(value) {
      this.selectValueAll = [];
      for (let i = 0; i < this.data.length; i++) {
        this.selectValueAll.push(false);
      }
      this.selectList = value;
      for (let i = 0; i < value.length; i++) {
        this.selectValueAll[value[i]] = true;
      }

      for (
        let i = (this.pageNow - 1) * this.pageSize;
        i < this.pageSize * this.pageNow;
        i++
      ) {
        if (this.selectValueAll[i] === true) {
          this.selectValueList.splice(i % this.pageSize, 1, true);
        } else {
          this.selectValueList.splice(i % this.pageSize, 1, false);
        }
      }
      let select = new Set(this.selectValueList);
      if (select.size === 1 && select.has(true)) {
        this.allValue = true;
      } else {
        this.allValue = false;
      }
      if (select.size > 1) {
        this.indeterminate = true;
      } else {
        this.indeterminate = false;
      }
    }
  },
  mounted() {
    const dataValue = this.data.concat();

    this.dataNow = dataValue
      .splice(this.pageSize * 0, this.pageSize * 1)
      .concat();
    this.sortType = this.data.concat();
    if (this.selector) {
      this.columns.unshift(0);
      for (let i = 0; i < this.data.length; i++) {
        this.selectValueAll.push(false);
      }
      for (let i = 0; i < this.pageSize; i++) {
        this.selectValueList.push(false);
      }
    }

    // 滚动条高度
    this.getScrollWidth();

    // 初始化列宽行高
    this.seTable();
  },
  methods: {
    changePage(value) {
      const dataValue = this.dataValue.concat();
      this.dataNow = [];
      this.pageNow = value;
      this.dataNow = dataValue
        .splice(this.pageSize * (value - 1), this.pageSize)
        .concat();
      if (this.selector) {
        this.allValue = false;
        this.selectValueList = [];
        let nowPageList = this.selectValueAll.slice(
          (this.pageNow - 1) * this.pageSize,
          this.pageNow * this.pageSize
        );
        this.selectValueList = nowPageList.concat();
        let select = new Set(this.selectValueList);
        if (select.size === 1 && select.has(true)) {
          this.allValue = true;
        } else {
          this.allValue = false;
        }
        if (select.size > 1) {
          this.indeterminate = true;
        } else {
          this.indeterminate = false;
        }
      }
      this.seTable();
    },
    changePageSize(value) {
      this.pageSize = value;
      this.seTable();
    },
    sortColumn(column, num, sort) {
      if (!column.sorter) {
        return '';
      }
      this.dataValue = this.sortType.concat();
      if (column.order === 'desc') {
        if (sort === 'desc') {
          this.dataValue.sort(column.sorter);
        } else if (sort === 'asc') {
          this.dataValue.sort(column.sorter).reverse();
        }
      } else {
        if (sort === 'desc') {
          this.dataValue.sort(column.sorter).reverse();
        } else if (sort === 'asc') {
          this.dataValue.sort(column.sorter);
        }
      }
    },

    checkAll(value) {
      let selectNum = new Set(this.selectList);
      this.allValue = !!value;
      this.selectValueList = [];
      this.indeterminate = false;
      if (this.allValue) {
        for (let i = 0; i < this.dataNow.length; i++) {
          this.selectValueList.push(true);
          selectNum.add((this.pageNow - 1) * this.pageSize + i);
          this.selectValueAll.splice(
            (this.pageNow - 1) * this.pageSize + i,
            1,
            true
          );
        }
      } else {
        for (let i = 0; i < this.dataNow.length; i++) {
          this.selectValueList.push(false);
          selectNum.delete((this.pageNow - 1) * this.pageSize + i);
          this.selectValueAll.splice(
            (this.pageNow - 1) * this.pageSize + i,
            1,
            false
          );
        }
      }
      this.selectList = [...selectNum].sort(function(a, b) {
        return a - b;
      });
      /**
       * 当前选中的行号
       */
      this.$emit('onChange', this.selectList);
    },

    setWidth(width) {
      this.itemWidth = width;
    },

    selectRow(list) {
      let selectNum = new Set(
        this.selectList.map(function(value, index) {
          if (value === true) {
            return index;
          }
        })
      );
      for (
        let i = (this.pageNow - 1) * this.pageSize;
        i < this.pageNow * this.pageSize;
        i++
      ) {
        if (list[i % this.pageSize] === true) {
          this.selectValueAll[i] = true;
          selectNum.add(i);
        } else {
          this.selectValueAll[i] = false;
          selectNum.delete(i);
        }
      }
      let select = new Set(this.selectValueList);
      if (select.size > 1) {
        this.indeterminate = true;
        this.allValue = false;
      } else {
        this.indeterminate = false;
        if (select.has(true)) {
          this.allValue = true;
        }
      }
      let selectNumAll = new Set(
        this.selectValueAll.map(function(value, index) {
          if (value === true) {
            return index;
          }
        })
      );
      this.selectList = [...selectNumAll].sort(function(a, b) {
        return a - b;
      });
      this.$emit('onChange', this.selectList);
    },

    moveScroll(name) {
      this.scrollName = name;
    },

    onScrollBorder(center) {
      let scrollHeightCol = center.scrollWidth - center.offsetWidth;
      if (center.scrollLeft > 0) {
        this.leftShabow = true;
      } else {
        this.leftShabow = false;
      }
      if (center.scrollLeft < scrollHeightCol) {
        this.rightShabow = true;
      } else {
        this.rightShabow = false;
      }
    },
    onScrollCol(e) {
      this.$nextTick(() => {
        let center = this.$refs.tbodyCenter;
        let centerHead = this.$refs.theadCenter;
        let right = this.$refs.tbodyRight;
        let left = this.$refs.tbodyLeft;
        if (this.scrollName === 'tbodyCenter') {
          if (right) {
            right.scrollTop = center.scrollTop;
            right.scrollLeft = center.scrollLeft;
          }
          if (left) {
            left.scrollTop = center.scrollTop;
            left.scrollLeft = center.scrollLeft;
          }
          centerHead.scrollLeft = center.scrollLeft;
          this.onScrollBorder(center);
        } else if (this.scrollName === 'tbodyLeft') {
          right.scrollTop = left.scrollTop;
          center.scrollTop = left.scrollTop;
        } else {
          left.scrollTop = right.scrollTop;
          center.scrollTop = right.scrollTop;
        }
      });
    },

    // 获取滚动条大小
    getScrollWidth() {
      const oDiv = document.createElement('DIV');
      oDiv.style.cssText =
        'position:absolute; top:-1000px; width:100px; height:100px; overflow:hidden;';
      const noScroll = document.body.appendChild(oDiv).clientWidth;
      oDiv.style.overflowY = 'scroll';
      const scroll = oDiv.clientWidth;
      document.body.removeChild(oDiv);
      this.scrollWidth = noScroll - scroll;
      return this.scrollWidth;
    },
    seTable() {
      this.$nextTick(() => {
        let dom = document.querySelectorAll(
          '.hive-table-fixed > .hive-table-fixed-body'
        );
        let domFixed = {};
        let domRight = {};
        let domLeft = {};
        for (let i = 0; i < dom.length; i++) {
          let head = dom[i].previousElementSibling;
          let headTd = head.querySelectorAll('th');
          let domTd = dom[i].querySelector('tr').querySelectorAll('td');
          let domTr = dom[i].querySelectorAll('tr');

          if (dom[i].nextElementSibling != null) {
            domFixed = dom[i].nextElementSibling;
            if (domFixed.nextElementSibling) {
              domRight = domFixed.nextElementSibling.querySelectorAll(
                '.hive-table-fixed-body tr'
              );
            }
            if (domFixed.className.indexOf('hive-table-fixed-right') !== -1) {
              domRight = domFixed.querySelectorAll('.hive-table-fixed-body tr');
            }
            for (let k = 0; k < domRight.length; k++) {
              domRight[k].style.height = domTr[k].offsetHeight + 'px';
            }
            if (domFixed.className.indexOf('hive-table-fixed-left') !== -1) {
              domLeft = domFixed.querySelectorAll('.hive-table-fixed-body tr');
            }
            for (let k = 0; k < domLeft.length; k++) {
              domLeft[k].style.height = domTr[k].offsetHeight + 'px';
            }
          }
          for (let j = 0; j < domTd.length; j++) {
            headTd[j].style.width = domTd[j].offsetWidth + 'px';
          }
        }

        // 每列宽度
        let width = [];
        let length = this.$refs.tbody.$refs.tbody[0].children.length;
        for (let i = 0; i < length; i++) {
          width.push(this.$refs.tbody.$refs.tbody[0].children[i].offsetWidth);
        }
        if (this.dataNow.length) {
        }
        this.itemWidth = width;
      });
    }
  }
};
</script>
