<template>
  <div class="content">
    <div class="form-group">
      <!-- <label v-show="isVisible[0]" class="col-xs-5 col-sm-4 col-md-3 col-lg-2 control-label">
				<span class="required-mark" v-if="field.mandatory">*</span>{{labelNames[0]}}
			</label> -->
      <div
        v-show="isVisible[0]"
        style="position:relative; padding-left: 0px;"
        class="col-xs-12 col-sm-12 col-md-12 col-lg-12"
      >
        <div class="input-group">
          <!-- <input :aria-describedby="'addon' + field.id" type="text" class="form-control" v-model="searchText" @input="textChange($event)" :readonly="readonly"/> -->
          <!-- <span @click="showSearchDialog" class="input-group-addon" :id="'addon' + field.id" :disabled="readonly">
							<span class="glyphicon glyphicon-search"></span>
						</span> -->

          <div
            class="box"
            :class="{'div-readonly':readonly}"
          >
            <span
              v-for="(item) in selectDatas"
              :key="item.id"
              class="selected-tag"
            >
              {{ item.text }}
              <button
                v-if="!readonly"
                type="button"
                class="close"
                aria-label="Remove option"
                @click="deleteRecord(item)"
              >
                <span aria-hidden="true">&times;</span>
              </button>
            </span>
            <span
              class="glyphicon glyphicon-search search-icon"
              @click="showSearchDialog"
            />
          </div>

          <Modal
            ref="modal"
            :full="true"
            @ok="searchDialogOk"
            @cancel="searchDialogCancel"
          >
            <template #default>
              <info
                ref="info"
                :info-window-no="infoWindowNo"
                @data-selected="dataSelected"
              />
            </template>

            <template #header>
              <div>
                {{ field.name }}
              </div>
            </template>
          </Modal>
        </div>
        <div
          v-show="isShowAuto"
          class="div-autoComplete"
        >
          <table class="table-bordered table-hover">
            <thead>
              <tr>
                <td
                  v-for="item in infoWindowDto.infoGridFields"
                  :key="'td-' + item.fieldName"
                  align="center"
                  width="100px"
                >
                  {{ item.name }}
                </td>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="item1 in infoWindowData.dataList"
                :key="'row-data-' + item1.id"
                height="40px"
                @click="selectNode(item1)"
              >
                <td
                  v-for="item2 in infoWindowDto.infoGridFields"
                  :key="'row-column-data-' + item1.id + '-' + item2.fieldName"
                  align="center"
                >
                  {{ item1.data[item2.fieldName].displayValue[0] }}
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <div
      v-for="(titleName, index) in titleNames"
      v-show="isVisible[index]"
      :key="titleName + '-' + index"
      :class="{'form-group' : index > 0}"
    >
      <label
        v-if="index > 0"
        class="col-xs-5 col-sm-4 col-md-3 col-lg-2 control-label"
      >
        <span
          v-if="field.mandatory"
          class="required-mark"
        >*</span>{{ titleName }}
      </label>
      <div
        v-if="index > 0"
        class="col-xs-7 col-sm-8 col-md-9 col-lg-10"
      >
        <input
          type="text"
          class="form-control"
          :value="getFieldStringValue(index)"
          disabled
        />
      </div>
    </div>
  </div>
</template>
<script>
var Modal = require('../../modal/src/Modal.vue').default;
var Info = require('../../info/src/InfoWindow.vue').default;
var Common = require('../../common/Common.js').default;

export default {

  components: {
    Modal, Info,
  },
  props: {
    'infoWindowNo':{
      type: String,
      default: null,
    }, 
    'field':{
      type: Object,
      default: null,
    }, 
    'fieldValue':{
      type: Object,
      default: null,
    }, 
    'readonly':{
      type: Boolean,
      default: false,
    },
  },

  emits: [ 'getData', 'valueChanged'],

  data: function () {
    return {
      isVisible: [],
      infoWindowDto: {},
      infoWindowData: {},
      isShowAuto: false,
      searchText: '',
      selectDatas: [],
    };
  },

  computed: {
    titleNames: function () {
      if (this.field == null && this.field.displayName == null) {
        return '';
      } else {
        let labelNames = this.field.displayName.split(',');
        return labelNames;
      }
    },
  },

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

  mounted: function () {
    this.getInfoWindowDto();
  },

  methods: {
    // 显示搜索对话框
    showSearchDialog: function () {
      var _self = this;
      if (this.readonly) {
        return;
      }
      _self.$refs.modal.showModal();
      _self.$nextTick(function () {
        _self.$refs.modal.showModal();
        if (this.$refs.info) {
          _self.$refs.info.refresh();
        }
      });
    },

    searchDialogOk: function () {

    },

    searchDialogCancel: function () {

    },

    // 输入的文本发生改变
    textChange: function (e) {
      var _self = this;
      var text = _self.searchText;

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

      if (text.trim() != '') {
        _self.getInfoWindowData(text);
      } else {
        _self.isShowAuto = false;
      }
    },

    /**
     * 查询InfoWindowDto
     * @return {void} 
     */
    getInfoWindowDto: function () {
      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;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },


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

      var infoQueryParam = {
        infoWindowNo: _self.infoWindowNo,
        start: 0,
        length: 5,
        sortClause: '',
        condition: text,
      };

      $.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;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 选择数据(自动提示框)
     * @return {void} 
     */
    selectNode: function (data) {
      var _self = this;
      _self.isShowAuto = false;
      _self.dataSelected(data);

    },

    deleteRecord: function (selectData) {
      var _self = this;
      var index = _self.selectDatas.indexOf(selectData);
      if (index > -1) {
        _self.selectDatas.splice(index, 1);
        _self.getSelectDataIds();
      }

    },

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

      var index = _self.selectDatas.indexOf(data);

      if (index > -1) {
        return;
      }

      if (this.$refs.modal != undefined) {
        this.$refs.modal.hideModal();
      }
      _self.$refs.modal.hideModal();

      var text = [];

      var listDisplayFieldNames = this.field.listDisplayFieldNames;
      var displayValues = listDisplayFieldNames.split(',');
      for (var i = 0; i < displayValues.length; i++) {
        var fieldValue = data.data[displayValues[i]];
        if (fieldValue != undefined && fieldValue.displayValue != undefined) {
          text[i] = fieldValue.displayValue[0];
        } else {
          text[i] = '';
        }
      }

      data.text = text[0];

      _self.selectDatas.push(data);


      /*var selectDataIds = [];
        _self.selectDatas.forEach(function(item){
            selectDataIds.push(item.id);
        })

        var newFieldValue = {
            displayValue: selectDataIds,
            fieldType: 'MultiSearchBoxEditor'
        }
        this.$emit("valueChanged", newFieldValue);*/

      _self.getSelectDataIds();
      this.$emit('getData', data);
    },

    getSelectDataIds: function () {
      var _self = this;
      var selectDataIds = [];
      _self.selectDatas.forEach(function (item) {
        selectDataIds.push(item.id);
      });

      var newFieldValue = {
        displayValue: selectDataIds,
        fieldType: 'MultiSearchBoxEditor',
      };
      this.$emit('valueChanged', newFieldValue);
    },

    // 获取String字符串
    getFieldStringValue: function (index) {
      if (this.fieldValue == undefined || this.fieldValue.displayValue == undefined || this.fieldValue.displayValue.length < index) {
        return '';
      } else {
        return this.fieldValue.displayValue[index];
      }
    },
  },
};
</script>

<style scoped>
.required-mark {
    color: red;
    margin-right: 10px;
}
.div-autoComplete {
    position: absolute;
    z-index: 99;
    background-color: #fff;
    border: 1px #e5e5e5 solid;
    padding: 0px 15px 15px 15px;
    box-shadow: 0 0 5px rgba(81, 203, 238, 1);
}
.box {
    width: 200px;
    min-height: 34px;
    border: 1px solid rgba(60, 60, 60, 0.26);
    border-radius: 4px;
    white-space: normal;
    transition: border-radius 0.25s;
    background-color: #ffffff;
    position: relative;
}
.div-readonly {
    background-color: #eee !important;
}
.close {
    float: none;
    margin-right: 0;
    font-size: 20px;
    appearance: none;
    padding: 0;
    cursor: pointer;
    background: 0 0;
    border: 0;
    font-weight: 700;
    line-height: 1;
    color: #000;
    text-shadow: 0 1px 0 #fff;
    filter: alpha(opacity=20);
    opacity: 0.2;
}
.selected-tag {
    color: #333;
    background-color: #f0f0f0;
    border: 1px solid #ccc;
    border-radius: 4px;
    height: 26px;
    margin: 4px 1px 0px 3px;
    padding: 3px 0.25em;
    line-height: 34px;
}
.search-icon {
    position: absolute;
    top: 9px;
    right: 7px;
}
.content {
    display: inline-block !important;
}
/*.img-box {
		width: 60px;
		float: left;
		text-align: center;
		margin-right: 20px;
	}
	.img-box div img{
		width: 60px;
		height: 60px;
	}
	.add-box {
		width: 60px;
		height: 60px;
		float: left;
		border-radius: 30px;
		border: 1px #999 dashed;
		text-align: center;
		margin-top: 20px;
	}
	.add-box:hover {
		cursor: pointer;
		background-color: #ccc;
	}
	.add-icon {
		width: 60px;
		height: 60px;
		color: #aaa;
		font-size: 40px;
		line-height: 60px;
		position: relative;
		top: -1px;
	}
	.remove-icon {
		color: red;
		position: relative;
		top: 10px;
		right: -30px;
		cursor: pointer;
	}*/
</style>