<template>
  <div class="container">
    <!-- 检索 -->
    <div class="table-filter" v-if="isShowFilter" @keyup.enter="enterHandle">
      <div
        class="filter-item"
        v-for="(item, index) in tableFilter"
        :key="index"
        :style="{
          float: item.align === 'right' ? 'right' : 'left'
        }"
      >
        <component
          v-model="filterData[item.value]"
          @click="filterClick(item)"
          :placeholder="item.placeholder"
          :is="item.name"
          :type="item.type && item.type"
          :format="item.format"
          :icon="item.icon"
          :style="{
            width: item.width || getComWidth(item)
          }"
          :disabled="item.disabled"
          :clearable="!item.unClearable"
          filterable
          @on-change="onChange($event, item)"
          @on-click="onChange($event, item)"
        >
          <!-- span 显示的字段 -->
          <span v-if="item.name === 'span'" :style="item.style">{{
            item.text
          }}</span>
          <!-- 按钮 显示的字段 -->
          <span v-if="item.name === 'Button'">{{ item.text }}</span>
          <!-- 单选框 显示列表 -->
          <Radio
            :label="radio.value"
            v-if="item.name === 'RadioGroup'"
            v-for="(radio, index) in item.list"
            :key="index"
          >
            {{ radio.label }}
          </Radio>
          <!-- 下拉框 显示列表 -->
          <Option
            v-if="item.name === 'Select'"
            v-for="select in item.list"
            :value="select.value"
            :key="select.value"
            >{{ select.label }}</Option
          >
        </component>
      </div>
    </div>
    <!-- 表格 -->
    <div ref="table-content" class="table-content">
      <Table
        ref="table"
        :columns="newColumns"
        :data="data"
        :border="border"
        :row-class-name="rowClassName"
        :height="height || computedHeight"
        @on-select="onselect"
        @on-select-cancel="onselectCancel"
        @on-select-all="onselectAll"
        @on-selection-change="onselectAllCancel"
        @on-row-click="rowClick"
      ></Table>
    </div>
    <!-- 分页 -->
    <div class="table-page" v-if="isShowPage">
      <slot name="total"></slot>
      <Page
        :current="tablePage.pageIndex"
        :page-size="tablePage.pageSize"
        :total="tablePage.total"
        :show-total="true"
        show-elevator
        @on-change="changePage"
      />
    </div>
  </div>
</template>

<script>
export default {
  props: {
    tooltip: {
      type: Boolean,
      default: false
    },
    height: {
      type: Number | String
    },
    // 是否显示边框
    border: {
      type: Boolean,
      default: false
    },
    // 是否单选
    multiple: {
      type: Boolean,
      default: false
    },
    // 已选择物料
    selectedList: {
      type: Array,
      default () {
        return []
      }
    },
    // 根据key来获取选中的数据
    selectKey: {
      type: String,
      default: 'code'
    },
    // 分页参数
    tablePage: {
      type: Object,
      default () {
        return {
          pageIndex: 1,
          pageSize: 10,
          total: 0
        }
      }
    },
    // 是否显示检索功能
    isShowFilter: {
      type: Boolean,
      default: true
    },
    // 是否显示分页功能
    isShowPage: {
      type: Boolean,
      default: true
    },
    /*
      检索配置信息
      align 组件位置
      name 组件名
      value 绑定值
      type 组件类型
      text 按钮的名称
      radios 单选框时显示的列表
    */
    tableFilter: {
      type: Array,
      default () {
        return []
      }
    },
    // 表格数据
    data: {
      type: Array,
      default () {
        return []
      }
    },
    // 表格配置信息
    columns: {
      type: Array,
      default () {
        return []
      }
    },
    rowClassNameFn:{
      type:Function
    },
    // 判断表单显示时的标识
    showFlag: Boolean,
    calcHeight:Number,
  },
  computed: {
    newColumns () {
      return this.columns.map(item => {
        return {
          ...item,
          tooltip: this.tooltip
        }
      })
    }
  },
  watch: {
    showFlag (val) {
      if (val) {
        this.historySelected()
      }
    },
    data () {
      this.resize()
    }
  },
  data () {
    return {
      valid: false,
      computedHeight: '',
      selectRow: '',
      filterData: {},
      tempList: []
    }
  },
  methods: {
    resize () {
      if (this.$refs['table-content']) {
        this.computedHeight = this.$refs['table-content'].clientHeight
        if (
          this.$refs['table-content'].getElementsByClassName(
            'ivu-table-overflowY'
          )[0]
        ) {
          this.$refs['table-content'].getElementsByClassName(
            'ivu-table-overflowY'
          )[0].scrollTop = 0
          this.$refs['table-content'].getElementsByClassName(
            'ivu-table-overflowX'
          )[0].scrollLeft = 0
        }
      } else {
        setTimeout(() => {
          this.resize()
        }, 500)
      }
    },
    rowClassName (row, index) {
      if (row.color === 'red') {
        return 'color-red'
      }
      return ''
    },
    rowClick (row, index) {
      this.selectRow = index
      this.$refs.table.toggleSelect(index)
    },
    /* 给检索框设置绑定一个值 */
    setModel (key, value) {
      this.$set(this.filterData, key, value)
      this.$emit('event-handle', { _evnet: 'search', ...this.filterData })
    },
    /* 数据回填时历史勾选 */
    historySelected () {
      if (!this.multiple && this.selectedList.length > 0) {
        this.tempList = this.selectedList
        this.data.forEach(item => {
          this.$set(item, '_checked', false)
        })
        this.setHistoryChecked()
        this.$emit('on-select', [...this.tempList], {})
      }
    },
    /* 清除历史勾选 */
    clearHistoryChecked () {},
    /* 清空临时勾选数据 */
    clearTempList () {
      this.tempList = []
    },
    /* 分页时勾选历史勾选 */
    setHistoryChecked () {
      this.data.forEach(item => {
        this.tempList.forEach(selected => {
          if (selected.code && item.code === selected.code) {
            this.$set(item, '_checked', true)
          }
        })
      })
    },
    onChange (data, item) {
      if (item.name === 'DatePicker') {
        console.log('DatePicker')
        if (item.type === 'daterange') {
          console.log('daterange')
          this.filterData[(item.value || '') + 'StartTime'] = data[0]
          this.filterData[(item.value || '') + 'EndTime'] = data[1]
        } else {
          this.filterData[item.value] = data
        }
        this.$emit('event-handle', { _evnet: item.e, ...this.filterData })
      } else if (item.name === 'RadioGroup') {
        this.$emit('event-handle', { _evnet: 'search', ...this.filterData })
      } else if (item.name === 'Input') {
        this.$emit('event-handle', { _evnet: item.e, ...this.filterData })
      } else if (item.name === 'Select') {
        this.$emit('event-handle', { _evnet: 'search', ...this.filterData })
      }
    },
    clear () {
      console.log('clear--------------')
      this.tempList = []
      this.$refs.table.selectAll(false)
    },
    // 表格复选框选择 获取选中数据
    onselect (selection, row) {
      if (!this.multiple) {
        let flag = false
        this.tempList.forEach(item => {
          if (item[this.selectKey] === row[this.selectKey]) {
            flag = true
          }
        })
        if (!flag) {
          this.tempList.push(row)
        }
        // 返回已选中的数据和单前数据
        this.$emit('on-select', [...this.tempList], { ...row })
      } else {
        setTimeout(() => {
          this.$refs.table.selectAll(false)
          let index = this.data.findIndex(item => item.id === row.id)
          this.$refs.table.$refs.tbody.objData[index]._isChecked = true
          this.$emit('on-select', [...selection], { ...row })
        }, 100)
      }
    },
    onselectAllCancel (selection) {
      if (!this.multiple && selection.length === 0) {
        for (const select of this.data) {
          this.tempList.forEach((item, index) => {
            if (item.code === select.code) {
              this.tempList.splice(index, 1)
            }
          })
        }
        this.$emit('on-select', [...this.tempList], {})
      }
    },
    onselectAll (selection) {
      // 多选时处理数据
      if (!this.multiple) {
        for (const select of selection) {
          let flag = false
          for (const item of this.tempList) {
            if (select[this.selectKey] === item[this.selectKey]) {
              flag = true
              break
            }
          }
          if (!flag) {
            this.tempList.push(select)
          }
        }
        this.$emit('on-select', [...this.tempList], {})
      } else {
        this.$refs.table.selectAll(false)
      }
    },
    onselectCancel (selection, row) {
      if (selection.length !== 0) {
        this.tempList.forEach((item, index) => {
          if (item[this.selectKey] === row[this.selectKey]) {
            this.tempList.splice(index, 1)
          }
        })
      }
      this.$emit('on-select', [...selection], { ...row })
    },
    // 过滤器功能点击
    filterClick (option) {
      if (option.name === 'Button') {
        this.$emit('event-handle', { _evnet: option.e, ...this.filterData })
      }
    },
    /* enter搜索 */
    enterHandle () {
      this.$emit('event-handle', { _evnet: 'search', ...this.filterData })
    },
    // 换页
    changePage (pageIndex) {
      this.$emit('on-change', pageIndex)
    },
    // 获取控件宽度
    getComWidth (item) {
      if (item.name === 'Button') {
        return '90px'
      } else if (['Input', 'Select'].includes(item.name)) {
        return '200px'
      }
    },
    // 获取表格高度
    getComHeight () {
      if(this.calcHeight){
        console.log(this.isShowPage)
        return 'calc(100% - '+ this.calcHeight +'px)'
      }else if (this.isShowFilter && this.isShowPage) {
        return 'calc(100% - 85px)'
      } else if (this.isShowFilter && !this.isShowPage) {
        return 'calc(100% - 42px)'
      } else if (!this.isShowFilter && this.isShowPage) {
        return 'calc(100% - 43px)'
      } else {
        return '100%'
      }
    },
    /* 节流 */
    throttle (fn, delay) {
      let _this = this
      this.valid = true
      return function () {
        if (!_this.valid) {
          // 休息时间 暂不接客
          return false
        }
        // 工作时间，执行函数并且在间隔期内把状态位设为无效
        _this.valid = false
        setTimeout(() => {
          fn()
          _this.valid = true
        }, delay)
      }
    }
  },
  created () {
    /* 实时计算表格的高度 */
    this.$nextTick(() => {
      this.resize()
      window.onresize = this.throttle(() => {
        this.resize()
      }, 100)
    })
    // 单选框默认选中第一个
    this.tableFilter.forEach(item => {
      if (item.name === 'RadioGroup') {
        this.$set(this.filterData, item.value, item.list[0].value)
      }
    })
  },
  beforeUpdate () {
    if (this.data !== null) {
      this.setHistoryChecked()
    }
  }
}
</script>
<style>
.color-red{
  color: red!important;
}
</style>
<style lang="less" scoped>

.container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  .table-filter {
    padding-bottom: 10px;
    line-height: 32px;
    overflow: hidden;
    .filter-item {
      margin-right: 10px;
      float: left;
      //&:last-child {
      //  margin-right: 0;
      //}
    }
  }
  .table-content {
    flex: 1;
    overflow: hidden;
  }
  .table-page {
    padding-top: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 43px;
    overflow: hidden;
  }
}
/deep/ .select-row-bg {
  background: #b1e0ff;
  td {
    background: transparent;
  }
}
</style>
