<template>
  <div
    v-loading="loading"
    class="he_tree_content he_tree_view"
    style="font-size: 14px"
  >
    <!-- <el-button
            @click="dialogFlag = true"
            class="new-add"
            icon="el-icon-plus"
            size="mini"
            style="margin-bottom: 10px"
            type="primary"
        >添加节点</el-button>-->
    <span
      class="new-add"
      style="margin-bottom: 10px"
      @click="
        dialogFlag = true;
        (dialogTitle = '添加节点'), (dialogDisabled = false);
      "
    >
      <img src="../../../assets/common/icon-add.png" />添加节点
    </span>
    <Tree ref="tree" :value="treeData" @drag="drag" @drop="drop">
      <div
        slot-scope="{ node, index, path, tree }"
        :style="{
          paddingLeft:
            node.is_courseware === 'false'
              ? node.nodexIndex * 22 + 8 + 'px'
              : '0px',
        }"
        class="tree_box"
      >
        <span
          v-if="node.is_courseware === 'false'"
          class="el-icon_box"
          @click="tree.toggleFold(node, path)"
        >
          <template
            v-if="
              node.children && node.children.length > 0 && node.$folded == true
            "
          >
            <img src="../../../assets/common/icon-tree-arrow-right.png" />
          </template>
          <template
            v-else-if="
              node.children && node.children.length > 0 && node.$folded == false
            "
          >
            <img src="../../../assets/common/icon-tree-arrow-bottom.png" />
          </template>
        </span>
        <span
          v-if="node.is_courseware === 'false'"
          :class="[
            'tree_box_item',
            'tree_box_' + node.nodexIndex,
            activeIndex !== '' && JSON.stringify(node).indexOf(activeIndex) > -1
              ? 'tree_box_item_light'
              : '',
          ]"
          @click="tree.toggleFold(node, path)"
        >
          <!-- <template>
                        <i class="el-icon-folder-add"></i>
                    </template>-->
          {{ node.name }}
        </span>
        <span
          v-else
          :class="[
            'tree_box_item',
            'tree_box_leaf',
            activeIndex == node.id ? 'tree_box_item_active' : '',
          ]"
          :style="{ paddingLeft: node.nodexIndex * 22 + 12 + 'px' }"
          @click="handleNodeClick(node, path)"
        >
          <template>
            <i class="el-icon-document" />
          </template>
          {{ node.name }}
        </span>
        <div class="btn_box">
          <i
            v-if="node.is_courseware === 'false'"
            class="el-icon-plus"
            @click="addNode(node, index)"
          />
          <el-popover placement="bottom" trigger="click" width="100">
            <div class="tree_other_btn">
              <p class="tree_rename" @click="rename(node, index)">重命名</p>
              <p class="tree_del" @click="remove(node, index)">删除</p>
              <p class="tree_free" v-if="node.is_courseware === 'true'">
                <el-checkbox
                  @change="tryFree(node, index)"
                  v-model="node.is_free_trial_bool"
                  >免费试看</el-checkbox
                >
              </p>
            </div>
            <span slot="reference">···</span>
          </el-popover>
        </div>
      </div>
    </Tree>
    <el-dialog :visible.sync="dialogFlag" :title="dialogTitle" width="40%">
      <div>
        <el-form ref="form" :model="formDialog" label-width="80px">
          <el-form-item label="节点名称">
            <el-input v-model="formDialog.name" maxlength="100" show-word-limit />
          </el-form-item>
          <el-form-item label="节点类型">
            <el-radio-group
              v-model="formDialog.radio"
              :disabled="dialogDisabled"
            >
              <el-radio label="1">章节</el-radio>
              <el-radio label="2">互动课件</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeNode">取 消</el-button>
        <el-button type="primary" @click="sureAddNode">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import "he-tree-vue/dist/he-tree-vue.css";
import { getContent } from "@/api/ajax";
import Cookies from "js-cookie";
import { Tree, Fold, Draggable } from "he-tree-vue";

export default {
  components: {
    Tree: Tree.mixPlugins([Fold, Draggable]),
  },
  props: [
    "changeId",
    "emptyQustion",
    "bookLevel",
    "bookNodeIndex",
    "changeTreeData",
    "currentTreeID",
  ],
  data() {
    return {
      treeData: [],
      foldAllAfterMounted: true,
      dialogFlag: false,
      formDialog: {
        name: "",
        radio: "1",
        is_courseware: "false",
        children: [],
      },
      curNode: null,
      curIndex: "",
      curINdexArr: [],
      ondragend: {},
      bookId: this.$route.query.bookId,
      oldLists: [], // 移动之前的数组
      oldPid: "", // 移动节点的父id
      oldId: "", // 移动节点的id
      destId: "", // 目标节点id
      destPosition: 0, // 目标位置0移动节点在前1后
      is_coursewareFlag: "false", // 移动的是否是课件节点
      activeIndex: "", // 高亮节点
      isDragFlag: false, // 是否可以移动
      type: "",
      isAddFlag: true, // 是否可以添加节点
      dialogTitle: "添加节点",
      dialogDisabled: false, // 是否禁用单选按钮
      loading: false, // 加载中
      pidList: [],
    };
  },
  mounted() {
    this.getList();
    // this.$refs.tree.foldAllAfterMounted = true;
    // 绑定enter事件
    this.BookenterKeyup();
  },
  created() {
    if (Cookies.get("bookIndex")) {
      this.activeIndex = Cookies.get("bookIndex");
    }
    if (this.bookNodeIndex) this.activeIndex = this.bookNodeIndex;
  },
  destroyed() {
    // 销毁enter事件
    this.enterKeyupDestroyed();
  },
  watch: {
    // 监听预览页面翻页的变化 树组件做出相同的操作
    async currentTreeID(newval, oldval) {
      if (newval) {
        this.activeIndex = newval;
        await this.unfoldData(this.activeIndex, this.treeData);
        await this.unfoldFather(this.treeData);
      }
    },
  },
  methods: {
    // 递归找到当前节点的所有父节点
    unfoldData(activeIndex, data, index, child) {
      data.forEach((item, i) => {
        if (item.id == activeIndex) {
          this.pidList.push(item.pid);
          if (Object.prototype.toString.call(index).indexOf("Number") != -1) {
            this.pidList.push(child.pid);
          }
        } else if (item.children) {
          this.unfoldData(activeIndex, item.children, i, item);
        }
      });
    },
    // 展示父节点
    unfoldFather(data) {
      data.forEach((item, i) => {
        this.pidList.forEach((p) => {
          if (item.id == p) {
            item.$folded = false;
          } else if (item.children) {
            this.unfoldFather(item.children);
          }
        });
      });
    },
    foldAll() {
      if (this.$refs.tree !== undefined) {
        this.$refs.tree.foldAll();
      }
    },
    // 拖拽节点
    drag(store) {
      const data = store.dragNode;
      this.oldPid = data.pid;
      this.oldId = data.id;
      this.is_coursewareFlag = data.is_courseware;
    },
    // 拖拽完成后执行
    drop(store) {
      this.type = "拖拽";
      this.onTreeDataChange();
    },
    onTreeDataChange() {
      this.handleFindId(this.treeData);
      if (this.isDragFlag) {
        const MethodName = "book-book_manager-MoveTreeNode_BookChapterStruct";
        const data = {
          id: this.oldId,
          dest_position: this.destPosition,
          dest_id: this.destId,
        };
        // if (this.is_coursewareFlag == "false") {
        //   MethodName = "book-chapter_manager-MoveChapter";
        //   data.dest_chapter_id = this.destId;
        // } else {
        //   MethodName = "book-courseware_manager-MoveCourseware";
        //   data.dest_courseware_id = this.destId;
        // }
        this.loading = true;
        getContent(MethodName, data)
          .then((res) => {
            this.loading = false;
            this.$message.success("移动成功");
            this.getList();
            this.dialogFlag = false;
            this.formDialog.name = "";
            this.formDialog.radio = "1";
            this.parent_id = "";
          })
          .catch(() => {
            this.loading = false;
          });
      } else {
        this.$nextTick(() => {
          this.foldAll();
        });
      }
    },
    // 找目标id
    handleFindId(list) {
      list.forEach((item, index) => {
        if (item.id == this.oldId) {
          if (list.length === 1) {
            this.isDragFlag = false;
            // 移动后只有这一个节点 不对
            this.treeData = this.oldLists;
            this.changeTreeData(this.oldLists);
            this.$message({
              type: "warning",
              message: "不能跨级移动！",
            });
            return false;
          } else {
            // 匹配和兄弟节点pid是否相同
            if (list[index - 1]) {
              if (item.pid === list[index - 1].pid) {
                // 父级相同 同级移动 可向下移动
                this.destId = list[index - 1].id;
                this.destPosition = 1;
                this.isDragFlag = true;
              } else {
                // if (item.pid === 'undefined')
                this.treeData = this.oldLists;
                this.changeTreeData(this.oldLists);

                this.isDragFlag = false;
                this.$message({
                  type: "warning",
                  message: "不能跨级移动！",
                });
                return false;
              }
            } else if (list[index + 1]) {
              if (item.pid === list[index + 1].pid) {
                // 父级相同 同级移动 可向上移动
                this.destId = list[index + 1].id;
                this.destPosition = 0;
                this.isDragFlag = true;
                // this.treeData.lists = list;
              } else {
                this.treeData = this.oldLists;
                this.changeTreeData(this.oldLists);

                this.isDragFlag = false;
                this.$message({
                  type: "warning",
                  message: "不能跨级移动！",
                });
                return false;
              }
            }
          }
        } else {
          if (item.children) {
            this.handleFindId(item.children);
          }
          // else {
          //     this.treeData.lists = this.treeData.oldLists
          //     this.$message({
          //         type: 'warning',
          //         message: '不能移动!3'
          //     })
          //     return false
          // }
        }
      });
    },
    addNode(node, index) {
      this.type = "添加";
      this.curNode = node;
      this.curIndex = node.level_index + "-0";
      this.parent_id = node.id;
      this.dialogTitle = "添加节点";
      this.dialogDisabled = false;
      this.dialogFlag = true;
    },
    sureAddNode() {
      this.formDialog.name = this.formDialog.name.trim();
      if (this.formDialog.name !== "") {
        if (this.dialogTitle == "添加节点") {
          let data = {
            name: this.formDialog.name,
            book_id: this.bookId,
            parent_id: this.parent_id,
          };
          let MethodName = "book-chapter_manager-AddChapterToBook";
          if (this.formDialog.radio === "2") {
            MethodName = "book-courseware_manager-AddCoursewareToBook";
            data = {
              name: this.formDialog.name,
              book_id: this.bookId,
              chapter_id: this.parent_id ? this.parent_id : "",
            };
          }
          if (this.isAddFlag) {
            this.isAddFlag = false;
            this.loading = true;
            getContent(MethodName, data)
              .then((res) => {
                this.loading = false;
                this.isAddFlag = true;
                this.$message({
                  message: "添加成功",
                  type: "success",
                });
                this.getList();
                // let node = JSON.parse(JSON.stringify(this.formDialog));
                // this.curNode.children.push(node);
                this.dialogFlag = false;
                this.formDialog.name = "";
                this.formDialog.radio = "1";
                this.parent_id = "";
              })
              .catch((error) => {
                this.loading = false;
                this.isAddFlag = true;
              });
          }
        } else {
          let MethodName = "";
          if (this.formDialog.radio === "2") {
            // 课件节点
            MethodName = "book-courseware_manager-UpdateCourseware";
          } else {
            MethodName = "book-chapter_manager-UpdateChapter";
          }
          const datas = {
            id: this.oldId,
            name: this.formDialog.name,
          };
          if (this.isAddFlag) {
            this.isAddFlag = false;
            this.loading = true;
            getContent(MethodName, datas)
              .then((res) => {
                this.loading = false;
                this.isAddFlag = true;
                this.type = "修改";
                this.getList();
                this.$message({
                  type: "success",
                  message: "修改成功!",
                });
                // let node = JSON.parse(JSON.stringify(this.formDialog));
                // this.curNode.children.push(node);
                this.dialogFlag = false;
                this.formDialog.name = "";
                this.formDialog.radio = "1";
                this.parent_id = "";
              })
              .catch(() => {
                this.isAddFlag = true;
                this.loading = false;
              });
          }
        }
      } else {
        this.$message({
          message: "节点名称不能为空",
          type: "warning",
        });
      }
    },
    // 点取消按钮
    closeNode() {
      this.dialogFlag = false;
      this.formDialog.name = "";
      this.formDialog.radio = "1";
      this.parent_id = "";
    },
    getList() {
      const _this = this;
      const MethodName = "book-book_manager-GetBookChapterStruct";
      const data = {
        book_id: this.bookId,
      };
      this.loading = true;
      getContent(MethodName, data)
        .then((res) => {
          this.loading = false;
          this.handleData(res, 0);
          let nodesData = res.nodes ? res.nodes : []
          this.treeData = JSON.parse(JSON.stringify(nodesData));
          this.oldLists = JSON.parse(JSON.stringify(nodesData));
          this.changeTreeData(nodesData);

          _this.$nextTick(() => {
            _this.foldAll();
            if (this.type) {
              this.curINdexArr = this.curIndex.split("-");
              this.handleFold(res, 0);
              this.treeData = JSON.parse(JSON.stringify(nodesData));
              this.changeTreeData(nodesData);
            } else if (this.bookLevel) {
              this.curINdexArr = this.bookLevel.split("-");
              this.handleFold(res, 0);
              this.treeData = JSON.parse(JSON.stringify(nodesData));
              this.changeTreeData(nodesData);
            }
          });
        })
        .catch((e) => {
          this.loading = false;
        });
    },
    // 递归
    handleData(data, nodeIndex) {
      if (data.nodes) {
        data.nodes.forEach((item) => {
          item.label = item.name;
          item.pid = data.id;
          item.fatherName = `${data.name}  /  ${item.name}`;
          item.nodexIndex = nodeIndex;
          item.$folded = true;
          item.is_free_trial_bool =
            item.is_free_trial === "true" ? true : false;
          if (item.nodes) {
            item.children = item.nodes;
            this.handleData(item, nodeIndex + 1);
          }
        });
      }
    },
    // 递归处理展开
    handleFold(data, index) {
      if (data.nodes) {
        data.nodes.forEach((item, indexs) => {
          if (
            this.curINdexArr[index] &&
            index !== this.curINdexArr.length - 1 &&
            this.curINdexArr[index] == indexs
          ) {
            if (item.nodes) {
              item.$folded = false;
              this.handleFold(item, index + 1);
            }
          }
        });
      }
    },
    handleNodeClick(data) {
      this.activeIndex = data.id;
      this.changeId(data.id, data.name, data.fatherName);
    },
    remove(data, index) {
      this.curIndex = data.level_index;
      const is_courseware = data.is_courseware;
      this.$confirm("确定要删除此节点吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let MethodName = "book-chapter_manager-DeleteChapter";
          if (is_courseware === "true") {
            // 课件节点
            MethodName = "book-courseware_manager-DeleteCourseware";
          }
          const datas = {
            id: data.id,
          };
          this.loading = true;
          getContent(MethodName, datas)
            .then((res) => {
              this.loading = false;
              this.type = "删除";
              this.getList();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              if(this.currentTreeID==data.id){
                  this.activeIndex = "";
                  this.emptyQustion();
              }
            })
            .catch(() => {
              this.loading = false;
            });
        })
        .catch(() => {});
    },
    // 重命名
    rename(data, index) {
      this.type = "修改";
      this.curNode = data;
      this.curIndex = data.level_index + "-0";
      this.parent_id = data.id;
      this.dialogTitle = "修改节点";
      this.dialogFlag = true;
      this.formDialog.name = data.name;
      this.dialogDisabled = true;
      const is_courseware = data.is_courseware;
      this.oldId = data.id;
      if (is_courseware === "true") {
        // 课件节点
        this.formDialog.radio = "2";
      } else {
        this.formDialog.radio = "1";
      }
    },
    //设置免费试看
    tryFree(data, index) {
      this.curIndex = data.level_index;
      let MethodName = "book-book_manager-SetTreeNodeMark_FreeTrial";
      let datas = {
        id: data.id,
        is_courseware: data.is_courseware,
        is_free_trial: JSON.stringify(data.is_free_trial_bool),
      };
      this.loading = true;
      getContent(MethodName, datas)
        .then((res) => {
          this.loading = false;
          this.type = "免费试看";
          this.getList();
          this.$message({
            type: "success",
            message: "设置成功!",
          });
        })
        .catch(() => {
          this.loading = false;
        });
    },
    BookenterKey(event) {
      const code = event.keyCode
        ? event.keyCode
        : event.which
        ? event.which
        : event.charCode;
      if (code == 13) {
        // this.sureAddNode();
      }
    },
    enterKeyupDestroyed() {
      document.removeEventListener("keyup", this.BookenterKey);
    },
    BookenterKeyup() {
      document.addEventListener("keyup", this.BookenterKey);
    },
  },
};
</script>
<style lang="scss" scoped>
.new-add {
  width: 116px;
  height: 36px;
  line-height: 36px;
  padding: 0 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #ff9900;
  border-radius: 4px;
  font-size: 14px;
  color: #ffffff;
  cursor: pointer;
  border: 0;
  margin-left: 8px;
  &:hover {
    opacity: 0.8;
  }
  img {
    width: 20px;
    margin-right: 4px;
  }
}
.new-add:hover {
  background: #ff8800;
}
.tree_box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 40px;
  cursor: pointer;
  position: relative;
  .kuazhan {
    font-size: 40px;
    padding: 0 10px;
    cursor: pointer;
  }
  .btn_box {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 30px;
    position: absolute;
    right: 5px;
    > span {
      margin-left: 10px;
      cursor: pointer;
      color: #2c2c2c;
    }
  }
  .tree_box_item {
    width: 100%;
    padding-left: 4px;
    color: #2c2c2c;
    height: 100%;
    align-items: center;
    line-height: 44px;
    padding-right: 60px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    font-weight: bold;
  }
  .tree_box_item:hover {
    color: #ff9900;
    > i {
      color: #ff9900;
    }
  }
  .tree_box_item_light,
  .tree_box_leaf:hover  {
    color: #ff9900;
    > i {
      color: #ff9900;
    }
  }
  .tree_box_item_active{
    color: #fff !important;
    background: #ff9900 !important;
    > i {
      color: #fff !important;
    }
  }
  .el-icon_box {
    width: 24px;
    text-align: center;
    font-size: 0;
    > img {
      width: 100%;
      margin-top: 4px;
    }
  }
}
.tree_other_btn {
  text-align: center;
  > p {
    font-size: 14px;
    cursor: pointer;
  }
}
</style>
<style lang="scss">
.he_tree_view .he-tree .tree-node {
  border: 0;
  padding: 0;
  margin: 0;
}
.he_tree_view {
  .tree-node-back {
    padding: 0 !important;
  }
  .tree_box_leaf {
    // padding-left: 80px !important;
    display: block;
    width: 340px !important;
    font-weight: normal !important;
  }
}
.he_tree_content {
  [class*=" el-icon-"],
  [class^="el-icon-"] {
    font-size: 14px;
  }
  .el-icon-plus {
    font-weight: bold;
  }
  .el-dialog__body {
    padding-right: 20px !important;
  }
}
</style>
