<template>
  <div class="doc-container">
    <div class="editor-top">
      <div class="left">
        <div class="doc">
          <span>当前打开文档：</span
          >{{ docAttr.title == "" ? "新建文档" : docAttr.title }}
        </div>
        <div class="creator" v-if="userInfo != null">
          <span>创建者：</span>{{ userInfo.username }}
        </div>
      </div>
      <div class="right">
        <el-button type="primary" size="mini" @click="onSaveAs"
          >保存文档</el-button
        ><!-- v-if="docAttr.id > 0" -->
        <el-button
          type="primary"
          size="mini"
          @click="onSave"
          v-if="docAttr.is_template == 0 && docAttr.id > 0"
          >更新文档</el-button
        >
        <el-button
          type="primary"
          size="mini"
          v-if="$store.state.user.name == 'admin'"
          @click="onSaveUpload"
          >保存并更新模版</el-button
        >
        <el-button type="primary" size="mini" @click="onOpenView"
          >预览导出
        </el-button>
        <el-button type="primary" size="mini" @click="onClose">
          关闭文档
        </el-button>
      </div>
    </div>
    <div class="editor-content">
      <div class="neary-doc">
        <div class="left-content">
          <div class="search">
            <el-input placeholder="搜索文档标题"></el-input>
          </div>
          <div class="new-article">
            <el-collapse
              v-model="activeNames"
              :accordion="true"
              @change="handleItemClick"
            >
              <el-collapse-item title="最新文档" name="-1" v-if="showView == 0">
                <div
                  v-for="(it, index) in articleList"
                  draggable
                  :key="it.id"
                  :data-index="index"
                  data-type="article"
                  class="sub-menus"
                >
                  <div @click="onLoadArticle(it)">{{ it.title }}</div>
                </div>
              </el-collapse-item>
              <el-collapse-item title="模版列表" name="-2" v-if="showView == 0">
                <div
                  v-for="(it, index) in templateList"
                  draggable
                  :key="it.id"
                  :data-index="index"
                  data-type="article"
                  class="sub-menus"
                >
                  <div @click="onTemplateInfo(it)">{{ it.title }}</div>
                </div>
              </el-collapse-item>

              <!--     <template v-for="(item, itemIndex) in categoryList">
                <div class="sub-title">{{ item.name }}</div>
                <template v-for="(subItem, subIndex) in item.children">
                  <el-collapse-item :title="subItem.name" :name="subItem.id">
                    <draggable
                      v-model="subItem.dataList"
                      :options="{
                        group: { name: 'itxst', pull: 'clone' },
                        sort: true,
                      }"
                      animation="300"
                    >
                      <transition-group>
                        <div
                          class="sub-menus"
                          v-for="(it, index) in subItem.dataList"
                          :key="index"
                        >
                          <div>{{ it.name }}</div>
                        </div>
                      </transition-group>
                    </draggable>
                  </el-collapse-item>
                </template>
              </template> -->
              <div v-if="showView == 1">
                <el-collapse-item
                  v-for="(item, itemIndex) in categoryList"
                  :key="itemIndex"
                  :title="item.name"
                  :name="item.id"
                >
                  <el-collapse
                    v-model="item.activeChildren"
                    @change="handleItemVal"
                    v-show="item.children"
                  >
                    <el-collapse-item
                      v-for="(child, childIndex) in item.children"
                      :key="childIndex"
                      :title="child.name"
                      :name="child.id"
                    >
                      <draggable
                        v-model="child.dataList"
                        :options="{
                          group: { name: 'itxst', pull: 'clone' },
                          sort: true,
                        }"
                      >
                        <transition-group>
                          <div
                            class="sub-menus"
                            v-for="(its, index) in child.dataList"
                            :key="index"
                          >
                            <div>{{ its.name }}</div>
                          </div>
                        </transition-group>
                      </draggable>
                    </el-collapse-item>
                  </el-collapse>
                  <draggable
                    v-model="item.dataList"
                    :options="{
                      group: { name: 'itxst', pull: 'clone' },
                      sort: true,
                    }"
                  >
                    <transition-group>
                      <div
                        class="sub-menus"
                        v-for="(it, index) in item.dataList"
                        :key="index"
                      >
                        <div>{{ it.name }}</div>
                      </div>
                    </transition-group>
                  </draggable>
                </el-collapse-item>
              </div>
            </el-collapse>
          </div>
        </div>
      </div>
      <div class="right-sidebarew">
        <div
          class="sidebar-item"
          :class="showView == 0 ? 'active-item' : ''"
          @click="viewDocument"
        >
          查看文档
        </div>
        <div
          class="sidebar-item"
          :class="showView == 1 ? 'active-item' : ''"
          @click="viewModule"
        >
          查看模块
        </div>
      </div>

      <div class="editor-main">
        <div class="menus-box">
          <menus
            @onEvents="onInsert"
            @onVariable="uptadeVariable"
            :comArr="coms"
          ></menus>
        </div>
        <div class="editor-box" ref="tabHtml" v-loading="loading">
          <editor
            :coms="coms"
            :comIndex="comIndex"
            :isAdmin="isAdmin"
            :templateCate="categoryList"
            :insertCmd="insertCmd"
            @onSetActiveIndex="onSetActiveIndex"
            @onInsert="onInsert"
            @onLoadArticle="onLoadArticle"
            @onDelete="onRemove"
            @onRebuild="onRebuild"
            @onSetComs="onSetComs"
          ></editor>
        </div>
      </div>

      <div class="editor-option">
        <div class="editor-menu">
          <div
            class="item"
            @click="onSetActiveIndex(9999)"
            :class="comIndex == 9999 ? 'active-item' : ''"
          >
            <span class="name">文档属性</span>
          </div>
          <div
            class="item"
            @click="onSetActiveIndex(9998)"
            :class="comIndex == 9998 ? 'active-item' : ''"
          >
            <span class="name">模块管理</span>
          </div>
          <div
            class="item"
            @click="onCatalogIndex(9997)"
            :class="catalogIndex == 9997 ? 'active-item' : ''"
          >
            <span class="name">目录信息</span>
          </div>
          <div
            class="item"
            @click="onAttributeIndex(1)"
            :class="AttributeIndex == 1 ? 'active-item' : ''"
          >
            <span class="name">属性变量</span>
          </div>
        </div>

        <template v-if="comIndex == 9999">
          <docAttr :attrs="docAttr"></docAttr>
        </template>
        <template v-if="comIndex == 9998">
          <comList
            :coms="coms"
            @onRemove="onRemove"
            @onSetActive="onSetActiveIndex"
            @onRebuild="onRebuild"
          ></comList>
        </template>
        <template v-if="catalogIndex == 9997">
          <Directory :coms="coms" />
        </template>
        <!-- comIndex != 9999 && comIndex != 9998 && comIndex != 9997 AttributeIndex==1-->
        <template
          v-if="
            comIndex != 9999 &&
            comIndex != 9998 &&
            catalogIndex != 9997 &&
            AttributeIndex != 1
          "
        >
          <Attribute
            :com="coms[comIndex]"
            @onRefresh="initCategoryList"
          ></Attribute>
        </template>
        <template v-if="AttributeIndex == 1">
          <attributeVar
            :com="coms[comIndex]"
            @onRefresh="initCategoryList"
          ></attributeVar>
        </template>
        <!-- <Directory :coms="coms" /> -->
      </div>
    </div>

    <el-dialog
      :visible.sync="showViewForm"
      :close-on-click-modal="false"
      append-to-body
      v-el-drag-dialog
      width="850px"
      custom-class="prod-verify"
      title="文档预览"
    >
      <ViewForm :coms="coms" :docAttr="docAttr"></ViewForm>
    </el-dialog>

    <el-dialog
      :visible.sync="showProductAttr"
      append-to-body
      v-el-drag-dialog
      :close-on-click-modal="false"
      width="850px"
      custom-class="prod-verify"
      title="插入产品属性"
    >
      <ProductAttr
        :docAttr="docAttr"
        @onInsertProductAttr="onInsertProductAttr"
      ></ProductAttr>
    </el-dialog>
  </div>
</template>

<script>
import utils from "@/utils/fun"; // 方法类
import { searchDocument } from "@/api/document";
import menus from "./com/menus";
import editor from "./com/editor";
import Attribute from "./com/components/Attribute";
import attributeVar from "./com/components/Attribute/attributeVar/index.vue";
import ProductAttr from "./com/components/ProductAttr";
import {
  searchTemplateCategory,
  searchTemplate,
  getTemplateInfo,
  getAllCategory,
} from "@/api/template";
import docAttr from "./com/components/Attribute/docAttr";
import comList from "./com/components/Attribute/comList";
import Directory from "./com/components/Attribute/Directory";
import { getCurrentUserInfo } from "@/api/api";
import {
  createDocument,
  updateDocument,
  getDocumentInfo,
  exportDocument,
} from "@/api/document";
import ViewForm from "./com/view";
import elDragDialog from "@/directive/el-drag-dialog";
import draggable from "vuedraggable";
import htmlDocx from "html-docx-js/dist/html-docx";
import axios from "axios";
// import htmlDocx from "htmlDocx";
export default {
  name: "create",
  components: {
    menus,
    editor,
    Attribute,
    comList,
    docAttr,
    ViewForm,
    ProductAttr,
    Directory,
    draggable,
    attributeVar,
  },
  directives: {
    elDragDialog,
  },
  data() {
    return {
      activeNames: "-1",
      nestedActiveNames: [],
      articleList: [],
      templateList: [],
      categoryList: [],
      //组件相关
      coms: [],
      comIndex: 0, //当前组件索引
      showProductAttr: false,
      comList: [],
      //文档属性
      docAttr: {
        id: 0,
        category_id: "",
        title: "",
        content: "",
        status: 5,
        links: "",
        linkProduct: [],
        linkProject: [],
        projects: "",
      },
      insertCmd: null,
      showViewForm: false,
      isAdmin: 2, //1是管理员，2非管理员
      //当前选中表格
      tabExt: {
        row: 0,
        col: 0,
      },
      userInfo: null,
      articleId: 0,
      loading: false, // 增加 loading 状态
      showView: 0, //查看 文档/模块
      childrenList: "",
      value: [],
      AttributeIndex: 0,
      catalogIndex: 0, //目录信息
    };
  },
  watch: {
    coms: {
      handler(val) {
        // console.log("watch com val:",val);
      },
      immediate: true, //立即执行
      deep: true,
    },
    articleId: {
      handler(val) {
        if (val == null || val == undefined || val <= 0) return;
        this.loadArticle(val);
      },
      immediate: true,
      deep: true,
    },
  },

  async mounted() {
    let _this = this;
    this.searchArticle();
    await this.initCategoryList();
    await this.initCurrentUser();
    this.articleId = this.$route.query.articleId;

    let templateId = this.$route.query.templateId;
    if (templateId > 0) {
      _this.loadTemplateInfo(templateId);
    }
    _this.isAdmin = _this.userInfo.roleInfo.is_admin;
  },

  methods: {
    handleItemVal(value) {
      this.$forceUpdate();
    },
    async handleItemClick(item) {
      const category = this.categoryList.find((cat) => cat.id === item);
      if (!category) return;

      if (!category.children) {
        try {
          const res = await searchTemplateCategory({ parent_id: item });
          if (res.status != 200 || res.data.length == 0) return;
          category.children = res.data;
          for (let i = 0; i < category.children.length; i++) {
            category.children[i].dataList = await this.getTemplateList(
              category.children[i].id
            );
          }
        } catch (error) {
          console.error("Error fetching template categories:", error);
        }
      }

      // 触发视图更新
      this.$set(category, "activeChildren", category.activeChildren || []);
    },
    /* 切换标签 */
    viewDocument() {
      this.showView = 0;
    },
    viewModule() {
      this.showView = 1;
    },
    /* 更新变量 */
    uptadeVariable(value) {
      for (const item of this.coms) {
        for (const el of item.attrs) {
          if (el.type === "variable") {
            if (el.data.id == value.id) {
              el.content = value.value;
            }
          }
        }
      }
    },
    /* 更新检索内容 */
    async uptadeSearch() {
      for (const item of this.coms) {
        for (const el of item.attrs) {
          if (el.type === "ai") {
            // await this.retrieval(el);
          }
        }
      }
    },
    /* 初始化检索 */
    async retrieval(el) {
      this.loading = true; // 开始加载动画
      try {
        const response = await axios.post(
          "http://58.246.234.210:7860/api/v1/run/3f84a841-cefd-44b3-9555-568cc3b6c2d2?stream=false",
          {
            input_value: el.search,
            output_type: "chat",
            input_type: "chat",
            tweaks: {
              "ChatInput-em6qC": {},
              "ParseData-yO3YQ": {},
              "Prompt-Wj75b": {},
              "ChatOutput-zy9na": {},
              "SplitText-O1knk": {},
              "File-4j6Zd": {},
              "OllamaEmbeddings-xbYXX": {},
              "Chroma-OIejP": {},
              "OllamaModel-04mEO": {},
              "OllamaEmbeddings-UGvLP": {},
              "Chroma-HzukO": {},
            },
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        );

        if (response.status === 200) {
          // 假设返回的数据在 response.data.outputs[0].outputs[0].results.message.data.text 中
          const resultText =
            response.data.outputs[0].outputs[0].results.message.data.text;
          // 将搜索词和生成的内容存储在 searchResult 对象中
          el.content = resultText; // 重新赋值给原数组的对应 content
        }
      } catch (error) {
        console.error("Error during retrieval:", error);
        this.$message.error("检索失败，请稍后重试");
      } finally {
        this.loading = false; // 结束加载动画
      }
    },
    loadTemplateInfo(e) {
      let _this = this;
      let par = {
        id: e,
      };
      getTemplateInfo(par).then((res) => {
        if (res.status != 200) return;
        res.data.attrs = JSON.parse(res.data.attrs);
        _this.coms = [res.data];
      });
    },
    onExport(e) {
      let _this = this;
      _this.comIndex = -1;
      let content = _this.$refs.tabHtml.innerHTML;
    },

    onOpenView(e) {
      this.showViewForm = true;
    },
    onClose() {
      window.close();
    },

    loadArticle(e) {
      let _this = this;
      getDocumentInfo({
        id: e,
      }).then((res) => {
        if (res.status != 200) return;
        _this.onLoadArticle(res.data);
      });
    },

    handleDragStart(e) {
      let data = {};
      if (e.target.dataset.type == "article") {
        let index = e.target.dataset.index;
        data = {
          optType: e.target.dataset.type,
          item: this.articleList[index],
        };
      } else {
        let index = e.target.dataset.index;
        let subIndex = e.target.dataset.subIndex;
        let item = this.categoryList[index].dataList[subIndex];
        delete item.category;
        data = {
          ...item,
          optType: e.target.dataset.type,
          key: "addNew",
          attrs: JSON.parse(item.attrs),
        };
      }
      e.dataTransfer.setData("item", JSON.stringify(data));
      this.operation = "drag";
    },

    onRebuild(e) {
      let _this = this;
      _this.coms = [...e];
    },
    //初始化当前用户信息
    async initCurrentUser() {
      let _this = this;
      let res = await getCurrentUserInfo();
      if (res.status != 200) return;
      _this.userInfo = res.data;
    },
    //加载文档信息
    onLoadArticle(e) {
      let _this = this;
      _this.docAttr = {
        id: e.id,
        category_id: e.category_id * 1,
        title: e.title,
        content: "",
        status: e.status,
        is_template: e.is_template,
        linkProduct: e.linkProduct,
        links: e.links,
        linkProject: e.linkProject,
        projects: e.projects,
      };

      _this.coms = JSON.parse(e.data);
      console.log(_this.coms);
      this.uptadeSearch();
    },
    /* 加载模版信息 */
    onTemplateInfo(e) {
      let _this = this;
      _this.docAttr = {
        id: e.id,
        category_id: e.category_id * 1,
        title: e.title,
        content: "",
        status: e.status,
        is_template: e.is_template,
        linkProduct: e.linkProduct,
        links: e.links,
        linkProject: e.linkProject,
        projects: e.projects,
      };
      _this.coms = JSON.parse(e.data);
      this.uptadeSearch();
    },
    onRemove(index) {
      this.coms.splice(index, 1);
    },
    /* 目录信息 */
    onCatalogIndex(e) {
      this.catalogIndex = e;
      if (
        this.comIndex == 9999 ||
        this.comIndex == 9998 ||
        this.AttributeIndex == 1
      ) {
        this.comIndex = 0;
        this.AttributeIndex = 0;
      }
    },
    //设置当前索引
    onSetActiveIndex(e) {
      this.comIndex = e;
      if (
        this.comIndex == 9999 ||
        this.comIndex == 9998 ||
        this.catalogIndex == 9997
      ) {
        this.catalogIndex = 0;
        this.AttributeIndex = 0;
      }
    },
    /* 属性变量 */
    onAttributeIndex(e) {
      this.AttributeIndex = e;
      if (
        this.comIndex == 9999 ||
        this.comIndex == 9998 ||
        this.catalogIndex == 9997
      ) {
        this.catalogIndex = 0;
        this.comIndex = 0;
      }
    },
    onSaveAs(e) {
      let _this = this;
      _this.docAttr.id = "";
      _this.onSave(e);
    },
    //保存文档
    onSave(e) {
      let _this = this;
      if (_this.coms.length <= 0) {
        _this.$alert("增加组件");
        return;
      }
      if (_this.docAttr.category_id == "" || _this.docAttr.category_id <= 0) {
        _this.$alert("请选择文档分类");
        return;
      }
      if (_this.docAttr.title == "") {
        _this.$alert("请填写文档标题");
        return;
      }

      _this.docAttr.links = JSON.stringify(_this.docAttr.linkProduct);
      _this.docAttr.projects = JSON.stringify(_this.docAttr.linkProject);
      _this.docAttr.data = JSON.stringify(_this.coms);
      _this.docAttr.is_template = 0;
      _this.docAttr.user_name = _this.$store.state.user.name;
      _this.docAttr.user_id = _this.$store.state.user.id;
      if (_this.docAttr.id > 0) {
        updateDocument(_this.docAttr).then((res) => {
          if (res.status != 200) return; //更新文档
          _this.docAttr.id = res.data;
          _this.$alert("文档更新成功");
          _this.searchArticle();
        });
      } else {
        createDocument(_this.docAttr).then((res) => {
          if (res.status != 200) return; //保存文档
          _this.docAttr.id = res.data;
          _this.$alert("文档保存成功");
          _this.searchArticle();
        });
      }
    },
    /* 保存并更新模版 */
    onSaveUpload(e) {
      let _this = this;
      if (_this.coms.length <= 0) {
        _this.$alert("增加组件");
        return;
      }
      if (_this.docAttr.category_id == "" || _this.docAttr.category_id <= 0) {
        _this.$alert("请选择分类");
        return;
      }
      if (_this.docAttr.title == "") {
        _this.$alert("请填写模版标题");
        return;
      }

      _this.docAttr.links = JSON.stringify(_this.docAttr.linkProduct);
      _this.docAttr.projects = JSON.stringify(_this.docAttr.linkProject);
      _this.docAttr.data = JSON.stringify(_this.coms);
      _this.docAttr.is_template = 1;
      _this.docAttr.user_name = _this.$store.state.user.name;
      _this.docAttr.user_id = _this.$store.state.user.id;
      if (_this.docAttr.id > 0) {
        updateDocument(_this.docAttr).then((res) => {
          if (res.status != 200) return; //更新文档
          _this.docAttr.id = res.data;
          _this.$alert("模版更新成功");
          _this.searchArticle();
        });
      } else {
        createDocument(_this.docAttr).then((res) => {
          if (res.status != 200) return; //保存文档
          _this.docAttr.id = res.data;
          _this.$alert("模版保存成功");
          _this.searchArticle();
        });
      }
    },

    //设置组件值
    onSetComs(e) {
      let _this = this;
      _this.coms = [...e];
    },
    onAddLayer(cateIndex, dataIndex) {
      let _this = this;
      let item = _this.categoryList[cateIndex].dataList[dataIndex];
      let data = {
        ...item,
        attrs: JSON.parse(item.attrs),
      };
      delete data.category;
      _this.coms.push(data);
      _this.comIndex = _this.coms.length - 1;
    },
    //处理插入事件
    onInsert(e) {
      let _this = this;
      switch (e.key) {
        case "article": //插入图文
          _this.insertArticle();
          break;
        case "table": //插入图表
          _this.insertTable();
          break;
        case "sourceData": //插入原数据
          _this.insertSourceData(e);
          break;
        case "formual": //插入公式
          _this.insertFormual(e);
          break;
        case "constant": //插入常量
          _this.insertConstant(e);
          break;
        case "variable": //插入变量
          _this.insertVariable(e);
          break;
        case "pager": //插入分页符
          _this.insertPager();
          break;
        case "attr":
          this.insertProductAttr();
          break;
        case "Directory": //插入主题
          _this.insertDirectory();
          break;
        case "addNew": //插入新记录
          _this.insertNew(e);
          break;
        case "ai": //插入ai
          _this.insertAI(e);
          break;
      }
    },
    /* 插入ai */
    insertAI(e) {
      let _this = this;
      if (_this.comIndex < 0) {
        _this.$alert("请选择插入图层");
        return false;
      }
      let com = _this.coms[_this.comIndex];

      let data = {
        type: "ai",
        id: "ai" + (com.attrs.length + 1),
        dataId: "",
        name: "AI",
        intro: "插入AI",
        content: e.content.result,
        search: e.content.searchTerm,
      };
      com.attrs.push(data);
      console.log(com.attrs);
      if (com.type == "TextArea") {
        //如果是图文，更新内容
        _this.insertCmd = {
          content: "{{" + data.id + "}}",
        };
      }
    },
    insertProductAttr() {
      if (this.docAttr.linkProduct.length <= 0) {
        this.$alert("请选择文档关联商品信息");
        return false;
      }
      this.showProductAttr = true;
    },
    //插入目录
    insertDirectory(e) {
      let _this = this;
      if (_this.comIndex < 0) {
        _this.$alert("请选择插入图层");
        return false;
      }
      console.log(e);
      let com = _this.coms[_this.comIndex];
      console.log("com:", com);
      let data = {
        type: "Directory",
        id: "Directory" + (com.attrs.length + 1),
        name: "目录信息",
        intor: "目录信息",
        content: "",
      };
      com.attrs.push(data);
      _this.insertCmd = {
        content: "<div>{{" + data.id + "}}</div>",
      };
      // com.content+='{{'+data.id+'}}';
    },

    onInsertProductAttr(e) {
      let _this = this;
      this.showProductAttr = false;
      if (_this.comIndex < 0) {
        _this.$alert("请选择插入图层");
        return false;
      }

      let com = _this.coms[_this.comIndex];

      let data = {
        type: "ProductAttr",
        id: "ProductAttr" + (com.attrs.length + 1),
        dataId: e.id,
        name: "商品属性",
        intor: "商品属性",
        content: "",
        attrs: e,
      };
      com.attrs.push(data);
      _this.insertCmd = {
        content: "{{" + data.id + "}}",
      };
    },

    //插入新记录
    insertNew(e) {
      let _this = this;
      _this.coms.push(e);
    },

    //插入分页
    insertPager() {
      let _this = this;
      if (_this.comIndex < 0) {
        _this.$alert("请选择插入图层");
        return false;
      }
      let com = _this.coms[_this.comIndex];
      let data = {
        type: "pager",
        id: "pager" + (com.attrs.length + 1),
        name: "分页符",
        intor: "强制分页",
        content: "",
      };
      com.attrs.push(data);
      if (com.type == "TextArea") {
        //如果是图文，更新内容
        _this.insertCmd = {
          content: "<div>{{" + data.id + "}}</div>",
        };
      }
    },

    //插入图文
    insertArticle() {
      let _this = this;
      _this.coms.push({
        type: "TextArea",
        lay_id: "textArea",
        code: "模块名",
        name: "图文",
        intro: "图文介绍",
        isEdit: 2,
        content: "请填写内容",
        attrs: [],
      });
      _this.comIndex = _this.coms.length - 1;
    },

    //插入表格
    insertTable() {
      let _this = this;
      _this.coms.push({
        type: "Table",
        lay_id: "Table",
        code: "模块名",
        name: "图表名称",
        intro: "图表介绍",
        isEdit: 2,
        tableHeader: this.initTableHeader(),
        tableData: [{}],
        htmlData: "",
        attrs: [],
      });
      _this.comIndex = _this.coms.length - 1;
    },
    initTableHeader() {
      var start = 65;
      var data = [];
      for (var i = start; i <= start + 25; i++) {
        data.push(String.fromCharCode(i));
      }
      return data;
    },
    //插入变量
    insertConstant(e) {
      let _this = this;
      // console.log("insertconstant");
      if (_this.comIndex < 0) {
        _this.$alert("请选择插入图层");
        return false;
      }
      let com = _this.coms[_this.comIndex];
      let data = {
        type: "constant",
        id: e.content.code + (com.attrs.length + 1),
        dataId: e.id,
        name: e.content.code,
        intro: e.content.intro,
        content: e.content.value,
        data: e.content,
      };

      com.attrs.push(data);
      if (com.type == "TextArea") {
        //如果是图文，更新内容
        _this.insertCmd = {
          content: "{{" + data.id + "}}",
        };
      } else {
        //仅对图表中插入有效
        if (_this.comIndex >= 0) {
          _this.setTableData(data.id);
        }
      }
    },

    //插入变量
    insertVariable(e) {
      let _this = this;
      if (_this.comIndex < 0) {
        _this.$alert("请选择插入图层");
        return false;
      }
      let com = _this.coms[_this.comIndex];
      let data = {
        type: "variable",
        id: e.content.code + (com.attrs.length + 1),
        dataId: e.id,
        name: e.content.code,
        intro: e.content.intro,
        content: e.content.value,
        data: e.content,
      };
      com.attrs.push(data);
      if (com.type == "TextArea") {
        //如果是图文，更新内容
        _this.insertCmd = {
          content: "{{" + data.id + "}}",
        };
      } else {
        //仅对图表中插入有效
        if (_this.comIndex >= 0) {
          debugger;
          _this.setTableData(data.id);
        }
      }
    },
    //插入原数据
    insertSourceData(e) {
      debugger;
      let _this = this;
      if (_this.comIndex < 0) {
        _this.$alert("请选择插入图层");
        return false;
      }
      let com = _this.coms[_this.comIndex];
      let data = {
        type: "sourceData",
        id: "sourceData" + (com.attrs.length + 1),
        dataId: "",
        name: "源数据",
        intro: "插入源数据",
        formula:
          "[R][" +
          e.content.tb +
          "][" +
          e.content.sheet +
          "][" +
          e.content.r +
          "," +
          e.content.c +
          "]",
        content: e.content.value,
        data: e.content,
      };
      com.attrs.push(data);
      if (com.type == "TextArea") {
        //如果是图文，更新内容
        _this.insertCmd = {
          content: "{{" + data.id + "}}",
        };
      }
    },
    //插入公式
    insertFormual(e) {
      let _this = this;
      if (_this.comIndex < 0) {
        _this.$alert("请选择插入图层");
        return false;
      }
      let com = _this.coms[_this.comIndex];
      let data = {
        type: "formual",
        id: "formual" + (com.attrs.length + 1),
        dataId: e.id,
        name: e.content.name,
        intro: e.content.intro,
        formula: e.content.formula,
        content: 0,
        data: e.content,
      };
      com.attrs.push(data);
      if (com.type == "TextArea") {
        //如果是图文，更新内容
        _this.insertCmd = {
          content: "{{" + data.id + "}}",
        };
      } else {
        //仅对图表中插入有效
        if (_this.comIndex >= 0) {
          // _this.setTableData(data.id);
        }
      }
    },

    //获取模板分类信息
    async initCategoryList() {
      let _this = this;
      /*  let res = await getAllCategory({list:1 });
        if(res.status!=200)return;
        let dataList=res.data;

        for(var i=0;i<dataList.length;i++){
           for (var j=0;j<dataList[i].children.length;j++){
             let dataId=dataList[i].children[j].id;

             for(var k=0;k<dataList[i].children[j].dataList.length;k++){
               dataList[i].children[j].dataList[k].attrs=JSON.parse(dataList[i].children[j].dataList[k].attrs)
             }
             // dataList[i].children[j].dataList=await _this.getTemplateList(dataId)
           }
        }

        // console.log("dataList",dataList)
       _this.categoryList=dataList; */
      let res = await searchTemplateCategory({
        page: 1,
        pageSize: 99,
        parent_id: 0,
        status: 5,
      });
      if (res.status != 200) return;
      _this.categoryList = res.data.dataList;
      for (var i = 0; i < _this.categoryList.length; i++) {
        _this.categoryList[i].dataList = await _this.getTemplateList(
          _this.categoryList[i].id
        );
      }
    },
    //获取模板列表
    async getTemplateList(categoryId) {
      let _this = this;
      let res = await searchTemplate({
        page: 1,
        pageSize: 999,
        category_id: categoryId,
        status: 5,
      });
      if (res.status != 200) return [];

      let dataList = res.data.dataList.map((item) => {
        item.attrs = JSON.parse(item.attrs);
        return item;
      });
      return dataList;
    },

    //获取文档列表
    searchArticle() {
      let _this = this;
      searchDocument({
        page: 1,
        pageSize: 99,
      }).then((res) => {
        if (res.status != 200) return;
        _this.articleList = res.data.dataList.filter(
          (el) => el.is_template == 0
        );
        _this.templateList = res.data.dataList.filter(
          (el) => el.is_template == 1
        );
      });
    },
  },
};
</script>

<style lang="scss">
@import "./create.scss";
</style>
