<!-- 分页表格穿梭框 -->
<template>
  <div class="transfer">
    <div class="transfer-panel">
      <p class="transfer-panel-header">
        <span>{{ titleTexts && titleTexts[0] }}</span>
        <span>{{ leftSelection.length }}/{{ leftTableData.length }}</span>
      </p>
      <div v-if="showQuery">
        <el-form :inline="true" :model="leftQueryCondition" class="query-form" @keyup.enter.native="onLeftQuerySubmit()">
          <slot name="leftCondition" :scope="leftQueryCondition" />
          <!-- <el-button type="primary" @click="onLeftQuerySubmit()">{{ queryTexts[0] }}</el-button> -->
          <i class="el-icon-search" style="color: blue; font-size: 20px;color: #266cff;" @click="onLeftQuerySubmit()" />
        </el-form>
      </div>
      <el-table
        ref="leftTable"
        size="small"
        :max-height="maxHeight"
        :height="minHeight"
        :data="leftTableData"
        :row-key="tableRowKey"
        :row-style="handleRowStyle"
        border
        stripe
        @row-click="handleLeftRowClick"
        @selection-change="handleLeftSelectionChange"
      >
        <el-table-column width="40px" type="selection" :selectable="handleSelectable" />
        <el-table-column v-for="col in leftColumns" :key="col.id" :prop="col.id" :label="col.label" :width="col.width">
          <template slot-scope="scope">
            <slot :name="col.id" :scope="{ row: scope.row, col: col }">
              <span>{{ scope.row[col.id] }}</span>
            </slot>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="showPagination"
        small
        :current-page="pageIndex"
        :page-size="pageSize"
        :pager-count="5"
        :total="totalSize"
        layout="total, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <div class="transfer-buttons">
      <el-button type="primary" class="min-width-auto" :class="buttonClasses" :disabled="disabledLeftButton" @click.native="addToRight">
        <!-- <span v-if="buttonTexts[0] !== undefined" class="button-text">{{ buttonTexts[0] }}</span> -->
        <i class="el-icon-arrow-right" />
      </el-button>
      <el-button type="primary" class="min-width-auto" :class="buttonClasses" :disabled="rightSelection.length === 0" @click.native="addToLeft">
        <i class="el-icon-arrow-left" />
        <!-- <span v-if="buttonTexts[1] !== undefined" class="button-text">{{ buttonTexts[1] }}</span> -->
      </el-button>
    </div>
    <div class="transfer-panel">
      <p class="transfer-panel-header">
        <span>{{ titleTexts && titleTexts[1] }}</span>
        <span>{{ rightSelection.length }}/{{ rightTableData.length }}</span>
      </p>
      <div v-if="showToQuery">
        <el-form :inline="true" :model="rightQueryCondition" class="query-form" @keyup.enter.native="onRightQuerySubmit()">
          <slot name="rightCondition" :scope="rightQueryCondition" />
          <!-- <el-button type="primary" @click="onRightQuerySubmit()">{{ queryTexts[0] }}</el-button> -->
          <i class="el-icon-search" style="color: blue; font-size: 20px;color: #266cff;" @click="onRightQuerySubmit()" />
        </el-form>
      </div>
      <el-table
        ref="rightTable"
        size="small"
        :max-height="maxHeight"
        :height="'345px'"
        :data="calcRightTableData"
        :row-key="tableRowKey"
        border
        stripe
        @row-click="handleRightRowClick"
        @selection-change="handleRightSelectionChange"
      >
        <el-table-column width="40px" type="selection" />
        <el-table-column
          v-for="col in rightColumns || leftColumns"
          :key="col.id"
          :prop="col.id"
          :label="col.label"
          :width="col.width"
        >
          <template slot-scope="scope">
            <slot :name="col.id" :scope="{ row: scope.row, col: col }">
              <span>{{ scope.row[col.id] }}</span>
            </slot>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-if="showPagination" :total="rightTableData.length" layout="total" />
    </div>
  </div>
</template>

<script>
export default {
  name: 'TableTransferBase',
  props: {
    value: {
      type: Array,
      default() {
        return []
      }
    },
    // 显示条件查询
    showQuery: {
      type: Boolean,
      default: false
    },
    // 显示条件查询
    showToQuery: {
      type: Boolean,
      default: false
    },
    // 显示分页
    showPagination: {
      type: Boolean,
      default: false
    },
    // 左侧分页回调
    paginationCallBack: {
      type: Function,
      default: function() {
        return new Promise((resolve, reject) => {
          try {
            resolve({ total: 0, data: null })
          } catch {
            reject()
          }
        })
      }
    },
    // 标题文本
    titleTexts: {
      type: Array,
      default() {
        return ['待选项', '已选项']
      }
    },
    // 按钮文本
    buttonTexts: {
      type: Array,
      default() {
        return []
      }
    },
    // 查询按钮文本
    queryTexts: {
      type: Array,
      default() {
        return ['查询', '筛选']
      }
    },
    // 左侧参数
    leftColumns: {
      type: Array,
      default() {
        return []
      }
    },
    // 右侧参数
    rightColumns: {
      type: Array,
      default() {
        return undefined
      }
    },
    // 表格最小高度
    minHeight: {
      type: String,
      default: '300px'
    },
    // 表格最大高度
    maxHeight: {
      type: String,
      default: '500px'
    },
    // 表格行数据的Key
    tableRowKey: {
      type: Function,
      default(row) {
        return row && row && row.id
      }
    },
    // 搜索key
    searchKeys: {
      type: Array,
      default() {
        return []
      }
    },
    pageSize: {
      type: Number,
      default: 25
    }
  },
  data() {
    return {
      leftTableData: [],
      rightTableData: this.value || [],
      pageIndex: 1,
      totalSize: 0,
      leftSelection: [],
      rightSelection: [],
      leftQueryCondition: {},
      rightQueryCondition: {},
      rightConditionTemp: undefined
    }
  },
  computed: {
    hasButtonTexts() {
      return this.buttonTexts.length === 2
    },
    buttonClasses() {
      return ['transfer-button', { 'is-with-texts': this.hasButtonTexts }]
    },
    disabledLeftButton() {
      return !this.leftSelection.some(leftRow => !this.rightTableData.some(rightRow => this.checkObjectIsEqual(leftRow, rightRow)))
    },
    calcRightTableData() {
      if (this.showToQuery && this.rightConditionTemp) {
        const conditionKeys = Object.keys(this.rightConditionTemp)
        return this.rightTableData.filter(data => {
          return conditionKeys.some(key => {
            const rowCellData = data[key]
            const condVal = this.rightConditionTemp[key].trim()
            if (rowCellData) {
              return String(rowCellData).indexOf(condVal) > -1
            }
            return true
          })
        })
      }
      return this.rightTableData
    }
  },
  watch: {
    value(val) {
      this.rightTableData = val
      this.handlePaginationCallBack()
    },
    leftQueryCondition: {
      handler(val) {
        this.handlePaginationCallBack()
      },
      deep: true
    },
    rightQueryCondition: {
      handler(val) {
        this.onRightQuerySubmit()
      },
      deep: true
    }
  },
  created() {
    this.handlePaginationCallBack()
  },
  methods: {
    handleLeftSelectionChange(selection) {
      this.leftSelection = selection
    },
    handleRightSelectionChange(selection) {
      this.rightSelection = selection
    },
    handleLeftRowClick(row) {
      if (!this.rightTableData.some(rightRow => this.checkObjectIsEqual(rightRow, row))) {
        this.$refs.leftTable.toggleRowSelection(row)
      }
    },
    handleRightRowClick(row) {
      this.$refs.rightTable.toggleRowSelection(row)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.handlePaginationCallBack()
    },
    handleCurrentChange(val) {
      this.pageIndex = val
      this.handlePaginationCallBack()
    },
    handlePaginationCallBack() {
      if (this.paginationCallBack) {
        const condition = {
          pageIndex: this.showPagination ? this.pageIndex : 1,
          pageSize: this.showPagination ? this.pageSize : Number.MAX_VALUE,
          ...this.leftQueryCondition
        }
        this.paginationCallBack.call(null, condition).then(result => {
          if (result && Array.isArray(result.data)) {
            this.leftTableData = result.data
            this.totalSize = result.total
          }

          this.$nextTick(() => {
            this.leftTableData.forEach(leftRow => {
              const isHave = this.rightTableData.some(rightRow => this.checkObjectIsEqual(rightRow, leftRow))
              this.$refs.leftTable.toggleRowSelection(leftRow, isHave)
            })
          })
        })
      }
    },
    handleRowStyle({ row }) {
      if (this.rightTableData.some(rightRow => this.checkObjectIsEqual(rightRow, row))) {
        return {
          color: 'blue'
        }
      }
      return {}
    },
    handleSelectable(row) {
      const selectable = !this.rightTableData.some(rightRow => this.checkObjectIsEqual(rightRow, row)) && !row.disabled // 右边有的禁用 && 手动禁用
      return selectable
    },
    addToRight() {
      for (const item of this.leftSelection) {
        const isHave = this.rightTableData.some(rightRow => this.checkObjectIsEqual(rightRow, item))
        if (!isHave) {
          this.rightTableData.push(item)
        }
      }
      this.$emit('input', this.rightTableData)
      this.handlePaginationCallBack()
    },
    addToLeft() {
      this.rightSelection.forEach(item => {
        const index = this.rightTableData.findIndex(rightRow => this.checkObjectIsEqual(rightRow, item))
        if (index !== -1) {
          this.rightTableData.splice(index, 1)

          const leftRow = this.leftTableData.find(leftRow => this.checkObjectIsEqual(leftRow, item))
          if (leftRow) {
            this.$refs.leftTable.toggleRowSelection(leftRow, false)
          }
        }
      })
      this.$emit('input', this.rightTableData)
      this.handlePaginationCallBack()
    },
    onLeftQuerySubmit() {
      this.handlePaginationCallBack()
    },
    onRightQuerySubmit() {
      this.rightConditionTemp = JSON.parse(JSON.stringify(this.rightQueryCondition))
    },
    checkObjectIsEqual(rowObj1, rowObj2) {
      return this.tableRowKey(rowObj1) === this.tableRowKey(rowObj2)
    },
    clear() {
      this.rightTableData = []
      this.$refs.leftTable.clearSelection()
      for (const key in this.leftQueryCondition) {
        this.leftQueryCondition[key] = undefined
      }
      for (const key in this.rightQueryCondition) {
        this.rightQueryCondition[key] = undefined
      }
      this.pageIndex = 1
      this.handlePaginationCallBack()
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
.transfer {
  font-size: 14px;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 457px;
}

.el-icon-arrow-right,
.el-icon-arrow-left {
  font-size: 40px;
  cursor: pointer;
}

.transfer-panel {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  overflow: hidden;
  background: #FFF;
  // display: inline-block;
  display: flex;
  flex-direction: column;
  width: calc((100% - 100px) / 2);
  max-height: 100%;
  box-sizing: border-box;
  position: relative;
  height: 100%;
}

.transfer-panel .transfer-panel-header {
  height: 40px;
  line-height: 40px;
  background: #F5F7FA;
  margin: 0;
  padding-left: 15px;
  border-bottom: 1px solid #EBEEF5;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  color: #000;
}

.transfer-panel-header span:last-child {
  position: absolute;
  right: 15px;
}

.transfer-buttons {
  display: inline-block;
  vertical-align: middle;
  width: 60px;
  min-width: 50px;
  margin: 0 10px;
  .el-button {
    width: 60px;
    min-width: 50px;
  }
}

.transfer-button {
  display: block;
  margin: 0 auto;
  padding: 10px;
  border-radius: 4px;
  color: #FFF;
  background-color: #409EFF;
  font-size: 0
}

.transfer-button .button-text {
  margin-left: 2px;
  margin-right: 5px;
}

.transfer-button.is-with-texts {
  border-radius: 4px
}

.transfer-button.is-disabled,
.transfer-button.is-disabled:hover {
  border: 1px solid #DCDFE6;
  background-color: #F5F7FA;
  color: #C0C4CC
}

.transfer-button:first-child {
  margin-bottom: 10px
}

.transfer-button:nth-child(2) {
  margin: 0 auto;
}

.transfer-button i,
.transfer-button span {
  font-size: 14px
}

.query-form {
  margin: 5px;
  display: flex;
  align-items: center;
}

.el-icon-search {
  @include clickActive;
}

// ----------修改elementui表格的默认样式-----------
.el-table {
  /deep/ .el-table__body-wrapper::-webkit-scrollbar {
    width: 10px; /*滚动条宽度*/
    height: 10px; /*滚动条高度*/
  }
  /*定义滚动条轨道 内阴影+圆角*/
  /deep/ .el-table__body-wrapper::-webkit-scrollbar-track {
    border: none;
    box-shadow: 0px 1px 3px #fff inset; /*滚动条的背景区域的内阴影*/
    border-radius: 10px; /*滚动条的背景区域的圆角*/
    background-color: #fff; /*滚动条的背景颜色*/
  }
  /*定义滑块 内阴影+圆角*/
  /deep/ .el-table__body-wrapper::-webkit-scrollbar-thumb {
    box-shadow: 0px 1px 3px #ccc inset; /*滚动条的内阴影*/
    border-radius: 10px; /*滚动条的圆角*/
    background-color: #ccc; /*滚动条的背景颜色*/
  }
  // 隐藏table gutter列和内容区右侧的空白 start
  /deep/ .el-table__header {
    width: 100% !important;
  }
  /deep/ .el-table__body{
    width: 100% !important;
  }
  /deep/ .el-table__empty-block {
    width: 100% !important;
  }
  &--scrollable-y { // 只有y轴可以滚动才控制gutter占位的固定宽度
    /deep/ th.gutter{
      display: table-cell !important;
      width: 10px !important;
    }
    /deep/ colgroup col[name='gutter']{
      display: table-cell !important;
      width: 10px !important;
    }
  }
  // 隐藏table gutter列和内容区右侧的空白 end
}
</style>

<style>
.query-form .el-form-item {
  margin-bottom: 0;
  width: 251px;
  .el-form-item__content {
    width: 100%
  }
}
</style>
