<template>
  <div class="school-set-target">
    <el-form
      ref="modalFormComp"
      label-width="100px"
      :model="modalForm"
      :rules="rules"
    >
      <el-form-item prop="attachmentId" label="选择文件：">
        <upload-file-view
          :upload-data="uploadData"
          :upload-url="uploadUrl"
          :format="format"
          input-width="300px"
          @valid-error="validError"
          @upload-success="uploadSuccess"
          ref="UploadFileView"
        ></upload-file-view>
        <div>
          <p class="tips-info">说明：支持格式doc/docx，文件大小不超过2M</p>
        </div>
      </el-form-item>
      <el-form-item v-if="info.value">
        <span class="cont-link" title="点击查看文件" @click="toView">
          <i class="el-icon-document mr-1"></i>课程目标达成度模板.doc
        </span>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="loading" @click="confirm"
          >保存</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  schoolSetCourseTargetQuery,
  schoolSetCourseTargetSave,
} from "../../api";
import UploadFileView from "@/components/UploadFileView.vue";

export default {
  name: "school-set-target",
  components: { UploadFileView },
  props: {
    school: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      loading: false,
      info: {},
      modalForm: { schoolId: "", attachmentId: "" },
      rules: {
        attachmentId: [
          {
            required: true,
            message: "请上传模板文件",
            trigger: "change",
          },
        ],
      },
      // upload
      format: ["doc", "docx"],
      uploadUrl: "/api/admin/common/file/upload",
      uploadData: {
        type: "UPLOAD",
      },
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    async initData() {
      this.modalForm.schoolId = this.school.id;
      const data = await schoolSetCourseTargetQuery(this.school.id);
      if (data && data.value) {
        this.info = data;
      }
    },
    toView() {
      window.open(this.info.value);
    },
    validError(errorData) {
      this.$message.error(errorData.message);
    },
    uploadSuccess(data) {
      this.$message.success("上传成功！");

      this.modalForm.attachmentId = data.id;
      this.$refs.modalFormComp.validateField("attachmentId");
    },
    async confirm() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.loading) return;
      this.loading = true;
      const res = await schoolSetCourseTargetSave(this.modalForm).catch(
        () => {}
      );
      this.loading = false;
      if (!res) return;

      this.$message.success("修改成功！");
      this.initData();
    },
  },
};
</script>
