<template>
  <div class="table">
    <el-table id="out-table"
              ref="table"
              :height="table.height"
              :header-cell-style="{color:'#000'}"
              :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 :type="columnType"></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'">

          </template>
        </el-table-column>
        <!--有背景的图片列-->
        <el-table-column v-if="col.tableType==='bcImage'"
                         :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">
            <div v-if="scope.row[col.key]"
                 class="img_bc"
                 :style="{background: col.bcColor?col.bcColor:'#e3271c'}">

              <img :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'">
            </div>

          </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"
                         show-overflow-tooltip
                         :align="columnAlign"
                         :header-align="headerAlign"
                         :formatter="col.formatter"></el-table-column>
      </template>
      <!--排序操作列-->
      <el-table-column v-if="orderOperations.length && orderOperations.length > 0"
                       label="移动"
                       :width="orderOperationWidth"
                       fixed="right"
                       align="center"
                       header-align="center"
                       class="operate">
        <template slot-scope="scope">

          <el-button v-for="(item,index) in orderOperations"
                     :key="index"
                     :style=item.style
                     :type=item.type
                     :size=item.size
                     :icon=item.icon
                     :plain=item.plain
                     @click.stop="handleMethod(scope.$index, scope.row,item.methodName)"></el-button>
        </template>
      </el-table-column>
      <!--操作列-->
      <el-table-column v-if="operations.length && operations.length > 0"
                       label="操作"
                       :min-width="operationWidth"
                       fixed="right"
                       header-align="center"
                       class="operate">
        <template slot-scope="scope">
          <!--传入的操作按钮属性    lyx   20190411   -->
          <el-button v-for="(item,index) in operations"
                     :key="index"
                     v-show="item.isShow(scope.row)"
                     :style=item.style
                     :type=item.type
                     :size=item.size
                     :plain=item.plain
                     @click.stop="handleMethod(scope.$index, scope.row,item.methodName)">{{typeof (item.lable) === 'function'?(item.lable)(scope.row[item.key]) :item.lable}}</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>

import CDialog from './CDialog'
import { mapGetters } from 'vuex'
import { requestPost } from "@/js/dai/request";
export default {
  components: { CDialog },
  data () {
    return {
      tableData: [],
      tableColumn: window.app.service.getColumns(this.keyword, 'table'),
      loading: false,
      table: {
        height: this.tableHeight,
        params: {}
      },

      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 []
      }
    },
    orderOperations: {
      type: Array,
      default () {
        return []
      }
    },
    tableHeight: {
      type: Number
    },
    pageVisible: Boolean, // 是否显示page分页     lyx   20190411

    filterParams: {
      type: Array,
      default () {
        return []
      }
    }
  },
  activated () {
    // debugger
    // this.$nextTick(() => {
    //   this.$refs.table.doLayout() // 解决表格错位
    // })
  },
  computed: {

    // 操作列宽度
    operationWidth: function() {

      if (this.operations.includes('add')) {
        return (this.operations.length - 1) * 80 // 操作列包含add类型按钮时返回
      } else if (this.operations.includes('analyze')) {
        return (this.operations.length + 0.5) * 80 // 操作列包含analyze类型按钮时返回
      } else {
        return this.operations.length * 80
      }
    },
    // 移动操作列宽度
    orderOperationWidth: function() {


      return this.orderOperations.length * 50

    },
    ...mapGetters(['resolution'])
  },
  methods: {
    doLayout () {
      this.$refs.table.doLayout() // 解决表格错位
    },
    render () {
      this.loadData()
    },
    async loadData () {
      this.$refs.table.doLayout() // 解决表格错位
      this.templateRadio = ''
      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)
      //  获取数据

      const { data, code, rspMsg } = await requestPost(this.url, this.table.params)
      if (code === 0) {
        if (data) {
          this.tableData = data
          // console.log("this.filterParams", this.filterParams)
          if (this.filterParams.length > 0) {

            this.filterParams.forEach(paramItem => {
              const key = this.filterParams[0].key
              const value = this.filterParams[0].value

              this.tableData = this.tableData.filter(item => {
                // console.log(item[key])
                // console.log(item[key].indexOf(value))
                return item[key].indexOf(value) != -1

              })
            })

          }
        }
        this.loading = false
      } else {
        this.$message.error(rspMsg)

        this.loading = false
      }

      // await window.app.ajax.post(
      //   this.url,
      //   this.table.params,
      //   (data, rspMsg) => {
      //     if (data) {
      //       this.tableData = data
      //       console.log("this.filterParams", this.filterParams)
      //       if (this.filterParams.length > 0) {

      //         this.filterParams.forEach(paramItem => {
      //           const key = this.filterParams[0].key
      //           const value = this.filterParams[0].value

      //           this.tableData = this.tableData.filter(item => {
      //             // console.log(item[key])
      //             // console.log(item[key].indexOf(value))
      //             return item[key].indexOf(value) != -1

      //           })
      //         })

      //       }
      //     }
      //     // console.log(this.tableData)
      //     this.loading = false

      //   },
      //   (rspMsg, data) => {

      //   }
      // )
    },
    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()
    },

    // 单选选中
    getRadioRow (index, row) { // 获取选中数据
      this.$emit('selectRadioRow', row)
    },
    // 导出表格
    handleOutTable (name) {
      window.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, index)
    },
    getTableData () {
      return this.tableData
    }


  }
}
</script>
<style >
.el-table td {
  padding: 6px 0 !important;
}

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

.operate {
  text-align: center;
}

.img_bc {
  width: 50px;
  height: 50px;
  margin: 5px auto;
  text-align: center;
  background: #e3271c;
  box-shadow: 0px 2px 12px 0px rgba(209, 34, 24, 0.57);
  border-radius: 50%;
  padding: 12px;
}
</style>
