<template>
  <div>
    <div class="table-header">
      <template v-for="(item, index) in table._defaultHeader_">
        <el-dropdown
          v-if="item == 'setcol'"
          placement="bottom-end"
          trigger="click"
          :hide-on-click="false"
          :key="index"
        >
          <el-button size="small">列设置</el-button>
          <el-dropdown-menu slot="dropdown" :class="'ex-table-setcol-dropdown'">
            <template v-for="(column, index) in setColumns">
              <el-dropdown-item
                v-if="!column._noset_"
                :key="'setColumns' + index"
              >
                <el-switch
                  v-model="column._hidden_"
                  :active-text="column.label"
                  :active-value="false"
                  :inactive-value="true"
                ></el-switch>
              </el-dropdown-item>
            </template>
          </el-dropdown-menu>
        </el-dropdown>
      </template>
      <slot
        name="table-header"
        :selection="tableSelection"
        :alldata="data"
      ></slot>
    </div>
    <el-table
      ref="elTable"
      :data="data"
      v-bind="table"
      :size="size"
      v-on="$listeners"
      @selection-change="tableSelection = $event"
      :span-method="arraySpanMethod"
      style="width: 100%"
    >
      <template v-for="(column, index) in columns">
        <el-table-column
          align="center"
          v-if="!column._hidden_ && column.type && !column._slot_"
          v-bind="column"
          :key="index"
          width="45px"
        ></el-table-column>
        <el-table-column
          v-else-if="!column._hidden_"
          v-bind="column"
          :key="index"
          show-overflow-tooltip
        >
          <template slot="header" slot-scope="scope">
            <span>{{ column.label }}</span>
            <span
              v-if="column._screen_"
              @click.stop="addConditionItemByCol(column, scope)"
            >
              <i
                v-if="column._screen_tip_ === false"
                :style="isHasScreenColumn(column) ? 'color:#3888e5;' : ''"
                class="el-icon-connection"
              />
              <el-tooltip
                v-else
                class="item"
                :effect="column._screen_tip_effect_ || 'dark'"
                :content="column._screen_tip_ || '筛选'"
                :placement="column._screen_tip_placement_ || 'top'"
              >
                <i
                  :style="isHasScreenColumn(column) ? 'color:#3888e5;' : ''"
                  class="el-icon-connection"
                />
              </el-tooltip>
            </span>
          </template>
          <slot
            v-if="column._slot_"
            slot-scope="scope"
            :name="column._slot_"
            :scope="scope"
          ></slot>
          <template v-else-if="column._render_" slot-scope="scope">
            <ex-slot
              :column="column"
              :render="column._render_"
              :scope="scope"
            ></ex-slot>
          </template>
          <template v-else slot-scope="scope" >
            <span>{{
              column._format_
                ? column._format_(scope.row)
                : getObjPrototype(scope.row, column.prop)
            }}</span>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <!-- <el-pagination
      v-if="page !== false && data && data.length > 0"
      :current-page="page.curr"
      :page-sizes="[10, 20, 50, 100]"
      :total="page.total"
      layout="total, sizes, prev, pager, next, jumper"
      style="text-align: right"
      class="fu-page"
      @current-change="$emit('page-curr-change', $event)"
      @size-change="$emit('page-size-change', $event)"
    />
  -->
    <div
      v-if="page !== false && data && data.length > 0"
      class="Pagination"
      style="text-align: right; margin-top: 10px"
    >
      <el-pagination
        :current-page="page.curr"
        :page-sizes="[15, 50, 100, 500]"
        :page-size="page.size"
        :size="searchSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="$emit('page-size-change', $event)"
        @current-change="$emit('page-curr-change', $event)"
      />
    </div>
  </div>
</template>

<script>
import Sortable from "sortablejs";
export default {
  name: "ex-table",
  components: {
    "ex-slot": {
      functional: true,
      props: {
        render: Function,
        scope: {
          type: Object,
          default: null,
        },
        column: {
          type: Object,
          default: null,
        },
      },
      render: (h, data) => {
        if (data.props.column) data.props.scope.column = data.props.column;
        return data.props.render(h, data.props.scope);
      },
    },
  },
  props: {
    /**
     * el-table 属性集合
     * 自定义属性：
     * @param {Array} _defaultHeader_  : 默认的表格头部，支持['setcol', 'screen'] setcol-列设置 screen-筛选
     * 可使用插槽扩展表格头部：
     * table-header - 具名插槽
     * slotProps：selection - 表格选中的数据  alldata - 表格当前全部数据
     * <template #table-header="slotProps">
     *   <el-button size="small" @click="click(slotProps)">扩展1</el-button>
     * </template>
     */
    table: {
      type: Object,
      default: () => {},
    },
    // el-table 表格数据 对应data字段
    data: {
      type: Array,
      default: () => [],
    },
    /**
     * el-table-column 表格列属性集合
     * 自定义属性：
     * @param {String}       _filter_       : 是否不允许设置列
     * @param {Boolean}       _noset_        : 是否不允许设置列
     * @param {Boolean}        _screen_      : 是否允许筛选
     * @param {Boolean}        _hidden_      : 是否隐藏列
     * @param {String/Boolean} _screen_tip_  : 筛选按钮提示信息，为false不提示
     * @param {String} _screen_tip_effect_   : 筛选按钮提示信息主题，dark/light
     * @param {String} _screen_tip_placement_: 筛选按钮提示信息位置，top/top-start/top-end/bottom/bottom-start/bottom-end/left/left-start/left-end/right/right-start/right-end
     * @param {Array}          _keys_        : 支持的筛选key
     * @param {Array}      _select_options_  : 若需支持包含select的key，value的备选数据，示例：{_select_options_: [{id:'', label:''},...]}
     * @param {Array}  _select_options_end_  : 若需支持包含select的key，value_end的备选数据，默认使用_select_options_，示例：{_select_options_: [{id:'', label:''},...]}
     * @param {Array}          _keys_        : 支持的筛选key
     * @param {String}         _slot_        : 使用具名插槽时的名称
     * @param {Function}       _format_      : 数据格式化函数，支持返回html
     * @param {Function}       _render_      : 自定义列，采用vue中的render函数，示例: { _render_:(h, scope) => { return h(...) } }
     */
    columns: {
      type: Array,
      default: () => [],
    },
    /**
     * el-pagination
     * @param {Boolean} page 是否开启表格分页，若不传或传false则不开启
     * @param {Object} page {
     *   size: '10'
     *   total: '100'
     *   curr: '1'
     * }
     * Event:
     * page-curr-change  分页当前页改变
     * page-size-change  分页大小改变
     */
    page: {
      type: [Boolean, Object],
      default: false,
    },
    /**
     * 筛选条件集合
     */
    conditions: {
      type: Array,
      default: () => [],
    },
    /**
     * 是否允许拖拽行
     */
    isRowDrop: {
      type: Boolean,
      default: false,
    },
    /**
     * 是否允许拖拽列
     */
    isColDrop: {
      type: Boolean,
      default: false,
    },
    /**
     * 表格大小
     */
    size: {
      type: String,
      default: "mini",
    },
  },
  computed: {
    // 允许筛选的列
    screenColumns() {
      return this.columns.filter((item) => item._screen_ === true);
    },
    // 允许设置的列
    setColumns() {
      return this.columns.filter((item) => !item._noset_);
    },
    // 筛选条件是否包含当前列
    isHasScreenColumn() {
      return function (col) {
        return this.conditions.some((item) => item.prop === col.prop);
      };
    },
  },
  data() {
    return {
      // 表格选中项
      tableSelection: [],
    };
  },
  watch: {},
  mounted() {
    // 拖拽绑定
    this.rowDrop();
    this.columnDrop();
  },
  directives: {
    // v-drap  可拖拽指令
    drap: {
      inserted: function (element, binding) {
        element.onmousedown = function (e) {
          let el = binding.modifiers.parent ? element.parentNode : element,
            bodyWidth = document.body.offsetWidth,
            bodyHeight = document.body.offsetHeight,
            elWidth = el.offsetWidth,
            elHeight = el.offsetHeight;
          // 开始拖动，记录左上角坐标点
          let disX = e.clientX - el.offsetLeft;
          let disY = e.clientY - el.offsetTop;
          document.onmousemove = function (e) {
            // 拖动中，修改dom的左上角坐标点
            let l = e.clientX - disX;
            let t = e.clientY - disY;
            if (binding.modifiers.limit) {
              l = l < 0 ? 0 : l;
              t = t < 0 ? 0 : t;
              l = l > bodyWidth - elWidth ? bodyWidth - elWidth : l;
              t = t > bodyHeight - elHeight ? bodyHeight - elHeight : t;
            }
            el.style.left = l + "px";
            el.style.top = t + "px";
          };
          document.onmouseup = function () {
            // 结束拖动
            document.onmousemove = null;
          };
        };
      },
    },
  },
  methods: {
    //
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      // if (rowIndex % 2 === 0) {
      //   if (columnIndex === 0) {
      //     return [1, 2];
      //   } else if (columnIndex === 1) {
      //     return [0, 0];
      //   }
      // }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (rowIndex % 2 === 0) {
          return {
            rowspan: 2,
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      }
    },

    //行拖拽
    rowDrop() {
      const tbody = document.querySelector(
        ".el-table__body-wrapper > table > tbody"
      );
      Sortable.create(tbody, {
        disabled: !this.isRowDrop,
        ghostClass: "sortable-ghost",
        animation: 180,
        delay: 0,
        onEndevt: (evt) => {
          const currItem = this.data.splice(evt.oldIndex, 1)[0];
          this.data.splice(evt.newIndex, 0, currItem);
        },
      });
    },
    //列拖拽
    columnDrop() {
      const wrapperTr = document.querySelector(".el-table__header-wrapper tr");
      Sortable.create(wrapperTr, {
        disabled: !this.isColDrop,
        ghostClass: "sortable-ghost",
        animation: 180,
        delay: 0,
        onEnd: (evt) => {
          const currItem = this.columns.splice(evt.oldIndex, 1)[0];
          this.columns.splice(evt.newIndex, 0, currItem);
        },
      });
    },
    // 获取对象的属性
    getObjPrototype(o, a) {
      if (o[a]) {
        let fn = Function;
        return new fn("obj", `return obj.${a}`)(o);
      } else {
        return "";
      }
    },
    /** 表格方法 传递给el-table，后续有需要可继续增加 **/
    // 对 Table 进行重新布局。当 Table 或其祖先元素由隐藏切换为显示时，可能需要调用此方法
    doLayout(...arg) {
      this.$refs.elTable.doLayout(...arg);
    },
    // 用于多选表格，清空用户的选择
    clearSelection(...arg) {
      this.$refs.elTable.clearSelection(...arg);
    },
    // 用于多选表格，切换某一行的选中状态
    toggleRowSelection(...arg) {
      this.$refs.elTable.toggleRowSelection(...arg);
    },
    // 用于多选表格，切换所有行的选中状态
    toggleAllSelection(...arg) {
      this.$refs.elTable.toggleAllSelection(...arg);
    },
    // 用于单选表格，设定某一行为选中行
    setCurrentRow(...arg) {
      this.$refs.elTable.setCurrentRow(...arg);
    },
    // 用于可展开表格与树形表格，切换某一行的展开状态，如果使用了第二个参数，则是设置这一行展开与否（expanded 为 true 则展开）
    toggleRowExpansion(...arg) {
      this.$refs.elTable.toggleRowExpansion(...arg);
    },
  },
};
</script>

<style lang="css">
.el-switch__core {
  flex-shrink: 0;
}
.el-switch,
.el-switch__label {
  height: auto;
}

.ex-table-setcol-dropdown {
  max-width: 180px;
  max-height: 280px;
  overflow-y: auto;
}
</style>

<style lang="scss" scoped>
.table-header {
  display: flex;
  display: -webkit-flex;
  // background-color: #f5f5f5;
  padding: 0 0;
}
.table-header > * {
  margin-top: 10px;
  margin-bottom: 12px;
}
// .table-header :nth-child(n + 2) {
//   margin-left: 10px;
// }
</style>
