<template>
  <el-dialog
    class="upload-paper-dialog"
    :visible.sync="modalIsShow"
    title="导入教务数据"
    top="10vh"
    width="550px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @opened="visibleChange"
  >
    <div class="file-upload-body">
      <el-form ref="modalFormComp" :model="modalForm" label-position="top">
        <el-form-item prop="printPlanId" label="印刷计划：">
          <el-select
            v-model="modalForm.printPlanId"
            placeholder="请选择"
            filterable
            :disabled="loading"
          >
            <el-option
              v-for="item in plans"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传文件：">
          <upload-file-view
            input-width="350px"
            :format="['xls', 'xlsx']"
            :upload-url="uploadUrl"
            :upload-data="modalForm"
            @uploading="uploading"
            @valid-error="validError"
            @upload-error="uplaodError"
            @upload-success="uploadSuccess"
            ref="UploadFileView"
            :disabled="loading || !modalForm.printPlanId"
          ></upload-file-view>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer">
      <el-button @click="cancel">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import UploadFileView from "@/components/UploadFileView";
import { printPlanQuery } from "../api";

export default {
  name: "upload-paper-dialog",
  components: { UploadFileView },
  data() {
    return {
      modalIsShow: false,
      loading: false,
      plans: [],
      // import
      uploadUrl: "/api/admin/exam/print/data_import",
      modalForm: {
        type: "FILE",
        printPlanId: "",
      },
    };
  },
  methods: {
    async getPlans() {
      const res = await printPlanQuery();
      this.plans = res.filter((item) => ["NEW", "READY"].includes(item.status));
    },
    visibleChange() {
      this.getPlans();
      this.modalForm.printPlanId = "";
      this.loading = false;
      if (this.plans.length === 1) {
        this.modalForm.printPlanId = this.plans[0].id;
      }
    },
    // upload-handler
    validError(errorData) {
      this.$message.error(errorData.message);
    },
    uplaodError() {
      this.loading = false;
    },
    uploadSuccess(res) {
      this.loading = false;
      this.$message.success("后台处理中，请在考务明细中查看导入结果！");
      this.$emit("modified");
      this.cancel();
    },
    uploading() {
      this.loading = true;
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
  },
};
</script>
