<template>
  <el-select
    v-model="selected"
    class="card-rule-select"
    :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"
    >
      <span>{{ item.name }}</span>
    </el-option>
  </el-select>
</template>

<script>
import { cardRuleQuery } from "../../modules/base/api";
import { COMMON_CARD_RULE_ID } from "@/constants/enumerate";

export default {
  name: "card-rule-select",
  props: {
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: "请选择" },
    value: { type: [Number, String], default: "" },
    clearable: { type: Boolean, default: true },
    showCommonCard: { type: Boolean, default: true },
    examId: { type: String, default: "" },
    watchResponse: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      optionList: [],
      selected: "",
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      },
    },
    examId(val, oldval) {
      if (!this.watchResponse) return;

      if (val !== oldval) {
        this.search();
        this.$emit("input", "");
        this.$emit("change", {});
      }
    },
  },
  created() {
    this.search();
  },
  methods: {
    async search() {
      const datas = {};
      if (this.examId) datas.examId = this.examId;

      const res = await cardRuleQuery(datas);
      this.optionList = res;
      if (this.showCommonCard)
        this.optionList.unshift({
          id: COMMON_CARD_RULE_ID,
          name: "全部通卡",
        });
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find((item) => item.id === this.selected)
      );
    },
  },
};
</script>
