<template>
  <el-container ref="table">
    <el-main>
      <el-form inline>
        <slot name="tableHead"></slot>
        <div v-if='(!$slots.tableHead && searchConfig.length>0) || isSearch' class="bgrey pt10 pb5 tableSearch">
          <template v-for="item in searchConfig">
            <hoc v-if="!item.hide && !(item.hideFun && item.hideFun(search))" :key="item.label" :item="item" :formData="search" :showLabel='true'></hoc>
          </template>
          <el-form-item class="pl17">
            <el-button v-if="(searchConfig&&searchConfig.length>0) && !$attrs.search" type="primary" @click="getTable()">查询</el-button>
            <el-button v-if="(searchConfig&&searchConfig.length>0) && !$attrs.search" @click="resetSearch">重置</el-button>
            <slot name="searchBtns" v-bind:search="search" v-bind:list="list">
            </slot>
          </el-form-item>
        </div>
      </el-form>
      <slot name="content" v-bind:search="search"></slot>
      <el-table :data="list" v-bind="$attrs" v-on="$listeners" v-loading="loading" ref="table" class="mb15" :header-cell-style="headerStyle" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55px" v-if="selection"></el-table-column>
        <el-table-column label="序号" type="index" v-if="index" :align="align" width="50px"></el-table-column>
        <el-table-column type="expand" v-if="expand">
          <template slot-scope="scope">
            <slot name='expand' v-bind:list="list" v-bind:row="scope.row" v-bind:index="scope.$index"></slot>
          </template>
        </el-table-column>
        <template v-for="item in column">
          <el-table-column v-bind="item.attrs" v-on="item.listeners" v-if="!item.template && !item.hide" :label="item.label" :prop="item.prop" :align="align" :width="item.width" :key="item.label">
            <template slot-scope="scope">
              {{getLabel(scope.row,item.prop,item)}}
            </template>
          </el-table-column>
          <el-table-column v-bind="item.attrs" v-on="item.listeners" v-if="item.template && !item.hide" :label="item.label" :align="align" :width="item.width" :key="item.label">
            <template slot-scope="scope">
              <img class="w100 h100" v-if="item.type=='img'" :src="scope.row[item.prop]" alt="">
              <slot v-if="!item.type" :name="item.prop" v-bind:row="scope.row" v-bind:index="scope.$index"></slot>
            </template>
          </el-table-column>
        </template>
        <el-table-column label="操作" :align="align" min-width="120px" fixed="right" v-if="$scopedSlots.default">
          <template slot-scope="scope">
            <slot v-bind:search="search" v-bind:list="list" v-bind:row="scope.row" v-bind:index="scope.$index"></slot>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-if="!$attrs.page" :background='true' :align="align" @size-change="getTable()" @current-change="getTable" :current-page.sync="search.page" :page-sizes="[5, 10, 20, 30]" :page-size.sync="search.page_size" layout="total, sizes, prev, pager, next, jumper" :total="total" class="pagination-style">
      </el-pagination>
    </el-main>
  </el-container>
</template>

<script>
import { hoc } from "../Base/BaseItemHoc";
import base from "../utils/dictionary.js";
import Sortable from "sortablejs";
export default {
  name: "mgTable",
  components: {
    hoc: hoc(),
  },
  props: {
    api: {
      type: Function,
    },
    //不通过接口获取数据源
    dataList: {
      type: Array,
    },
    // 查询表单配置
    searchConfig: {
      type: Array,
      default: () => [],
    },
    // 查询表单固定参数
    params: {
      type: Object,
      default: () => { },
    },
    // 表格列配置
    column: {
      type: Array,
      default: () => [],
    },
    selection: {
      type: Boolean,
    },
    index: {
      type: Boolean,
    },
    expand: {
      type: Boolean,
      default: false,
    },
    row: {
      //是否拖拽排序
      type: Boolean,
    },
    headerStyle: {
      type: Object,
    },
    prop: {
      //api参数
      type: String,
    },
    align: {
      type: String,
      default: "left",
    },
    //是否默认显示筛选
    // isSearch: {
    //   type: Boolean,
    //   default: true,
    // },
  },
  computed: {
    list() {
      let arrayTemp = [];
      if (this.dataList) {
        arrayTemp = this.dataList;
      } else {
        arrayTemp = this.tableData;
      }
      return arrayTemp;
    },
  },
  data() {
    return {
      multipleSelection: [],
      isSearch: false, //是否显示筛选
      loading: false,
      total: 0,
      tableData: [],
      search: {},
    };
  },
  created() {
    this.resetSearch();
    // this.columnDrop()
    // console.log(this.scrollerWidth, 999)
  },
  mounted() {
    if (this.row) {
      this.rowDrop();
    }
    // this.rowDrop()
    // this.columnDrop()
  },
  methods: {
    rowDrop() {
      const tbody = this.$el.querySelector(".el-table__body-wrapper tbody");
      const self = this;
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          if (self.dataList) {
            const currRow = self.dataList[oldIndex];
            self.dataList.splice(oldIndex, 1);
            self.dataList.splice(newIndex, 0, currRow);
          } else {
            const currRow = self.tableData.splice(oldIndex, 1)[0];
            self.tableData.splice(newIndex, 0, currRow);
          }
        },
      });
    },
    //列拖拽
    // columnDrop() {
    //   const wrapperTr = this.$el.querySelector('.el-table__header-wrapper tr')
    //   let self = this;
    //   this.sortable = Sortable.create(wrapperTr, {
    //     animation: 180,
    //     delay: 0,
    //     onEnd: evt => {
    //       const oldItem = self.column[evt.oldIndex]
    //       self.column.splice(evt.oldIndex, 1)
    //       self.column.splice(evt.newIndex, 0, oldItem)
    //     }
    //   })
    // },
    getLabel(row, prop, item) {
      prop = prop.split(".");
      let value = "",
        temp = row;
      prop.forEach((element) => {
        if (temp[element] != undefined) {
          temp = temp[element];
          value = temp;
        } else {
          value = "";
        }
      });
      if (item.enum || item.options) {
        value = base.getName(item.enum, value, item.options);
      }

      if (item.isList && value) {
        let list = [];
        value = JSON.parse(value);
        value.forEach((data) => {
          list.push(data.name);
        });
        value = list.join(",");
      }
      //添加前后固定元素
      if (item.front) {
        value = item.front + value
      }
      if (item.back) {
        value = value + item.back
      }
      return value;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getSelect() {
      return this.multipleSelection;
    },
    getList() {
      return this.list;
    },
    getData() {
      return this.data;
    },
    fetch() {
      this.getTable(this.search.page);
    },
    resetSearch() {
      if (!this.$attrs.page) {
        this.search = Object.assign(
          {
            page: 1,
            page_size: 10,
          },
          this.params
        );
      } else {
        this.search = Object.assign({}, this.params);
      }
      this.getTable();
    },
    getTable(page) {
      this.loading = true;
      if (!this.$attrs.page) {
        this.search.page = page || 1;
        this.search.pageSize = this.search.page_size;
        this.search.pageNum = this.search.page;
      }
      if (this.dataList) {
        this.loading = false;
      } else {
        this.api(this.search)
          .then((res) => {
            const { data } = res;
            if (this.prop) {
              this.tableData = data[this.prop];
            } else {
              this.tableData = data.records || data;
            }
            this.data = data;
            this.total = data.total;
          })
          .catch(() => {
            this.tableData = [];
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },
  },
};
</script>
