<template>
  <div style="width: 100%">
    <a-input-group compact>
      <a-select 
        v-model:value="selectedValue" 
        :style="{ width: inputWidth}" 
        :disabled="readonly"
        :suffix-icon="null"
        :open="false"
        mode="multiple"
        @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 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>
  </div>
  <div>
    <Modal
      v-model:show="modal"
      :full="true"
      @ok="searchDialogOk"
      @cancel="searchDialogCancel"
    >
      <template #header>
        {{ field.name }}
      </template>
      <InfoWindow
        v-if="modal"
        ref="info" 
        :multiple="true"
        :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"
        @delete-selected="deleteSelected"
      />
    </Modal>
    <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 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;
      },
    },
    modelData: {
      type: Object,
      default : function(){
        return null;
      },
    },
    parentModelData: {
      type: Object,
      default : function(){
        return null;
      },
    },
    infoWindowNo: {
      type: String,
      default: null,
    },
  },

  
  emits: ['valueChanged'],


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

  computed: {
    inputWidth: function () {
      if (this.field.linkCurdWindowNo) return 'calc(100% - 94px)';
      return 'calc(100% - 32px)';
    },
  },

  watch: {
    fieldValue: function () {
      this.reComputeSearchText(this.fieldValue);
    },
  },

  mounted: function () {
    this.reComputeSearchText(this.fieldValue);
  },

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

    searchDialogOk: function () {

    },

    searchDialogCancel: function () {

    },

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

      if (data == undefined) {
        return;
      }

      console.log('已经选择了数据:' + data.id);

      var newIds = [];
      if (_self.fieldValue.ids != undefined) {
        for (var i = 0; i < _self.fieldValue.ids.length; i++) {
          newIds.push(_self.fieldValue.ids[i]);
        }
      }

      if (newIds.indexOf(data.id) < 0) {
        newIds.push(data.id);
      }

      var newFieldValue = {
        displayValue: [],
        fieldType: 'ManyToManyKey',
        ids: newIds,
      };

      $.ajax({
        url: Common.getApiURL('FieldResource/getFieldValues?windowNo='+_self.windowNo+'&tabIndex='+_self.tabIndex+'&fieldName='+_self.field.fieldName),
        type: 'post',
        contentType: 'application/json',
        data: JSON.stringify(newFieldValue.ids),
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          newFieldValue.displayValue = data;
          _self.reComputeSearchText(newFieldValue);
          _self.$emit('valueChanged', newFieldValue);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    // 值改变
    valueChanged: function (fieldValue) {
      this.$emit('valueChanged', fieldValue);
      this.reComputeSearchText(fieldValue);
    },

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

      // 当前没有数据，不能跳转
      if (_self.fieldValue == undefined || recordIds == undefined || recordIds.length < 0 || recordIds == '') {
        Notify.error('不能跳转', '未选择数据，不能跳转，您可以新建数据。',false);

        return;
      }

      if (recordIds != undefined) {
        for (var i = 0; i < recordIds.length; i++) {
          var recordId = recordIds[i];
          _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);
      });
    },

    /**
         * 重新计算显示值
         * @package [fieldValue]
         * @return {[type]}
         */
    reComputeSearchText: function (fieldValue) {
      var arr = [];
      var fieldValue1 = this.fieldValue;
      var ids = fieldValue1.ids;
      var displayValue = fieldValue1.displayValue;
      if (ids != undefined && displayValue != undefined && ids.length == displayValue.length) {
        for (var i = 0; i < ids.length; i++) {
          var obj = {
            id: ids[i],
            value: displayValue[i],
          };
          arr.push(obj);
        }
      }
      this.selectedValue = ids;
      const options = arr.map(item => {
        return {
          value: item.id,
          label: item.value,
        };
      });
      return this.selectedDatas = options;
    },

    // 删除选中数据
    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: 'ManyToManyKey',
          ids: newIds,
        };

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

        // 触发父组件更新
        this.$emit('valueChanged', newFieldValue);
      }
    },
  },
};
</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;
}

.icon1 {
    position: absolute;
    top: 0px;
    right: 68px;
    color: #555;
    background-color: #eee;
    border: 1px solid #ccc;
    border-radius: 4px;
    width: 34px;
    height: 32px;
    line-height: 32px;
    text-align: center;
}

.icon2 {
    position: absolute;
    top: 0px;
    right: 34px;
    color: #555;
    background-color: #eee;
    border: 1px solid #ccc;
    border-radius: 4px;
    width: 34px;
    height: 32px;
    line-height: 32px;
    text-align: center;
}

.icon3 {
    position: absolute;
    top: 0px;
    right: 0px;
    color: #555;
    background-color: #eee;
    /* border: 1px solid #ccc; */
    border-radius: 4px;
    width: 34px;
    height: 32px;
    line-height: 32px;
    text-align: center;
}

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