<template>
  <div class="question-folder">
    <div v-if="isEdit" class="folder-action box-justify margin-bottom-15">
      <el-button
        type="primary"
        :disabled="curNodeData.level >= MAX_FOLDER_LEVEL"
        @click="toAddFolder"
        >新建文件夹</el-button
      >
      <el-button
        type="danger"
        :disabled="curNodeData.level >= MAX_FOLDER_LEVEL"
        @click="toDeleteFolder"
        >删除文件夹</el-button
      >
    </div>

    <el-tree
      class="folder-tree"
      :data="classifyTree"
      node-key="questionClassifyId"
      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 === null" 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"
                :disabled="loading"
                @click="toCreateFolder"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-close"
                :disabled="loading"
                style="margin-left: 6px"
                @click="toRemoveFolder(node, data)"
              ></el-button>
            </el-form-item>
          </el-form>
        </span>
        <span
          v-else
          :class="['node-cont', { 'is-active': curNodeData.id === data.id }]"
          >{{ data.name }}</span
        >
      </span>
    </el-tree>
  </div>
</template>

<script>
import { classifyTreeApi, updateClassifyApi, deleteClassifyApi } from "../api";

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

export default {
  name: "QuestionFolder",
  props: {
    isEdit: {
      type: Boolean,
      default: true,
    },
    folderId: {
      type: [Number, String],
      default: "",
    },
  },
  data() {
    return {
      MAX_FOLDER_LEVEL: 3,
      classifyTree: [
        {
          id: 0,
          parent: null,
          name: "根目录",
          children: [],
        },
      ],
      defaultProps: {
        label: "name",
      },
      curNodeData: {},
      loading: false,
      modalForm: {
        ...initModalForm,
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入文件夹名称",
            trigger: "change",
          },
        ],
      },
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    async initData() {
      await this.getClassifyTree();
      if (this.folderId && !this.isEdit) {
        this.curNodeData = this.findNodeById(this.folderId);
      }
    },
    async getClassifyTree() {
      const res = await classifyTreeApi();
      this.classifyTree[0].children = res.data || [];
    },
    nodeClick(data) {
      if (!data.id && data.id !== 0) {
        this.$emit("selected", null);
        return;
      } else {
        this.$emit("selected", data);
      }

      if (data.id === null || data.id === this.curNodeData.id) return;

      this.clearPreNewNode();
      this.$nextTick(() => {
        this.curNodeData = this.findNodeById(data.id);
      });
    },
    findNodeById(id) {
      let curNode = null;
      const findNode = (data, level) => {
        if (curNode) return;
        level++;
        data.forEach((item) => {
          if (curNode) return;

          if (item.id === id) {
            curNode = item;
            curNode.level = level;
            return;
          }
          if (item.children && item.children.length)
            findNode(item.children, level);
        });
      };
      findNode(this.classifyTree, -1);

      return curNode || {};
    },
    clearPreNewNode() {
      const removePreNewChild = (data) => {
        data = data.filter((item) => item.id !== null);
        return data.map((item) => {
          if (item.children && item.children.length)
            item.children = removePreNewChild(item.children);
          return item;
        });
      };
      this.classifyTree = removePreNewChild(this.classifyTree);
    },
    toAddFolder() {
      if (!this.curNodeData.id && this.curNodeData.id !== 0) {
        this.$message.error("请先选择文件夹！");
        return;
      }
      if (this.curNodeData.level >= this.MAX_FOLDER_LEVEL) {
        this.$message.error(`最多允许${this.MAX_FOLDER_LEVEL}级目录`);
        return;
      }
      if (
        this.curNodeData.children &&
        this.curNodeData.children.find((item) => item.id === null)
      ) {
        this.$message.closeAll();
        this.$message.error("有未创建完成的目录！");
        return;
      }
      const newChild = {
        ...initModalForm,
        parentId: this.curNodeData.id,
      };
      if (!this.curNodeData.children) {
        this.$set(this.curNodeData, "children", []);
      }
      this.curNodeData.children.push(newChild);
      this.modalForm = { ...newChild };
    },
    async toCreateFolder() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.loading) return;
      this.loading = true;
      const res = await updateClassifyApi({ ...this.modalForm }).catch(
        () => {}
      );
      this.loading = false;
      if (!res) return;
      this.$message.success("操作成功");
      const newChild = this.curNodeData.children.find(
        (item) => item.id === null
      );
      newChild.id = res.data;
      newChild.name = this.modalForm.name;
    },
    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);
    },
    async toDeleteFolder() {
      if (!this.curNodeData.id) return;
      const confirm = await this.$confirm(`确定要删除选中的文件夹吗?`, "提示", {
        type: "warning",
      }).catch(() => {});
      if (confirm !== "confirm") return;

      if (this.loading) return;
      this.loading = true;
      const res = await deleteClassifyApi(this.curNodeData.id).catch(() => {});
      this.loading = false;
      if (!res) return;
      this.$message.success("操作成功");
      await this.getClassifyTree();
    },
    getSelectedNode() {
      return this.curNodeData;
    },
  },
};
</script>
