<template>
  <div>
    <Select
      ref="select"
      :size="size"
      :model-value="parseComboData()"
      @update:model-value="$event => setComboData($event)"
      :disabled="readonly"
      :clearable="true"
      :multiple="multi"
      filterable
      remote
      :remote-method="remoteMethod"
      :style="{ width: column.controlWidth == null ? null : column.controlWidth + 'px' }"
      :placeholder="column.placeholder"
      :transfer="true"
      @on-change="selected => onChange(selected)"
      @on-query-change="query => onComboQueryChange(query)"
      @on-clear="remoteMethod"
    >
      <Option v-for="(item, index) in getDataSource(data, column)" :key="index" :value="item.id">{{ item.name }}</Option>
    </Select>
  </div>
</template>
<script>
  import mixinPage from '../../mixins/page';
  import modelApi from '../../api/model';
  import customModelApi from '../../api/customModel';

  /**
   * @displayName combo-select 可筛选选择框
   */
  export default {
    mixins: [mixinPage],
    data() {
      return {
        selected: null,
        selectedData: null
      };
    },
    props: {
      /**
       * @model
       */
      modelValue: {
        type: [Array, Number, String]
      },
      /**
       * 大小
       * @values small, default, large
       */
      size: {
        type: String
      },
      /**
       * 数据源数据列名
       */
      remoteMethod: {
        type: Function
      },
      /**
       * 只读
       */
      readonly: {
        type: Boolean,
        default: false
      },
      /**
       * 数据
       */
      data: {
        type: Object,
        default() {
          return {};
        }
      },
      /**
       * 参数
       */
      param: {
        type: Object,
        default() {
          return {};
        }
      },
      /**
       * 列
       */
      column: {
        type: Object,
        default() {
          return {};
        }
      },
      /**
       * 能否多选
       */
      multi: {
        type: Boolean,
        default: false
      }
    },
    computed: {},
    watch: {
      modelValue(value) {
        this.selected = value;
        this.showSelected();
      }
    },
    mounted() {
      //this.showSelected();
    },
    methods: {
      parseComboData() {},
      setComboData(value) {
        /**
         * 输入事件
         * @property {object} value 选中的值 }
         */
        this.$emit('update:modelValue', value);
      },
      // 加载可筛选选择框显示内容
      async showSelected() {
        if (this.column.isStaticItem || (this.column.dataType && this.column.dataType.startsWith('Enum:'))) {
          return;
        }

        if (this.$refs.select) {
          let values = this.$refs.select.values;
          //values.length = 0;

          let pendings = [];
          if (this.multi) {
            values.length = 0;
            this.selected.forEach(value => {
              if (!values.some(v => v.value == value)) {
                // 不在选中项中
                let newValue = { value, label: null, disabled: false };

                values.push(newValue);
                pendings.push(newValue);
              }
            });
          } else {
            values.length = 0;
            this.$refs.select.query = '';
            if (!values.some(v => v.value == this.selected)) {
              // 不在选中项中
              let newValue = { value: this.selected, label: null, disabled: false };

              values.push(newValue);

              if (this.selected != null && this.selected != '') {
                pendings.push(newValue);
              }
            }
          }

          // 读取显示内容
          setTimeout(async () => {
            if (pendings.length > 0) {
              let param = this.param;
              param[this.column.sourceDataCode] = pendings.map(item => item.value).join(',');
              let res;

              if (this.column.isSourceCustom) {
                res = await customModelApi.query(this.column.source, param, [this.column.sourceDataCode, this.column.sourceDisplayCode]);
              } else {
                res = await modelApi.query(this.column.source, param, [this.column.sourceDataCode, this.column.sourceDisplayCode]);
              }

              res.data.forEach(item => {
                let v = this.parseData(item, this.column.sourceDataCode);
                let label = this.parseData(item, this.column.sourceDisplayCode);

                if (!this.multi) {
                  // 添加筛选内容
                  this.$refs.select.query = label;
                }

                let newValue = pendings.find(i => i.value == v);

                if (newValue) {
                  newValue.label = label;
                }
              });

              this.$forceUpdate();
            }
          });
        }
      },
      // 可筛选下拉框搜索条件变化
      onComboQueryChange(query) {
        if (!(query || '').trim() && !this.multi) {
          this.remoteMethod(query);
        }
      },
      // 数据变化
      onChange(selected) {
        /**
         * 选中项变化事件
         * @property {object} row 选中项 }
         */
        this.$emit('on-change', selected);
      },
      // 获取数据源
      getDataSource() {
        if (!this.column.isStaticItem && this.column.dataType.startsWith('Enum:')) {
          // 枚举
          return this.getEnumList(this.column.dataType.split(':')[1]);
        } else {
          return this.column.dataSource == null ? [] : this.column.dataSource;
        }
      }
    }
  };
</script>
