<template>
  <div>
    <div class="edition">
      <div class="flex-align" @click="handleShowDropdown">
        <span class="edition-name only-line-1">{{activeBookVersion.name}}</span>
        <span>
          <a-icon :type="iconCaret" class="edition-icon" />
        </span>
      </div>
      <div class="drop-down" :class="{'drop-down-show':isShowDropdown}" @mouseleave="hideSropdown">
        <div class="drop-down-content">
          <div
            :class="['drop-down-item',{'active-btn':item.id==activeKey?true:false}]"
            v-for="(item,index) in bookVersions"
            :key="index"
            @click="editionClick(item)"
          >{{item.name}}</div>
        </div>
      </div>
    </div>
    <div class="tree-box">
      <a-spin :spinning="spinning">
        <a-tree
          v-if="treeData.length>0"
          @select="onSelect"
          :treeData="treeData"
          :load-data="onLoadData"
          :replace-fields="replaceFields"
          :selectedKeys="[ChapterId]"
        >
          <template slot="custom" slot-scope="item">
            <div class="custom-box">
              <a-tooltip
                overlayClassName="custom-title"
                placement="top"
                :title="item.title"
                :get-popup-container="getPopupContainer"
              >
                <span>{{fontSplice(item.title)}}</span>
              </a-tooltip>
              <span class="toolbar">
                <a-popover placement="right">
                  <template slot="content">
                    <div
                      class="blue-hover"
                      style="margin-bottom: 8px;"
                      @click="showModal('add',item)"
                    >
                      <a-icon type="plus" style="margin-right: 8px;" />添加目录
                    </div>
                    <div
                      class="blue-hover"
                      style="margin-bottom: 8px;"
                      @click="showModal('edit',item)"
                    >
                      <a-icon type="form" style="margin-right: 8px;" />修改名称
                    </div>
                    <div class="blue-hover" @click="_ChapterDelete(item)">
                      <a-icon type="close" style="margin-right: 8px;" />删除目录
                    </div>
                  </template>
                  <a-icon type="ellipsis" class="blue-hover tool-icon" />
                </a-popover>
              </span>
            </div>
          </template>
        </a-tree>
        <a-empty v-else />
      </a-spin>
    </div>
    <EditChapterMenus ref="EditChapterMenus" />
  </div>
</template>
<script>
import { TextbookGetList, ChapterGetList, ChapterDelete } from "@/api/api";
import EditChapterMenus from "./EditChapterMenus.vue";
import { searchOption } from "@/utils/tools";
export default {
  components: {
    EditChapterMenus
  },
  props: ["activeSubject"],
  data() {
    return {
      spinning: false,
      replaceFields: {
        key: "id",
        title: "name"
      },
      activeKey: "",
      treeData: [],
      bookVersions: [], //教材版本
      activeBookVersion: {}, //当前教材版本
      ChapterId: "", //选中的章节id

      isShowDropdown: false,
      iconCaret:'caret-right',
    };
  },
  watch: {
    activeSubject(nval) {
      console.log(nval, "66666");
      this.bookVersions = [];
      this.activeBookVersion = {};
      this._TextbookGetList();
      this.$emit("getQuestion");
    },
    activeBookVersion(nval) {
      console.log(nval);
      this._ChapterGetList();
    }
  },
  created() {},
  mounted() {},
  methods: {
    getPopupContainer(trigger) {
      return trigger.parentElement;
    },
    fontSplice(str) {
      if (str.length > 10) return str.slice(0, 10) + "...";
      else return str;
    },
    clearChapter() {
      if (!this.ChapterId) {
        return;
      }
      console.log("章节清了");
      this.ChapterId = "";
    },
    //删除章节
    _ChapterDelete(record) {
      console.log(record, "record");
      let _this = this;
      this.$confirm({
        okText: '确认',
        cancelText: '取消',
        mask: false,
        title: `您确认要删除"${record.name}"章节吗?`,
        onOk() {
          console.log(record.id, "record.id");
          console.log(_this.ChapterId, "ChapterId");
          _this.spinning = true;
          let data = {
            id: record.id
          };
          ChapterDelete(data)
            .then(res => {
              console.log(record.dataRef, "record.dataRef");
              console.log(_this.treeData, "_this.treeData");
              searchOption(record.dataRef, _this.treeData);
              _this.treeData = [..._this.treeData];
              _this.$message.success("删除成功！");
              if (record.id === _this.ChapterId) {
                _this.$emit("getQuestion");
              }
              _this.spinning = false;
            })
            .catch(err => {
              _this.spinning = false;
            });
        }
      });
    },
    //增加，修改章节
    showModal(type, record = {}) {
      this.$refs.EditChapterMenus.showModal(type, record);
    },
    onLoadData(treeNode) {
      console.log(treeNode, "treeNode");
      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve();
          return;
        }
        this.spinning = true;
        let data = {
          ParentId: treeNode.dataRef.id,
          TextbookId: this.activeBookVersion.id,
          KeyWord: "",
          SkipCount: 0,
          MaxResultCount: 99999
        };
        ChapterGetList(data)
          .then(res => {
            treeNode.dataRef.children = res.items.map(item => {
              if (!item.hasChild) {
                item.isLeaf = true;
              }
              let obj = {
                key: item.id,
                title: item.name,
                scopedSlots: { title: "custom" },
                ...item
              };
              return obj;
            });
            this.treeData = [...this.treeData];
            this.spinning = false;
            resolve();
          })
          .catch(err => {
            this.spinning = false;
          });
      });
    },
    //章节列表
    _ChapterGetList() {
      this.spinning = true;
      let data = {
        ParentId: "",
        TextbookId: this.activeBookVersion.id,
        KeyWord: "",
        SkipCount: 0,
        MaxResultCount: 99999
      };
      ChapterGetList(data)
        .then(res => {
          console.log(res, "章节树");
          this.treeData = res.items.map(item => {
            if (!item.hasChild) {
              item.isLeaf = true;
            }
            let obj = {
              key: item.id,
              title: item.name,
              scopedSlots: { title: "custom" },
              ...item
            };
            return obj;
          });
          this.spinning = false;
          console.log(this.treeData, "this.treeData ");
        })
        .catch(err => {
          this.spinning = false;
        });
    },
    loadChild(record) {
      console.log(record, "record66666");
      this.spinning = true;
      let data = {
        ParentId: record.id || "", //父级知识点id
        TextbookId: this.activeBookVersion.id, //教材id
        KeyWord: "",
        SkipCount: 0,
        MaxResultCount: 99999
      };
      ChapterGetList(data)
        .then(res => {
          console.log(res, "子节点66");
          if (res.totalCount > 0) {
            record.dataRef.isLeaf = false;
          }
          record.dataRef.children = res.items.map(item => {
            if (!item.hasChild) {
              item.isLeaf = true;
            }
            let obj = {
              key: item.id,
              title: item.name,
              scopedSlots: { title: "custom" },
              ...item
            };
            return obj;
          });
          this.treeData = [...this.treeData];
          console.log(this.treeData, "treeData");
          this.spinning = false;
        })
        .catch(err => {
          this.spinning = false;
        });
    },
    //获取学科下的教材版本
    _TextbookGetList() {
      if (!this.activeSubject.id) {
        return;
      }
      let data = {
        DisciplineId: this.activeSubject.id, //学科id
        IsActive: true,
        SkipCount: 0,
        MaxResultCount: 99999
      };
      TextbookGetList(data).then(res => {
        console.log(res, "学科下的教材版本");
        this.bookVersions = res.items;
        if (!this.activeBookVersion.id && res.items.length > 0) {
          console.log("进这了", res.items[0]);
          this.activeBookVersion = res.items[0];
          this.activeKey = res.items[0].id;
          this._ChapterGetList();
        }
      });
    },
    editionClick(item) {
      console.log(item, "activeBookVersion");
      this.activeKey = item.id;
      this.activeBookVersion = item;
      this.hideSropdown()
    },
    onSelect(selectedKeys) {
      console.log(selectedKeys, "selectedKeys");
      let data = {
        ChapterId: selectedKeys[0] || ""
      };
      this.ChapterId = data.ChapterId;
      this.$emit("getQuestion", data);
      this.$emit("clearPoints");
    },
    handleShowDropdown(e){
      e.preventDefault();
      this.isShowDropdown=!this.isShowDropdown;
      if(this.isShowDropdown){
        this.iconCaret='caret-down';
      }
      else{
        this.iconCaret='caret-right';
      }
    },
    hideSropdown() {
      this.isShowDropdown=false;
      this.iconCaret='caret-right';
    }
  }
};
</script>
<style scoped>
.active-btn {
  color: #fff;
  background-color: #1980ff;
}

.edition {
  padding: 8px 16px;
  border-bottom: 1px solid rgba(232, 232, 232, 1);
  cursor: pointer;
  position: relative;
}

.edition:hover .edition-name {
  color: rgb(24, 144, 255);
}

.drop-down {
  width: 100%;
  max-height: 0px;
  position: absolute;
  top: 40px;
  left: 0;
  background-color: #fff;
  z-index: 99;
  transition: all 1s;
  overflow: hidden;
}

.edition:hover .drop-down {
  /* max-height: 200px; */
}

.drop-down.drop-down-show {
  max-height: 200px;
}

.drop-down-content {
  padding: 8px;
  border-bottom: 1px solid rgba(232, 232, 232, 1);
  display: flex;
  flex-wrap: wrap;
}

.tree-box {
  width: 100%;
  min-height: 200px;
  overflow-x: auto;
}

::v-deep .custom-title{
    font-size: 1px;
}
.drop-down-item {
  padding: 0 6px;
  border-radius: 2px;
  margin-bottom: 6px;
  cursor: pointer;
}

.drop-down-item:hover:not(.active-btn) {
  color: rgb(24, 144, 255);
}

.toolbar {
  position: absolute;
  right: 10px;
  margin-top: 0px;
  border: none;
  font-size: 16px;
  font-weight: bold;
}

.tool-icon {
  font-size: 20px;
}
</style>