<template>
  <el-dialog
    :visible.sync="show"
    :append-to-body="true"
    :title="dialogTitle"
    width="60%"
    top="10vh"
    :fullscreen="true"
    :before-close="handleClose"
    class="dialog_diy"
    ref="docxTemplateDialogRef"
  >
    <div class="box" v-loading="loading">
      <div
        class="b_left"
        v-loading="wordContentLoading"
        ref="wordAreaRef"
        :contenteditable="downFileData"
      >
        <VueOfficeDocx
          ref="vueOfficeDocxRef"
          v-if="downFileData && !downFileData.txtUrl"
          :src="downFileData ? downFileData.url : ''"
        />

        <txtHtmlView
          ref="txtHtmlViewRef"
          v-if="downFileData && downFileData.txtUrl"
          :url="downFileData.txtUrl"
          @getTxtContent="getTxtContent"
        />

        <div class="cover_box" v-if="!downFileData">
          <el-button type="primary" @click.stop="uploadWord"
            >上传文档</el-button
          >
        </div>
      </div>
      <div class="b_right">
        <div class="d_box">
          <!-- <div class="d_b_step">
            <h2>第一步：下载模板文档</h2>
            <p>点击下载模板文档来下载指定文档</p>
            <el-button
              class="d_b_s_button"
              type="primary"
              :disabled="!downFileData"
              @click="downloadTemplateDocx()"
              >下载模板文档</el-button
            >
          </div> -->

          <div class="d_b_step">
            <h2>第一步：填入模板变量</h2>
            <p>按需制作排版Word模板文档,目前支持docx格式</p>
            <p>
              在文件中指定位置输入下方的"字段变量"，用于显示真实数据的准确位置
            </p>

            <h3>文本：</h3>
            <img
              src="https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/default%2F%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_202410090922471728436994846.png"
            />

            <h3>选择题：</h3>
            <div class="d_b_s_imgList">
              <img
                src="https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/41728546186962.png"
              />
              <img
                src="https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/51728546189479.png"
              />
            </div>
            <div class="foldMenu">
              <span v-if="foldField" @click="foldField = false"
                >折叠字段变量</span
              >
              <span v-if="!foldField" @click="foldField = true"
                >显示字段变量</span
              >
            </div>
            <div
              v-for="(item, index) in fieldList"
              :key="index"
              class="d_b_s_fieldListItem"
              v-if="foldField"
            >
              <span
                >{{ item.name }}：{{
                  "{" + (item.type == "image" ? "%" : "") + item.field + "}"
                }}</span
              >
              <span
                @click="
                  copyContent(
                    `{${item.type == 'image' ? '%' : ''}${item.field}}`
                  )
                "
              >
                <svg
                  width="14"
                  height="14"
                  viewBox="0 0 14 14"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    fill-rule="evenodd"
                    clip-rule="evenodd"
                    d="M1.85645 2.28599C1.85645 2.0493 2.04832 1.85742 2.28502 1.85742H8.71359C8.95028 1.85742 9.14216 2.0493 9.14216 2.28599C9.14216 2.52269 8.95028 2.71456 8.71359 2.71456H2.71359V8.71456C2.71359 8.95126 2.52171 9.14314 2.28502 9.14314C2.04832 9.14314 1.85645 8.95126 1.85645 8.71456V2.28599Z"
                  />
                  <path
                    fill-rule="evenodd"
                    clip-rule="evenodd"
                    d="M4.42871 4.85631C4.42871 4.61961 4.62059 4.42773 4.85728 4.42773H11.7144C11.9511 4.42773 12.143 4.61961 12.143 4.85631V11.7134C12.143 11.9501 11.9511 12.142 11.7144 12.142H4.85728C4.62059 12.142 4.42871 11.9501 4.42871 11.7134V4.85631ZM5.28585 5.28488V11.2849H11.2859V5.28488H5.28585Z"
                  />
                </svg>
              </span>
            </div>
          </div>

          <!-- <div class="d_b_step">
            <h2>第三步：上传填入后的模板文档</h2>
            <div v-if="uploadTemplateDocxData" class="d_b_s_fileCard">
              <svg
                t="1728376433028"
                class="icon"
                viewBox="0 0 1024 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="5172"
                width="200"
                height="200"
              >
                <path
                  d="M815.5 160v704c0 17.7-14.3 32-32 32h-543c-17.7 0-32-14.3-32-32V160c0-17.7 14.3-32 32-32h543c17.7 0 32 14.3 32 32z m0-96h-607c-35.3 0-64 28.7-64 64v768c0 35.3 28.7 64 64 64h607c35.3 0 64-28.7 64-64V128c0-35.3-28.7-64-64-64z"
                  p-id="5173"
                ></path>
                <path
                  d="M703.5 320h-384c-17.7 0-32-14.3-32-32s14.3-32 32-32h384c17.7 0 32 14.3 32 32s-14.3 32-32 32zM703.5 512h-384c-17.7 0-32-14.3-32-32s14.3-32 32-32h384c17.7 0 32 14.3 32 32s-14.3 32-32 32zM511.5 704h-192c-17.7 0-32-14.3-32-32s14.3-32 32-32h192c17.7 0 32 14.3 32 32s-14.3 32-32 32z"
                  p-id="5174"
                ></path>
              </svg>

              <span>{{ uploadTemplateDocxData.name }}</span>
              <span class="d_b_s_f_c_del" @click="clearUploadTemplateDocxData()"
                >删除</span
              >
            </div>
            <el-button
              class="d_b_s_button"
              type="primary"
              :disabled="uploadTemplateDocxData != null"
              @click="uploadTemplateDocx()"
              >上传填入后的模板文档</el-button
            >
          </div> -->

          <div class="d_b_step">
            <h2>第二步：点击导出</h2>
            <p></p>
            <el-button
              class="d_b_s_button"
              type="primary"
              :disabled="!downFileData"
              @click="exportDocx3()"
              >导出Word文档</el-button
            >
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import PizZip from "pizzip";
import Docxtemplater from "docxtemplater";
import ImageModule from "docxtemplater-image-module-free";
import { saveAs } from "file-saver";
import topicVue from "../../testStudent/view/component/topic.vue";
// import { renderAsync } from 'docx-preview/dist/docx-preview.js'
import VueOfficeDocx from "@vue-office/docx";
import "@vue-office/docx/lib/index.css";
// import { renderAsync } from 'docx-preview/dist/docx-preview.js'
import htmlDocx from "html-docx-js/dist/html-docx";
import txtHtmlView from "./txtHtmlView.vue";
import JSZip from "jszip";
// import a from './docx-preview.js'
const getFile = url => {
  return new Promise((resolve, reject) => {
    var credentials = {
      accessKeyId: "AKIATLPEDU37QV5CHLMH",
      secretAccessKey: "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"
    }; //秘钥形式的登录上传
    window.AWS.config.update(credentials);
    window.AWS.config.region = "cn-northwest-1"; //设置区域
    let url2 = url;
    let _url2 = "";
    if (
      url2.indexOf("https://view.officeapps.live.com/op/view.aspx?src=") != -1
    ) {
      _url2 = url2.split(
        "https://view.officeapps.live.com/op/view.aspx?src="
      )[1];
    } else {
      _url2 = url2;
    }
    var s3 = new window.AWS.S3({ params: { Bucket: "ccrb" } });
    let name = decodeURIComponent(
      _url2.split("https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/")[1]
    );
    var params = {
      Bucket: "ccrb",
      Key: name
    };
    s3.getObject(params, function(err, data) {
      if (err) {
        console.log(err, err.stack);
        resolve({ data: 1 });
      } else {
        resolve({ data: data.Body });
        console.log(data);
      }
    });
  });
};

export default {
  props: {},
  components: {
    topicVue,
    VueOfficeDocx,
    txtHtmlView
  },
  data() {
    return {
      show: false,
      loading: false,
      fieldList: [
        // { name: "第五题", field: "ti_05", type: "text", value: "第五题ti_05" },
        // {
        //   name: "图片1",
        //   field: "image_01",
        //   type: "image",
        //   value:
        //     "https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/default%2F%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_202410090922471728436994846.png"
        // }
      ],
      useFieldList: [],
      uploadTemplateDocxData: null, //上传的模板文档
      downFileData: null, // 下载模板文档的url
      checkJson: [],
      foldField: true,
      wordContent: "",
      wordContentLoading: true,
      courseId: "",
      testJson: null
      // fileList:[],
    };
  },
  methods: {
    handleClose(done) {
      this.close();
      done();
    },
    open(data) {
      this.init();
      console.log(data);
      let _fileData = data.fileData;
      this.downFileData = _fileData;
      this.courseId = data.courseId;
      this.checkJson = data.formData[0].array;
      this.testJson = data.testJson;
      this.fieldList = this.getFieldData(data.formData[0].array);
      let useFieldList = [];
      data.formData.forEach(i => {
        let obj = {
          name: i.name,
          id: i.id,
          userId: i.userid,
          fieldList: this.getFieldData(i.array),
          time: this.formatTime(i.time)
        };
        useFieldList.push(obj);
      });
      this.useFieldList = useFieldList;
      this.getWordContent(this.downFileData);
      this.show = true;
    },
    close() {
      this.show = false;
      this.init();
    },
    init() {
      // 初始化
      this.downFileData = null;
      this.fieldList = [];
      this.uploadTemplateDocxData = null;
      this.foldField = true;
      // this.fileList = [];
    },

    getFieldData(array) {
      let _list = [];
      let _index = 0;
      for (let i = 0; i < array.length; i++) {
        let _item = array[i];
        if (_item.type == 3) {
          //问答题
          let _item2 = _item.json;
          _list.push({
            name: _item2.title,
            field: `ti_${_index}`,
            type: "text",
            value: _item2.answer2
          });
          _index++;
        } else if (_item.type == 1) {
          //单选题
          let _item2 = _item.json;
          let choseTxt = ``;
          _item2.array.forEach((i, index2) => {
            choseTxt += `${
              _item2.answer2 === index2 || _item2.answer2.includes(index2)
                ? "☑"+i.option
                : ""
            }`;
          });
          _list.push({
            name: _item2.title,
            field: `ti_${_index}`,
            type: "text",
            value: choseTxt
          });
          _index++;
        } else if (_item.type == 8) {
          //日期
          let _item2 = _item.json;
          _list.push({
            name: _item2.title,
            field: `ti_${_index}`,
            type: "text",
            value: _item2.answer2
          });
          _index++;
        } else if (_item.type == 12) {
          //扫一扫
          let _item2 = _item.json;
          _list.push({
            name: _item2.title,
            field: `ti_${_index}`,
            type: "text",
            value: _item2.answer2
          });
          _index++;
        } else if (_item.type == 7) {
          //评分
          let _item2 = _item.json;
          _list.push({
            name: _item2.title,
            field: `ti_${_index}`,
            type: "text",
            value: _item2.answer2
          });
          _index++;
        } else if (_item.type == 5) {
          //附件
          let _item2 = _item.json;
          // let _value = ``;
          // _item2.file.forEach(f => {
          //   if (/\.(jpeg|jpg|gif|png|svg|bmp|webp)$/i.test(f.url)) {
          //     _value += `<img src="${f.url}" alt="${f.name}" width="100" height="100"/>
          // 		`;
          //   } else {
          //     _value += `<a href="${f.url}" target="_blank">${f.name}</a>
          // 		`;
          //   }
          // });
          _list.push({
            name: _item2.title,
            field: `ti_${_index}`,
            type: "file",
            value: _item2.file
          });
          _index++;
        }else if(_item.type == 13){
          //数字
          let _item2 = _item.json;
          _list.push({
            name:_item2.title,
            field:`ti_${_index}`,
            type:"text",
            value:`${_item2.answer2}${_item2.type=='4'?'%':''}`
          })
          _index++;
        }
      }
      return _list;
    },
    downloadTemplateDocx() {
      const officeViewer = this.$refs.vueOfficeDocxRef;
      // console.log(this.$refs.docxTemplateDialogRef)
      // console.log(officeViewer)
      const blob = new Blob([officeViewer.$el.innerHTML], {
        type:
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
      });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = this.downFileData.fileName;
      a.click();
      this.$message.success("下载成功");

      // console.log(officeViewer.$data)
      // officeViewer.exportDocx()
      // officeViewer.getContent().then(content => {
      // 	console.log(content)
      // })
      // console.log(this.$refs.vueOfficeDocxRef.$el);
      // const el = this.$refs.vueOfficeDocxRef.$el;
      // const body = el.querySelector(".docx");
      // console.log("👉",body);
      // this.generateDocx(this.downFileData.fileName,officeViewer.$el.innerHTML)
      return;
      getFile(this.downFileData.url).then(data => {
        if (data.data != 1) {
          // 下载文件, 并存成ArrayBuffer对象
          const file_name = this.downFileData.fileName; // 获取文件名
          const file_data = data.data; // 获取文件数据
          let url = window.URL.createObjectURL(new Blob([file_data]));
          let a = document.createElement("a");
          a.name = file_name;
          a.href = url;
          a.download = file_name;
          a.click();
          console.log(data);
          this.$message.success("下载成功");
        } else {
          this.$message.error("下载失败");
        }
      });
    },
    uploadTemplateDocx() {
      let input = document.createElement("input");
      input.type = "file";
      // input.accept = ".wav";
      // input.accept = "audio/*, .txt, .pdf, .xlsx";
      input.accept = ".docx";
      input.click();
      input.onchange = () => {
        this.loading = true;
        let file = input.files[0];
        if (!/\.(docx)$/i.test(file.name)) {
          this.loading = false;
          return this.$message.error("请上传.docx格式的文件");
        }
        console.log(file);
        this.uploadTemplateDocxData = file;
        this.loading = false;
        // this.uploadWavFileAndGetText(file);
      };
    },
    async exportDocx3() {
      if (!this.downFileData) return this.$message.error("请先上传模板文档");
      const el = this.$refs.vueOfficeDocxRef
        ? this.$refs.vueOfficeDocxRef.$el
        : this.$refs.txtHtmlViewRef.$el;
      const body = el.querySelector(".docx-wrapper");
      const html = body.innerHTML;
      let promiseList = [];
      this.useFieldList.forEach((i, index) => {
        promiseList.push(
          this.getUseFieldListFile({
            fileName: `${i.name}_${this.testJson.title}_${i.time}.docx`,
            fieldList: i.fieldList,
            html
          })
        );
      });
      Promise.all(promiseList).then(async res => {
        let fileList = res;
        if (fileList.length == 0) {
          this.$message.error("无文档导出");
        } else if (fileList.length == 1) {
          saveAs(fileList[0], fileList[0].name);
          this.$message.success("导出成功");
        } else {
          const zip = new JSZip();
          fileList.forEach(i => {
            zip.file(`${i.name}`, i, { binary: true });
          });
          zip.generateAsync({ type: "blob" }).then(content => {
            // 生成二进制流
            saveAs(content, `${this.testJson.title}.zip`); // 利用file-saver保存文件  自定义文件名
          });
          this.$message.success("导出成功");
        }

        if (
          !this.downFileData.txtUrl ||
          this.downFileData.txt !== el.innerHTML
        ) {
          let txt = el.innerHTML;
          // 创建Blob对象
          const blob = new Blob([txt], { type: "text/plain;charset=utf-8" });
          blob.lastModifiedDate = new Date();
          blob.name = `${this.downFileData.fileName}_wordHtml.txt`;
          let url = await this.uploadFile(blob);
          if (url && this.courseId) {
            this.downFileData.txt = txt;
            this.downFileData.txtUrl = url;
            this.changeDownFileData(this.downFileData);
            this.$forceUpdate();
          }
        }
      });
    },
    async getUseFieldListFile({ fileName, fieldList, html }) {
      return new Promise(async (resolve, reject) => {
        let _html = html;
        for (let i = 0; i < fieldList.length; i++) {
          if (fieldList[i].type == "image") {
            const img = await this.convertImageUrlToBase64(fieldList[i].value);
            _html = _html.replaceAll(
              `{%${fieldList[i].field}}`,
              `<img src="${img.url}" width="${img.width}" height="${img.height}" />`
            );
          } else if (fieldList[i].type == "text") {
            _html = _html.replaceAll(
              `{${fieldList[i].field}}`,
              fieldList[i].value
            );
          } else if (fieldList[i].type == "file") {
            let _text = ``;
            // this.fieldList[i].value.forEach(async f => {
            for (let j = 0; j < fieldList[i].value.length; j++) {
              let f = fieldList[i].value[j];
              if (/\.(jpeg|jpg|gif|png|svg|bmp|webp)$/i.test(f.url)) {
                // const img = await this.convertImageUrlToBase64(f.url);
                // _text += `<img src="${f.url}" width="${100}" height="100" style="object-fit:contain"/><br/>`;
                let _imageWidthAndHeight = await this.getImageWidthAndHeight(f.url);
                let _setWidth = 100;
                let _setHeight = (_imageWidthAndHeight.height / _imageWidthAndHeight.width) * _setWidth; // 根据比例计算高度
                _text += `<img src="${f.url}" width="${_setWidth}" height="${_setHeight}" style="object-fit:contain"/><br/>`;
                console.log(_text)
              } else {
                _text += `<a href="${f.url}" target="_blank">${f.name}</a><br/>`;
              }
            }
            _html = _html.replaceAll(`{${fieldList[i].field}}`, _text);
            // });
          }
        }

        let blob = await this.getGenerateDocxHtml(_html);
        const file = new File([blob], fileName, {
          type: ".docx",
          lastModified: new Date().getTime()
        });
        // this.fileList.push(file)
        resolve(file);
      });
    },
    async exportDocx2() {
      const el = this.$refs.vueOfficeDocxRef
        ? this.$refs.vueOfficeDocxRef.$el
        : this.$refs.txtHtmlViewRef.$el;
      console.log(el);
      const body = el.querySelector(".docx-wrapper");

      let _html = body.innerHTML;

      for (let i = 0; i < this.fieldList.length; i++) {
        if (this.fieldList[i].type == "image") {
          const img = await this.convertImageUrlToBase64(
            this.fieldList[i].value
          );
          _html = _html.replaceAll(
            `{%${this.fieldList[i].field}}`,
            `<img src="${img.url}" width="${img.width}" height="${img.height}" />`
          );
        } else if (this.fieldList[i].type == "text") {
          _html = _html.replaceAll(
            `{${this.fieldList[i].field}}`,
            this.fieldList[i].value
          );
        } else if (this.fieldList[i].type == "file") {
          let _text = ``;
          console.log(this.fieldList[i].value);
          // this.fieldList[i].value.forEach(async f=>{
          // for (let j = 0; j < this.fieldList[i].value.length; j++) {
          //   let f = this.fieldList[i].value[j];
          // 	console.log("👉f",f)
          //   if (/\.(jpeg|jpg|gif|png|svg|bmp|webp)$/i.test(f.url)) {
          //     const img = await this.convertImageUrlToBase64(f.url);
          //     _text += `<img src="${img.url}" width="${img.width}" height="${img.height}" />\n`;
          //   } else {
          //     _text += `<a href="${f.url}" target="_blank">${f.name}</a>\n`;
          //   }
          // }
          // _html = _html.replaceAll(`{${this.fieldList[i].field}}`, _text);
          // })
        }
      }
      return;
      // this.fieldList.forEach(i => {
      // _html = _html.replace(`{${i.field}}`,i.value)
      // })
      // 下载word文档
      await this.generateDocx(this.downFileData.fileName, _html);

      if (!this.downFileData.txtUrl || this.downFileData.txt !== el.innerHTML) {
        let txt = el.innerHTML;
        // 创建Blob对象
        const blob = new Blob([txt], { type: "text/plain;charset=utf-8" });
        blob.lastModifiedDate = new Date();
        blob.name = `${this.downFileData.fileName}_wordHtml.txt`;
        let url = await this.uploadFile(blob);

        if (url && this.courseId) {
          console.log("修改文件");
          console.log(url);
          console.log(this.courseId);
          this.downFileData.txt = txt;
          this.downFileData.txtUrl = url;
          this.changeDownFileData(this.downFileData);
          this.$forceUpdate();
        }
      }
      // const uploadBlob = await this.getGenerateDocxHtml(body.out)

      // let reader = new FileReader();
      // reader.readAsArrayBuffer(uploadBlob);
      // reader.onload = async e => {
      // 	try {
      // 		const binary = new Uint8Array(reader.result);
      // 		//创建一个PizZip实例
      // 		const zip = new PizZip(binary);
      // 		// 将模板内容加载到 Docxtemplater 中
      // 		const doc = new Docxtemplater().loadZip(zip);
      // 		const output = doc.getZip().generate({
      //       type: "blob",
      //       mimeType:
      //         "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      //       compression: "DEFLATE"
      //     });

      // 		const file = new File([output],this.downFileData.fileName,{type:".docx",lastModified:new Date().getTime()})

      // 		const url = await this.uploadFile(file)
      // 		console.log(url)

      // 	}catch(e){
      // 		console.log(e)
      // 	}
      // }
      // const file = new File([uploadBlob],this.downFileData.fileName,{type:".docx",lastModified:new Date().getTime()})

      // const url = await this.uploadFile(file)
      // console.log(url)
      // if(url){

      // }else{

      // }
      return;
      // const blob = await this.getGenerateDocxHtml(body.innerHTML);
      // if (!blob) return this.$message.error("导出失败");

      // let reader = new FileReader();
      // reader.readAsArrayBuffer(blob);
      // reader.onload = async e => {
      //   try {
      //     this.loading = true;
      //     const binary = new Uint8Array(reader.result);
      //     //创建一个PizZip实例
      //     const zip = new PizZip(binary);
      //     // 将模板内容加载到 Docxtemplater 中
      //     const doc = new Docxtemplater().loadZip(zip);

      //     let _data = {};
      //     let _image = {};
      //     // 设置模板值
      //     // this.fieldList.forEach(i => {
      //     //   _data[i.field] = i.value;
      //     // });
      //     for (let i = 0; i < this.fieldList.length; i++) {
      //       // console.log(this.fieldList[i])
      //       if (this.fieldList[i].type == "text") {
      //         //文本处理
      //         _data[this.fieldList[i].field] = this.fieldList[i].value;
      //       } else if (this.fieldList[i].type == "image") {
      //         //图片处理
      //         let _imageObj = await this.convertImageUrlToBase64(
      //           this.fieldList[i].value
      //         );
      //         _data[this.fieldList[i].field] = _imageObj.url;
      //         _image[this.fieldList[i].field] = {
      //           width: _imageObj.width,
      //           height: _imageObj.height
      //         };
      //       }
      //     }
      //     // return this.loading = false;

      //     // 图片处理
      //     const opts = {
      //       centered: false,
      //       fileType: "docx",
      //       getImage: (value, value2, value3) => {
      //         return this.base64DataURLToArrayBuffer(value);
      //       },
      //       getSize: (arrayValue, value, tagName) => {
      //         // console.log(_image)
      //         // console.log(tagName)
      //         let newWidth = _image[tagName].width;
      //         let newHeight = _image[tagName].height;

      //         // let newWidth = 550;
      //         // let newHeight = 100;
      //         return [newWidth, newHeight];
      //       }
      //     };
      // 		console.log()
      //     doc.attachModule(new ImageModule(opts));
      //     //渲染模板
      //     doc.setData(_data);
      //     doc.render();
      //     //获取渲染后的文本
      //     const output = doc.getZip().generate({
      //       type: "blob",
      //       mimeType:
      //         "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      //       compression: "DEFLATE"
      //     });

      //     saveAs(output, `${this.downFileData.fileName}`);
      //     // let link = document.createElement("a");
      //     // link.download = this.uploadTemplateDocxData.name;
      //     // link.style.display = "none";
      //     // let blob = new Blob([output]);
      //     // link.href = URL.createObjectURL(blob);
      //     // document.body.appendChild(link);
      //     // link.click();
      //     // document.body.removeChild(link);
      //     this.loading = false;
      //     this.$message.success("导出成功");
      //   } catch (error) {
      //     console.log(error);
      //     this.loading = false;
      //     return this.$message.error("导出失败");
      //   }
      // };
    },
    async exportDocx() {
      console.log(this.useFieldList);
      if (!this.uploadTemplateDocxData)
        return this.$message.error("请先上传模板文档");
      let reader = new FileReader();
      reader.readAsArrayBuffer(this.uploadTemplateDocxData);
      reader.onload = async e => {
        try {
          this.loading = true;
          const binary = new Uint8Array(reader.result);
          //创建一个PizZip实例
          const zip = new PizZip(binary);
          // 将模板内容加载到 Docxtemplater 中
          const doc = new Docxtemplater().loadZip(zip);

          let _data = {};
          let _image = {};
          // 设置模板值
          // this.fieldList.forEach(i => {
          //   _data[i.field] = i.value;
          // });
          for (let i = 0; i < this.fieldList.length; i++) {
            // console.log(this.fieldList[i])
            if (this.fieldList[i].type == "text") {
              //文本处理
              _data[this.fieldList[i].field] = this.fieldList[i].value;
            } else if (this.fieldList[i].type == "image") {
              //图片处理
              let _imageObj = await this.convertImageUrlToBase64(
                this.fieldList[i].value
              );
              _data[this.fieldList[i].field] = _imageObj.url;
              _image[this.fieldList[i].field] = {
                width: _imageObj.width,
                height: _imageObj.height
              };
            }
          }
          // return this.loading = false;

          // 图片处理
          const opts = {
            centered: false,
            fileType: "docx",
            getImage: (value, value2, value3) => {
              return this.base64DataURLToArrayBuffer(value);
            },
            getSize: (arrayValue, value, tagName) => {
              // console.log(_image)
              // console.log(tagName)
              let newWidth = _image[tagName].width;
              let newHeight = _image[tagName].height;

              // let newWidth = 550;
              // let newHeight = 100;
              return [newWidth, newHeight];
            }
          };
          doc.attachModule(new ImageModule(opts));
          //渲染模板
          doc.setData(_data);
          doc.render();
          //获取渲染后的文本
          const output = doc.getZip().generate({
            type: "blob",
            mimeType:
              "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            compression: "DEFLATE"
          });

          saveAs(output, `${this.uploadTemplateDocxData.name}`);
          // let link = document.createElement("a");
          // link.download = this.uploadTemplateDocxData.name;
          // link.style.display = "none";
          // let blob = new Blob([output]);
          // link.href = URL.createObjectURL(blob);
          // document.body.appendChild(link);
          // link.click();
          // document.body.removeChild(link);
          this.loading = false;
          this.$message.success("导出成功");
        } catch (error) {
          console.log(error);
          this.loading = false;
          return this.$message.error("导出失败");
        }
      };
    },
    clearUploadTemplateDocxData() {
      this.uploadTemplateDocxData = null;
    },
    copyContent(content) {
      const input = document.createElement("input");
      // 设置 display为none会导致无法复制
      // input.style.display = "none";
      // 所以只能用其他方法隐藏
      input.style.opacity = 0;
      // 为了不影响布局
      input.style.position = "fixed";
      input.style.left = "-100%";
      input.style.top = "-100%";
      input.value = content;
      document.body.appendChild(input);
      input.select();
      const success = document.execCommand("copy");
      document.body.removeChild(input);
      if (!success) {
        return this.$message.error("复制失败");
      } else {
        return this.$message.success("复制成功");
      }
    },
    convertImageUrlToBase64(imageUrl) {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.crossOrigin = "Anonymous"; // 允许跨域请求
        img.src = imageUrl;

        img.onload = () => {
          const canvas = document.createElement("canvas");
          canvas.width = img.width;
          canvas.height = img.height;
          const ctx = canvas.getContext("2d");
          ctx.drawImage(img, 0, 0);
          const base64 = canvas.toDataURL("image/png");
          resolve({ url: base64, width: img.width, height: img.height });
        };

        img.onerror = error => {
          console.log("图片转base64失败");
          console.log(error);
          resolve({ url: "", width: 0, height: 0 });
        };
      });
    },
    getImageWidthAndHeight(imageUrl){
      return new Promise((resolve)=>{
        let _img = new Image();
        _img.src = imageUrl;
        _img.onload = () =>{
          resolve({width:_img.width,height:_img.height})
        }
      })
    },
    base64DataURLToArrayBuffer(dataURL) {
      const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;
      if (!base64Regex.test(dataURL)) {
        return false;
      }
      const stringBase64 = dataURL.replace(base64Regex, "");
      let binaryString;
      if (typeof window !== "undefined") {
        binaryString = window.atob(stringBase64);
      } else {
        binaryString = new Buffer(stringBase64, "base64").toString("binary");
      }
      const len = binaryString.length;
      const bytes = new Uint8Array(len);
      for (let i = 0; i < len; i++) {
        const ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
      }
      return bytes.buffer;
    },
    async getWordContent(fileData) {
      console.log(fileData);
      this.wordContentLoading = true;
      return (this.wordContentLoading = false);
      try {
        // console.log(a)
        // let response = await getFile(fileData.url);
        // if (response.data == 1) {
        //   this.wordContentLoading = false;
        //   return this.$message.error("文件不存在");
        // }

        // await renderAsync(response.data,this.$refs.wordAreaRef);
        this.wordContentLoading = false;
      } catch (error) {
        console.log(error);
        this.wordContentLoading = false;
        this.$message.error("加载文件失败");
      }
    },
    // 导出docx
    async generateDocx(name, html) {
      // 将html文件中需要用到的数据挂载到store上
      const content = `<!DOCTYPE html>
      <html xmlns:v='urn:schemas-microsoft-com
      :vml'xmlns:o='urn:schemas-microsoft-com:office
      :office'xmlns:w='urn:schemas-microsoft-com:office
      :word'xmlns:m='http://schemas.microsoft.com/office/2004/12/omml'
      xmlns='http://www.w3.org/TR/REC-html40'
      xmlns='http://www.w3.org/1999/xhtml'>
      <head>
          <meta charset="UTF-8">
          <meta http-equiv="X-UA-Compatible" content="IE=edge">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>${name}</title>
          <style>
						*{
							font-family: '宋体';
							margin:0;
							padding:0;
							line-height:1;
						}
            table {
              border-collapse: collapse; /* 折叠边框 */
              width: 100%;
							font-size:10.5pt;
            }
            th, td {
              border: 1px solid black; /* 线条样式 */
              padding: 8px;
              text-align: left;
							font-size:10.5pt;
            }
						ol,ul{
							margin:0;
							padding:0;
							margin-right:-1in;
						}
						li{
							margin-bottom:0.1in
							margin-right:-1in;
						}
						p{
							line-height:1;
							margin:0;
							padding:0
						}
						.vue-office-docx{height:100%;overflow-y:auto}
						.vue-office-docx .docx-wrapper>section.docx{margin-bottom:5px}
						@media screen and (max-width: 800px){
							.vue-office-docx .docx-wrapper{padding:10px}
							.vue-office-docx .docx-wrapper>section.docx{padding:10px!important;width:100%!important}
						}

.docx-wrapper { background: gray; padding: 30px; padding-bottom: 0px; display: flex; flex-flow: column; align-items: center; }
.docx-wrapper>section.docx { background: white; box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); margin-bottom: 30px; }
.docx { color: black; hyphens: auto; text-underline-position: from-font; }
section.docx { box-sizing: border-box; display: flex; flex-flow: column nowrap; position: relative; overflow: hidden; }
section.docx>article { margin-bottom: auto; z-index: 1; }
section.docx>footer { z-index: 1; }
.docx table { border-collapse: collapse; }
.docx table td, .docx table th { vertical-align: top; }
.docx p { margin: 0pt; min-height: 1em; }
.docx span { white-space: pre-wrap; overflow-wrap: break-word; }
.docx a { color: inherit; text-decoration: inherit; }
.docx svg { fill: transparent; }
.docx {
  --docx-majorHAnsi-font: Calibri Light;
  --docx-minorHAnsi-font: Calibri;
  --docx-dk1-color: #000000;
  --docx-lt1-color: #FFFFFF;
  --docx-dk2-color: #44546A;
  --docx-lt2-color: #E7E6E6;
  --docx-accent1-color: #5B9BD5;
  --docx-accent2-color: #ED7D31;
  --docx-accent3-color: #A5A5A5;
  --docx-accent4-color: #FFC000;
  --docx-accent5-color: #4472C4;
  --docx-accent6-color: #70AD47;
  --docx-hlink-color: #0563C1;
  --docx-folHlink-color: #954F72;
}
.docx span {
  font-family: Times New Roman;
}
.docx p, p.docx_1 {
  text-align: justify;
}
.docx p, p.docx_1 span {
  font-family: var(--docx-minorHAnsi-font);
  min-height: 10.50pt;
  font-size: 10.50pt;
}
.docx table, table.docx_2 td {
  padding-top: 0.00pt;
  padding-left: 5.40pt;
  padding-bottom: 0.00pt;
  padding-right: 5.40pt;
}
table.docx_3 p {
  text-align: justify;
}
table.docx_3 td {
  border-top: 0.50pt solid black;
  border-left: 0.50pt solid black;
  border-bottom: 0.50pt solid black;
  border-right: 0.50pt solid black;
  padding-top: 0.00pt;
  padding-left: 5.40pt;
  padding-bottom: 0.00pt;
  padding-right: 5.40pt;
}
	p.docx-num-2-0:before {
  content: ""counter(docx-num-2-0, decimal)"、";
  counter-increment: docx-num-2-0;
}
p.docx-num-2-0 {
  display: list-item;
  list-style-position: inside;
  list-style-type: none;
}
p.docx-num-1-0:before {
  content: ""counter(docx-num-1-0, decimal)"、";
  counter-increment: docx-num-1-0;
}
p.docx-num-1-0 {
  display: list-item;
  list-style-position: inside;
  list-style-type: none;
}
.docx-wrapper {
  counter-reset: docx-num-2-0 4 docx-num-1-0 0;
}



          </style>
      </head>
      <body>
      ${html}
      </body>
      </html>`;
      // console.log(content)
      // return console.log(content)
      // debugger
      let blob = htmlDocx.asBlob(content);

      // const uploadFile = new File([blob], `${name}.docx`, {
      //   type:
      //     "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
      // });
      saveAs(blob, `${name}.docx`);
      return true;
      // this.beforeUploadHtml(uploadFile);
    },
    async getGenerateDocxHtml(html) {
      const content = `<!DOCTYPE html>
      <html xmlns:v='urn:schemas-microsoft-com
      :vml'xmlns:o='urn:schemas-microsoft-com:office
      :office'xmlns:w='urn:schemas-microsoft-com:office
      :word'xmlns:m='http://schemas.microsoft.com/office/2004/12/omml'
      xmlns='http://www.w3.org/TR/REC-html40'
      xmlns='http://www.w3.org/1999/xhtml'>
      <head>
          <meta charset="UTF-8">
          <meta http-equiv="X-UA-Compatible" content="IE=edge">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>DOCX</title>
          <style>
						*{
							font-family: '宋体';
							margin:0;
							padding:0;
							line-height:1;
						}
            table {
              border-collapse: collapse; /* 折叠边框 */
              width: 100%;
							font-size:10.5pt;
            }
            th, td {
              border: 1px solid black; /* 线条样式 */
              padding: 8px;
              text-align: left;
							font-size:10.5pt;
            }
						ol,ul{
							margin:0;
							padding:0;
							margin-right:-1in;
						}
						li{
							margin-bottom:0.1in
							margin-right:-1in;
						}
						p{
							line-height:1;
							margin:0;
							padding:0
						}
						.vue-office-docx{height:100%;overflow-y:auto}
						.vue-office-docx .docx-wrapper>section.docx{margin-bottom:5px}
						@media screen and (max-width: 800px){
							.vue-office-docx .docx-wrapper{padding:10px}
							.vue-office-docx .docx-wrapper>section.docx{padding:10px!important;width:100%!important}
						}

.docx-wrapper { background: gray; padding: 30px; padding-bottom: 0px; display: flex; flex-flow: column; align-items: center; }
.docx-wrapper>section.docx { background: white; box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); margin-bottom: 30px; }
.docx { color: black; hyphens: auto; text-underline-position: from-font; }
section.docx { box-sizing: border-box; display: flex; flex-flow: column nowrap; position: relative; overflow: hidden; }
section.docx>article { margin-bottom: auto; z-index: 1; }
section.docx>footer { z-index: 1; }
.docx table { border-collapse: collapse; }
.docx table td, .docx table th { vertical-align: top; }
.docx p { margin: 0pt; min-height: 1em; }
.docx span { white-space: pre-wrap; overflow-wrap: break-word; }
.docx a { color: inherit; text-decoration: inherit; }
.docx svg { fill: transparent; }
.docx {
  --docx-majorHAnsi-font: Calibri Light;
  --docx-minorHAnsi-font: Calibri;
  --docx-dk1-color: #000000;
  --docx-lt1-color: #FFFFFF;
  --docx-dk2-color: #44546A;
  --docx-lt2-color: #E7E6E6;
  --docx-accent1-color: #5B9BD5;
  --docx-accent2-color: #ED7D31;
  --docx-accent3-color: #A5A5A5;
  --docx-accent4-color: #FFC000;
  --docx-accent5-color: #4472C4;
  --docx-accent6-color: #70AD47;
  --docx-hlink-color: #0563C1;
  --docx-folHlink-color: #954F72;
}
.docx span {
  font-family: Times New Roman;
}
.docx p, p.docx_1 {
  text-align: justify;
}
.docx p, p.docx_1 span {
  font-family: var(--docx-minorHAnsi-font);
  min-height: 10.50pt;
  font-size: 10.50pt;
}
.docx table, table.docx_2 td {
  padding-top: 0.00pt;
  padding-left: 5.40pt;
  padding-bottom: 0.00pt;
  padding-right: 5.40pt;
}
table.docx_3 p {
  text-align: justify;
}
table.docx_3 td {
  border-top: 0.50pt solid black;
  border-left: 0.50pt solid black;
  border-bottom: 0.50pt solid black;
  border-right: 0.50pt solid black;
  padding-top: 0.00pt;
  padding-left: 5.40pt;
  padding-bottom: 0.00pt;
  padding-right: 5.40pt;
}
	p.docx-num-2-0:before {
  content: ""counter(docx-num-2-0, decimal)"、";
  counter-increment: docx-num-2-0;
}
p.docx-num-2-0 {
  display: list-item;
  list-style-position: inside;
  list-style-type: none;
}
p.docx-num-1-0:before {
  content: ""counter(docx-num-1-0, decimal)"、";
  counter-increment: docx-num-1-0;
}
p.docx-num-1-0 {
  display: list-item;
  list-style-position: inside;
  list-style-type: none;
}
.docx-wrapper {
  counter-reset: docx-num-2-0 4 docx-num-1-0 0;
}
</style>
</head>
<body>
${html}
</body>
</html>`;
      // console.log(content)
      // return console.log(content)
      // debugger
      let blob = htmlDocx.asBlob(content);
      return blob;
    },
    uploadFile(file) {
      return new Promise((resolve, reject) => {
        var credentials = {
          accessKeyId: "AKIATLPEDU37QV5CHLMH",
          secretAccessKey: "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"
        }; //秘钥形式的登录上传
        window.AWS.config.update(credentials);
        window.AWS.config.region = "cn-northwest-1"; //设置区域

        var bucket = new window.AWS.S3({ params: { Bucket: "ccrb" } }); //选择桶
        var _this = this;

        if (file) {
          // this.loading = true;
          var params = {
            Key:
              file.name.split(".")[0] +
              new Date().getTime() +
              "." +
              file.name.split(".")[file.name.split(".").length - 1],
            ContentType: file.type,
            Body: file,
            "Access-Control-Allow-Credentials": "*",
            ACL: "public-read"
          }; //key可以设置为桶的相抵路径，Body为文件， ACL最好要设置
          var options = {
            partSize: 2048 * 1024 * 1024,
            queueSize: 2,
            leavePartsOnError: true
          };
          bucket
            .upload(params, options)
            .on("httpUploadProgress", function(evt) {
              //这里可以写进度条
              _this.progressData.value = parseInt(
                (evt.loaded * 100) / evt.total
              );
              // console.log("Uploaded : " + parseInt((evt.loaded * 80) / evt.total) + '%');
            })
            .send(function(err, data) {
              if (err) {
                _this.$message.error("上传失败");
              } else {
                resolve(data.Location);
              }
            });
        }
      });
    },
    changeDownFileData(data) {
      let _data = JSON.parse(JSON.stringify(data));
      delete _data.txt;

      let params = [
        {
          cid: this.courseId,
          ncover: JSON.stringify(_data)
        }
      ];
      this.$emit("changeCover", JSON.stringify(_data));
      this.ajax
        .post(this.$store.state.api + "update_testCourseCoverById", params)
        .then(res => {
          console.log(res.data);
        });
    },
    getTxtContent(txt) {
      this.downFileData.txt = txt;
    },
    uploadWord() {
      let input = document.createElement("input");
      input.type = "file";
      // input.accept = ".wav";
      // input.accept = "audio/*, .txt, .pdf, .xlsx";
      input.accept = ".docx";
      input.click();
      input.onchange = async () => {
        this.loading = true;
        let file = input.files[0];
        if (!/\.(docx)$/i.test(file.name)) {
          this.loading = false;
          return this.$message.error("请上传.docx格式的文件");
        }
        let uploadData = await this.uploadFile(file);
        if (uploadData == 1) {
          this.loading = false;
          return this.$message.error("文件上传失败");
        }
        let obj = {
          fileName: file.name,
          url: uploadData
        };
        this.downFileData = obj;
        this.changeDownFileData(this.downFileData);
        this.loading = false;
        console.log(uploadData);
      };
    },
    formatTime(timeString) {
      let [datePart, timePart] = timeString.split(" ");
      let formattedTime =
        timePart.replace(/:/g, (match, offset) => {
          if (offset === 2) return "时";
          if (offset === 5) return "分";
          return match;
        }) + "秒";
      return datePart + " " + formattedTime;
    }
  },
  computed: {
    dialogTitle() {
      let _result = "word导出";
      if (this.useFieldList.length == 0) {
        _result = "word导出";
      } else if (this.useFieldList.length == 1) {
        _result = `${this.useFieldList[0].name}数据word导出`;
      } else {
        _result = `批量word导出`;
      }
      return _result;
    }
  }
};
</script>

<style scoped>
.dialog_diy >>> .el-dialog {
  /* height: 100%; */
  /* margin: 0 auto !important; */
}

.dialog_diy >>> .el-dialog__header {
  padding: 15px 20px;
  background-color: #454545 !important;
  color: #fff !important;
}

.dialog_diy >>> .el-dialog__body {
  height: calc(100% - 54px);
  box-sizing: border-box;
  padding: 0px;
}

.dialog_diy >>> .el-dialog__title {
  color: #fff;
}

.dialog_diy >>> .el-dialog__headerbtn {
  top: 19px;
}

.dialog_diy >>> .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

.dialog_diy >>> .el-dialog__headerbtn .el-dialog__close:hover {
  color: #fff;
}

.dialog_diy >>> .el-dialog__body,
.dialog_diy >>> .el-dialog__footer {
  background: #fff;
}

.box {
  width: 100%;
  height: 100%;
  padding: 0 20px 15px;
  display: flex;
  box-sizing: border-box;
  overflow: auto;
}

.b_left {
  flex: 1;
  height: 100%;
  border: none;
  outline: none;
  box-sizing: border-box;
  padding-top: 20px;
}

.b_right {
  flex: 1;
  min-width: 700px;
  max-width: 700px;
  height: 100%;
}

.d_box {
  width: 100%;
  height: 100%;
  overflow: auto;
}

.d_b_step {
  width: 100%;
  max-width: 100%;
  height: auto;
  padding: 20px;
  box-sizing: border-box;
  /* background-color: red; */
}

.d_b_step > h2 {
  margin-bottom: 10px;
}

.d_b_step > h3 {
  margin-top: 20px;
}

.d_b_step > p {
  font-size: 16px;
}

.d_b_step > img {
  width: 100%;
  margin-top: 10px;
}

.d_b_s_button {
  margin-top: 10px;
}

.d_b_s_fieldListItem {
  margin-top: 15px;
  font-size: 16px;
  display: flex;
  align-items: center;
}

.d_b_s_fieldListItem > span {
  display: flex;
  align-items: center;
  justify-content: center;
}

.d_b_s_fieldListItem > span > svg {
  width: 15px;
  height: 15px;
  cursor: pointer;
  fill: #000;
  margin-left: 10px;
  transition: 0.3s;
  fill-opacity: 0.6;
}

.d_b_s_fieldListItem > span > svg:hover {
  fill: #409eff;
  fill-opacity: 1;
}

.d_b_s_fileCard {
  width: 100%;
  height: 45px;
  border-radius: 2px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  padding: 0 10px;
  border: solid 1px #dfdfdf;
  position: relative;
  cursor: default;
}

.d_b_s_fileCard > svg {
  width: 30px;
  height: 30px;
  fill: #a3a8ac;
  margin-right: 10px;
}

.d_b_s_fileCard > span {
  max-width: calc(100% - 100px);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 16px;
}

.d_b_s_f_c_del {
  position: absolute;
  right: 10px;
  cursor: pointer;
  color: #e60012;
}

.d_b_s_imgList {
  margin-top: 10px;
}

.d_b_s_imgList > img {
  width: 100%;
}

.foldMenu {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin: 10px 0;
}

.foldMenu > span {
  cursor: pointer;
  color: #409eff;
  font-size: 16px;
}

.cover_box {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
