<template>
  <div style="width: 100%">
    <a-input-group compact>
      <a-select
        v-model:value="selectedValue" :style="{ width: inputWidth }" :suffix-icon="null" :open="false"
        mode="multiple" max-tag-count="responsive" @deselect="(value) => deleteSelected(value, 'antd')"
      >
        <a-select-option
          v-for="keyValue in selectedDatas" :key="keyValue.value" :value="keyValue.value"
          style="display: none"
        >
          {{ keyValue.label }}
        </a-select-option>
      </a-select>
      <a-button @click="showSearchDialog">
        <template #icon>
          <SearchOutlined />
        </template>
      </a-button>
    </a-input-group>
    <Modal
      :key="'modal-info-window-' + infoWindowNo" v-model:show="modal" :title="titleName" :full="true" @ok="searchDialogOk"
      @cancel="searchDialogCancel" 
    >
      <InfoWindow 
        v-if="modal"
        ref="info" :key="'info-window-' + infoWindowNo" :multiple="true" :info-window-no="infoWindowNo"
        :where-clause-source="whereClauseSource" :is-search-widget="true" :field-value="fieldValue"
        @data-selected="dataSelected" @delete-selected="deleteSelected"
      />
      <template #header>
        {{ infoWindowDto.name }}
      </template>
    </Modal>
    <Loading v-if="loading" />
  </div>
</template>
<script>

import Common from '../../common/Common.js';
import { SearchOutlined } from '@ant-design/icons-vue';


export default {

  components: {
    SearchOutlined,
  },
  /**
   * widgetId: 控件Id
   * infoWindowNo: 查询窗口编号
   * whereClauseSource: 查询窗口额外的HQL语句
   * displayName：查询窗口的显示字段
   * fieldValue: 显示的值
   * 		{
   * 			displayValue: [],
   * 			fieldType: 'Key',
   * 			ids: []
   * 		}
   */
  props: {

    widgetId: {
      type: String,
      default: null,
    },
    infoWindowNo: {
      type: String,
      default: null,
    },
    displayName: {
      type: String,
      default: null,
    },
    whereClauseSource: {
      type: Object,
      default: function () {
        return null;
      },
    },
    titleName: {
      type: String,
      default: null,
    },
    fieldValue: {
      type: Object,
      default: function () {
        return null;
      },
    },
  },


  emits: ['valueChanged'],


  data: function () {
    return {
      labelNames: [],
      infoWindowDto: {},
      infoWindowData: {},
      isShowAuto: false,
      searchText: '',
      selectIndex: -1,
      fieldValueInternal: {
        displayValue: [],
        fieldType: 'MultiSearchBoxEditor',
        ids: [],
      },
      loading: false,
      modal: false,
      selectedValue: [],
      selectedDatas: [],
    };
  },

  computed: {
    inputWidth: function () {
      return 'calc(100% - 32px)';
    },
  },

  watch: {
    fieldValue: function (currentValue, oldValue) {
      if (currentValue) {
        if (
          currentValue.displayValue == undefined ||
          currentValue.displayValue.length == 0
        ) {
          currentValue.displayValue = [];
        }
        if (currentValue.ids == undefined || currentValue.ids.length == 0) {
          currentValue.ids = [];
        }
        this.fieldValueInternal.ids = currentValue.ids;
        this.selectedValue = currentValue.ids;
        this.fieldValueInternal.displayValue = currentValue.displayValue;
        this.selectedDatas = currentValue.displayValue.map((text, index) => ({
          value: currentValue.ids[index],
          label: text,
        }));
      }
    },

    widgetId: function () {
      // 当widgetId发生变化的时候，选择的值设置成undefined
      // bug fixed by jack 20180201
      this.clearSearchCondition();
    },
  },

  mounted: function () {
    if (this.fieldValue != null && this.fieldValue.ids != null) {
      this.fieldValueInternal.ids = this.fieldValue.ids;
      this.selectedValue = this.fieldValue.ids;
      this.fieldValueInternal.displayValue = this.fieldValue.displayValue;
      this.selectedDatas = this.fieldValue.displayValue.map(text => ({
        value: text,
        label: text,
      }));
    }
  },

  methods: {
    /**
     * 显示搜索对话框
     */
    showSearchDialog: function () {
      var _self = this;
      _self.modal = true;

    },

    searchDialogOk: function () { },

    searchDialogCancel: function () { },

    /**
     * 数据选择事件
     */
    dataSelected: function (data) {
      var _self = this;

      if (data == undefined) {
        return;
      }

      if (_self.displayName == undefined || _self.displayName == '') {
        console.log('多选搜索框未定义显示名称。');
      }

      if (_self.fieldValueInternal.ids.indexOf(data.id) < 0) {
        _self.fieldValueInternal.ids.push(data.id);
        var arr = _self.displayName.split(',');
        var text = '';
        arr.forEach(function (item) {
          if (data.data[item] == undefined) {
            console.log('显示名称不正确:' + item);
          } else {
            console.log('选择的text:' + data.data[item].displayValue[0]);
            text += data.data[item].displayValue[0];
          }
        });

        _self.fieldValueInternal.displayValue.push(text);
        _self.selectedDatas.push({
          value: data.id,
          label: text,
        });
        console.log('selectedDatas:', _self.selectedDatas);
      }

      _self.$emit('valueChanged', _self.fieldValueInternal);
    },

    /**
     * 删除了选中项
     */
    deleteItem: function (index) {
      var _self = this;
      _self.fieldValueInternal.displayValue.splice(index, 1);
      _self.fieldValueInternal.ids.splice(index, 1);
      this.$emit('valueChanged', _self.fieldValueInternal);
    },

    /**
     * 删除选中数据实现
     */
    // deleteSelected: function (item) {
    //   let index = this.fieldValueInternal.ids.indexOf(item.id);
    //   if (index >= 0) {
    //     this.deleteItem(0);
    //   }
    // },
    // 删除选中数据
    deleteSelected: function (item, flag) {
      // 获取要删除的ID
      const id = flag === 'antd' ? item : item.id;

      // 创建新的数组副本（保持响应式）
      const newIds = [...this.fieldValue.ids];
      const displayValues = [...this.fieldValue.displayValue];

      // 查找索引位置
      const index = newIds.indexOf(id);
      if (index > -1) {
        // 同步删除两个数组中的对应项
        newIds.splice(index, 1);
        displayValues.splice(index, 1);

        // 创建新字段值对象
        const newFieldValue = {
          displayValue: displayValues,
          fieldType: 'MultiSearchBoxEditor',
          ids: newIds,
        };

        // 立即更新本地状态
        this.selectedValue = newIds;
        this.selectedDatas = newIds.map((id, i) => ({
          value: id,
          label: displayValues[i],
        }));

        this.fieldValueInternal = newFieldValue;

        // 触发父组件更新
        this.$emit('valueChanged', newFieldValue);
      }
    },
    /**
     * 清楚选择的数据
     */
    clearSearchCondition: function () {
      if (this.fieldValueInternal != undefined) {
        if (this.fieldValueInternal.displayValue != undefined) {
          this.fieldValueInternal.displayValue.splice(
            0,
            this.fieldValueInternal.displayValue.length,
          );
        }
        if (this.fieldValueInternal.ids != undefined) {
          this.fieldValueInternal.ids.splice(
            0,
            this.fieldValueInternal.ids.length,
          );
        }
      }
    },
  },
};
</script>

<style scoped>
.required-mark {
  color: red;
  margin-right: 10px;
}

.box {
  width: 100%;
  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;
}

.search-icon {
  position: absolute;
  top: 9px;
  right: 7px;
}

.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;
}

.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;
}

.div-readonly {
  background-color: #eee !important;
}

.content {
  display: inline-block !important;
  width: 570px;
}
</style>