<template>
  <div>
    <vxe-grid
      ref="xTable"
      :show-overflow="hideOverflow === undefined || hideOverflow === true?true:false"
      :auto-resize="true"
      :height="500"
      :loading="loading"
      :pager-config="
      hidePage === undefined?{total:getPage.total,currentPage:getPage.current,pageSize:getPage.size,pageSizes:pageSizeOpts,background:true}:null"
      :scroll-y="setOptimization === undefined?defOptimization:setOptimization"
      :checkbox-config="selectConfig"
      @checkbox-all="_selectAll"
      @checkbox-change="_selectRowChange"
      @page-change="_pageSizeChange"
      :cell-class-name="_tableCellClassName"
      :row-class-name="_tableRowClassName"
      :edit-config="editConfig"
      :row-key="true"
      :tooltip-config="{enterable:true}"
      size="mini"
      border
      resizable
      stripe
      show-header-overflow
    >
      <vxe-table-column
        v-if="hideCheckbox===undefined || hideCheckbox === false"
        type="checkbox"
        fixed="left"
        width="50"
        align="center"/>
      <vxe-table-column
        type="seq"
        fixed="left"
        title="序号"
        width="50"
        align="center"/>
      <slot></slot>
      <vxe-table-column
        :width="$optColWidth(iconMsg)"
        v-if="$optColWidth(iconMsg)>0?true:false"
        title="操作"
        align="center" fixed="right">
        <template slot-scope="scope">
          <VXEIconList :msg="iconMsg" @on-result-change="_iconClick" :rowData="scope.row"
                       :rowIndex="scope.rowIndex"></VXEIconList>
        </template>
      </vxe-table-column>
      <slot name="col"></slot>
    </vxe-grid>
    <!--自定义表格列-->
    <div style="position: absolute;right:0;top:0;z-index:2000">
      <slot name="setting"></slot>
    </div>
  </div>
</template>
<script>
/**
 * VXE-TABLE 数据录入用(分包数据录入，检测数据录入 专用)
 */
import VXEIconList from '../base/VXEIconList'

export default {
  components: { VXEIconList },
  props: {
    hideOverflow: null,
    hidePage: null,
    pageColumns: null,
    // tableHeight: 500,
    hideCheckbox: null,
    optColWidth: null,
    getPage: null,
    iconMsg: null,
    warnKey: null,
    selectData: null,
    hideElevator: null,
    hideTotal: null,
    hideSizer: null,
    clickValue: null, // 单击返回值
    noWarning: null, // 不显示警告提示

    isDataTest: null, // 判断是否是数据检测
    tableName: null, // 该值存在，则支持自定义表格
    setOptimization: null, // 加载滚动配置项
    rows: null
  },
  data() {
    return {
      formId: '',
      extendsData: {},
      loading: false,
      pageParams: {
        page: 1,
        rows: this.rows !== undefined ? this.rows : this.$defRow
      },
      rowData: {},
      checkData: [],
      sampleHandleValue: '',
      // 一系列配置
      pageSizeOpts: [50, 100, 500, 1000],
      // 默认的配置
      defOptimization: this.$setOptimization(),
      selectConfig: { checkField: 'checked', trigger: 'row' },
      editConfig: {
        trigger: 'click',
        mode: 'cell',
        showIcon: true,
        autoClear: false,
        showStatus: true
      }
    }
  },
  watch: {
    // // 监听数据
    'getPage.records': function(newVal, oldVal) {
      this._loadData(newVal)
    }
  },
  methods: {
    _loadData(data) {
      // 阻断 vue 对大数组的双向绑定，大数据性能翻倍提升
      if (this.$refs.xTable) {
        this.$refs.xTable.loadData(data)
      }
    },
    // 刷新column 和刷新数据
    _refreshColumn() {
      this.$refs.xTable.refreshColumn()
      this.$refs.xTable.syncData()
    },
    _pageSizeChange(row) {
      switch (row.type) {
        case 'size':
          this.pageParams.page = 1
          this.pageParams.rows = row.pageSize
          this._pageParamsChange()
          break
        case 'current':
          this._pageChange(row.currentPage)
          break
      }
    },
    _pageChange(page) {
      this.pageParams.page = page
      this._pageParamsChange()
    },
    _pageParamsChange() {
      this.$emit('on-result-change', 'changeSize')
    },
    _searchParams() {
      const data = {}
      const serData = this.$serialize(this.formId)
      Object.assign(data, serData, this.extendsData)
      if (this.hidePage === undefined) {
        return this.$extend(data, this.pageParams)
      } else {
        return this.$extend(data)
      }
    },
    _page(formId, uri, extendsData) {
      this.loading = true
      if (this.tableName !== undefined) {
        // tableName存在-----支持自定义表格
        this._settingCol(formId, uri, extendsData)
      } else {
        this._pageTemp(formId, uri, extendsData)
      }
    },
    _settingCol(formId, uri, extendsData) {
      if (uri) {
        // 为了避免uri为undefined
        this.$store
          .dispatch('SysTableColumn/getByTableName', this.tableName)
          .then(() => {
            // 查询用户下的表格数据
            const userTableCode = this.$store.state.SysTableColumn.model
            this.$emit(
              'on-result-change',
              'table-col',
              this.$tableColumns(this.pageColumns, userTableCode)
            )
            this._pageTemp(formId, uri, extendsData)
          })
      }
    },
    // 临时
    _pageTemp(formId, uri, extendsData) {
      this.formId = formId
      if (extendsData) {
        this.extendsData = extendsData
      }
      this.$store.dispatch(uri, this._searchParams()).then(() => {
        this.loading = false
        this.$emit('on-result-change', 'page', '')
        this._refreshColumn()
      })
    },
    // 多选
    _selectAll: function(data) {
      this._selectRowChange(data)
    },
    _selectRowChange(data) {
      // 可编辑单元格
      if (this.hideCheckbox === undefined || this.hideCheckbox === false) {
        const selData = data.selection
        this.checkData = selData
        // 默认返回的是id数组
        if (this.selectData === undefined) {
          const idList = []
          for (let i = 0; i < selData.length; i++) {
            idList.push(selData[i].id)
          }
          this.$emit('on-result-change', 'selectIds', idList)
          this.$emit('on-result-change', 'selectData', selData)
        } else {
          // 有selectData参数时执行
          this.$emit('on-result-change', 'selectData', selData)
        }
      }
    },
    // 单元格变色
    _tableCellClassName({ row, column, rowIndex, columnIndex }) {
      // if (column.property === 'name' && row['progress'] && row.progress.display.indexOf('退回') !== -1) {//含有退回就变红
      //   return 'cell-red';
      // }
      if (
        column.property === 'serviceType' &&
        row.serviceType &&
        row.serviceType.indexOf('加急') !== -1
      ) {
        // 含有加急就变红
        return 'cell-red'
      }
      // if (column.property === 'name' && row['name'] && row.name.indexOf('复测') !== -1) {//含有加急就变红
      //   return 'cell-red';
      // }
    },
    // 整行变色
    _tableRowClassName({ row, rowIndex }) {
      // console.log('row==', row, rowIndex)
      if (this.checkData.length !== 0) {
        /* 选中的进行高亮显示 */
        const index = this.checkData.indexOf(row)
        if (index !== -1) {
          return 'high-light-row'
        }
      } else {
        /* 没选中的根据页面逻辑变色 */
      }
    },
    // 操作列回调
    _iconClick(name, rowData, componentName, rowIndex, obj) {
      this.$emit('on-result-change', 'iconClick', {
        name: name,
        rowData: rowData,
        componentName: componentName,
        rowIndex: rowIndex,
        obj: obj
      })
    },
    // 关闭loading
    _hideLoading() {
      this.loading = false
    },
    // 打开loading
    _showLoading() {
      this.loading = true
    },
    // 清空选中checkbox状态
    _clearSelection() {
      this.$nextTick(function() {
        this.$refs.xTable.clearCheckboxRow()
      })
      this.checkData = []
      if (this.hideCheckbox === undefined || this.hideCheckbox === false) {
        if (this.selectData === undefined) {
          this.$emit('on-result-change', 'selectIds', [])
        } else {
          this.$emit('on-result-change', 'selectData', [])
        }
      }
    },
    // 激活单元格编辑 row:当前行数据，field:单元格的英文名称
    _activeCell(obj) {
      this.$refs.xTable.setActiveCell(obj.row, obj.field)
      if (obj.msg === 'left') {
        // 向左返回的时候 清除滚动状态
        this.$refs.xTable.clearScroll()
      }
    },
    // 只刷新选中行的数据
    _refreshRows(rowList) {
      const records = this.getPage.records
      for (let i = 0; i < rowList.length; i++) {
        const index = records.findIndex(item => item.id === rowList[i].id)
        if (index !== -1) {
          this.$set(this.getPage.records, index, rowList[i])
        }
      }
    }
  }
}
</script>
