<template>
  <div v-show="field.visible" style="width: 100%">
    <a-input-group compact style="width: 230px">
      <a-input
        v-model:value="searchText" :class="validInput" :style="{ width: inputWidth }" :disabled="readonly"
        @input="textChange($event)" @keyup.up="selectUp" @keyup.down="selectDown" @keyup.enter="selectEnter"
        @keyup.esc="autoCompleteVisible = false" @blur="modalHide()"
      />
      <a-button v-if="field.linkCurdWindowNo" :disabled="readonly" @click="linkAdd">
        <template #icon>
          <PlusOutlined />
        </template>
      </a-button>
      <a-button v-if="field.linkCurdWindowNo" :disabled="readonly" @click="linkSkip">
        <template #icon>
          <LinkOutlined />
        </template>
      </a-button>
      <a-button :disabled="readonly" @click="showSearchDialog">
        <template #icon>
          <SearchOutlined />
        </template>
      </a-button>
    </a-input-group>
    <Modal
      v-model:show="modal"
      :full="true"
      @ok="searchDialogOk"
      @cancel="searchDialogCancel"
    >
      <InfoWindow
        ref="info"
        :field-value="fieldValue"
        :info-window-no="infoWindowNo"
        :where-clause-source="{'curdTabDataSourceField': { 'curdWindowNo' : windowNo, 'tabIndex' : tabIndex, 'fieldName' : field.fieldName}}"
        :is-search-widget="true"
        :parent-model-data="parentModelData"
        :model-data="modelData"
        @data-selected="dataSelected"
      />
      <template #header>{{ field.name }}</template>
    </Modal>
  </div>
  <SearchAutoCompleteWidget
    ref="autoComplete"
    v-model:show="autoCompleteVisible"
    style="z-index: 1000 !important;"
    :field-id="field.fieldId"
    :info-window-no="infoWindowNo"
    :where-clause-source="{'curdTabDataSourceField': { 'curdWindowNo' : windowNo, 'tabIndex' : tabIndex, 'fieldName' : field.fieldName}}"
    :parent-model-data="parentModelData"
    :model-data="modelData"
    @select-data="dataSelected"
  />
  <Loading v-if="loading" />
</template>

<script>
import WindowClientUtil from '../../resource/dictionary/WindowClientUtil.js';
import WindowServerUtil from '../../resource/dictionary/WindowServerUtil.js';
import Common from '../../common/Common.js';

import FieldResource from '../../api/dic/FieldResource.js';
import TabResource from '../../api/dic/TabResource.js';
import { Notify, Uuid } from 'pc-component-v3';
import { PlusOutlined, LinkOutlined, SearchOutlined } from '@ant-design/icons-vue';




export default {

  components: { PlusOutlined, LinkOutlined, SearchOutlined },



  props: {
    windowNo: {
      type: String,
      default: null,
    },
    tabIndex: {
      type: Number,
      default: null,
    },
    readonly: {
      type: Boolean,
      default: null,
    },
    field: {
      type: Object,
      default : function(){
        return null;
      },
    },
    infoWindowNo: {
      type: String,
      default: null,
    },
    modelData: {
      type: Object,
      default : function(){
        return null;
      },
    },
    parentModelData: {
      type: Object,
      default : function(){
        return null;
      },
    },
    fieldValue: {
      type: Object,
      default : function(){
        return null;
      },
    },
  },

  emits: ['valueChanged'],

  data: function () {
    return {
      labelNames: [],
      searchText: '',
      loading: false,
      modal: false,
      autoCompleteVisible: false,
    };
  },

  computed: {
  

    /**
         * 是否是有效的数据
         */
    validInput: function () {
      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;
        }
      }

      return {
        'invalid-input': isValid == false,
      };
    },
    inputWidth: function () {
      if (this.field.linkCurdWindowNo) return '59%';
      return '86%';
    },
  },

  watch: {
    'fieldValue': {
      deep: true,
      handler(curVal, oldVal) {
        this.reComputeSearchText(curVal);
      },
    },
  },

  mounted: function () {
    var _self = this;
    if (this.fieldValue != undefined && this.fieldValue.displayValue != undefined && this.fieldValue.displayValue.length > 0) {
      this.searchText = this.fieldValue.displayValue[0];
    } else {
      this.searchText = '';
    }

  },

  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.autoCompleteVisible = false;
      } else {
        if (_self.searchText == undefined || _self.searchText.length == 0) {
          if (_self.autoCompleteVisible == true) {
            _self.autoCompleteVisible = false;
          } else {
            _self.$refs.autoComplete.initSearch('');
          }
        }
      }
    },

    // 显示搜索对话框
    showSearchDialog: function () {
      var _self = this;
      if (_self.readonly) {
        return;
      }
      
      _self.modal=true;
      _self.autoCompleteVisible = false;
    },

    /**
         * 搜索框【确定】按钮点击事件
         */
    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 _self = this;
            
      // if(e.inputType === 'insertFromPaste'){
      //   // 如果是粘贴的文本，那么则直接返回
      //   // e.stopPropagation();
      //   e.target.value = _self.searchText;
      //   _self.onpaste();
      //   return;
      // }

      console.log('输入的文本: ' + e.target.value);
      var text = e.target.value;
      if (text == undefined || text.length == 0) {
        var newFieldValue = {
          id: null,
          displayValue: [],
          fieldType: 'Key',
        };
        this.$emit('valueChanged', newFieldValue);
      }
      // toggled by jack 20200815
      // else {
      //     // add by jack 20180917

      //     var newFieldValue = {
      //         id: null,
      //         displayValue: [text],
      //         fieldType: 'Key'
      //     }
      //     this.$emit("valueChanged", newFieldValue);
      // }

      this.$refs.autoComplete.initSearch(text);
    },

    // 数据已经选择
    dataSelected: function (data) {
      var _self = this;
      _self.modal=false;

      _self.autoCompleteVisible = false;

      if (data == undefined) {
        return;
      }

      console.log('已经选择了数据:' + data.id);
      var newFieldValue = {
        id: data.id,
        displayValue: [],
        fieldType: 'Key',
      };

      FieldResource.getFieldValue1(_self.windowNo, _self.tabIndex, _self.field.fieldName, data.id).then(successData => {
        newFieldValue.displayValue = successData;
        _self.reComputeSearchText(newFieldValue);
        _self.$emit('valueChanged', newFieldValue);
      }, errorData => {
        Common.processException(errorData);
      });
    },

    // 获取String字符串
    getFieldStringValue: function () {
      if (this.field != null && this.fieldValue == undefined || this.fieldValue.displayValue == undefined || this.fieldValue.displayValue.length < this.field.entityFieldIndex) {
        return '';
      } else {
        return this.fieldValue.displayValue[this.field.entityFieldIndex];
      }
    },

    /**
         * 链接列跳转
         * @return {void} 
         */
    linkSkip: function () {
      var _self = this;
      var linkCurdWindowNo = _self.field.linkCurdWindowNo;
      var recordId = _self.fieldValue.id;

      if (_self.fieldValue == undefined || recordId == undefined || recordId < 0 || recordId == '') {
        Notify.error('不能跳转', '未选择数据，不能跳转，您可以新建数据。', false);
        return;
      }
      _self.loading=true;

      TabResource.getWindowOpenParam(linkCurdWindowNo, _self.field.fieldName, recordId).then(successData => {
        _self.loading=false;
        WindowClientUtil.openNewCurdViewWindow(successData);
      }, errorData => {
        _self.loading=false;
        Common.processException(errorData);
      });
    },

    /**
         * 链接列新增
         * @return {void} 
         */
    linkAdd: function () {
      var _self = this;
      _self.loading=true;
      var linkCurdWindowNo = _self.field.linkCurdWindowNo;

      TabResource.getWindowOpenParam(linkCurdWindowNo, _self.field.fieldName, null).then(successData => {
        _self.loading=false;
        WindowClientUtil.openNewCurdNewWindow(successData);
      }, errorData => {
        _self.loading=false;
        Common.processException(errorData);
      });
    },

    /**
         * 重新计算SearchText
         * @package [fieldValue]
         * @return {[type]}
         */
    reComputeSearchText: function (fieldValue) {
      if (fieldValue != undefined && fieldValue.displayValue != undefined && fieldValue.displayValue.length > 0) {
        this.searchText = fieldValue.displayValue[0];
      } else {
        this.searchText = '';
      }
    },
    modalHide: function () {
      var _self = this;
      setTimeout(function () {
        _self.autoCompleteVisible = false;
      }, 500);
    },

    /**
         * 复制
         */
    oncopy: function (event) {
      var _self = this;

      _self.modal=false;

      if (_self.fieldValue != null && _self.fieldValue.id != null) {
        let newFieldValue = {};
        Object.assign(newFieldValue, _self.fieldValue);
        newFieldValue.infoWindowNo = _self.infoWindowNo;

        localStorage.setItem('clipboardData', JSON.stringify(newFieldValue));
        console.log('复制成功。');
        this.$toasted.show('复制成功。').goAway(1000);
      }

      event.preventDefault();
    },

    /**
         * 粘贴
         */
    onpaste: function () {
      var _self = this;

      _self.modal=false;


      let fieldValueText = localStorage.getItem('clipboardData');
      if (fieldValueText != null && fieldValueText.length > 0) {
        try {
          let newFieldValue = JSON.parse(fieldValueText);
          if (newFieldValue != null && newFieldValue.id != null && newFieldValue.displayValue != null && newFieldValue.fieldType === 'Key') {
            if (newFieldValue.infoWindowNo === _self.infoWindowNo) {
              newFieldValue.infoWindowNo = null;
              _self.$emit('valueChanged', newFieldValue);
              this.$toasted.show('粘贴成功。').goAway(1000);
              _self.$nextTick(function () {
                _self.modal=false;
                
              });
            } else {
              console.error('粘贴失败，不同的搜索框之间不能粘贴。%s', fieldValueText);
            }
          } else {
            console.error('粘贴失败。%s', fieldValueText);
          }
        } catch (error) {
          console.error('粘贴失败，粘贴的对象不能解析成JSON。%o', error);
        }
      }
    },

  },
};
</script>

<style scoped>
.input-group-cus {
    margin-bottom: 0px !important;
}

.invalid-input {
    color: #fff;
    background-color: #d9534f;
    border-color: #d43f3a;
}

.m-input-group-addon {
    width: 38px !important;
}

.m-input-group-addon-samll {
    width: 26px !important;
    padding: 6px 0px;
}

</style>