<template>
  <div v-show="field.visible" style="width: 100%">
    <a-input-group compact>
      <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 style="width: 20px;" />
        </template>
      </a-button>
      <a-button v-if="field.linkCurdWindowNo" :disabled="readonly" @click="linkSkip">
        <template #icon>
          <LinkOutlined style="width: 20px;" />
        </template>
      </a-button>
      <a-button :disabled="readonly" @click="showSearchDialog">
        <template #icon>
          <SearchOutlined style="width: 20px;" />
        </template>
      </a-button>
    </a-input-group>

    <div>
      <a-modal
        v-model:open="modal" :title="field.displayName" width="100%"
        @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"
        />
      </a-modal>
    </div>
    <SearchAutoCompleteWidget
      ref="autoComplete" v-model:show="autoCompleteVisible" :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" />
  </div>
</template>
<script>
import Common from '../../common/Common.js';

import WindowClientUtil from '../../resource/dictionary/WindowClientUtil.js';
import WindowServerUtil from '../../resource/dictionary/WindowServerUtil.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;
      },
    },
    fieldValue: {
      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;
      },
    },
  },


  emits: ['valueChanged'],



  data: function () {
    return {
      infoWindowDto: {},
      infoWindowData: {},
      isShowAuto: false,
      searchText: '',
      selectIndex: -1,
      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 'calc(100% - 94px)';
      return 'calc(100% - 32px)';
    },
  },

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

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

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

    // 显示搜索对话框
    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;
      var text = _self.searchText;

      // 当文本清空以后，触发valueChanged，表示该字段无值。
      if (text == undefined || text.length == 0) {
        var newFieldValue = {
          id: null,
          displayValue: [],
          fieldType: 'Key',
        };
        this.$emit('valueChanged', newFieldValue);
      }
      _self.$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);
        },
      );
    },

    /**
     * 链接列跳转
     * @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;

      var linkCurdWindowNo = _self.field.linkCurdWindowNo;
      _self.loading = true;

      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);
    },
  },
};
</script>

<style scoped>
.invalid-input {
  color: #fff;
  background-color: #d9534f;
  border-color: #d43f3a;
}

.m-input-group-addon {
  width: 38px !important;
}
</style>