<!-- -->
<template>
  <div class="exhibiton-unit" ref="exhibitionUnit">
    <el-row class="tree-container" v-if="treeData.length > 0">
      <el-col :span="8">
        <el-tree :data="treeData" node-key="euId" default-expand-all>
          <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="16">
        <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">
            <el-select
              v-model="currentData.crIds"
              multiple
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词搜索文物"
              :remote-method="searchCR"
              :loading="loading"
              style="width: 100%"
            >
              <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">
            <!-- <el-input
              placeholder="请输入介绍"
              v-model="currentData.intro"
              type="textarea"
              rows="4"
              maxlength="800"
              show-word-limit
            >
            </el-input> -->
            <quill-editor
              ref="myQuillEditor"
              v-model="currentData.intro"
              :options="editorOption"
              @blur="onEditorBlur($event)"
              @focus="onEditorFocus($event)"
              @ready="onEditorReady($event)"
              class=".editor"
            />
          </el-col>
        </el-row>
        <el-collapse-transition>
          <el-row :gutter="50">
            <el-col :span="24">
              <div>单元封面：</div>
              <ManualImageUploader
                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-col>
    </el-row>
    <el-button
      v-if="!treeData.length > 0"
      type="primary"
      icon="el-icon-circle-plus-outline"
      @click="handleAddUnit"
      size="small"
      >手动添加展览单元</el-button
    >
    <el-button
      v-if="!treeData.length > 0"
      type="success"
      @click="handleAddUnit"
      size="small"
    >
      <svg-icon icon-class="word"></svg-icon>
      Word批量导入
    </el-button>
    <el-button
      v-if="!treeData.length > 0"
      type="success"
      @click="handleAddUnit"
      size="small"
    >
      <svg-icon icon-class="excel"></svg-icon>
      Excel批量导入</el-button
    >
  </div>
</template>

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

import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import { quillEditor } from "vue-quill-editor";

export default {
  components: {
    ManualImageUploader,
    quillEditor,
  },
  props: {
    exhibitionUnits: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    exhibitionUnits: {
      handler: function (value) {
        if (value) {
          let that = this;
          // debugger
          that.treeData = JSON.parse(JSON.stringify(value));
          // console.log('currentData',this.treeData);
          if (value.length > 0) {
            that.currentData = that.treeData[0];
            loopData(that.treeData);
            function loopData(arr) {
              if (arr.length > 0) {
                console.log(arr);
                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);
                    });
                    item.imagesVo = item.imagesVo ? item.imagesVo : [];
                    item.videosVo = item.videosVo ? item.videosVo : [];
                  } else {
                    that.$set(that, "CRList", []);
                  }
                  if (item.children) {
                    loopData(item.children);
                  }
                });
              }
            }
          }
        }
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    // 工具栏配置
    const toolbarOptions = [
      ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
      ["blockquote", "code-block"], // 引用  代码块-----['blockquote', 'code-block']
      [{ header: 1 }, { header: 2 }], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
      [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
      [{ script: "sub" }, { script: "super" }], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
      [{ indent: "-1" }, { indent: "+1" }], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
      [{ direction: "rtl" }], // 文本方向-----[{'direction': 'rtl'}]
      [{ size: ["small", false, "large", "huge"] }], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
      [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
      [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
      [{ font: [] }], // 字体种类-----[{ font: [] }]
      [{ align: [] }], // 对齐方式-----[{ align: [] }]
      ["clean"], // 清除文本格式-----['clean']
      ["image", "video"], // 链接、图片、视频-----['link', 'image', 'video']
    ];

    return {
      treeData: [],
      CRList: [], //文物列表，关联文物使用
      loading: false,
      imagesVo: [],
      videosVo: [],
      currentData: {}, //当前点击的树节点
      // 富文本编辑器默认内容
      content: "",
      //富文本编辑器配置
      editorOption: {
        //  富文本编辑器配置
        modules: {
          //工具栏定义的
          toolbar: toolbarOptions,
        },
        //主题
        theme: "snow",
        placeholder: "请输入单元介绍",
      },
    };
  },
  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 getCulturalRelicList(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;
    },
    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: "",
        crIds: [],
        videos: "",
        children: [],
        // unit: "",
        // imagesVo: [],
        // videosVo: [],
      };
      if (!data.children) {
        this.$set(data, "children", []);
      }
      data.children.push(newChild);
    },
    appendPeerNode(node, data) {
      // debugger
      const parent = node.parent.data;
      const newChild = {
        euId: euId++,
        unit: "",
        title: "单元标题",
        intro: "",
        crIds: [],
        showMediaUploader: false,
        images: "",
        videos: "",
        children: [],
      };
      parent.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);
    },

    handleAddUnit() {
      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];
    },

    //失去焦点事件
    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;
    },
  },
};
</script>

<style lang="scss" scoped>
.exhibition-units-tree-node {
  display: flex;
  width: 100%;
  flex-direction: column;
  .title {
    width: 100px;
    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;
  }
}
</style>

<style lang='scss' >
// 富文本编辑器汉化
.editor {
  line-height: normal !important;
  height: 500px;
}
.ql-snow .ql-tooltip[data-mode="link"]::before {
  content: "请输入链接地址:";
}
.ql-snow .ql-tooltip.ql-editing a.ql-action::after {
  border-right: 0px;
  content: "保存";
  padding-right: 0px;
}

.ql-snow .ql-tooltip[data-mode="video"]::before {
  content: "请输入视频地址:";
}
.ql-snow .ql-picker{
  height: 40px;
}
.ql-snow .ql-picker.ql-size .ql-picker-label::before,
.ql-snow .ql-picker.ql-size .ql-picker-item::before {
  content: "14px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="small"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="small"]::before {
  content: "10px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="large"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="large"]::before {
  content: "18px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="huge"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="huge"]::before {
  content: "32px";
}

.ql-snow .ql-picker.ql-header .ql-picker-label::before,
.ql-snow .ql-picker.ql-header .ql-picker-item::before {
  content: "文本";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
  content: "标题1";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
  content: "标题2";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
  content: "标题3";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
  content: "标题4";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
  content: "标题5";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
  content: "标题6";
}

.ql-snow .ql-picker.ql-font .ql-picker-label::before,
.ql-snow .ql-picker.ql-font .ql-picker-item::before {
  content: "标准字体";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="serif"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="serif"]::before {
  content: "衬线字体";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="monospace"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="monospace"]::before {
  content: "等宽字体";
}
</style>

