<template>
  <div
    v-if="show"
    class="div-autoComplete"
    :style="{ left: realLeftComputed }"
  >
    <div class="table-responsive">
      <table class="table table-bordered table-hover">
        <thead>
          <tr>
            <td
              v-for="item in infoWindowDto.infoGridFields"
              :key="'td-info-grid-field-' + item.fieldName"
              align="center"
              width="100px"
              height="40px"
            >
              {{ item.name }}
            </td>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="(item1, index) in infoWindowData.dataList"
            :key="'tr-' + item1.id"
            height="40px"
            :class="{'select-tr': index == selectIndex}"
            @click="selectNode(item1)"
          >
            <td
              v-for="item2 in infoWindowDto.infoGridFields"
              :key="'tr-' + item1.id + '-td-' + item2.fieldName"
              align="center"
            >
              {{ (item1.data[item2.fieldName] == undefined) ? "" : item1.data[item2.fieldName].displayValue[0] }}
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="clearfix" />
  </div>
</template>
<script>
import Common from '../../common/Common.js';

export default {
  name: 'SearchAutoCompleteWidget',
  props: {
    /**
     * 是否显示自动提示列表
     */
    'show':{
      type: Boolean,
      default: false,
    },
    'infoWindowNo':{
      type: String,
      default: null,
    },
    'leftPosition':{
      type: Number,
      default: null,
    },
    'whereClauseSource':{
      type: Object,
      default: null,
    },
    'parentModelData': {
      type: Object,
      default: null,
    },
    'modelData': {
      type: Object,
      default: null,
    },
  },

  emits: ['selectData', 'update:show'],

  data: function () {
    return {
      infoWindowDto: {},
      infoWindowData: {},
      selectIndex: -1,
      realLeft: {},
      isSearchWidget: true,
    };
  },

  computed: {
    realLeftComputed: function () {
      return (((this.realLeft > 0) ? this.realLeft : 0) + 'px');
    },
  },

  watch: {
    infoWindowData: function (val) {
      var _self = this;
      if (val.dataList != undefined && val.dataList.length > 0) {
        _self.$emit('update:show', true);
      } else {
        _self.$emit('update:show', false);
      }
    },

    /**
     * 距离左侧的距离
     * @param  {[type]} currentValue [description]
     * @param  {[type]} oldValue     [description]
     * @return {[type]}              [description]
     */
    leftPosition: function (currentValue, oldValue) {
      var _self = this;
      console.log('initialLeft changed: ' + currentValue);
      _self.realLeft = currentValue;
      console.log('realLeft2:' + _self.realLeft);
    },
  },

  mounted: function () {

  },

  methods: {
    /**
     * 向下
     * @return {void} 
     */
    selectDown: function () {
      var _self = this;
      var length = _self.infoWindowData.dataList.length;
      if (_self.selectIndex < (length - 1)) {
        _self.selectIndex++;
      }
    },

    /**
     * 向上
     * @return {void} 
     */
    selectUp: function () {
      var _self = this;
      var length = _self.infoWindowData.dataList.length;
      if (_self.selectIndex > 0) {
        _self.selectIndex--;
      }
    },

    /**
     * 获取当前数据 供外部调用
     * @return {Object} ModelData
     */
    getSelectData: function () {
      var _self = this;

      if (_self.selectIndex < 0) {
        return undefined;
      }

      var data = _self.infoWindowData.dataList[_self.selectIndex];
      return data;
    },

    /**
     * 获取第一行数据
     */
    getFirstData: function () {
      var _self = this;
      if (_self.infoWindowData != null && _self.infoWindowData.dataList != null && _self.infoWindowData.dataList.length > 0) {
        return _self.infoWindowData.dataList[0];
      }
      return null;
    },

    /**
     * 查询InfoWindowDto
     * @return {void} 
     */
    getInfoWindowDto: function (resolve, reject) {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('InfoWindowResource/uniqueByNo'),
        type: 'GET',
        dataType: 'json',
        data: { 'infoWindowNo': _self.infoWindowNo },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.infoWindowDto = data;
          resolve();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
          reject();
        },
      });
    },

    /**
     * 根据条件初始化查询
     * @param  {String} text 查询条件
     * @return {void}      
     */
    initSearch: function (text) {
      var _self = this;
      if (text != undefined) {
        if (_self.infoWindowDto == undefined || _self.infoWindowDto.infoGridFields == undefined) {
          new Promise(_self.getInfoWindowDto).then(function (value) {
            // success
            _self.getInfoWindowData(text);
          }, function (error) {
            // error
          });
        } else {
          _self.getInfoWindowData(text);
        }
      } else {
        _self.$emit('update:show', false);
      }
    },

    /**
     * 选择节点
     * @return {void} 
     */
    selectNode: function (data) {
      this.$emit('selectData', data);
    },


    /**
     * 查询infoWindowData
     * @return {void} 
     */
    getInfoWindowData: function (text) {
      var _self = this;

      var infoQueryParam = {
        infoWindowNo: _self.infoWindowNo,
        start: 0,
        length: 10,
        sortClause: '',
        infoFilterFieldValues: text,
        whereClauseSource: _self.whereClauseSource,
        modelData: _self.modelData,
        parentModelData: _self.parentModelData,
        isSearchWidget: _self.isSearchWidget,
      };

      $.ajax({
        url: Common.getApiURL('InfoWindowResource/queryInfoWindowDataSimple'),
        type: 'post',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        contentType: 'application/json',
        data: JSON.stringify(infoQueryParam),
        success: function (data) {
          _self.infoWindowData = data;
          _self.selectIndex = -1;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
  },
};
</script>

<style scoped>
.div-autoComplete {
    position: absolute;
    z-index: 999;
    background-color: #fff;
    border: 1px #e5e5e5 solid;
    padding: 15px 15px 0px 15px;
    box-shadow: 0 0 5px rgba(81, 203, 238, 1);
    /*width: 300px;*/
    /*height: 300px;*/
    /*max-height: 400px;*/
    max-width: 800px;
    min-width: 400px;
    /*overflow: auto;*/
    top: 32px;
}

.no-padding-left {
    padding-left: 0px !important;
}

.select-tr {
    background-color: #eee;
}
</style>