<!-- -->
<template>
  <div class="exhibiton-unit" ref="exhibitionUnit">
    <el-row class="tree-container" v-if="treeData.length > 0">
      <el-col :span="9">
        <el-tree :data="treeData" node-key="euId">
          <div class="exhibition-units-tree-node" slot-scope="{ node, data }">
            <div style="display: flex; align-items: center">
              <div class="title" @click="handleClickNode(node, data)">
                <el-input
                  placeholder="请输入标题"
                  v-model="data.title"
                  v-if="data.isEditing"
                  :ref="data.euId + 'Title'"
                  @blur="() => handleInputBlur(node, data)"
                >
                </el-input>
                <span v-else>{{ data.title }}</span>
              </div>
              <el-tooltip content="编辑标题" placement="top">
                <i
                  v-if="!data.isEditing"
                  class="el-icon-edit plus-peer"
                  @click="() => editNode(node, data)"
                ></i>
              </el-tooltip>
              <el-tooltip content="添加子节点" placement="top">
                <svg-icon
                  @click="() => appendChild(data)"
                  icon-class="node-child2"
                  class="plus-child"
                  style="font-size: 32px; color: #409eff"
                ></svg-icon>
              </el-tooltip>
              <el-tooltip content="添加同级节点" placement="top">
                <i
                  class="el-icon-plus plus-peer"
                  @click="() => appendPeerNode(node, data)"
                ></i>
              </el-tooltip>
              <el-tooltip content="删除当前节点" placement="top">
                <i
                  class="el-icon-close delete"
                  @click="() => remove(node, data)"
                ></i>
              </el-tooltip>
            </div>
          </div>
        </el-tree>
      </el-col>
      <el-col class="node-detail" :span="15">
        <el-row :gutter="20">
          <el-col :span="24" class="mg-bt20">
            <el-input placeholder="请输入标题" v-model="currentData.title">
            </el-input>
          </el-col>
          <el-col :span="24" class="mg-bt20">
            <VueQuillEditor
              v-model="currentData.intro"
              placeholder="请输入单元介绍"
            />
          </el-col>
          <el-col :span="24" class="mg-bt20">
            <el-select
              v-model="currentData.crIds"
              multiple
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词搜索文物"
              :remote-method="searchCR"
              :loading="loading"
              style="width: 100%"
              ref="remoteSelect"
            >
              <el-option
                v-for="item in crList"
                :key="item.crId"
                :label="item.name"
                :value="item.crId"
              >
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="24">
            <div>单元图片：</div>
            <ManualUploader
              v-model="currentData.imagesVo"
              :files="currentData.imagesVo"
              :fileLimit="7"
              :fileSize="50"
              :fileType="['jpeg', 'jpg', 'png']"
              listType="picture-card"
              :ref="'unit-images-' + currentData.euId"
            />
          </el-col>
        </el-row>
        <!-- <el-collapse-transition>
          <el-row :gutter="50">
           
          </el-row>
        </el-collapse-transition> -->
        <div class="next-prev">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-back"
            @click="handleToUnit('prev')"
            >上一节点</el-button
          >
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-right"
            @click="handleToUnit('next')"
            >下一节点</el-button
          >
        </div>
      </el-col>
    </el-row>
    <el-button
      v-if="!treeData.length > 0"
      type="primary"
      icon="el-icon-circle-plus-outline"
      @click="handleAddUnit('manual')"
      size="small"
      >手动添加展览单元</el-button
    >
    <!-- <el-button
      v-if="!treeData.length > 0"
      type="success"
      @click="handleAddUnit('word')"
      size="small"
    >
      <svg-icon icon-class="word"></svg-icon>
      Word批量导入
    </el-button>
    <el-button
      v-if="!treeData.length > 0"
      type="success"
      @click="handleAddUnit('excel')"
      size="small"
    >
      <svg-icon icon-class="excel"></svg-icon>
      Excel批量导入</el-button
    > -->
  </div>
</template>

<script>
let euId = 1000;
import ManualUploader from "@/components/Uploader/ManualUploader.vue";
import { getCulturalRelicListPer } from "@/api/culturalRelic";
import VueQuillEditor from "@/components/VueQuillEditor";

export default {
  components: {
    ManualUploader,
    VueQuillEditor,
  },
  props: {
    exhibitionUnits: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    exhibitionUnits: {
      handler: function (value) {
        if (value) {
          let that = this;
          that.treeData = JSON.parse(JSON.stringify(value));
          if (value.length > 0) {
            that.currentData = that.treeData[0];
            loopData(that.treeData);
            function loopData(arr) {
              if (arr.length > 0) {
                arr.forEach((item) => {
                  if (item.culturalRelics && item.culturalRelics.length > 0) {
                    that.$set(that, "crList", item.culturalRelics);

                    item.crIds = [];
                    item.culturalRelics.map((cr) => {
                      // item.crIds.push(cr.crId);

                      that.$nextTick(() => {
                      // console.log("remoteSelect", that.$refs["remoteSelect"]);
                      that.$refs["remoteSelect"].cachedOptions.push({
                        currentLabel: cr.name, // 	当前绑定的数据的label
                        currentValue: cr.crId, // 当前绑定数据的value
                        label: cr.name, // 当前绑定的数据的label
                        value: cr.crId, // 当前绑定数据的value
                      });
                    });
                    });
                   
                  } else {
                    that.$set(that, "crList", []);
                  }
                  item.imagesVo = item.imagesVo || [];
                  item.videosVo = item.videosVo || [];
                  if (item.children) {
                    loopData(item.children);
                  }
                });
              }
            }
          }
        }
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      treeData: [],
      crList: [], //文物列表，关联文物使用
      loading: false,
      imagesVo: [],
      videosVo: [],
      currentData: {}, //当前点击的树节点
      // 富文本编辑器默认内容
    };
  },
  methods: {
    getUnitData() {
      return this.treeData;
    },
    // 关联文献查询
    searchCR(queryString) {
      if (!queryString.trim()) {
        this.crList = [];
        return;
      }
      this.loading = true;
      const params = {
        name: queryString,
        page: "1",
        limit: "100",
      };
      setTimeout(async () => {
        this.loading = false;
        const res = await getCulturalRelicListPer(params);
        if (res.code == 0) {
          this.crList = res.data.records;
        } else {
          this.crList = [];
          this.$message.error(res.msg);
        }
      }, 500);
    },
    handleInputBlur(node, data) {
      this.$set(data, "isEditing", false);
    },

    handleClickNode(node, data) {
      this.currentData = data;
      // debugger
    },
    editNode(node, data) {
      this.$set(data, "isEditing", true);
      setTimeout(() => {
        let ref = data.euId + "Title";
        this.$refs[ref].focus();
        console.log(this.$refs[`1Title`]);
      }, 100);
      // this.$refs[data.euId+'Title'].focus();
    },

    appendChild(data) {
      const newChild = {
        euId: euId++,
        title: "单元标题",
        intro: "",
        showMediaUploader: false,
        images: "",
        imagesVo: [],
        crIds: [],
        videos: "",
        children: [],
        // unit: "",
        // imagesVo: [],
        // videosVo: [],
      };
      if (!data.children) {
        this.$set(data, "children", []);
      }
      data.children.push(newChild);
    },
    appendPeerNode(node, data) {
      const parent = node.parent.data;
      const newChild = {
        euId: euId++,
        unit: "",
        title: "单元标题",
        intro: "",
        crIds: [],
        showMediaUploader: false,
        images: "",
        imagesVo: [],
        videos: "",
        children: [],
      };
      // return
      if (parent instanceof Array) {
        parent.push(newChild);
      } else {
        parent.children.push(newChild);
      }
    },
    remove(node, data) {
      const parent = node.parent;
      let children = "";
      if (parent.data instanceof Array) {
        children = parent.data;
      } else {
        children = parent.data.children;
      }
      const index = children.findIndex((d) => d.euId === data.euId);
      children.splice(index, 1);
    },
    changeFileList(fileList) {
      this.currentData.imagesVo = fileList;
    },
    handleAddUnit(type) {
      switch (type) {
        case "manual":
          let obj = {
            euId: 1, //后期去掉
            unit: "", //单元名称,如前言、第一单元，暂时忽略
            title: "单元标题", //单元标题，类似主题名称
            intro: "", //单元介绍
            images: "", //图片id集合
            videos: "", //视频id集合
            crIds: [], //关联文物集合
            // showMediaUploader: false,
          };
          this.$set(this.treeData, 0, obj);
          this.currentData = this.treeData[0];
          break;
        default:
          this.$message.info("该功能仍在开发中，敬请期待");
          break;
      }
    },

    //失去焦点事件
    onEditorBlur(quill) {
      console.log("editor blur!", quill);
    },
    //获得焦点事件
    onEditorFocus(quill) {
      console.log("editor focus!", quill);
    },
    // 准备富文本编辑器
    onEditorReady(quill) {
      console.log("editor ready!", quill);
    },
    //内容改变事件
    onEditorChange({ quill, html, text }) {
      console.log("editor change!", quill, html, text);
      this.content = html;
    },

    handleToUnit(type) {
      // debugger
      const { euId } = this.currentData;
      let next = {};
      let prev = {};
      let that = this;
      // debugger
      traverseTree(this.treeData);
      console.log("next", next);
      console.log("prev", prev);
      function traverseTree(arr) {
        if (arr && arr.length > 0) {
          arr.map((item, index) => {
            if (item.euId == euId) {
              console.log(item);
              switch (type) {
                case "next":
                  if (arr[index + 1]) {
                    next = arr[index + 1];
                    that.currentData = next;
                  } else {
                    that.$message.info("已是最后一个节点！");
                  }
                  break;
                case "prev":
                  if (arr[index - 1]) {
                    prev = arr[index - 1];
                    that.currentData = prev;
                  } else {
                    that.$message.info("已是第一个节点！");
                  }
                  break;
              }
            } else {
              // debugger
              if (item.children && item.children.length > 0) {
                traverseTree(item.children);
              }
            }
          });
        }
      }
      // this.treeData.map();
      // switch (type) {
      //   case "prev":
      //     console.log(1);
      //     break;
      //   case "next":
      //     console.log(-1);

      //     break;
      // }
    },
  },
};
</script>

<style lang="scss" scoped>
.exhibition-units-tree-node {
  display: flex;
  width: 100%;
  flex-direction: column;
  .title {
    width: 200px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
::v-deep .el-tree-node__content {
  // padding: 10px;
  // min-height: 140px;
  height: auto;
  padding: 10px 46px;
  display: flex;
  align-items: flex-start;
}

.tree-container {
  border: 1px #ccc dashed;
}
.node-detail {
  background: #f4f9ff;
  padding: 16px;
}

.plus-child {
  font-size: 20px;
  // font-weight: bold;
  color: #409eff;
  transition: all ease 0.5s;
  padding: 4px;
  border-radius: 4px;
  margin-left: 10px;
  &:hover {
    background-color: rgba($color: #000000, $alpha: 0.05);
    //
  }
}
.plus-peer {
  font-size: 20px !important;
  // font-weight: bold;
  color: #409eff;
  transition: all ease 0.5s;
  padding: 4px;
  border-radius: 4px;
  margin-left: 10px;
  &:hover {
    background-color: rgba($color: #000000, $alpha: 0.05);
    //
  }
}
.delete {
  font-size: 20px;
  // font-weight: bold;
  color: #f56c6c;
  transition: all ease 0.5s;
  padding: 4px;
  border-radius: 4px;
  margin-left: 10px;
  &:hover {
    background-color: rgba($color: #000000, $alpha: 0.05);
    //
  }
}
.add-image {
  display: flex;
  align-items: center;
  .svg-icon {
    width: 24px;
    height: 24px;
    color: #409eff;
    margin-left: 10px;
    padding: 4px;
    border-radius: 4px;
    box-sizing: border-box;
  }
}
.mg-bt20 {
  margin-bottom: 20px;
}
::v-deep .images-list {
  & > div {
    white-space: pre-wrap;
  }
}
.next-prev {
  display: flex;
  justify-content: flex-end;
}
</style>



