<template>
  <div>
    <el-dialog
      class="modify-course"
      :visible.sync="modalIsShow"
      :title="title"
      top="10vh"
      width="550px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      @open="visibleChange"
    >
      <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
            :disabled="isEdit"
          ></el-input>
        </el-form-item>
        <el-form-item prop="teachingRoomId" label="开课学院：">
          <org-select
            v-model="modalForm.teachingRoomId"
            style="width: 100%"
            placeholder="开课学院"
          ></org-select>
        </el-form-item>
        <el-form-item label="授课班级：">
          <clazz-select
            v-model="modalForm.clazzIdSet"
            placeholder="请选择授课班级"
            multiple
            clearable
            style="width: 100%"
          ></clazz-select>
        </el-form-item>
      </el-form>
      <el-form>
        <el-form-item label="授课老师：">
          <el-button type="primary" size="mini" @click="toSelectTeacher"
            >选择</el-button
          >
          <br />
          <el-tag v-for="item in teachList" :key="item.id">
            {{ item.name }}({{ item.orgName }})
          </el-tag>
        </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>

    <SelectTypeUser
      ref="SelectTypeUser"
      special-privilege="TEACHER"
      dialog-title="选择授课老师"
      :user-ids="modalForm.teachIdSet"
      :user-limit-count="0"
      @confirm="userSelected"
    />
  </div>
</template>

<script>
import { updateCourse, getCode } from "../api";
import SelectTypeUser from "../../stmms/components/SelectTypeUser.vue";

const initModalForm = {
  id: null,
  courseName: "",
  courseCode: "",
  teachingRoomId: "",
  clazzIdSet: "",
  teachIdSet: [],
};

export default {
  name: "modify-course",
  components: { SelectTypeUser },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "课程";
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
      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",
          },
        ],
        teachingRoomId: [
          {
            required: true,
            message: "请选择开课学院",
            trigger: "change",
          },
        ],
        clazzIdSet: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value || !value.length) {
                return callback(new Error("请选择授课班级"));
              }

              callback();
            },
            trigger: "change",
          },
        ],
      },
      teachList: [],
    };
  },
  methods: {
    initData(val) {
      if (val.id) {
        this.modalForm = this.$objAssign(initModalForm, val);
        this.modalForm.clazzIdSet = val.clazzList.map((item) => item.id);
        this.modalForm.teachIdSet = val.teachList.map((item) => item.id);
        this.teachList = val.teachList;
      } else {
        this.modalForm = { ...initModalForm };
        this.teachList = [];
        this.createCode();
      }
    },
    async createCode() {
      this.modalForm.courseCode = await getCode("COURSE_CODE");
    },
    visibleChange() {
      this.initData(this.instance);
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    toSelectTeacher() {
      this.$refs.SelectTypeUser.open();
    },
    userSelected(users) {
      this.teachList = users;
      this.modalForm.teachIdSet = users.map((item) => item.id);
    },
    async submit() {
      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 updateCourse(datas).catch(() => {
        this.isSubmit = false;
      });

      if (!data) return;

      this.isSubmit = false;
      this.$message.success(this.title + "成功！");
      this.$emit("modified");
      this.cancel();
    },
  },
};
</script>
