<template>
  <el-dialog
    class="transfer-user-dialog"
    :visible.sync="modalIsShow"
    title="请选择转办人"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form ref="modalFormComp" :model="modalForm" :rules="rules">
      <el-form-item prop="transferId">
        <el-select
          v-model="modalForm.transferId"
          class="width-full"
          filterable
          clearable
        >
          <el-option
            v-for="item in optionList"
            :key="item.userId"
            :value="item.userId"
            :label="`${item.realName}（${item.roleName}）`"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <div slot="footer">
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { examTransferUser, examSecretaryList } from "../api";

export default {
  name: "select-transfer-user",
  props: {
    task: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      optionList: [],
      modalForm: {
        transferId: "",
      },
      rules: {
        transferId: [
          {
            required: true,
            message: "请选择转办人",
            trigger: "change",
          },
        ],
      },
    };
  },
  mounted() {
    this.getUsers();
  },
  methods: {
    visibleChange() {
      this.modalForm.transferId = null;
    },
    async getUsers() {
      this.optionList = [];
      const data = await examSecretaryList();
      this.optionList = data || [];
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

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

      const res = await examTransferUser({
        transferId: this.modalForm.transferId,
        courseId: this.task.courseId,
        paperNumber: this.task.paperNumber,
        examId: this.task.examId,
      }).catch(() => {});
      this.isSubmit = false;

      if (!res) return;
      this.$message.success("操作成功");
      this.cancel();
      this.$emit("modified");
    },
  },
};
</script>
