<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"
          v-if="docAttr.id > 0"
          >另存为</el-button
        >
        <el-button type="primary" size="mini" @click="onSave">保存</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">
              <el-collapse-item title="最新文档" name="-1">
                <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>

              <!--     <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> -->
              <el-collapse-item
                v-for="(item, itemIndex) in categoryList"
                :title="item.name"
                :name="item.id"
              >
                <draggable
                  v-model="item.dataList"
                  :options="{
                    group: { name: 'itxst', pull: 'clone' },
                    sort: true,
                  }"
                  animation="300"
                >
                  <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>
            </el-collapse>
          </div>
        </div>
      </div>

      <div class="editor-main">
        <div class="menus-box">
          <menus @onEvents="onInsert"></menus>
        </div>
        <div class="editor-box" ref="tabHtml">
          <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="onSetActiveIndex(9997)" :class="comIndex==9997?'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="comIndex==9997">
          <Directory :coms="coms" />
        </template> -->

        <template
          v-if="comIndex != 9999 && comIndex != 9998 && comIndex != 9997"
        >
          <Attribute
            :com="coms[comIndex]"
            @onRefresh="initCategoryList"
          ></Attribute>
        </template>
        <Directory :coms="coms" />
      </div>
    </div>

    <el-dialog
      :visible.sync="showViewForm"
      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
      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 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 htmlDocx from "htmlDocx";
export default {
  name: "create",
  components: {
    menus,
    editor,
    Attribute,
    comList,
    docAttr,
    ViewForm,
    ProductAttr,
    Directory,
    draggable,
  },
  directives: {
    elDragDialog,
  },
  data() {
    return {
      activeNames: "-1",
      articleList: [],
      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,
    };
  },
  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: {
    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,
        linkProduct: e.linkProduct,
        links: e.links,
        linkProject: e.linkProject,
        projects: e.projects,
      };
      _this.coms = JSON.parse(e.data);
    },
    onRemove(index) {
      this.coms.splice(index, 1);
    },
    //设置当前索引
    onSetActiveIndex(e) {
      this.comIndex = e;
    },

    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);

      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;
      }
    },

    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;
      }
      let com = _this.coms[_this.comIndex];
      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) {
          _this.setTableData(data.id);
        }
      }
    },
    //插入原始数据
    insertSourceData(e) {
      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,
        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: 10,
      }).then((res) => {
        if (res.status != 200) return;
        _this.articleList = res.data.dataList;
      });
    },
  },
};
</script>

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