<template>
  <el-select
    v-model="selected"
    filterable
    :clearable="clearable"
    :disabled="disabled"
    :placeholder="placeholder"
    @change="select"
  >
    <el-option
      v-for="item in optionList"
      :key="item.id"
      :value="item.id"
      :label="item.name"
    ></el-option>
  </el-select>
</template>

<script>
import {
  propertyFirstQueryApi,
  propertySecondQueryApi,
} from "@/modules/question/api";

export default {
  name: "PropertyNameSelect",
  props: {
    value: {
      type: [String, Number],
      default: "",
    },
    options: { type: Array, default: () => [] },
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: "请选择属性名" },
    clearable: { type: Boolean, default: true },
    parentId: {
      type: [String, Number],
      default: "",
    },
    dataType: {
      type: String,
      default: "first",
    },
  },
  data() {
    return {
      optionList: this.options,
      selected: "",
      loading: false,
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      },
    },
    parentId(val, oldval) {
      if (val !== oldval) {
        this.search();
        this.selected = "";
        this.select();
      }
    },
  },
  methods: {
    async search() {
      if (!this.parentId) {
        this.optionList = [];
        return;
      }

      this.loading = true;
      const func =
        this.dataType === "first"
          ? propertyFirstQueryApi
          : propertySecondQueryApi;
      const res = await func(this.parentId);
      this.optionList = res.data || [];
      this.loading = false;
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find((item) => item.id === this.selected)
      );
    },
  },
};
</script>
