<template>
  <div class="input-group">
    <input
      aria-describedby="addon"
      type="text"
      class="form-control"
      :class="validInput"
      style="border-top-right-radius: 0; border-bottom-right-radius: 0;"
      :value="searchText"
      :readonly="readonly"
      @input="textChange($event)"
      @keyup.up="selectUp"
      @keyup.down="selectDown"
      @keyup.enter="selectEnter"
      @keyup.esc="$refs.autoComplete.hide()"
    />
    <div :class="[classSize != undefined ? 'input-group-btn classSize' : 'input-group-btn']">
      <button
        type="button"
        :class="[classSize != undefined ? 'btn btn-default classSize' : 'btn btn-default']"
        @click="showSearchDialog"
      >
        <span class="glyphicon glyphicon-search" />
      </button>
      <slot name="button1" />
      <slot name="button2" />
      <slot name="button3" />
    </div>

    <Modal
      ref="modal"
      :full="true"
      @ok="searchDialogOk"
      @cancel="searchDialogCancel"
    >
      <template #default>
        <info
          ref="info"
          :field-value="fieldValue"
          :where-clause="whereClause"
          :is-search-widget="true"
          :model-data="modelData"
          @data-selected="dataSelected"
        />
      </template>
      <template #header>
        <div>{{ titleName }}</div>
      </template>
    </Modal>

    <SearchAutoCompleteWidget
      ref="autoComplete"
      :info-window-no="infoWindowNo"
      :where-clause="whereClause"
      class="auto-complete"
      @select-data="dataSelected"
    />

    <Loading ref="loading" />
  </div>
</template>


<script>
var Modal = require('../../modal/src/Modal.vue').default;
var Info = require('./InfoWindow.vue').default;
var SearchAutoCompleteWidget = require('./SearchAutoCompleteWidget.vue').default;
var Loading = require('../../loading/src/Loading.vue').default;

export default {
  name: 'SearchWidget',

  components: {
    Modal, Info, SearchAutoCompleteWidget, Loading,
  },
  // infoWindowNo: 查询窗口编号
  // fieldValue: 显示的值
  // fieldValue:{
  //		displayValue: ['Jack'],
  //		fieldType: 'Key',
  //		id: 1
  // }
  // titleName: 弹出窗口的标题
  // displayName: 文本框中显示的字段
  // whereClause: 约束条件

  props: {
    'infoWindowNo':{
      type: String,
      default: null,
    },
    'fieldValue': {
      type: Object,
      default: null,
    },
    'titleName':{
      type: String,
      default: null,
    },
    'displayName':{
      type: String,
      default: null,
    },
    'whereClause':{
      type: String,
      default: null,
    },
    'readonly': {
      type: Boolean,
      default: false,
    },
    'modelData': {
      type: Object,
      default: null,
    },
    'classSize':{
      type: String,
      default: null,
    },
  },

  emits: ['valueChanged', 'dataSelected'],

  data: function () {
    var inputSearchText = this.initSearchText(this.fieldValue);

    return {
      isVisible: [],
      searchText: inputSearchText,
      leftPosition: 0,
    };
  },

  computed: {


    /**
             * 是否是有效的数据
             */
    validInput: function () {
      var _self = this;
      var isValid = true;
      if (this.searchText != undefined && this.searchText.length > 0) {
        if (this.fieldValue != undefined && (this.fieldValue.id == undefined || this.fieldValue.id <= 0)) {
          isValid = false;
        } else if (this.fieldValue != undefined && (this.fieldValue.displayValue != undefined && this.fieldValue.displayValue[0] != this.searchText)) {
          isValid = false;
        }
      }
      var isflag = false;
      if (_self.classSize != undefined) {
        isflag = true;
      }
      var ss = {
        'invalid-input': isValid == false,
        'classSize': isflag == true,
      };
      return ss;
    },
  },

  watch: {
    redraw: function () {
      console.log('searchWidgetRedraw');
    },

    fieldValue: {
      handler(currentValue, oldValue) {
        console.log('currentValue:' + JSON.stringify(currentValue));
        this.searchText = this.initSearchText(currentValue);
        console.log('searchText:' + this.searchText);
      },
      deep: true,
    },

    // 查询条件变化时，重新查询数据
    whereClause: function () {
      this.$refs.info.loadByInfoWindowNo(this.infoWindowNo);
    },
  },

  created: function () {
  },

  methods: {
    selectDown: function () {
      this.$refs.autoComplete.selectDown();
    },

    selectUp: function () {
      this.$refs.autoComplete.selectUp();
    },

    selectEnter: function () {
      var _self = this;

      var data = _self.$refs.autoComplete.getSelectData();
      if (data != undefined) {
        _self.dataSelected(data);
        _self.$refs.autoComplete.hide();
      } else {
        if (_self.searchText == undefined || _self.searchText.length == 0) {
          if (_self.$refs.autoComplete.isVisible() == true) {
            _self.$refs.autoComplete.hide();
          } else {
            _self.$refs.autoComplete.initSearch('');
          }
        }
      }
    },

    // 显示搜索对话框
    showSearchDialog: function () {
      var _self = this;

      // 如果是只读，则直接返回。
      if (_self.readonly != undefined && _self.readonly == true) {
        return;
      }

      console.log(this.$refs.modal);
      this.$refs.modal.showModal();

      _self.$refs.autoComplete.hide();

      if (this.$refs.info.infoWindowNo != _self.infoWindowNo) {
        this.$refs.info.loadByInfoWindowNo(this.infoWindowNo);
      } else {
        _self.$refs.info.refresh();
      }
    },

    /**
             * 搜索框【确定】按钮点击事件
             */
    searchDialogOk: function () {
      var _self = this;
      var selectedModelDatas = _self.$refs.info.getSelectedModelDatas();
      if (selectedModelDatas != undefined || selectedModelDatas.length > 0) {
        // 选中了数据，更新数据
        _self.dataSelected(selectedModelDatas[0]);
      }
    },

    searchDialogCancel: function () {

    },

    // 输入的文本发生改变
    textChange: function (e) {
      var text = e.target.value;
      console.log('textChange： ' + text);
      if (text == undefined || text.length == 0) {
        var newFieldValue = {
          id: undefined,
          displayValue: [],
          fieldType: 'Key',
        };
        this.$emit('valueChanged', newFieldValue);
      }
      this.$refs.autoComplete.initSearch(text);
    },

    // 数据已经选择
    dataSelected: function (modelData) {
      var _self = this;
      this.$refs.modal.hideModal();

      _self.$refs.autoComplete.hide();

      if (modelData == undefined) {
        return;
      }

      console.log('已经选择了数据:' + modelData.id);
      var displayValue = '';
      if (modelData.data && modelData.data[_self.displayName]) {
        displayValue = modelData.data[_self.displayName].displayValue[0];
      } else if (modelData[_self.displayName]) {
        displayValue = modelData[_self.displayName];
      }

      var newFieldValue = {
        id: modelData.id,
        displayValue: [displayValue],
        fieldType: 'Key',
      };

      if (newFieldValue.displayValue.length > 0) {
        _self.searchText = newFieldValue.displayValue[0];
      }
      this.$emit('valueChanged', newFieldValue);
      this.$emit('dataSelected', modelData);
    },

    initSearchText: function (tempFieldValue) {
      if (tempFieldValue == undefined || tempFieldValue.displayValue == undefined || tempFieldValue.displayValue.length == 0) {
        return '';
      } else {
        return tempFieldValue.displayValue[0];
      }
    },
  },
};
</script>

<style scoped>
.auto-complete {
    left: 0px;
    top: 34px;
}

.m-input-group-addon {
    border-top-right-radius: 5px !important;
    border-bottom-right-radius: 5px !important;
}

.invalid-input {
    color: #fff;
    background-color: #d9534f;
    border-color: #d43f3a;
}
.classSize {
    font-size: 40px;
    height: 60px;
}
</style>
