<template>
  <div class="flexYbox" :class="{ height100: heights != 'auto' }" style="margin:1px">
    <div class="flexbox pdt5 pdb5" v-if="showSearch">
      <ts-input
        placeholder="请输入关键字搜索"
        width="'200px'"
        type="search"
        suffix-icon="'iconfont icon-Group-14'"
      ></ts-input>
    </div>
    <!-- 列表 -->
    <div class="flex hidden">
      <div
        class="table__box"
        :style="{width: widths, height: heights == 'auto' ? '':heights}"
        style="position: relative;"
      >
        <div
          :style="{width: widths, height: heights == 'auto' ? '':'calc(' + heights + ' - ' + m_h + 'px) !important'}"
        >
          <!-- 普通网格 -->
          <vxe-table
            :tooltip-config="{ enterable: true }"
            :show-header="showHeader"
            ref="tstable"
            class="sortable-column-demo"
            column-key
            :row-id="rowId || 'id'"
            :height="heights != 'auto' ? 'auto':''"
            :border="border ? border : 'full'"
            :row-style="rowStyle"
            :cell-class-name="cellClassName"
            :header-cell-style="headerCellStyle"
            :cell-style="cellStyle"
            :stripe="stripe"
            @header-cell-click="headerClickEvent"
            :data="sources.data"
            :id="sources.id"
            :show-header-overflow="!headerOverflow"
            :key="uuid"
          >
            <vxe-table-column type="seq" width="40" align="center" :visible="rownumbers" title="序号"></vxe-table-column>
            <vxe-table-column
              v-for="(config) in colModel"
              v-bind="config"
              :width="!isNaN(Number(config.width)) ? (Number(config.width) + 20):config.width"
              :key="config.id"
            >
              <table-child-column
                v-for="(c_item, index) in config.children"
                :column="c_item"
                :key="index"
              ></table-child-column>
            </vxe-table-column>
          </vxe-table>
        </div>
        <div class="pageDataGrid" v-if="offPage == false">
          <div class="fl">
            <span class="icn">
              <i class="iconfont icon-houtui font12"></i>
            </span>
            <span class="icn">
              <i class="iconfont icon-cebianlanshouqi font12"></i>
            </span>
            <vxe-input v-model="nowPage" placeholder class="nowPage" align="center"></vxe-input>
            <!-- <div class="nowPage vxe-input type--text is--center is--controls">
              <input v-model="nowPage" type="text" placeholder="" autocomplete="off" class="vxe-input--inner" @change="pageGo('go')">
            </div>-->
            <span class="icn">
              <i class="iconfont icon-cebianlanzhankai font12"></i>
            </span>
            <span class="icn">
              <i class="iconfont icon-qianjin font12"></i>
            </span>
            <vxe-select v-model="pageSize" placeholder class="select">
              <vxe-option
                v-for="(item, index) in pageSizeArr"
                :key="index"
                :value="item.value"
                :label="`${item.text}`"
              ></vxe-option>
            </vxe-select>
          </div>
          <div
            class="fr font12"
          >当前页第{{ (pageNo - 1) * pageSize + 1 }}-{{ pageNo * pageSize > totalCount ? totalCount: pageNo * pageSize }}条，共{{ totalCount }}条</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
export default {
  name: 'biTable',
  components: {
    'table-child-column': {
      name: 'table-child-column',
      props: ['column'],
      data: function() {
        return {}
      },
      template: `
       <vxe-table-column v-bind="column" :width="!isNaN(Number(column.width)) ? (Number(column.width) + 20):column.width" :sortable="column.sortable">
          <table-child-column v-for="(c_item, index) in column.children" :column="c_item" :key="index"></table-child-column>
        </vxe-table-column>
      `
    }
  },
  props: {
    showSearch: {
      type: [Boolean],
      default: false
    },
    headerOverflow: {
      type: [String, Boolean],
      default: false
    },
    styleData: {
      type: [Object, Array, Boolean],
      default: false
    },
    showHeader: {
      type: [Boolean, String],
      default: true
    },
    source: Object,
    colModels: String,
    offPages: Boolean,
    width: [String, Number, Boolean],
    height: [String, Number, Boolean],
    rowId: String,
    border: String,
    rownumbers: Boolean,
    keyId: String
  },
  data() {
    return {
      offPage: this.offPages,
      sources: this.source,
      widths: this.width || '100%', //  宽
      heights: this.height || 'auto', // 表格高度
      colModel: [], // 表格基本属性
      rows: 1, // 表头行数
      data: [], // 表格数据
      pageSize: 0, // 当页条数
      nowPage: '1', // 当前分页
      pageNo: 1, // 当前分页
      totalCount: 0, // 总条数
      pageCount: 1, // 总页数
      pageSizeArr: this.pageSizeArrFn(), // 页数选中对象
      stripe: true, // 斑马纹
      m_h: 30,
      isLoad: true,
      isHasChild: false,
      uuid: this.$utils.uuid(6)
    }
  },
  created() {
    const _this = this
    let isbutton = false
    if (this.sources.isPage === true || this.sources.offPage === true) {
      this.offPage = true
      this.m_h = 0
    } else {
      this.offPage = false
    }
    this.colModelFn(this.sources.colModel) // 格式化列表配置
    // this.rowsCount() // 计算合并表头行
    this.rows = this.colModel.length // 表头行数
    this.pageSize = this.sources.pageSize || 100 // 当页条数
  },
  mounted() {
    if (this.showHeader) {
      //显示表头
      this.columnDrop()
    }
    if (this.styleData && this.styleData.backgroundColor != '#fff') {
      //如果有列表样式则无斑马纹
      this.stripe = false
    }
    this.$eventBus.$on('refreshTable' + this.keyId, this.refreshTable)
  },
  methods: {
    refreshTable() {
      this.uuid = this.$utils.uuid(6)
    },
    // 列拖拽
    columnDrop() {
      let _this = this
      this.$nextTick(() => {
        let xTable = this.$refs.tstable
        this.sortable = Sortable.create(
          xTable.$el.querySelector(
            '.body--wrapper>.vxe-table--header .vxe-header--row'
          ),
          {
            handle: '.vxe-header--column:not(.col--fixed)',
            onEnd: ({ item, newIndex, oldIndex }) => {
              let {
                fullColumn,
                tableColumn,
                collectColumn
              } = xTable.getTableColumn()
              let targetThElem = item
              let wrapperElem = targetThElem.parentNode
              let newColumn = collectColumn[newIndex]
              if (newColumn.fixed) {
                // 错误的移动
                if (newIndex > oldIndex) {
                  wrapperElem.insertBefore(
                    targetThElem,
                    wrapperElem.children[oldIndex]
                  )
                } else {
                  wrapperElem.insertBefore(
                    wrapperElem.children[oldIndex],
                    targetThElem
                  )
                }
                return this.$utils.msg(this, '固定列不允许拖动！', 'warning')
              }
              // _this.$emit('columnDrop',oldIndex,newIndex)
              // let currRow = _this.colModel.splice(oldIndex, 1)[0]
              // _this.colModel.splice(newIndex, 0, currRow)
              // console.log(currRow,oldIndex,newIndex)
              // xTable.refreshColumn() // 重新计算宽度
              // 转换真实索引
              let oldColumnIndex = xTable.getColumnIndex(
                collectColumn[oldIndex]
              )
              let newColumnIndex = xTable.getColumnIndex(
                collectColumn[newIndex]
              )
              // 移动到目标列
              let currRow = collectColumn.splice(oldColumnIndex, 1)[0]
              collectColumn.splice(newColumnIndex, 0, currRow)
              xTable.loadColumn(collectColumn)
              // 发监听
              _this.$emit('columnDrop', oldIndex, newIndex)
            }
          }
        )
      })
    },
    rowStyle({ row, rowIndex }) {
      if (this.styleData.stripe == 'false' || this.styleData.stripe == false) {
        return { backgroundColor: this.styleData.backgroundColor }
      } else {
        if (rowIndex % 2 == '0') {
          return { backgroundColor: this.styleData.backgroundColor }
        } else {
          return { backgroundColor: this.styleData.anotherBackgroundColor }
        }
      }
    },

    headerCellStyle({ column, columnIndex }) {
      if (this.sources.headColor || this.source.headBackground) {
        return {
          backgroundColor: this.sources.headBackground,
          color: this.sources.headColor
        }
      } else {
        return {
          backgroundColor: '',
          color: ''
        }
      }
    },
    cellClassName({ column, columnIndex }) {
      if (this.styleData) {
        for (let i = 1; i < this.styleData.cols.length - 1; i++) {
          if (columnIndex == i) {
            if (this.styleData.cols[columnIndex].clickEvent) {
              return 'hastable'
            }
          }
        }
      }
    },
    cellStyle({ row, rowIndex, column, columnIndex }) {
      if (this.styleData && column.type != 'seq') {
        if (row.KSMC && row.KSMC == '合计') {
          //合计特需处理 自定义报表返回的结果
          return {
            fontWeight: 600,
            fontSize: '13px',
            color: '#333'
          }
        }
        let col = this.sources.rownumbers
          ? this.styleData.cols[columnIndex - 1]
          : this.styleData.cols[columnIndex]
        if (col) {
          return {
            backgroundColor: col.backgroundColor,
            color: col.fontColor,
            fontSize: col.fontSize + 'px'
          }
        }
      } else {
        return {
          fontSize: '12px',
          color: '#333'
        }
      }
    },
    // 列表配置格式化
    colModelFn(arr) {
      // const _this = this
      // const _arr = []
      // this.sources.dataType = this.sources.dataType || 'json'
      let isChildren = false
      arr.forEach((v, i) => {
        if (v.frozen === true) {
          v.fixed = 'left'
        }
        // v.sortable = v.sortable != false // 排序无法联动，故先置否
        v.children = v.isHasChild ? v.children : []
        if (v.children.length > 0) {
          // for (let child of v.children) {
          //   child.sortable = child.sortable != false // 排序无法联动，故先置否
          // }
          isChildren = true
        }
      })
      this.colModel = JSON.parse(JSON.stringify(arr))
      if (isChildren) {
        this.$nextTick(() => {
          if (isChildren) {
            let ss = this.$refs.tstable.$el.getElementsByClassName(
              'vxe-table--body-wrapper'
            )
            ss[0].style.height = '10px !important'
          }
        })
      }
      //假如有child 重载表格 如果没有就不用
      return isChildren
    },
    // 每页条数
    pageSizeArrFn() {
      return [
        { value: 50, text: '50' },
        { value: 100, text: '100' },
        { value: 200, text: '200' },
        { value: 500, text: '500' },
        { value: 1000, text: '1000' }
      ]
    },
    // 获取所有的表格列
    getTableColumn() {
      return this.$refs.tstable.getTableColumn()
    },
    headerClickEvent({ row, column }) {
      this.$emit('HeaderClick', row, column)
    }
  },
  destroyed() {
    this.$eventBus.$off('refreshTable' + this.keyId, this.refreshTable)
  },
  watch: {
    // source:{
    //   handler(val){
    //     this.sources = val
    //   },
    //   deep:true
    // },
    colModels: {
      handler(o, a) {
        let isNeed = this.colModelFn(JSON.parse(o))
        // console.log(this.getTableColumn().collectColumn)
        // this.$nextTick(() => {
        //   // 重新计算宽度
        //   // if (isNeed) {
        //   this.$refs.tstable.reloadColumn(this.getTableColumn().collectColumn) // 重新计算宽度
        //   // }
        //   this.$refs.tstable.refreshColumn()
        // })
        // 处理所有列出现的问题
        // if (this.rownumbers && this.colModel[0].type != 'seq') {
        //   this.colModel.unshift({ type: 'seq', width: '40', align: 'center',title:'序号' })
        // }
        this.$refs.tstable.refreshColumn(this.colModel)
      }
    },
    rownumbers: {
      handler(o, a) {
        if (o && this.colModel[0].type != 'seq') {
          // 显示行号
          this.colModel.unshift({
            type: 'seq',
            width: '40',
            align: 'center',
            title: '序号'
          })
        } else {
          // 不显示行号
          if (this.colModel[0].type == 'seq') {
            this.colModel.shift()
          }
        }
        this.$refs.tstable.reloadColumn(this.colModel)
      }
    },
    offPages: {
      handler(o, a) {
        this.offPage = o
        if (o === true) {
          this.m_h = 0
        } else {
          this.m_h = 30
        }
      }
    },
    'styleData.backgroundColor': {
      handler(o) {
        if (this.styleData && this.styleData.backgroundColor != '#fff') {
          //如果有列表样式则无斑马纹
          this.stripe = false
        } else {
          this.stripe = true
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .el-checkbox__label {
  line-height: 28px;
}
/deep/
  .table__box
  > div
  > .vxe-table
  > .vxe-table--main-wrapper
  > .vxe-table--body-wrapper {
  height: 100%;
}
.pageDataGrid {
  position: absolute;
  width: 100%;
  .font12 {
    margin-right: 6px;
  }
}
// /deep/ .tb_column div{
//   writing-mode: tb-rl;
// }
/deep/
  .sortable-column-demo
  .vxe-header--row
  .vxe-header--column.sortable-ghost,
.sortable-column-demo .vxe-header--row .vxe-header--column.sortable-chosen {
  background-color: #dfecfb;
}
/deep/.vxe-table .vxe-header--column.col--right {
  text-align: right !important;
}
</style>
