<template>
  <el-select
    v-model="selected"
    :placeholder="placeholder"
    filterable
    :clearable="clearable"
    :disabled="disabled"
    @change="select"
  >
    <el-option
      v-for="item in optionList"
      :key="item.id"
      :value="item.id"
      :label="`${item.name}（${item.code}）`"
    >
      <span>{{ `${item.name}（${item.code}）` }}</span>
    </el-option>
  </el-select>
</template>

<script>
import { conditionTrainingPlanCourseList } from "../../modules/base/api";

export default {
  name: "training-plan-course-select",
  props: {
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: "请选择" },
    value: { type: [Number, String], default: "" },
    clearable: { type: Boolean, default: true },
    professionalId: { type: String, default: "" },
    cultureProgramId: { type: String, default: "" },
    defaultSelect: { type: Boolean, default: false },
  },
  data() {
    return {
      optionList: [],
      selected: "",
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      },
    },
    professionalId(val, oldval) {
      if (val !== oldval) {
        this.search();
        this.$emit("input", "");
        this.$emit("change", {});
      }
    },
    cultureProgramId(val, oldval) {
      if (val !== oldval) {
        this.search();
        this.$emit("input", "");
        this.$emit("change", {});
      }
    },
  },
  created() {
    this.search();
  },
  methods: {
    async search() {
      this.optionList = [];
      // if (!this.professionalId || !this.cultureProgramId) return;
      const res = await conditionTrainingPlanCourseList({
        professionalId: this.professionalId,
        cultureProgramId: this.cultureProgramId,
      });
      this.optionList = res;

      if (this.defaultSelect && !this.value) this.selectDefault();
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find((item) => item.id === this.selected)
      );
    },
    selectDefault() {
      const defaultData = this.optionList[0];
      if (defaultData) {
        this.selected = defaultData.id;
        this.$emit("input", this.selected);
        this.$emit("change", defaultData);
        this.$emit("default-selected", defaultData);
      }
    },
  },
};
</script>
