<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)
          }"
          :clearable="true"
          @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
      class="table-content"
      :style="{
        height: getComHeight()
      }"
    >
      <Table
        ref="table"
        :columns="newColumns"
        :data="data"
        :border="border"
        :row-class-name="rowClassName"
        @on-select="onselect"
        @on-select-cancel="onselectCancel"
        @on-select-all="onselectAll"
        @on-select-all-cancel="allCancel"
        @on-selection-change="onselectAllCancel"
        @on-row-click="rowClick"
      ></Table>
    </div>
    <!-- 分页 -->
    <div class="table-page" v-if="isShowPage">
      <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: {
    // 是否显示边框
    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 []
      }
    },
    // 判断表单显示时的标识
    showFlag: Boolean
  },
  computed: {
    newColumns () {
      return this.columns.map(item => {
        return {
          ...item,
          // tooltip: true
        }
      })
    }
  },
  watch: {
    showFlag (val) {
      if (val) {
        console.log('显示----')
        this.historySelected()
      }
    }
  },
  data () {
    return {
      filterData: {},
      tempList: [],
      selectRow: ''
    }
  },
  methods: {
    rowClassName (row, index) {
      if(row.bgRed == true)
        return 'select-row-bg-red'
      if (index === this.selectRow) {
        return 'select-row-bg'
      }
      
    },
    rowClick (row, index) {
      console.log(this.selectRow)
      if(this.selectRow === index){
        
        this.$emit('on-row-click',false)
      }else{
        this.$emit('on-row-click',row)
        this.selectRow = index
      }
      
      if(row._disabled) return
      this.$refs.table.toggleSelect(index)
      
    },
    /* 给检索框设置绑定一个值 */
    setModel (key, value) {
      this.$set(this.filterData, key, value)
      console.log('this.model---------------')
      console.log(this.filterData)
      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
        }
      } 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 })
      }
    },
    clear () {
      console.log('clear--------------')
      this.tempList = []
      this.$refs.table.selectAll(false)
    },
    // 表格复选框选择 获取选中数据
    onselect (selection, row) {
      console.log('select')
      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', [], { ...row })
        }, 100)
      }
    },
    onselectAllCancel (selection) {
      console.log('onselectAllCancel')
      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 ], {})
      }
    },
    allCancel() {
      console.log('allCancel')
      this.$emit('on-select-all-cancel', this.data)
    },
    onselectAll (selection) {
      console.log('onselectAll')
      // 多选时处理数据
      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-all', [ ...this.tempList ], {})
      } else {
        this.$refs.table.selectAll(false)
      }
    },
    onselectCancel (selection, row) {
      console.log('onselectCancel')
      this.tempList.forEach((item, index) => {
        if (item[this.selectKey] === row[this.selectKey]) {
          this.tempList.splice(index, 1)
        }
      })
      this.$emit('on-select-cancel', [ ...this.tempList ], { ...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.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%'
      }
    },
    /* 外部通过code来取消勾选 */
    handleCancel(code) {
      this.tempList.forEach((item, index) => {
        if (item.code === code) {
          this.tempList.splice(index, 1)
        }
      })
      this.data.forEach(item => {
        this.$set(item, '_checked', false)
      })
      if (this.tempList.length > 0) {
        this.data.forEach(item => {
          this.tempList.forEach(data => {
            if (item.code === data.code) {
              console.log('set true-----------------')
              this.$set(item, '_checked', true)
            }
          })
        })
      } else {
        // this.data.forEach(item => {
        //   this.$set(item, '_checked', false)
        // })
        // this.$refs.table.selectAll(false)
      }
    }
  },
  created () {
    // 单选框默认选中第一个
    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 lang="scss" scoped>
.container {
  height: 100%;
  .table-filter {
    padding-bottom: 10px;
    height: 42px;
    line-height: 32px;
    overflow: hidden;
    .filter-item {
      margin-right: 10px;
      float: left;
      //&:last-child {
      //  margin-right: 0;
      //}
    }
  }
  .table-content {
    overflow: auto;
  }
  .table-page {
    padding-top: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 43px;
    overflow: hidden;
  }
}
/deep/ .select-row-bg {
  background: #ebf7ff;
  td {
    background: transparent;
  }
}

/deep/ .select-row-bg-red {
  background: #ebf7ff;
  td {
    background: #FFE7E7;
    color:#6E6E6E;
  }
}
</style>
