 <template>
  <div :id="elId"
       style="width:100%;height:100%">
    <el-table style="width:100%;height:100%;overflow: auto;"
              :data="this.grouptableData"
              :style="tableStyle"
              :header-cell-style="setHeaderRowStyle"
              :row-style="setRowStyle"
              :cell-style="setcellStyle"
              :max-height="maxHeight"
              :border="configData.built_border"
              :show-header="!configData.hideHeader"
              @row-click="tableRowClick"
              @cell-click='tableCellClick'
              @cell-mouse-enter="tableCellmouse"
              @cell-mouse-leave="tableCelleave">
      <!-- <el-table-column type="selection"
                       width="55">
      </el-table-column> -->
      <template v-for="(item,index) in key_arr">
        <template v-if="item.length===1">
          <template>
            <el-table-column :label="item[0].startsWith('img_')?item[0].slice(4):item[0]"
                             :width="configData.setWidth?configData.setWidth.styleArr[index] : ''"
                             :show-overflow-tooltip="configData.showTooltip"
                             :sortable="configData.sortable?configData.sortable.styleArr[index]:false"
                             :key="index">
              <template slot-scope="scope">
                <template v-if="item[0].startsWith('img_')">
                  <el-image :src="scope.row[item[0]]"
                            :fit="fit"
                            :style="imgStyle"></el-image>
                </template>
                <template v-else>
                  <template v-if="detailVisible2">
                    <el-popover placement="top-start"
                                width="400"
                                trigger="hover">
                      <el-table :data="tableDataDetail"
                                style="width: 100%">
                        <el-table-column v-for="(prop,index) in tableHeader"
                                         :prop="prop"
                                         :label="prop"
                                         :key="index">
                        </el-table-column>
                      </el-table>
                      <span slot="reference">{{scope.row[item[0]]}}</span>
                    </el-popover>
                  </template>
                  <template v-else>
                    <span>{{scope.row[item[0]]}}</span>
                  </template>
                </template>
              </template>
            </el-table-column>
          </template>
        </template>
        <template v-else>
          <el-table-column :label="item[0].split('__')[0]"
                           :key="index">
            <el-table-column v-for="item2 in item"
                             :key="item2"
                             :label="item2.split('__')[1]"
                             :width="configData.setWidth?configData.setWidth.styleArr[index] : ''"
                             :show-overflow-tooltip="configData.showTooltip"
                             :sortable="configData.sortable?configData.sortable.styleArr[index]:false">
              <template slot-scope="scope">
                <template>
                  <span>{{scope.row[item2]}}</span>
                </template>
              </template>
            </el-table-column>
          </el-table-column>
        </template>
      </template>
    </el-table>
    <el-pagination v-if="pagination"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   :current-page.sync="paginationPage"
                   :page-sizes="[50, 100, 200, 500]"
                   :page-size="paginationPageSize"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="pagination.total">
    </el-pagination>
    <jsoneditor v-model='jsoneditorVisible'
                :elInfo='params'
                :downSql='downSql'
                :layout='layout'
                :initStyle='initStyle'
                :saveConfigDataFun='saveConfigDataFun'
                :jsoneditorData='jsoneditorData'>
    </jsoneditor>
    <tableDeatil v-model='detailVisible'
                 :tableData='tableDataDetail'></tableDeatil>
  </div>
</template>
<script>
import uuidv1 from 'uuid/v1'
import dataDemo from './dataDemo.js'
import * as Action from './action.js'
import jsoneditor from '../commonC/jsoneditor'
import groupBy from 'lodash/groupBy'
import values from 'lodash/values'
import tableDeatil from './tableDetail'
export default {
  components: {
    jsoneditor,
    tableDeatil
  },
  name: 'hsTable',
  props: {
    allSourceData: {
      type: Object,
      default() {
        return {
          config: {},
          sourceData: []
        }
      }
    },
    isCarousel: {
      type: Boolean,
      default() {
        return true
      }
    },
    params: {
      type: Object,
      default() {
        return {
          el: 'hsTable',
          page: 'page1',
          position: 'table1'
        }
      }
    },
    saveConfigDataFun: {
      type: Function
    },
    downSql: {
      type: Function
    },
    layout: {},
    initStyle: {}
  },
  data() {
    return {
      jsoneditorData: {},
      elId: '',
      tableData: [],
      configData: {},
      key_arr: [],
      jsoneditorVisible: false,
      tableStyle: '',
      imgStyle: '',
      headerRowStyleArr: [],
      rowStyleArr: [],
      columnStyleArr: [],
      pageArr: {},
      page: 0,
      currentPage: 0,
      grouptableData: [],
      tableObj: {},
      time: 0,
      timer: null,
      fit: 'fill',
      pagination: null,
      paginationPage: 1,
      paginationPageSize: 50,
      detailVisible: false,
      detailVisible2: false,
      tableDataDetail: [],
      tableHeader: [],
      outBoxDom: null,
      maxHeight: 'none'
    }
  },
  watch: {
    allSourceData: {
      handler: function(newVal, oldVal) {
        if (newVal.sourceData && newVal.config) {
          this.configData = newVal.config
          if (Array.isArray(newVal.sourceData)) {
            this.tableData = newVal.sourceData
          } else {
            this.tableData = newVal.sourceData.data
            this.pagination = newVal.sourceData.pagination// 分页信息
            this.paginationPage = this.pagination.currentPage // 当前页
            this.paginationPageSize = this.pagination.pageSize // 分页条数
          }
        } else {
          this.tableData = dataDemo.tableData
          this.configData = dataDemo.configData
        }
      },
      deep: true
    },
    tableData: {
      handler: function(newVal, oldVal) {
        this.alterTableAction()
        this.alterConfigAction()
      },
      deep: true
    },
    configData: {
      handler: function(newVal, oldVal) {
        this.alterTableAction()
        this.alterConfigAction()
      },
      deep: true
    },
    jsoneditorVisible(val) {
      const configKeys = Object.keys(this.configData)
      if (configKeys.length) {
        this.jsoneditorData.config = this.configData
      } else {
        this.jsoneditorData.config = dataDemo.configData
      }
      if (this.tableData.length) {
        this.jsoneditorData.sourceData = this.tableData
      } else {
        this.jsoneditorData.sourceData = dataDemo.tableData
      }
    },
    isCarousel: {
      handler: function(newVal, oldVal) {
        if (newVal && this.timer !== null) {
          this.timer = setInterval(this.changeTableDataFun, newVal)
        } else {
          clearInterval(this.timer)// 清除定时器
          this.timer = null
        }
      },
      deep: true
    },
    time: {
      handler: function(newVal, oldVal) {
        if (newVal > 0 && this.isCarousel) {
          this.timer = setInterval(this.changeTableDataFun, newVal)
        }
      },
      deep: true
    }
  },
  created() {
    this.elId = uuidv1() // 获取随机id
  },
  mounted() {
    if (this.allSourceData.sourceData && this.allSourceData.config) {
      this.configData = this.allSourceData.config
      if (Array.isArray(this.allSourceData.sourceData)) {
        this.tableData = this.allSourceData.sourceData
      } else {
        this.tableData = this.allSourceData.sourceData.data
        this.pagination = this.allSourceData.sourceData.pagination// 分页信息
        this.paginationPage = this.pagination.currentPage // 当前页
        this.paginationPageSize = this.pagination.pageSize // 分页条数
      }
    } else {
      this.tableData = dataDemo.tableData
      this.configData = dataDemo.configData
    }
    // 没有数据的时候显示local数据
    if (!this.tableData.length) {
      this.initLocalData()
    }
    this.showEditJsonDialog()
    if (this.params.page !== 'page1') {
      this.maxHeight = document.getElementById(this.params.page + this.params.position).offsetHeight
    }
  },
  destroyed() {
    this.outBoxDom.removeEventListener('mousedown', this.boxEventMouse)
    this.chart = null
  },
  beforeDestroy() {
    clearInterval(this.timer)// 清除定时器
    if (this.chart) {
      this.chart.clear()
    }
    this.grouptableData = null
    this.chart = null
    this.timer = null
    this.time = 0
  },
  methods: {
    tableRowClick(row, column, event) {
      this.$emit('RowClick', {
        row: row,
        column: column,
        event: event
      })
    },
    // 单击某个单元格的时候 弹出明细
    tableCellClick(row, column, cell, event) {
      const key = column.label
      if (row[`_data_${key}`]) {
        this.detailVisible = true
        const _data_value = row[`_data_${key}`]
        this.tableDataDetail = _data_value
      } else {
        this.$emit('CellClick', {
          row: row,
          column: column,
          cell: cell,
          event: event
        })
      }
    },
    // 鼠标移入事件
    tableCellmouse(row, column, cell, event) {
      const key = column.label
      if (row[`_data_${key}`]) {
        this.detailVisible2 = true
        const _data_value = row[`_data_${key}`]
        this.tableDataDetail = _data_value
        if (!this.tableDataDetail.length) return
        this.tableHeader = Object.keys(this.tableDataDetail[0])
      }
      if (this.configData.hover) {
        cell.parentNode.style.background = this.configData.hover.hoverBackground
      }
    },
    // 鼠标离开事件
    tableCelleave(row, column, cell, event) {
      this.detailVisible2 = false
      if (this.configData.hover) {
        cell.parentNode.style.background = this.configData.hover.leaveBackground
      }
    },
    handleSizeChange(pageSize) {
      this.paginationPageSize = parseInt(pageSize)
      if (this.paginationPage !== 1) {
        this.paginationPage = 1
      }
      this.$emit('paginationFun', {
        elInfo: this.elInfo, // 此处把组件信息返回出去 方便queryBi统一处理
        pageSize: this.paginationPageSize,
        page: this.paginationPage
      })
    },
    // 当前页 change cb
    handleCurrentChange(currentPage) {
      this.paginationPage = parseInt(currentPage)
      this.$emit('paginationFun', {
        elInfo: this.elInfo,
        pageSize: this.paginationPageSize,
        page: this.paginationPage
      })
    },
    initLocalData() {
      this.tableData = dataDemo.tableData
      this.configData = dataDemo.configData
    },
    // 轮播table数据
    changeTableDataFun() {
      if (this.currentPage === this.page) {
        this.currentPage = 0
      }
      this.grouptableData = this.pageArr[this.currentPage]
      this.currentPage = this.currentPage + 1
    },
    boxEventMouse(event) {
      const that = this
      event.stopPropagation()
      if (event.shiftKey && event.altKey && !event.ctrlKey) {
        that.jsoneditorVisible = true
      }
    },
    // 弹出可编辑的弹框
    showEditJsonDialog() {
      this.outBoxDom = document.getElementById(this.elId)
      this.outBoxDom.addEventListener('mousedown', this.boxEventMouse)
    },
    // 修改表头样式
    setHeaderRowStyle(row) {
      if (this.configData.headerRow) {
        if (this.configData.headerRow.styleArr) {
          for (let i = 0; i < this.configData.headerRow.indexArr.length; i++) {
            if (this.configData.headerRow.indexArr[i] === row.columnIndex) {
              return this.headerRowStyleArr[i]
            }
          }
        }
        return this.configData.headerRow.allStyle
      } else {
        return ''
      }
    },
    // 修改行样式
    setRowStyle(row) {
      if (this.configData.row) {
        if (this.configData.row.styleArr) {
          for (let i = 0; i < this.configData.row.indexArr.length; i++) {
            if (this.configData.row.indexArr[i] === row.rowIndex) {
              return this.rowStyleArr[i]
            }
          }
        }
        return this.configData.row.allStyle
      } else {
        return ''
      }
    },
    // 修改列样式
    setcellStyle(row) {
      if (this.configData.column) {
        if (this.configData.column.styleArr) {
          for (var i = 0; i < this.configData.column.indexArr.length; i++) {
            if (this.configData.column.indexArr[i] === row.columnIndex) {
              return this.columnStyleArr[i]
            }
          }
        }
        return this.configData.column.allStyle
      } else {
        return ''
      }
    },
    alterTableAction() {
      if (this.tableData.length > 0 && this.configData.hs && this.configData.hs.hs_group_time) {
        for (var v in this.tableData[0]) {
          this.tableObj[v] = ''
        }
        this.pageArr = values(groupBy(this.tableData, '_iPage'))
        for (var i = 0; i < this.pageArr.length; i++) {
          if (this.pageArr[i].length < this.configData.hs.hs_group_count) {
            const count = this.configData.hs.hs_group_count - this.pageArr[i].length
            for (let j = 0; j < count; j++) {
              this.pageArr[i].push(this.tableObj)
            }
          }
        }
        this.grouptableData = this.pageArr[0]
        this.page = this.pageArr.length
        this.time = this.configData.hs.hs_group_time
      } else {
        this.grouptableData = this.tableData
      }
      this.key_arr = Action.get_attr_complex(Action.get_attr(this.tableData[0]))
    },
    alterConfigAction() {
      if (this.configData.tableStyle) {
        this.tableStyle = JSON.stringify(this.configData.tableStyle).replace(new RegExp('\"', 'g'), '').replace(new RegExp('{', 'g'), '').replace(new RegExp('\,', 'g'), ';').replace(new RegExp('}', 'g'), ';')
      }
      if (this.configData.imgStyle) {
        this.imgStyle = JSON.stringify(this.configData.imgStyle).replace(new RegExp('\"', 'g'), '').replace(new RegExp('{', 'g'), '').replace(new RegExp('\,', 'g'), ';').replace(new RegExp('}', 'g'), ';')
      }
      if (this.configData.headerRow && this.configData.headerRow.styleArr) {
        this.headerRowStyleArr = Action.joinObj(this.configData.headerRow.styleArr, this.configData.headerRow.allStyle)
      }
      if (this.configData.row && this.configData.row.styleArr) {
        this.rowStyleArr = Action.joinObj(this.configData.row.styleArr, this.configData.row.allStyle)
      }
      if (this.configData.column && this.configData.column.styleArr) {
        this.columnStyleArr = Action.joinObj(this.configData.column.styleArr, this.configData.column.allStyle)
      }
      if (this.configData.gutter) {
        var tableId = document.getElementById(this.elId)
        if (!tableId) return
        var gutterArr = tableId.getElementsByClassName('gutter')
        if ((gutterArr && !gutterArr.length) || !gutterArr) return
        gutterArr[0].style.background = this.configData.gutter.background
        gutterArr[0].style.border = this.configData.gutter.border
        gutterArr[0].style.borderTop = this.configData.gutter.borderTop
        gutterArr[0].style.borderBottom = this.configData.gutter.borderBottom
        gutterArr[0].style.borderLeft = this.configData.gutter.borderLeft
        gutterArr[0].style.borderRight = this.configData.gutter.borderRight
      }
    }
  }

}
</script>
<style>
/* 禁止掉默认的hover事件 */
.el-table--striped .el-table__body tr.current-row > td,
.el-table__body tr.hover-row.current-row > td,
.el-table__body tr.hover-row.el-table__row--striped.current-row > td,
.el-table__body tr.hover-row.el-table__row--striped > td,
.el-table__body tr.hover-row > td {
  background-color: transparent !important;
}
.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: transparent !important;
}

/* 表格背景色透明 */
.el-table th,
.el-table thead.is-group th,
.el-table tr,
.el-table,
.el-table__expanded-cell {
  background-color: transparent;
}

/* 去除表格边框线 */
.el-table::before,
.el-table::after {
  height: 0 !important;
}

/* 多个table组件拼接页面，表头一栏会受其他组件的影响会出现表头错误问题 */
/* 添加上后在合并单元格状态，右边多一个gutter单元格 */
body .el-table th.gutter {
  display: table-cell !important;
}

/* 放大缩小表格产生的滚动条 */

.el-table::-webkit-scrollbar,
.scroll_area::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 0.05rem; /*高宽分别对应横竖滚动条的尺寸*/
  height: 0.01rem;
}
.el-table__body-wrapper::-webkit-scrollbar {
  width: 0.05rem; /*高宽分别对应横竖滚动条的尺寸*/
  height: 0.05rem;
}
.el-table::-webkit-scrollbar-thumb,
.scroll_area::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 0;
  box-shadow: none;
  -webkit-box-shadow: none;
  /*background: #232449;*/
  opacity: 0.7;
}
.el-table__body-wrapper::-webkit-scrollbar-thumb {
  border-radius: 0.04rem;
  box-shadow: none;
  -webkit-box-shadow: none;
  background-color: rgba(186, 186, 255, 0.3);
  opacity: 0.1;
}
.el-table::-webkit-scrollbar-track,
.scroll_area::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  box-shadow: none;
  -webkit-box-shadow: none;
  border-radius: 0;
  background: transparent;
}
.el-table__body-wrapper::-webkit-scrollbar-track {
  box-shadow: none;
  -webkit-box-shadow: none;
  border-radius: 0;
  background: transparent;
}
.el-table__body-wrapper::-webkit-scrollbar {
  /*display: none;*/
  width: 0; /*高宽分别对应横竖滚动条的尺寸*/
  height: 0.05rem;
}
</style>
