
<!--
  @row-click="handleRowClick" 当某一行被点击时会触发该事件
  @cell-click="handleCellClick" 当某个单元格被点击时会触发该事件
  @sort-change="sortChange" 排序触发事件
  sortable 配置排序
  default-sort: prop默认字段 order排序方式
  slot='key_header' scopeHeader 支持表头可自定义
  highlightCurrentRow 单行选中状态
-->
<template>
  <div class="table-content">
    <FElTable
      ref="lxTableRef"
      v-loading="loading"
      v-bind="$attrs"
      :data="tableData"
      :empty-text="(customConfig || {}).emptyText || ''"
      :highlight-current-row="highlightCurrentRow"
      :row-class-name="tableRowClassName"
      :default-sort="(customConfig || {}).sortValue || defaultSort"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      @cell-click="handleCellClick"
      @sort-change="sortChange"
    >
      <ElTableColumn
        v-if="customConfig.selection && customConfig.selection.isOpenSelection"
        type="selection"
        :width="customConfig.selection.width"
      />
      <ElTableColumn
        v-for="(item, index) in cloumns"
        :key="`${item}_${index}`"
        :label="item"
        :prop="keys[index]"
        :sortable="getFieldFromConfig(keys[index], 'sortable')"
        :width="getFieldFromConfig(keys[index], 'width')"
        :min-width="getFieldFromConfig(keys[index], 'minWidth')"
        :fixed="getFieldFromConfig(keys[index], 'fixed')"
      >
        <template
          slot="header"
          slot-scope="scope"
        >
          <slot
            v-if="getFieldFromConfig(keys[index], 'scopeHeader')"
            template
            :name="`${keys[index]}_header`"
            :keys="keys[index]"
            :row="scope.row"
            :lable="scope.column"
            :column="scope.$index"
          />
          <span v-else>
            {{ item }}
          </span>
        </template>
        <template slot-scope="scope">
          <!-- 支持keys字段为'car.id'或者'id' -->
          <div v-if="keys[index].indexOf('.') != -1">
            <!-- 一个td需要展示多个字段名 -->
            <div v-if="Array.isArray(keys[index])">
              <div
                v-for="(array, i) in keys[index]"
                :key="i"
              >
                {{ scope.row[array] }}
              </div>
            </div>
            <!-- 字段formatters存在,数据过滤-->
            <span
              v-else-if="getFieldFromConfig(keys[index], 'formatters')"
            >
              {{ formatterMethods(scope.row[keys[index].split('.')[0]][keys[index].split('.')[1]], (customConfig[keys[index]].formatters)) }}
            </span>
            <!-- 复杂情况需要自定义---当前keys存在于customConfig.template数据定义中，传入slot的name作为唯一标识符 -->
            <slot
              v-else-if="getFieldFromConfig(keys[index], 'template')"
              template
              :name="keys[index]"
              :keys="keys[index]"
              :row="scope.row"
              :lable="scope.column"
              :column="scope.$index"
            />
            <div v-else>
              <!-- 传入不需要截取的列 -->
              <span v-if="getFieldFromConfig(keys[index], 'templateCutOut')">
                {{ scope.row[keys[index].split('.')[0]][keys[index].split('.')[1]] | formateValue }}
              </span>
              <Ellipsis
                v-else
                :popover-name="popoverName"
                :line-count="getFieldFromConfig(keys[index], 'lineCount')"
                :content="[`${scope.row[keys[index].split('.')[0]][keys[index].split('.')[1]]}`] | formateValue"
              >
                <div slot="popover">
                  <div>{{ scope.row[keys[index].split('.')[0]][keys[index].split('.')[1]] | formateValue }}</div>
                </div>
              </Ellipsis>
            </div>
          </div>
          <div v-else>
            <!-- 一个td需要展示多个字段名 -->
            <div v-if="Array.isArray(keys[index])">
              <div
                v-for="(array, i) in keys[index]"
                :key="i"
              >
                {{ scope.row[array] }}
              </div>
            </div>
            <!-- 字段formatters存在,数据过滤-->
            <span
              v-else-if="getFieldFromConfig(keys[index], 'formatters')"
            >
              {{ formatterMethods(scope.row[keys[index]], (customConfig[keys[index]].formatters)) }}
            </span>
            <!-- 复杂情况需要自定义---当前keys存在于customConfig.template数据定义中，传入slot的name作为唯一标识符 -->
            <slot
              v-else-if="getFieldFromConfig(keys[index], 'template')"
              template
              :name="keys[index]"
              :keys="keys[index]"
              :row="scope.row"
              :lable="scope.column"
              :column="scope.$index"
            />
            <div v-else>
              <!-- 传入不需要截取的列 -->
              <span v-if="getFieldFromConfig(keys[index], 'templateCutOut')">
                {{ scope.row[keys[index]] | formateValue }}
              </span>
              <Ellipsis
                v-else
                :popover-name="popoverName"
                :line-count="getFieldFromConfig(keys[index], 'lineCount')"
                :content="[`${scope.row[keys[index]]}`] | formateValue"
              >
                <div slot="popover">
                  <div>{{ scope.row[keys[index]] | formateValue }}</div>
                </div>
              </Ellipsis>
            </div>
          </div>
        </template>
      </ElTableColumn>
    </FElTable>
    <ElPagination
      :background="background"
      v-if="currentPage"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="totals"
      layout="total, prev, pager, next, jumper, slot"
      @current-change="handleCurrentChange"
    />
  </div>
</template>
<script>
  import Ellipsis from '../Ellipsis';
  import { Table } from 'element-ui'
  const FElTable = {
    extends: Table,
    methods: {
      doLayout (...args) {
        Table.methods.doLayout.call(this, ...args)
        this.fixLayout() // Looks like we can do it once?
      },
      fixLayout () {
        // Safari header/content misalign fix (possible other browsers?)
        this.columns.forEach(c => {
          // element-ui/packages/table/src/layout-observer.js:49
          const width = c.realWidth || c.width
          const th = this.$el.querySelector(`table.el-table__header th.${c.id}`)
          if (th) {
            if (th.offsetWidth !== width) {
              th.style = `min-width: ${width}px; max-width: ${width}px;`
            }
            let td
            for (td of this.$el.querySelectorAll(`table.el-table__body td.${c.id}`)) {
              if (td.offsetWidth === width) break
              td.style = `min-width: ${width}px; max-width: ${width}px;`
            }
          }
        })
      }
    }
  }

  export default {
    name: 'LxTable',
    components: {
      Ellipsis,
      FElTable
    },
    filters: {
      formateValue (val) {
        if (Array.isArray(val) && (val[0] === 'null' || val[0] === '')) {
          val = '';
        }
        return (val || val === 0) ? val : '--';
      },
    },
    props: {
      tableData: {
        type : Array,
        default: () => [],
      },
      cloumns: {
        type : Array,
        default: () => [],
      },
      customConfig: Object,
      keys: {
        type : Array,
        default: () => [],
      },
      defaultSort: {
        prop: '',
        order: null,
      },
      stripe: {
        type: Boolean,
        default: true,
      },
      loading: {
        type: Boolean,
        default: false,
      },
      background: {
        type: Boolean,
        default: true,
      },
      totals: Number,
      pageSize: Number,
      currentPage: Number,
      popoverName: String,
      parentFn: {
        type : String,
        default: '',
      },
      highlightCurrentRow: {
        type: Boolean,
        default: true,
      },
      tableRowClassName: {},
    },
    data() {
      return {
        scope: 'scope',
      };
    },
    methods: {
      handleCurrentChange(val) {
        this.$emit('handleCurrentChange', val);
      },
      handleSelectionChange(val) {
        this.$emit('handleSelectionChange', val);
      },
      handleRowClick(row, column, cell, event) {
        this.$emit('handleRowClick', row, column, cell, event);
      },
      handleCellClick(row, column, cell, event){
        this.$emit('handleCellClick', row, column, cell, event);
      },
      sortChange(column, prop, order) {
        this.$emit('sortChange', column, prop, order);
      },
      formatterMethods(key, keyData) {
        // 返回数据，可类型转换; 可添加单位;
        let value = '--';
        if (key || key === 0) {
          const keyValue = keyData[key] || key;
          const unit = keyData.unit || '';
          value = `${keyValue}${unit}`;
        }
        return value;
      },
      formateValue (val) {
        return val || val === 0 ? val : '--';
      },
      getFieldFromConfig(index, name) {
        return this.customConfig && this.customConfig[index] && this.customConfig[index][name];
      },
    }
  }
</script>
<style type="scss">
  .table-content .el-pagination {
    text-align: right;
    padding: 14px 0;
  }
</style>

