<template>
  <el-dialog
    class="modify-course-simple"
    :visible.sync="modalIsShow"
    title="添加课程"
    top="10px"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <div class="mb-4 tab-btns">
      <el-button
        v-for="tab in tabs"
        :key="tab.val"
        size="medium"
        :type="curTab == tab.val ? 'primary' : 'default'"
        @click="selectMenu(tab.val)"
        >{{ tab.name }}
      </el-button>
    </div>
    <!-- input -->
    <div v-if="curTab === 'input'" class="tab-body">
      <el-form
        ref="modalFormComp"
        :model="modalForm"
        :rules="rules"
        :key="modalForm.id"
        label-width="100px"
      >
        <el-form-item prop="courseName" label="课程名称：">
          <el-input
            v-model.trim="modalForm.courseName"
            placeholder="请输入课程名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="courseCode" label="课程编码：">
          <el-input
            v-model.trim="modalForm.courseCode"
            placeholder="请输入课程编码"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <!-- select -->
    <div v-if="curTab === 'select'" class="tab-body">
      <select-simple-course
        ref="SelectSimpleCourse"
        v-model="selectedCourseIds"
      ></select-simple-course>
    </div>
    <!-- import -->
    <div v-if="curTab === 'import'" class="tab-body">
      <el-button
        type="success"
        icon="el-icon-download"
        @click="downloadTemplate('teachCourse')"
        >模板下载</el-button
      >
      <upload-button
        btn-icon="el-icon-circle-plus-outline"
        btn-content="批量导入"
        btn-type="success"
        :upload-url="uploadUrl"
        :format="['xls', 'xlsx']"
        accept=".xls,.xlsx"
        @valid-error="validError"
        @upload-success="uploadSuccess"
      >
      </upload-button>
    </div>
    <div v-if="!IS_IMPORT" slot="footer">
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateCourseSimple, batchAddCourseSimple } from "../../api";
import UploadButton from "@/components/UploadButton";
import SelectSimpleCourse from "./SelectSimpleCourse.vue";
import templateDownload from "@/mixins/templateDownload";

const initModalForm = {
  id: null,
  courseName: "",
  courseCode: "",
};

export default {
  name: "modify-course-simple",
  components: { UploadButton, SelectSimpleCourse },
  mixins: [templateDownload],
  computed: {
    IS_IMPORT() {
      return this.curTab === "import";
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      curTab: "select",
      tabs: [
        {
          name: "手动添加",
          val: "input",
        },
        {
          name: "课程表选择",
          val: "select",
        },
        {
          name: "批量导入",
          val: "import",
        },
      ],
      modalForm: { ...initModalForm },
      courses: [],
      rules: {
        courseName: [
          {
            required: true,
            // pattern: /^[0-9a-zA-Z\u4E00-\u9FA5]{1,20}$/,
            // message: "课程名称只能输入汉字、数字和字母，长度不能超过20",
            message: "课程名称不能超过30个字",
            max: 30,
            trigger: "change",
          },
        ],
        courseCode: [
          {
            required: true,
            pattern: /^[0-9a-zA-Z_-]{3,30}$/,
            message: "课程编码只能由数字字母短横线组成，长度在3-30之间",
            trigger: "change",
          },
        ],
      },
      selectedCourseIds: [],
      // import
      uploadUrl: "/api/admin/teach/course/import",
      dfilename: "教学课程导入模板.xlsx",
    };
  },
  methods: {
    visibleChange() {
      this.modalForm = { ...initModalForm };
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    selectMenu(tab) {
      this.curTab = tab;
    },
    submit() {
      const submitFunc = {
        input: this.submitInput,
        select: this.submitSelect,
      };
      submitFunc[this.curTab]();
    },
    async submitInput() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      let datas = { ...this.modalForm };
      const data = await updateCourseSimple(datas).catch(() => {
        this.isSubmit = false;
      });

      if (!data) return;

      this.isSubmit = false;
      this.$message.success("添加成功！");
      this.$emit("modified");
      this.cancel();
    },
    async submitSelect() {
      if (!this.selectedCourseIds.length) {
        this.$message.error("请选择科目");
        return;
      }

      if (this.isSubmit) return;
      this.isSubmit = true;
      const data = await batchAddCourseSimple({
        basicCourseIdList: this.selectedCourseIds.join(),
      }).catch(() => {});
      this.isSubmit = false;

      if (!data) return;

      this.$message.success("添加成功！");
      this.$emit("modified");
      this.selectedCourseIds = [];
      this.$refs.SelectSimpleCourse.clearSelection();
    },
    // import
    validError(errorData) {
      this.$message.error(errorData.message);
    },
    uploadSuccess(data) {
      this.$message.success(data.data || "课程导入成功！");
      this.$emit("modified");
      this.cancel();
    },
  },
};
</script>
