<template>
  <div id="dg-transfer">
    <div v-if="isFilter" class="transfer_search">
      <el-input
        v-model="searchKey"
        class="transfer_search_input"
        placeholder="请输入关键字"
        @keyup.enter.native="queryBtn"
      >
        <el-button slot="append" icon="el-icon-search" @click.native="queryBtn"></el-button>
      </el-input>
    </div>
    <el-transfer
      ref="transfer"
      v-model="tableValue"
      :style="{ height: transferHeight }"
      :api-code="apiCode"
      :render-content="renderContent"
      :data="curTableList"
      :props="props"
      :filterable="filterable"
      :filter-placeholder="filterPlaceholder"
      :filter-method="filterMethod"
      :titles="titles"
      v-bind="$attrs"
      @change="change"
    >
    </el-transfer>
    <el-pagination
      v-if="pagination"
      slot="left-footer"
      style="float: left"
      class="transfer-footer"
      small
      layout="total, sizes, prev, pager, next"
      :current-page.sync="pageNum"
      :page-size="sonPageSize"
      :page-sizes="[20, 100, 300, 500]"
      :total="tableListTotal"
      @size-change="handleSizeChange"
      @current-change="currentChange"
    ></el-pagination>
    <div style="float: right; font-size: 14px; margin-top: 2px">已选：{{ tableValue.length }}</div>
  </div>
</template>

<script>
export default {
  name: 'DgTransfer',

  model: {
    prop: 'value',
    event: 'change',
  },

  props: {
    checkedList: {
      type: Array,
      default: () => [],
    },
    value: {
      type: Array,
      default: () => [],
    }, // 接受外部v-model传入的值
    apiCode: {
      type: String,
      default: () => '',
    },
    getDataFn: {
      type: Function,
      default: null,
    },
    tableList: {
      type: Array,
      default: () => [],
    },
    queryTerms: {
      type: String,
      default: () => '',
    },
    props: {
      type: Object,
      default: () => {
        'id'
        'value'
      },
    },
    isFilter: {
      type: Boolean,
      default: () => false,
    },
    filterable: {
      type: Boolean,
      default: () => false,
    },
    filterPlaceholder: {
      type: String,
      default: () => '请输入关键字',
    },
    filterRemote: {
      type: Boolean,
      default: () => false,
    },
    pageSize: {
      type: Number,
      default: 20,
    },
    disabledItems: {
      type: Array,
      default: () => [],
    },
    renderContent: {
      type: Function,
      default: null,
    },
    pagination: {
      type: Boolean,
      default: false,
    },
    titles: {
      type: Array,
      default: () => [],
    },
  },

  data() {
    return {
      curTableList: [],
      tableListTotal: 0,
      tableValue: [],
      pageNum: 1,
      sonPageSize: null,
      searchKey: null,
      transferHeight: 'calc(100% - 16px)',
      integralTableValue: [],
    }
  },

  watch: {
    // 判断值是否有改变
    tableValue(val, oldVal) {
      if (val != oldVal) {
        this.$emit('input', val)
      }
    },
    value(val, oldVal) {
      this.tableValue = val
    },
    queryTerms(val, oldVal) {
      this.getData(this.searchKey)
    },
  },

  created() {
    this.curTableList = this.tableList
    this.sonPageSize = this.pageSize
    this.transferHeight = this.isFilter ? 'calc(100% - 69px)' : 'calc(100% - 32px)'
    this.tableValue = this.value
    this.getData()
  },

  methods: {
    // 获取数据
    // async getData () {
    //   const pageNum = this.pageNum;
    //   const pageSize = this.pageSize;
    //   let params = `command=init&limit=${pageSize}&start=${pageNum}`
    //   if (this.queryTerms) params += `&${this.queryTerms}`
    //   let res = await DgJsonStore({
    //     apiCode: this.apiCode,
    //     params: params
    //   })
    //   if (res.root) {
    //     this.tableList = res.root
    //   }
    //   this.disabledItems.forEach(item => {
    //     for (let i in this.tableList) {
    //       if (this.tableList[i][this.props.key] === item) {
    //         this.tableList[i].disabled = true
    //       }
    //     }
    //   })
    //   this.tableListTotal = res.count
    // },
    async queryBtn() {
      console.log(this.searchKey)
      this.pageNum = 1
      this.getData(this.searchKey)
      // const pageNum = this.pageNum;
      // const pageSize = this.pageSize;
      // let res = await DgJsonStore({
      //   apiCode: this.apiCode,
      //   params: `command=init&limit=${pageSize}&start=${pageNum}&${this.props.label}=${this.searchKey}`
      // })
      // if (res.root) {
      //   this.tableList = res.root
      // }
      this.tableValue.forEach((item) => {
        for (let i in this.curTableList) {
          if (this.curTableList[i][this.props.key] === item) {
            this.curTableList[i].disabled = true
          }
        }
      })
      // this.tableListTotal = res.count
    },
    async getData(name) {
      let res = null
      if (this.getDataFn) {
        res = await this.getDataFn(this.toolbarData, this.sonPageSize, this.pageNumber)
      } else if (this.apiCode) {
        const limit = this.sonPageSize
        let start = (this.pageNum - 1) * limit
        let params = `command=init&limit=${limit}&start=${start}`
        if (name) {
          const paramName = this.props.label
          params += `&${paramName}=${name}`
        }
        if (this.queryTerms) params += `&${this.queryTerms}`
        res = await this.$api.DgJsonStore({
          apiCode: this.apiCode,
          params: params,
        })
      }
      if (this.getDataFn || this.apiCode) {
        this.curTableList = []
        res.root.forEach((item) => {
          // if (!this.tableValue.includes(item[this.props.key])) {
          this.curTableList.push({
            ...item,
            disabled: item.DISABLED === 'true',
          })
          // }
        })
        this.tableListTotal = res.count
      } else {
        this.tableListTotal = this.curTableList.length
      }
      if (this.checkedList && this.checkedList.length > 0) {
        // this.curTableList = [...this.checkedList]
        this.tableValue = this.checkedList.map((item) => {
          // this.curTableList.push(item)
          return item[this.props.key]
        })
      }
      this.disabledItems.forEach((item) => {
        for (let i in this.curTableList) {
          if (this.curTableList[i][this.props.key] === item) {
            this.curTableList[i].disabled = true
          }
        }
      })
      // 穿梭框右侧内容不分页，往curTableList中追加选中数据且去重
      if (!name && this.integralTableValue.length > 0) {
        let tempArr = JSON.parse(JSON.stringify(this.integralTableValue))
        this.curTableList = this.unique([...this.curTableList, ...tempArr])
      }
      console.log(this.curTableList, this.tableValue)
    },
    filterMethod(query, item) {
      if (this.filterRemote) {
        this.getData(query)
      } else {
        if (!this.props || !this.props.label) {
          console.error('穿梭框找不到key, 无法过滤！')
          return
        }
        if (item && item[this.props.label]) {
          return item[this.props.label].indexOf(query) > -1
        }
      }
    },
    change(val, direction, movedKeys) {
      this.$emit('change', val, this.curTableList)
      if (!this.pagination) return

      this.$nextTick(() => {
        if (direction === 'right') {
          if (this.$refs['transfer'].targetData.length > 0) {
            let tempArr = JSON.parse(JSON.stringify(this.$refs['transfer'].targetData))
            // 去重
            this.integralTableValue = this.unique([...this.integralTableValue, ...tempArr])
          }
        }
        if (direction === 'left') {
          let a = new Set(this.integralTableValue)
          let b = new Set(movedKeys)
          // 取交集
          this.integralTableValue = [...new Set([...a].filter((x) => !b.has(x[this.props.key])))]
        }
        console.log('integralTableValue------', this.integralTableValue)
      })
      // this.$emit('change', this.tableValue)
    },
    currentChange() {
      this.getData(this.searchKey)
    },
    handleSizeChange(val) {
      this.sonPageSize = val
      this.pageNum = 1
      this.getData(this.searchKey)
    },
    unique(arr) {
      let obj = {}
      return arr.reduce((cur, next) => {
        obj[next[this.props.key]] ? '' : (obj[next[this.props.key]] = true && cur.push(next))
        return cur
      }, [])
    },
  },
}
</script>
