<template>
  <div style="width: 100%;">
    <a-select v-model:value="selected" mode="multiple" style="width: 100%" :options="options" @change="selectChange" />
  </div>
</template>

<script>

export default {

  components: {},


  props: {

    readonly: {
      type: Boolean,
      default: null,
    },
    field: {
      type: Object,
      default: function () {
        return null;
      },
    },
    fieldValue: {
      type: Object,
      default: function () {
        return null;
      },
    },
  },


  emits: ['valueChanged'],

  data: function () {
    return {
      selectedValue: (this.fieldValue == undefined) ? '' : this.fieldValue.id,
      // selected: null,
      selected: ((this.fieldValue == undefined || this.fieldValue.id == undefined) ? [] : this.fieldValue.id),
      options: [],
    };
  },
  watch: {
    // selected: function(to, from){
    //   var datas = [];
    //   if(to != undefined){
    //     to.forEach(function(item){
    //       datas.push(item.value);
    //     });
    //   }
    //   var newFieldValue = {
    //     id: null,
    //     displayValue: [datas.join(',')],
    //     fieldType: 'String',
    //   };
    //   this.$emit('valueChanged', newFieldValue);
    // },
  },
  mounted: function () {
    this.initOptions();
  },
  methods: {
    selectChange: function (value) {
      let newFieldValue = {
        id: null,
        displayValue: value.length ? [value.join(',')] : [],
        fieldType: 'String',
      };
      this.$emit('valueChanged', newFieldValue);
    },
    initData: function () {
      var _self = this;
      if (_self.fieldValue != undefined && _self.fieldValue.displayValue != undefined && _self.fieldValue.displayValue[0] != undefined) {
        var arr = _self.fieldValue.displayValue[0].split(',');
        arr.forEach(function (item) {
          _self.options.forEach(function (item1) {
            if (item == item1.value) {
              if (_self.selected == undefined) {
                _self.selected = new Array();
              }
              _self.selected.push(item1);
            }
          });
        });
      }
    },

    initOptions: function () {
      var _self = this;
      var arr = [];
      if (_self.field.keyValues != undefined) {
        _self.field.keyValues.forEach(function (item) {
          var obj = {
            label: item.value,
            value: item.keyStr,
          };
          arr.push(obj);
        });
        _self.options = arr;
        _self.initData();
      }
    },
  },
};

</script>