<!--
 * @Descripttion: Element Ui Table 表格二次封装
 * @Author: 周连
 -->
<template>
  <div class="TableView">
    <el-table class="elTable" :class="{ 'no-row-line': stripe }" :size="mySize" ref="dataTable" :data="tableData"
      :max-height="tableHeight" :stripe="stripe" :highlight-current-row="highlightCurrentRow"
      @selection-change="selectLine" @current-change="handleCurrentChange" @sort-change="changeSort"
      @row-dblclick="rowdblclick" @row-click="rowClick" :row-key="rowKey"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column v-if="showSelect" type="selection" width="50" align="center" :selectable="checkboxT"
        reserve-selection>
      </el-table-column>

      <el-table-column type="expand" v-if="isExpand">
        <template slot-scope="scope">
          <slot name="expand" :data="scope" />
        </template>
      </el-table-column>
      <el-table-column label="序号" v-if="showIndex" type="index" width="50" align="center">
        <template slot-scope="scope">
          <span>{{ (pageRequest.pageIndex - 1) * pageRequest.pageSize + scope.$index + 1 }}</span></template>
      </el-table-column>
      <!-- 文本数据渲染 -->
      <template v-for="item in tableHead">
        <!--自定义列 操作模块   fixed="right" -->
        <el-table-column v-if="item.columnType == 'operation' && item.isShow" :prop="item.prop" :label="item.label"
          :key="item.prop" :min-width="item.minWidth" :width="item.width" :align="item.align || 'center'" fixed="right">
          <template slot-scope="scope">
            <slot :name="item.slotName" :data="scope" />
          </template>
        </el-table-column>

        <!--自定义列 :sortable="sortable ? sortable :'custom' "-->
        <el-table-column :show-overflow-tooltip="item.tooltip == null ? true : item.tooltip"
          v-else-if="item.columnType == 'slot' && item.isShow" :prop="item.prop" :label="item.label" :key="item.prop"
          :min-width="item.minWidth" :width="item.width" :align="item.align ? item.align : 'center'"
          :sortable="item.sortable == null ? false : item.sortable">
          <template slot-scope="scope">
            <slot :name="item.slotName" :data="scope" />
          </template>
        </el-table-column>

        <!--普通文本 :sort-orders="['ascending', 'descending']" -->
        <el-table-column :show-overflow-tooltip="item.tooltip == null ? true : item.tooltip"
          v-else-if="item.isShow && !item.type && !item.columnType" :prop="item.prop" :label="item.label"
          :key="item.prop" :min-width="item.minWidth" :width="item.width" :align="item.align ? item.align : 'center'"
          :sortable="item.sortable == null ? false : item.sortable"></el-table-column>

        <!--根据不同类型显示不同的输入框 可以是下拉选择 /按钮 /输入框 还可以自己定义更多 -->
        <el-table-column v-else-if="item.type && item.isShow && !item.columnType" :label="item.label" :key="item.prop"
          :min-width="item.minWidth" :width="item.width" :align="item.align ? item.align : 'center'"
          :sortable="item.sortable == null ? false : item.sortable">
          <template slot-scope="scope">
            <el-select v-if="item.type == 'select'" size="mini" v-model="scope.row[item.prop]"
              @change="handleEdit(scope.$index, scope.row)" placeholder="请选择" clearable filterable value>
              <el-option v-for="option in item.data" :disabled="disabled" :value="option.name" :key="option.name"
                :label="option.name" />
            </el-select>
            <el-button v-else-if="item.type == 'btn'" :disabled="disabled" @click="onSelected(scope.$index, scope.row)"
              type="primary" size="mini">{{ item.text }}</el-button>
            <el-input v-else-if="item.type == 'text'" size="mini" :disabled="item.disabled || disabled"
              v-model="scope.row[item.prop]" placeholder="请输入" @change="handleEdit(scope.$index, scope.row)" />

            <el-input v-only-number="{ min: 0, precision: 2 }" v-else-if="item.type == 'money'" size="mini"
              :disabled="item.disabled || disabled" v-model="scope.row[item.prop]" placeholder="请输入"
              @change="handleEdit(scope.$index, scope.row)" />

            <el-input-number v-onlyInt size="mini" v-else-if="item.type === 'number'" v-model="scope.row[item.prop]"
              :min="0" label="排序编号" @change="handleEdit(scope.$index, scope.row)"></el-input-number>
            <!-- <span>{{scope.row[item.prop]}}</span> -->
          </template>
        </el-table-column>
      </template>
    </el-table>

    <div class="paginationInfo" v-show="pageShow">
      <pagination ref="p" :page-size="pageRequest.pageSize" :total="total" :current-page="pageRequest.pageIndex"
        @changePage="changePage" @changePageSize="changePageSize" :layout="layout"></pagination>
      <div class="pool">{{ totalizeStr }}</div>
    </div>
  </div>
</template>

<script>
import pagination from '@/components/pagination';
export default {
  name: 'e-table',
  components: { pagination },
  /**
   * @name:
   * @test: test font
   * @msg:
   * @param {
   *  接收参数:
   *      tableHeadConfig 列的名称、接收值     |     Array
   *        label         列的名称                      |     String
   *        prop          列的对应值                    |     String
   *        columnType    定义当前列为插槽    |   slot   |     String
   *        slotName      定义当前列插槽的名字           |     String
   *        width         定义当前列的宽度               |     String
   *        sortable      列的排序
   *        isTime        列是否是时间
   * tooltip :false
   *
   *  示例：配置
   *      tableHeadConfig:[
   *              {
   *                label       : "缩略图",
   *                prop       : "skuName",
   *                columnType  : "slot",
   *                slotName    : "thumbnail",
   *                width       : 240
   *              }
   *            ]
   *
   *      tableLoadData     异步获取的table文本数据信息
   *      align             表格单元格内容排列顺序      left|center|right
   *      showSelect         表格是否可多选
   *      height            表格默认撑开高度（未用）
   *      heightOffset      表格最大高度偏移量
   *      pageShow   显示分页（默认显示）
   *      pageSize 分页》 页条
   *      total  分页》 总数
   *      currentPage 分页 》当前页码
   *      totalizeStr  合计说明处理
   *  事件：
   *      获取当前选中行
   *      调用页面用  @selectLine="xxx" 进行监听处理
   *      从后台获取数据,重新排序   changeSort
   *      双击行事件rowdblclick
   *      分页获取更改的页码  changePage
   *      分页获取更改条数/页  changePageSize
   * }
   * @return:
   */
  props: {
    tableHeadConfig: {
      type: Array,
      default: () => {
        return [
          {
            label: 'skuId',
            prop: 'skuId',
          },
          {
            label: '操作',
            columnType: 'slot',
            slotName: 'operation',
          },
        ];
      },
    },
    tableLoadData: {
      type: Array,
      default: () => {
        return [];
      },
    },
    highlightCurrentRow: {
      type: Boolean,
      default: false,
    },
    align: {
      type: String,
      default: 'center',
    },
    showIndex: {
      type: Boolean,
      default: false,
    },
    isRequest: {
      type: Boolean,
      default: false,
    },
    isSerial: {
      type: Boolean,
      default: true,
    },
    isExpand: {
      type: Boolean,
      default: false,
    },
    sortable: {
      type: Boolean,
      default: false,
    },
    showSelect: {
      type: Boolean,
      default: false,
    },
    height: {
      type: [Number, String],
      default: 50,
    },
    heightOffset: {
      type: [Number, String],
      default: 50,
    },
    isDisabled: {//是否禁用
      type: Boolean,
      default: true,
    },
    tagIndex: { //多个table标签
      type: Number,
      default: 0,
    },
    isTime: {
      type: Boolean,
      default: false,
    },
    pageShow: {//显示分页
      type: Boolean,
      default: true,
    },
    total: {//总数量
      type: [Number, String],
      default: 0,
    },
    pageSize: {//每页数量
      type: [Number, String],
      default: 10,
    }, 
    currentPage: {//分页页码
      type: Number,
      default: 1,
    },
    totalizeStr: {
      type: String,
      default: '',
    },
    selectQuantity: {//设置选择数量
      type: [String, Number],
      default: 0,
    },
    layout: {
      type: String,
      default: 'total, sizes, prev, pager, next',
    },
    stripe: {//是否为斑马纹 table
      type: Boolean,
      default: true,
    },
    autoHeight: {
      type: Boolean,
      default: false,
    },
    rowKey: {
      type: String,
      default: 'id',
    },
    multiple: {//是否多选
      type: Boolean,
      default: true,
    },
    mySize:{
      type:String,
      default:'medium'
    }
  },

  data() {
    return {
      selectioned: '',//单选中的值
      selectList: [],
      disabled: false,
      // 分页信息
      pageRequest: {
        pageIndex: 1,
        pageSize: 10,
        sort: null,
        order: null,
      },
      tableHeight: null,
    };
  },
  computed: {
    tableData() {
      return this.tableLoadData;
    },
    tableHead() {
      return this.tableHeadConfig;
    },
  },
  created() { },
  mounted() {
    if (this.isRequest) this.getPageList();
    if (this.autoHeight) {

      // 监听窗口大小变化
      let self = this;
      this.$nextTick(() => {
        self.tableHeight =
          window.innerHeight -
          self.$refs.dataTable.$el.offsetTop -
          self.heightOffset;


        window.onresize = function () {
          if (self.$refs.dataTable) {
            self.tableHeight =
              window.innerHeight -
              self.$refs.dataTable.$el.offsetTop -
              self.heightOffset;
          }
        };
        //this.$refs.dataTable.$el.offsetTop：表格距离浏览器的高度
        //50表示你想要调整的表格距离底部的高度（你可以自己随意调整），因为我们一般都有放分页组件的，所以需要给它留一个高度
      });
    }
  },
  watch: {
    currentPage(val) {
      this.pageRequest.pageIndex = val;
    },
    pageSize(val) {
      this.pageRequest.pageSize = val;
    }
  },

  methods: {
    /*实现单选*/
    dialogCheck: function (selection, row) {
      this.$refs.dataTable.clearSelection()
      if (selection.length === 0) { // 判断selection是否有值存在
        return
      }
      if (row) {
        this.selectioned = row
        this.$refs.dataTable.toggleRowSelection(row, true)
      }
    },


    checkboxT(val) {
      return this.isDisabled;
      // return val.isDisabled
    },
    // 分页查询
    getPageList() {
      this.$emit('getPageList', this.pageRequest);
    },
    onResetPage() {
      this.pageRequest = {
        pageIndex: 1,
        pageSize: 10,
        sort: null,
        order: null,
      };
    },
    // 从后台获取数据,重新排序
    changeSort(val) {
      if (val) {
        this.pageRequest.pageIndex = 1;
        this.pageRequest.sort = val.prop;
        this.pageRequest.order =
          val.order == 'descending'
            ? 'desc'
            : val.order == 'ascending'
              ? 'asc'
              : '';
        this.getPageList();
      }
      console.log(this.pageRequest, val);
    },
    // 分页获取更改的页码
    changePage(val) {
      this.pageRequest.pageIndex = val;
      this.getPageList();
      this.$emit('changePage', val);
    },
    // 分页获取更改条数/页
    changePageSize(val) {
      this.pageRequest.pageSize = val;
      this.pageRequest.pageIndex = 1;
      this.getPageList();
      this.$emit('changePageSize', val);
    },
    //双击行事件
    rowdblclick(row) {
      console.log(row);
    },
    // 选择切换
    handleCurrentChange(val) {
      this.$emit('handleCurrentChange', val);
    },
    //选择
    selectLine(val) {
      this.selectList = val;
      if (this.selectQuantity > 0) {
        if (this.selectList.length > this.selectQuantity) {
          // 截取前20位
          this.selectList = val.slice(0, this.selectQuantity);
          // 截取20位之后的数组  禁止选中
          let tempArr = val.slice(this.selectQuantity);
          if (tempArr.length !== 0) {
            tempArr.forEach((ele) => {
              this.$refs.dataTable.toggleRowSelection(ele, false);
            });
          }
          this.$message.closeAll();
          this.$message.warning('只能请选择' + this.selectQuantity + '个');
        }
      }
      else {//单选处理
        if (!this.multiple) {  
          if (this.selectList.length > 1) {
            this.$refs.dataTable.clearSelection();
            this.$refs.dataTable.toggleRowSelection(val.pop());
          }  
        }
      }
      this.$emit('selectLine', this.selectList, this.tagIndex);
    },

    handleEdit(index, row) {
      this.$emit('handleEdit', { index: index, row: row });
    },
    onSelected: function (index, row) {
      this.$emit('onTableBtn', { index: index, row: row });
    },
    rowClick(row) {
      this.$emit('clickTable', row);
    },
    // 清空选择
    clearSelection() {
      this.$nextTick(() => {
        this.$refs.dataTable.clearSelection()
      })
    },
  },
};
</script>
<style lang="less" scoped>
.TableView {
  margin-top: 10px !important;
  background: #fff;
}
.elTable {
  & /deep/ .el-table__header-wrapper .el-table__cell .cell {
    font-family: PingFang SC;
    font-weight: 400;
    color: #3a3b3d;
  }
}
.el-table::before {
  height: 0;
}
.el-table /deep/ th {
  background: #f5f7fd;
}

// .el-table /deep/ th.el-table__cell.is-leaf,
// .el-table /deep/ td.el-table__cell {
//   border: none;
// }
.paginationInfo {
  display: flex;
  justify-content: flex-end;
  padding: 7px 0;
  margin-top: 10px;
  .pool {
    padding: 10px 10px;
    color: #6c6c6c;
    text-align: right;
  }
}
</style>
