<template>
  <div class="ecs-exam-select">
    <el-select
      v-model="selected"
      :placeholder="placeholder"
      filterable
      :clearable="clearable"
      :disabled="disabled || loading"
      @change="select"
    >
      <el-option
        v-for="item in optionList"
        :key="item.examId"
        :value="item.examId"
        :label="`${item.examId}-${item.examName}`"
      >
      </el-option>
    </el-select>
    <el-button
      icon="el-icon-refresh"
      type="primary"
      title="同步考试"
      :loading="loading"
      @click="toSync"
    ></el-button>
  </div>
</template>

<script>
import { ecsExamQuery, ecsExamSync } from "../../modules/base/api";

export default {
  name: "ecs-exam-select",
  props: {
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: "请选择考试" },
    value: { type: [Number, String], default: "" },
    clearable: { type: Boolean, default: true },
    collegeId: { type: [Number, String], default: "" },
  },
  data() {
    return {
      optionList: [],
      selected: "",
      loading: false,
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      },
    },
    collegeId(val, oldval) {
      if (val !== oldval) {
        this.search();
        this.$emit("input", "");
        this.$emit("change", {});
      }
    },
  },
  created() {
    this.search();
  },
  methods: {
    async search() {
      this.optionList = [];
      if (!this.collegeId) return;

      const res = await ecsExamQuery(this.collegeId);
      this.optionList = res;
    },
    async toSync() {
      if (!this.collegeId) {
        this.$message.error("请先选择学院！");
        return;
      }

      if (this.loading) return;
      this.loading = true;

      const res = await ecsExamSync(this.collegeId).catch(() => {});
      this.loading = false;
      if (res) this.optionList = res;
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find((item) => item.examId === this.selected)
      );
    },
  },
};
</script>
