<template>
  <div ref="selectBox" class="select-table-box grid-content">
    <el-form-item :label="$Tools.$t(selectForm.label)" :prop="selectForm.prop" :label-width="selectForm.labelWidth?selectForm.labelWidth:'80px'">
      <el-input v-model="formvalue[selectForm.modelValue]" :placeholder="$Tools.$t(selectForm.placeholder)" clearable auto-complete="off" @click.native="showSlectTable($event)" @clear="clearVal">
        <i slot="suffix" :class="{'is-reverse':selectForm.showSelect}" class="el-input__icon el-icon-arrow-down el-select-icon" />
      </el-input>
    </el-form-item>
    <div v-show="selectForm.showSelect" ref="selectTable" :style="{width: selectForm.selectwidth}" class="select-table">
      <el-input
        v-model="searchText"
        :style="{width: selectForm.selectwidth}"
        autofocus
        auto-complete="off"
        :placeholder="$t('KeywordSearch')"
        clearable
        suffix-icon="el-icon-search"
        @clear="clearSearch"
        @keydown.native="mouseMove($event)"
      />
      <div ref="dormitoryTable" :style="{width: selectForm.selectwidth}" class="dormitoryData">
        <el-table ref="tableBox" v-loading="loading" :height="selectForm.height?selectForm.height:300" :data="tableSearch" :style="{width: selectForm.selectwidth}" @row-click="selectSearch">
          <el-table-column v-for="(item,index) in selectForm.tablecolumns" :key="index" :label="$Tools.$t(item.label)" :width="item.width?item.width:''" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row[item.value]===undefined">-</span>
              <span v-else v-html="showhighLight(scope.row[item.value])" />
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="showPage"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          :total="totalPage"
          layout="sizes, prev, pager, next, jumper,total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'DropDownSelect',
  props: {
    selectForm: {
      type: Object,
      default: () => {}
    },
    formvalue: {
      type: Object,
      default: () => {}
    }
  },
  data: function() {
    return {
      searchText: '',
      currentLine: 0,
      offsetTr: 0,
      mutipleRows: [],
      showPage: false,
      selectText: '',
      totalWidth: 0,
      totalPage: 10,
      currentPage: 1,
      pageSizes: [10, 20, 30],
      pageSize: 50,
      enterRow: {},
      curtableData: [],
      dataLength: 50,
      loading: false
    }
  },
  computed: {
    tableSearch: function() {
      var search = this.searchText
      if (search) {
        return this.selectForm.tableData.filter(function(item) {
          return Object.keys(item).some(function(key) {
            return String(item[key]).toLowerCase().indexOf(search.toLowerCase()) > -1
          })
        })
      } else {
        if (this.selectForm.tableData.length > 200) {
          return this.selectForm.tableData.slice(0, 100)
        } else {
          return this.selectForm.tableData
        }
      }
    }
  },
  created: function() {

  },
  mounted: function() {
    var _this = this
    // this.totalWidth = 1000
    var elSelects = document.getElementsByClassName('el-select')
    for (var j = 0; j < elSelects.length; j++) {
      elSelects[j].onclick = function() {
        _this.selectForm.showSelect = false
      }
    }
  },
  methods: {
    // 获取新的参数方法
    getnewParams: function(curpage, pagesize) {
      var curPage = {
        currentPage: curpage,
        pageSize: pagesize
      }
      var newParams = {}
      if (this.selectForm.param !== undefined) {
        newParams = Object.assign({}, this.selectForm.param, curPage)
      } else if (this.selectForm.param === undefined) {
        newParams = {
          currentPage: curpage,
          pageSize: pagesize
        }
      }
      // console.log(newParams);
      return newParams
    },
    // 改变每页页数
    handleSizeChange: function(size) {
      this.pageSize = size
      this.getTableData()
    },
    // 改变当前页
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
      this.getTableData()
    },
    clearSearch: function() {
      var mytable = this.$refs.dormitoryTable
      var trlist = mytable.getElementsByTagName('tr')
      this.changeBackground(trlist)
    },
    clearVal: function() {
      this.$emit('clearval')
    },
    mouseMove: function(event) {
      var mytable = this.$refs.dormitoryTable
      var trlist = mytable.getElementsByTagName('tr')
      var table = mytable.getElementsByClassName('el-table__body')[0]
      var tablewrap = mytable.getElementsByClassName('el-table__body-wrapper')[0]
      if (event.keyCode === 38) {
        this.offsetTr = 0
        this.currentLine--
        this.changeItem(trlist, table, tablewrap)
      } else if (event.keyCode === 40) {
        this.offsetTr = 50
        this.currentLine++
        this.changeItem(trlist, table, tablewrap)
      } else if (event.keyCode === 13 && this.currentLine > -1) {
        this.enterRow = this.tableSearch[this.currentLine - 1]
        this.hideNewSlectTable(this.enterRow)
        this.currentLine = 0
        this.changeBackground(trlist)
      }
    },
    // 行高亮颜色切换
    changeItem: function(trlist, table, tablewrap) {
      if (this.currentLine < 0) this.currentLine = trlist.length - 1
      this.changeBackground(trlist)
      if (this.currentLine >= trlist.length) this.currentLine = 1
      trlist[this.currentLine].className = 'selectColor'
      if (table.offsetHeight >= tablewrap.offsetHeight) {
        tablewrap.scrollTop = trlist[this.currentLine].offsetTop - this.offsetTr
      }
    },
    changeBackground: function(trlist) {
      for (var i = 1; i < trlist.length; i++) {
        if (i % 2 === 0) {
          trlist[i].className = 'noSelectColor'
        } else {
          trlist[i].className = 'noSelectColor'
        }
      }
    },
    showhighLight: function(val) {
      val = val + ''
      if (val.indexOf(this.searchText) !== -1 && this.searchText !== '') {
        return val.replace(this.searchText, '<font class="highLight">' + this.searchText + '</font>')
      } else {
        return val
      }
    },
    getTableData: function() {
      this.loading = true
      var self = this	// template/crud/demo/querySiteNameList2.do
      const param = this.getnewParams(self.currentPage, self.pageSize)
      if (self.selectForm.method === 'get') {
        this.$request({
          url: this.selectForm.url,
          method: 'get',
          params: param
        }).then(res => {
          this.loading = false
          self.selectForm.tableData = res.data.list
          self.$emit('getselectdata', res.data)
        })
      } else {
        this.$request({
          url: this.selectForm.url,
          data: { parameter: param }
        }).then(res => {
          this.loading = false
          // console.log('select-res--', res)
          self.selectForm.tableData = res.data.list
          self.$emit('getselectdata', res.data.list)
        })
      }
    },
    closest: function(el, selector) {
      var matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector
      while (el) {
        if (matchesSelector.call(el, selector)) {
          break
        }
        el = el.parentElement
      }
      return el
    },
    showSlectTable: function(event) {
      if (this.selectForm.url !== undefined && this.selectForm.tableData.length === 0) {
        this.getTableData()
      }
      var _this = this
      this.setPosition(event, this.selectForm.selectwidth)
      this.selectForm.showSelect = true
      var vueComponents = this.$root.$refs
      Object.keys(vueComponents).forEach(function(key) {
        if (key !== _this.selectForm.ref && vueComponents[key].selectForm !== undefined) {
          vueComponents[key].selectForm.showSelect = false
        }
      })
      _this.formvalue[_this.selectForm.modelValue] = ''
      this.$nextTick(function() {
        this.$refs.selectTable.getElementsByClassName('el-input__inner')[0].focus()
        // console.log(this.$refs.selectTable.getElementsByClassName('el-input__inner')[0]) ;
      })
      document.addEventListener('click', (e) => {
        var ev = e || window.event
        if (this.closest(ev.target, '.select-table-box') === null) {
          _this.selectForm.showSelect = false
        }
      })
      var curRow = this.formvalue[this.selectForm.modelValue]
      var mytable = this.$refs.dormitoryTable
      var trlist = mytable.getElementsByTagName('tr')
      this.changeBackground(trlist)
      var curtableData = this.tableSearch
      var enterRow = this.enterRow
      if (curRow !== '') {
        for (var i = 0; i < curtableData.length; i++) {
          if (this.isObjectValueEqual(enterRow, curtableData[i]) === true) {
            trlist[i + 1].className = 'selectColor'
          }
        }
        // this.searchText = curRow;
      }
    },
    isObjectValueEqual: function(a, b) {
      var aProps = Object.getOwnPropertyNames(a)
      var bProps = Object.getOwnPropertyNames(b)
      if (aProps.length !== bProps.length) {
        return false
      }
      for (var i = 0; i < aProps.length; i++) {
        var propName = aProps[i]
        if (a[propName] !== b[propName]) {
          return false
        }
      }
      return true
    },
    selectSearch: function(row, event, column) {
      var self = this
      if (self.selectForm.type === 'multiple') {
        self.mutipleRows.push(row)
        self.$emit('moreselect', row)
        if (self.mutipleRows.length >= self.selectForm.max) {
          // self.$root.Message.warning({
          //   message: '最多只能选择' + self.selectForm.max + '条数据'
          // })
          self.selectForm.showSelect = false
          self.formvalue[self.selectForm.modelValue] = self.formvalue[self.selectForm.modelValue].substr(0, self.formvalue[self.selectForm.modelValue].length - 1)
          self.mutipleRows = []
        }
      } else {
        self.selectForm.showSelect = false
        self.enterRow = row
        self.$emit('selectsearch', row)
      }
    },
    hideNewSlectTable: function(row) {
      this.selectSearch(row)
    },
    setPosition: function(event, width) {
      const left = this.$refs.selectBox.offsetLeft
      const inputWidth = event.target.getBoundingClientRect().width
      const selectWidth = Number(width.split('p')[0])
      const totalWidth = this.closest(event.target, '.el-form').clientWidth
      const paddingLeft = document.defaultView.getComputedStyle(this.$refs.selectBox, null)['paddingLeft']
      if (totalWidth - left < selectWidth) {
        this.$refs.selectTable.style.left = -(selectWidth - inputWidth) + paddingLeft.split('px')[0] + 'px'
        return false
      } else {
        this.$refs.selectTable.style.left = paddingLeft
      }
    }
  }

}
</script>

<style>
  /*下拉表格样式*/
  .select-table-box{
    position: relative;
  }
  .select-table-box .el-form-item{
    width: 100%;
  }
  .select-table{
    z-index: 999;
    position: absolute;
    top: 62px;
    left: 0;
  }
  .select-table .el-input__prefix{
    display: inline-block;
  }
  .dormitoryData{
    border: 1px solid #ccc;
    border-top: none;
    border-radius: 3px;
  }
  .select-table .el-table th, .select-table .el-table thead.is-group th{
    background-color: #f5f7fa;
    color: #404042;
    font-weight: bold;
  }
  .select-table .el-input .el-input__inner{
    border: 1px solid #999;
    padding-left: 30px;
    width: 100%;
  }
  .select-table .el-input .el-input__inner:focus{
    border-color: #398bf0;
  }
  .el-autocomplete-suggestion li.highlighted, .el-autocomplete-suggestion li:hover{
    background-color: rgba(89,216,255,.9);
    color: #fff;
  }
  .select-table .el-table td{
    border-bottom: 1px solid #ddd;
  }
  .highLight{
    color:#ea232a;
    font-weight: 600;
  }
  .el-select-icon{
    -webkit-transition: -webkit-transform .3s;
    transition: -webkit-transform .3s;
    transition: transform .3s;
    transition: transform .3s,-webkit-transform .3s;
    -webkit-transform: rotateZ(0deg);
    transform: rotateZ(0deg);
  }
  .el-select-icon.is-reverse{
    -webkit-transform: rotateZ(180deg);
    transform: rotateZ(180deg);
  }
  .el-table tr.selectColor{
    background-color: #38a9ef;
    color: #fff;
  }
  .el-table tr.noSelectColor{
    background-color: #fff;
  }
</style>
