<template>
  <div class="filter-item-group">
    <div
      class="filter-item"
      v-for="(column, columnIndex) in columns"
      :key="columnIndex"
    >
      <div class="filter-item-label">{{ column.label }}</div>
      <div class="filter-item-content">
        <el-select
          :value="column.value"
          v-bind="column.componentProps"
          @change="onChange($event, columnIndex)"
        >
          <el-option
            v-for="option in column.options"
            :key="option[column.fileNames ? column.fileNames.value : 'value']"
            :label="option[column.fileNames ? column.fileNames.label : 'label']"
            :value="option[column.fileNames ? column.fileNames.value : 'value']"
          />
        </el-select>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "SelectGroupJoin",
  props: {
    /**
     * 配置每个下拉选项对象
     */
    columns: {
      type: Array,
      default: () => []
    }
  },
  methods: {
    setValues(values) {
      values.forEach((value, columnIndex) => {
        this.columns[columnIndex].value = value;
      });
    },
    setColumnValue(columnIndex, value) {
      this.onChange(value, columnIndex);
    },
    onChange(value, columnIndex) {
      const column = this.columns[columnIndex];
      column.value = value;

      let n = columnIndex;
      while (n + 1 < this.columns.length) {
        n++;
        this.columns[n].value = this.columns[n].defaultValue;
      }
      this.$emit("change", { selectedValues: this.columns.map(v => v.value) });

      const nextColumnIndex = columnIndex + 1;
      if (nextColumnIndex < this.columns.length) {
        this.loadData(nextColumnIndex);
      }
    },
    loadData(index = 0) {
      const column = this.columns[index];

      return (
        column.api &&
        column.api().then(res => {
          column.options = res.data || [];
          if (typeof column.afterFetch === "function") {
            column.options = column.afterFetch(res.data) || [];
          }
        })
      );
    }
  }
};
</script>

<style lang="scss" scoped></style>
