<template>
  <el-dialog
    :title="title"
    :visible="visible"
    width="460px"
    :show-close="false"
    class="add-chapter"
    @close="dialogClose"
  >
    <el-form ref="form" :model="data" :rules="rules" label-width="80px">
      <el-form-item label="章节名称" prop="name">
        <el-input ref="name" v-model="data.name" placeholder="请输入章节名称" />
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="dialogClose">取消</el-button>
      <el-button type="primary" @click="addChapterNode">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'AddChapter',
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    id: {
      type: String,
      default: '',
    },
    parentId: {
      type: String,
      default: '',
    },
    curSelectId: {
      type: String,
      default: '',
    },
    addType: {
      type: String,
      default: 'chapter',
    },
  },
  data() {
    return {
      data: {
        name: '',
        book_id: this.id,
      },
      rules: {
        name: [{ required: true, message: '请输入章节名称', trigger: 'blur' }],
      },
    };
  },
  computed: {
    title() {
      return this.addType === 'chapter' ? '添加章节' : '添加课件';
    },
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          this.$refs.form.clearValidate();
          this.$refs.name.focus();
        });
      }
    },
  },
  methods: {
    dialogClose() {
      this.$emit('close');
      this.data.name = '';
    },
    addChapterNode() {
      if (this.addType === 'chapter') {
        this.$emit('addChapterNode', {
          ...this.data,
          parent_id: this.parentId,
          is_leaf: 'false',
        });
      } else {
        this.$emit('addCourseware', {
          ...this.data,
          chapter_id: this.curSelectId,
        });
      }
      this.data.name = '';
    },
  },
};
</script>
