<template>
  <el-dialog
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :key="modalForm.id"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="所属知识点：">
        <el-select
          v-model="modalForm.parentId"
          placeholder="请选择"
          filterable
          clearable
        >
          <el-option
            v-for="item in mainOptions"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="name" label="知识点名称：">
        <el-input
          v-model.trim="modalForm.name"
          placeholder="知识点名称"
          clearable
        ></el-input>
      </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 { updateCourseOutlineKnowledge } from "../../api";

const initModalForm = {
  id: null,
  parentId: "",
  name: "",
};

export default {
  name: "modify-course-outline-knowledge",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
    mainOptions: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
      rules: {
        name: [
          { required: true, message: "请输入知识点名称", trigger: "change" },
          {
            message: "知识点名称不能超过30个字",
            max: 30,
            trigger: "change",
          },
        ],
      },
    };
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "知识点";
    },
  },
  methods: {
    visibleChange() {
      this.modalForm = this.$objAssign(initModalForm, this.instance);
    },
    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 data = await updateCourseOutlineKnowledge(this.modalForm).catch(
        () => {}
      );
      this.isSubmit = false;

      if (!data) return;

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