<template>
  <div class="table">
    <el-table id="out-table"
              ref="table"
              class="tableLimit"
              :height="table.height"
              :data="tableData"
              :style="{width: '100%'}"
              border
              v-loading="loading"
              element-loading-text="正在加载中"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255, 255， 255, 0.8)"
              @select="handleSelect"
              @select-all="handleSelectAll"
              @cell-click="handleCellClick"
              @row-click="handleRowClick">
      <!--设置index索引-->
      <div v-if="columnType==='index'">
        <el-table-column label="序号" :type="columnType" width="50"></el-table-column>
      </div>
      <!--设置checkbox-->
      <div v-if="columnType==='selection'">
        <el-table-column :type="columnType"></el-table-column>
      </div>
      <div v-if="columnType==='radio'">
        <el-table-column label=""
                         width="35"
                         center>
          <template slot-scope="scope">
            <el-radio :label="scope.row.id"
                      v-model="templateRadio"
                      @change.native="getRadioRow(scope.$index,scope.row)">&nbsp;</el-radio>
          </template>
        </el-table-column>

      </div>
      <template v-for="col in tableColumn">
        <!--渲染列-->
        <el-table-column v-if="col.tableType==='span'"
                         :key="col.key"
                         :label="col.title"
                         :min-width="col.width"
                         :fixed="col.isFrozen"
                         show-overflow-tooltip
                         :align="columnAlign"
                         :header-align="headerAlign">
          <template slot-scope="scope">
            <span v-html="col.render(scope.row[col.key])"></span>
          </template>
        </el-table-column>
        <!--图片列-->
        <el-table-column v-if="col.tableType==='image'"
                         :key="col.key"
                         :label="col.title"
                         :min-width="col.width"
                         :fixed="col.isFrozen"
                         show-overflow-tooltip
                         :align="'center'"
                         :header-align="headerAlign"
                         :formatter="col.formatter">
          <template slot-scope="scope">
            <img v-if="scope.row[col.key]"
                 :src="scope.row[col.key]"
                 :style="{width: col.imgWidth?col.imgWidth:'50px',height:col.imgHeight?col.imgHeight:'50px'}"
                 class="function-icon"
                 :fit=" col.fill?col.fill:'fill'">
            <span v-else>--</span>

          </template>
        </el-table-column>

        <!--普通列-->
        <el-table-column v-if="!col.tableType||col.tableType===''"
                         :key="col.key"
                         :label="col.title"
                         :min-width="col.width"
                         :fixed="col.isFrozen"
                         :align="columnAlign"
                         :header-align="headerAlign"
                         :formatter="col.formatter"></el-table-column>
      </template>
      <!--操作列-->
      <el-table-column v-if="operations.length && operations.length > 0"
                       label="操作"
                       fixed="right"
                       :min-width="operationWidth"
                       header-align="center"
                       :align="buttonAlign"
                       class="operate">
        <template slot-scope="scope">
          <!--传入的操作按钮属性    lyx   20190411   -->
          <el-button v-for="item in operations"
                     v-show="item.isShow(scope.row)"
                     :key="item.lable"
                     :type="item.type"
                     :style="item.style"
                     :size="item.size"
                      :class="item.class"
                     @click.stop="handleMethod(scope.$index, scope.row,item.methodName)">{{item.lable}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <!-- <el-row class="page "
            v-if="pageVisible">
      <el-col :span="8"
              style="text-align: leftline-height: 32px">
        <slot style="text-align: left"></slot>
        <div></div>
      </el-col>
      <el-col :span="16">
        <el-pagination @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       @prev-click="handlePrevClick"
                       @next-click="handleNextClick"
                       :current-page="pageNo"
                       :page-sizes="tablePageSizes"
                       :page-size="pageSize"
                       layout="jumper, prev, pager, next,sizes, total"
                       :total="total"></el-pagination>
      </el-col>
    </el-row> -->
    <div v-if="pageVisible" class="pagination-diy">
      <div class="pagination-left">
        <slot></slot>
      </div>
      <div class="pagination-left">
        <el-pagination @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       @prev-click="handlePrevClick"
                       @next-click="handleNextClick"
                       :current-page="pageNo"
                       :page-sizes="tablePageSizes"
                       :page-size="pageSize"
                       layout="jumper, prev, pager, next,sizes, total"
                       :total="total"></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>

import CDialog from './CDialog'
import { mapGetters } from 'vuex'
export default {
  components: { CDialog },
  data () {
    return {
      tableData: [],
      tableColumn: window.app.service.getColumns(this.keyword, 'table'),
      loading: false,
      table: {
        height: this.tableHeight,
        params: {
          pageSize: Number, // 当前页数显示记录数
          pageNo: this.pageNo // 当前页数
        }
      },
      total: 0,
      selected: false,
      visiblePopover: false, //  删除弹出层开关
      templateRadio: ''
    }
  },
  watch: {
    tableHeight (height) {
      this.table.height = height
    },
  },
  props: {
    keyword: {
      type: String,
      required: true
    },
    columnType: {
      type: String
    },
    columnAlign: {
      type: String,
      default: 'left'
    },
    headerAlign: {
      type: String,
      default: 'center'
    },
    url: {
      type: String,
      required: true
    },
    params: {
      type: Object,
      default () {
        return {}
      }
    },
    operations: {
      type: Array,
      default () {
        return []
      }
    },
    pageNo: {
      type: Number,
      default: 1
    },

    tableHeight: {
      type: Number
    },
    pageVisible: { // 是否显示page分页     lyx   20190411
      type: Boolean,
      default: true
    },
    operationWidth: {
      type: Number,
      default: 120
    },
    filterParams: {
      type: Array,
      default () {
        return []
      }
    },
    //操作列对齐模式
    buttonAlign: {
      type: String,
      default: "center"
    }

  },
  computed: {

    pageSize: {

      //getter 方法
      get () {
        if (this.resolution === 'small') {
          this.table.params.pageSize = 10

          return 10
        } else {
          this.table.params.pageSize = 20
          return 20
        }
      },
      //setter 方法
      set (newValue) {

        console.log('computed setter...')
        this.table.params.pageSize = newValue
        // return newValue
      }



    },
    tablePageSizes () {
      if (this.resolution === 'small') {
        return [10, 20, 50]
      } else {
        return [20, 30, 50]
      }
    },
    ...mapGetters(['resolution'])

  },
  methods: {
    render () {
      this.loadData()
    },
    loadData () {
      // eslint-disable-next-line
      this.loading = true
      Object.keys(this.params).forEach(key => {
        if (this.params[key] instanceof Array) {
          this.params[key] = this.params[key].join(',')
        }
      })
      Object.assign(this.table.params, this.params)

      //  获取数据
      window.app.ajax.post(
        this.url,
        this.table.params,
        (data, rspMsg) => {

          if (data) {
            this.total = data.total
            this.tableData = data.list

            if (this.filterParams.length > 0) {

              this.filterParams.forEach(paramItem => {
                const key = paramItem.key
                const value = paramItem.value
                this.tableData = this.tableData.filter(item => {
                  item[key].indexOf(value) > 0
                })
              })

            }

          }

          this.loading = false

        },
        (rspMsg, data) => {
          this.$message.error(rspMsg)
          this.loading = false
        }
      )
    },
    handleClearSelection () {
      //  清空选择
      this.$refs['table'].clearSelection()
    },
    // 选中复选框
    handleSelect (selection, row) {
      this.$emit('select', selection)
      // console.log(selection, row)
    },
    // 全选复选框
    handleSelectAll (selection) {
      this.$emit('selectAll', selection)
    },
    handleCellClick (row, column, cell, event) { },
    handleRowClick (row) {
      //  切换该列的勾选状态
      this.selected = !this.selected
      this.$refs['table'].toggleRowSelection(row, this.selected)
    },

    handleEdit (index, row) {
      //  因为操作列与数据列属于同一行，编辑某一列后会继续触发table的row-click事件，所以在按钮上添加stop修饰符阻止事件的继续传播
      this.handleClearSelection()
      this.$refs['table'].toggleRowSelection(row)
      this.$emit('update', row)
    },
    handleAnalyze (index, row) {
      this.handleClearSelection() //  清空选择
      this.$refs['table'].toggleRowSelection(row, true)
      this.$emit('analyze', row)
    },
    handleDelete (index, row) {
      this.handleClearSelection() //  删除选择
      this.$refs['table'].toggleRowSelection(row, true)
      this.$emit('delete', row)
    },
    handleDeleteCancel (scope) {
      //  关闭popover弹出层
      scope._self.$refs[`popover-${scope.$index}`].doClose()
    },
    handleSizeChange (pageSize) {

      this.table.params.pageSize = pageSize

      this.table.params.pageNo = 1
      this.$nextTick(() => {
        this.loadData()
      })
    },
    // 改变当前页
    handleCurrentChange (pageNo) {
      this.table.params.pageNo = pageNo
      this.$nextTick(() => {
        this.loadData()
      })
    },
    // 点击上一页
    handlePrevClick (pageNo) {
    },
    // 点击下一页
    handleNextClick (pageNo) {
    },

    // 单选选中
    getRadioRow (index, row) { // 获取选中数据
      this.$emit('selectRadioRow', row)
    },
    // 导出表格
    handleOutTable (name) {
      //  app.util.exportExcel(name, '#out-table')
    },
    //  exportExcel (tHeader, filterVal) {
    //    require.ensure([], () => {
    //      const { export_json_to_excel } = require('@js/excel/Export2Excel')

    //      const list = this.tableData
    //      const data = this.formatJson(filterVal, list)
    //      export_json_to_excel(tHeader, data, '列表excel')
    //    })
    //  },
    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    // 操作列点击实现方法    lyx   20190411
    handleMethod (index, row, methodName) {
      this.handleClearSelection()
      this.$refs['table'].toggleRowSelection(row, true)
      this.$emit(methodName, row)
    },
    // 解决表格错位
    doLayout () {
      this.$refs['table'].doLayout()
    },
    getTableData () {
      return this.tableData
    }
  }
}
</script>
<style>
.el-table td {
  padding: 6px 0 !important;
}

.page {
  padding: 0 6px;
  text-align: right;
}

.operate {
  text-align: center;
}

.tableLimit tr td .cell {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2; /*可以显示的行数，超出部分用...表示 */
  -webkit-box-orient: vertical;
}
.el-table .cell {
  white-space: pre-line; /*保留换行符*/
}
.pagination-diy {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
