<template>
  <div class="com-viewer">
      <div class="content">
         <template v-for="(item,index) in coms">
          <component
          :is="item.type"
          :com="item"
          :coms="comList"
          :currentIndex="index"
          :isActive="false"
          @onUpdateData="onUpdateData"
          />
         </template>
      </div>
      <div class="export">
        <el-button @click="onExport" type="primary">导出</el-button>
      </div>
  </div>
</template>

<script>
  import {exportDocument,exportDemoDocument} from "@/api/document"
  import TextArea from "./components/TextView";
  import htmlDocx from 'html-docx-js/dist/html-docx';
  import saveAs from 'file-saver';
  import jsPDF from 'jspdf';
  import { createDocument} from 'html-to-docx';

  export default{
    name:"viwer",
    components:{
      TextArea
    },
    props:{
      id:{
        type:Number,
        default:0,
      },
      coms:{
        type:Array,
        default:null,
      },
      docAttr:{
        type:Object,
        default:()=>{
          return {
            title:'',
          }
        }
      }
    },
    watch:{
      'coms':{
        handler(val){
            let _this=this;
            if(val==null)return;
            this.comList=JSON.parse(JSON.stringify(val));
        },
        immediate:true,
        deep:true,
      }
    },
    data(){
      return{
        comList:[],
        content:"",
      }
    },
    methods:{
      //更新内容
      onUpdateData(index,data){
        this.comList[index].content=data;
        this.rebuildContent();
      },
      rebuildContent(){
        let _this=this;
        this.content='';
        for(var i=0;i<this.comList.length;i++){
          this.content+=this.comList[i].content;
        }
      },
      onExport(e){
          let contentData = `<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body><p class="header1"></p> ${this.content} </body></html>`;

          let title=this.docAttr.title;
          let _this=this;
         contentData=contentData.replaceAll("<table ",`<table  style="border-collapse: collapse;" `)
         contentData=contentData.replaceAll("<td>",`<td  style="border: 1px solid black;">`)
          // exportDemoDocument({}).then(res=>{
          //   console.log('res',res);
          // })
          // return;
          exportDocument({content:contentData,title:title}).then(res=>{
            if(res.status!=200){
              _this.$alert(res.errMsg);
              return;
            }
            let a=document.createElement('a');
            a.href=res.data;
            a.target="_blank";
            a.click();
          })
      },
    },
  }
</script>

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

