<template>
  <el-dialog
    custom-class="side-dialog"
    :visible.sync="modalIsShow"
    :title="title"
    width="600px"
    :modal="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-tree
      class="folder-tree"
      :data="folderTree"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false"
      :props="defaultProps"
      @node-click="nodeClick"
    >
      <span slot-scope="{ node, data }">
        <i class="icon icon-files-act node-icon"></i>
        <span v-if="data.id === 'none'" class="node-form">
          <el-form
            ref="modalFormComp"
            :model="modalForm"
            :rules="rules"
            size="mini"
            :show-message="false"
            inline
          >
            <el-form-item prop="name">
              <el-input
                v-model="modalForm.name"
                placeholder="请输入文件夹名称"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-check"
                @click="toCreateFolder"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-close"
                @click="toRemoveFolder(node, data)"
              ></el-button>
            </el-form-item>
          </el-form>
        </span>
        <span
          v-else
          :class="['node-cont', { 'is-active': curNodeData.id === data.id }]"
          >{{ node.label }}</span
        >
      </span>
    </el-tree>

    <div slot="footer" class="box-justify">
      <el-button v-if="isEdit" type="primary" @click="toAddFolder"
        >新建文件夹</el-button
      >
      <div>
        <el-button v-if="!isEdit" type="primary" @click="confirm"
          >确定</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "QuestionFolderDialog",
  props: {
    folderId: {
      type: [String, Number],
      default: "",
    },
    isEdit: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      modalIsShow: false,
      folderTree: [
        {
          id: "1",
          parent: null,
          name: "根目录",
          children: [
            {
              id: "101",
              parent: "1",
              name: "2021-2022第一学期期末考试用",
            },
            {
              id: "102",
              parent: "1",
              name: "2021-2022第二学期期末考试用",
            },
          ],
        },
      ],
      defaultProps: {
        label: "name",
      },
      curNodeData: {},
      modalForm: {
        name: "",
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入文件夹名称",
            trigger: "change",
          },
        ],
      },
    };
  },
  computed: {
    title() {
      return this.isEdit ? "新建文件夹" : "选择文件夹";
    },
  },
  methods: {
    visibleChange() {
      if (this.folderId && !this.isEdit) {
        this.curNodeData = this.findNodeById(this.folderId);
      }
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    nodeClick(data) {
      if (data.id === "none" || data.id === this.curNodeData.id) return;
      this.clearPreNewNode();
      this.$nextTick(() => {
        this.curNodeData = this.findNodeById(data.id);
      });
    },
    findNodeById(id) {
      let curNode = null;
      const findNode = (data) => {
        if (curNode) return;

        data.forEach((item) => {
          if (curNode) return;

          if (item.id === id) {
            curNode = item;
            return;
          }
          if (item.children && item.children.length) findNode(item.children);
        });
      };
      findNode(this.folderTree);

      return curNode || {};
    },
    clearPreNewNode() {
      const removePreNewChild = (data) => {
        data = data.filter((item) => item.id !== "none");
        return data.map((item) => {
          if (item.children && item.children.length)
            item.children = removePreNewChild(item.children);
          return item;
        });
      };
      this.folderTree = removePreNewChild(this.folderTree);
    },
    toAddFolder() {
      if (!this.curNodeData.id) {
        this.$message.error("请先选择文件夹！");
        return;
      }
      const newChild = { id: "none", name: "", parentId: this.curNodeData.id };
      if (!this.curNodeData.children) {
        this.$set(this.curNodeData, "children", []);
      }
      this.curNodeData.children.push(newChild);
      this.modalForm = { name: "" };
    },
    async toCreateFolder() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;
    },
    toRemoveFolder(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex((d) => d.id === data.id);
      children.splice(index, 1);
    },
    confirm() {
      if (!this.curNodeData.id) {
        this.$message.error("请选择文件夹！");
        return;
      }
      this.$emit("selected", this.curNodeData);
    },
  },
};
</script>
