<template>
  <div>
    <div class="allContent">
      <div class="topBut">
        <div class="topBut_left">
          <el-button type="primary" size="medium" @click="downLoadFile">
            <span class="d-in-block v-mid font-size-16">下载</span>
          </el-button>
          <el-button type="primary" size="medium" @click="uplozdFile">
            <span class="d-in-block v-mid font-size-16">上传</span>
          </el-button>
        </div>
        <!-- <div class="topBut_right" @click="generatePicture">盖章</div> -->
        <div class="topBut_right">
          <span @click="toHisRecord">历史操作记录</span>
        </div>
      </div>
      <!-- <div class="ImgUrlShow" v-if="singleData.gw_ylfj_img">
        <img :src="singleData.gw_ylfj_img" alt="">
      </div> -->
      <div class="onlineShow" v-if="singleData.gw_ylfj_pdf">
        <iframe :src="prefixPDFUrl + singleData.gw_ylfj_pdf" v-if="singleData.gw_ylfj_pdf"
                style="width: 100%; min-height: 600px; border: 0" name="ifrmname" id="ifrmid"></iframe>
      </div>
      <div class="fileShow" id="exportBox" v-else>
        <div ref="imageDom" id="specialD" class="specialD">
          <div class="titleHeader">
            <div style="text-align: center">
              <img src="../../../../assets/images/fileTitle1.png" alt="" v-if="singleData.lb_id == 1"/>
              <img src="../../../../assets/images/fileTitle2.png" alt="" v-else-if="singleData.lb_id == 2"/>
              <img src="../../../../assets/images/fileTitle3.png" alt="" v-else-if="singleData.lb_id == 3"/>
              <img src="../../../../assets/images/fileTitle4.png" alt="" v-else-if="singleData.lb_id == 4"/>
              <img src="../../../../assets/images/fileTitle5.png" alt="" v-else-if="singleData.lb_id == 5"/>
              <img src="../../../../assets/images/fileTitle6.png" alt="" v-else/>
            </div>
            <div class="secPart">{{ singleData.gw_zh }}</div>
            <h3>{{ singleData.gw_title }}</h3>
            <p v-html="singleData.gw_content"></p>
          </div>
          <div class="footerInfo posiR">
            <p>景宁畲族自治县教育局</p>
            <p>{{ singleData.fb_dateline }}</p>
            <!-- 章定位 -->
            <div class="zhang" v-show="zhangSwitch">
              <img src="../../../../assets/images/zhang1.png" alt="" v-if="singleData.lb_id == 1"
                   crossorigin="“anonymous”"/>
              <img src="../../../../assets/images/zhang2.png" alt="" v-else-if="singleData.lb_id == 2"
                   crossorigin="“anonymous”"/>
              <img src="../../../../assets/images/zhang3.png" alt="" v-else-if="singleData.lb_id == 3"
                   crossorigin="“anonymous”"/>
              <img src="../../../../assets/images/zhang4.png" alt="" v-else-if="singleData.lb_id == 4"
                   crossorigin="“anonymous”"/>
              <img src="../../../../assets/images/zhang5.png" alt="" v-else-if="singleData.lb_id == 5"
                   crossorigin="“anonymous”"/>
              <img src="../../../../assets/images/zhang6.png" alt="" v-else/>
            </div>
          </div>
          <div class="reaFooter">
            <div class="reaFooter_left">{{ singleData.gw_fqks_name }}</div>
            <div class="reaFooter_right">{{ singleData.fb_dateline }}印发</div>
          </div>
        </div>
      </div>

      <div class="approvalRecord">
        <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center">
          </el-table-column>
          <el-table-column label="步骤名称">
            <template slot-scope="scope">{{ scope.row.sh_dept_name }}</template>
          </el-table-column>
          <el-table-column prop="sh_user_name" label="审核人">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <div v-if="scope.row.sh_status == 2">通过</div>
              <div v-else-if="scope.row.sh_status == 1">
                <el-button type="primary" size="mini" @click="myCheckDialog(scope.row)">
                  <span class="d-in-block v-mid font-size-16">审核</span>
                </el-button>
              </div>
              <div v-else>不通过</div>
            </template>
          </el-table-column>
          <el-table-column prop="sh_reason" label="处理意见" show-overflow-tooltip>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- dialog 审核 -->
    <el-dialog title="审核" :visible.sync="dialogFormVisible_check" @close="closeCheckDialog" width="50%">
      <el-form :model="dialogForm_check" ref="addForm_check" :rules="rules_check" label-width="90px"
               label-position="left">
        <el-form-item label="审核结果" prop="shjg">
          <el-radio-group v-model="dialogForm_check.shjg">
            <el-radio :label="2">通过</el-radio>
            <el-radio :label="3">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理意见" prop="clyj">
          <el-input type="textarea" v-model="dialogForm_check.clyj" :autosize="{ minRows: 5, maxRows: 10 }"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancleCheck()">取 消</el-button>
        <el-button type="primary" @click="addFormSubmitCheck('addForm_check')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- dialog 下载 -->
    <el-dialog title="下载" :visible.sync="dialogFormVisible_downLoad" width="600px">
      <el-form :model="dialogForm_down" ref="addForm_down" :rules="rules_down" label-width="90px" label-position="left">
        <el-form-item label="审核结果" prop="shjg">
          <el-radio-group v-model="dialogForm_down.shjg">
            <el-radio :label="2">Wps</el-radio>
            <el-radio :label="3">Office</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogFormVisible_downLoad = false">取 消</el-button>
        <el-button type="primary" @click="addFormSubmitDownLoad('addForm_down')">下载</el-button>
      </div>
    </el-dialog>

    <!-- dialog 上传 -->
    <el-dialog title="上传" :visible.sync="dialogFormVisible_upload" width="600px" v-loading="uploadLoading"
               class="uploadDiacla">
      <el-form :model="dialogForm_upload" label-width="120px" label-position="left" ref="addForm_upload">
        <el-form-item label="上传文件">
          <!-- :rules="rules_upload" -->
          <el-upload v-model="dialogForm_upload.fj" class="upload-demo" action="#" :http-request="appendixHttpRequest"
                     :on-remove="handleRemoveAppendix" :limit="1" :file-list="appendixList" accept=".doc,.docx">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              支持文件类型:.doc(.docx)文件格式
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogFormVisible_upload = false">取 消</el-button>
        <el-button type="primary" @click="formSubmit_upload('addForm_upload')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- dialog 最终文稿预览 -->
    <el-dialog title="最终发文预览" :visible.sync="dialogFormVisible_finalview" width="794px" class="finalView"
               @close="closeFinalDialog" v-loading.fullscreen="finalLoading">
      <div class="moveBox" style="min-height:300px;">
        <div class="imgView" id="finalIma" ref="finalimageDomOut" style="position: relative; width: 100%">
          <!-- <div ref="finalimageDom" id="finalimageDomId" style="min-height:100px;" v-if="finalViewSwitch"></div> -->
          <div ref="finalimageDom" id="finalimageDomId" style="min-height:100px;">
            <img :src="item" v-for="(item, index) in uploadPdfImg" :key="index" alt="">
          </div>
          <VueDragResize>
            <!-- draggable="true" @dragstart="dragstart($event)" @dragend="dragend($event)" :style="`right:${elLeft}px;bottom:${elTop}px`" -->
            <div class="lastZhang" ref="lastZhang" :w="currentImgW" :h="currentImgH" :z="2" :isResizable="false"
                 :parent-limitation="true">
              <img src="../../../../assets/images/zhang1.png" alt="" v-if="singleData.lb_id == 1"
                   crossorigin="“anonymous”"/>
              <img src="../../../../assets/images/zhang2.png" alt="" v-else-if="singleData.lb_id == 2"
                   crossorigin="“anonymous”"/>
              <img src="../../../../assets/images/zhang3.png" alt="" v-else-if="singleData.lb_id == 3"
                   crossorigin="“anonymous”"/>
              <img src="../../../../assets/images/zhang4.png" alt="" v-else-if="singleData.lb_id == 4"
                   crossorigin="“anonymous”"/>
              <img src="../../../../assets/images/zhang5.png" alt="" v-else-if="singleData.lb_id == 5"
                   crossorigin="“anonymous”"/>
              <img src="../../../../assets/images/zhang6.png" alt="" v-else/>
            </div>
          </VueDragResize>

        </div>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="finalConfirmPosi()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import  htmlDocx from "html-docx-js/dist/html-docx";
// import saverFile from "file-saver";
import docxtemplater from "docxtemplater";
import PizZip from "pizzip";
import JSZipUtils from "jszip-utils";
import {saveAs} from "file-saver";
// import  htmlDocx from "@/html-docx-js/dist/html-docx";
import html2canvas from "html2canvas";
import * as PDFJS from "pdfjs-dist";
import * as pdfjsLib from "pdfjs-dist";
import pdfjsWorker from "pdfjs-dist/build/pdf.worker.entry";
import VueDragResize from 'vue-drag-resize'
import {
  common_edit,
  common_detail,
  gw_check,
  gw_download,
  gw_expWord,
  org_users,
} from "./itemApi";
import {request} from "@/utils/request";
import {useUserStore} from "@/stores/user";

const {real_name, user_id, dept_ids, token} = useUserStore();
export default {
  name: "sh",
  components: {
    VueDragResize
  },
  data() {
    const validateLogo = (rule, value, callback) => {
      if (!this.dialogForm_lxmb.fj) {
        callback(new Error("请上传附件"));
      } else {
        callback();
      }
    };
    return {
      singleData: "",
      tableData: [],
      uploadPdfImg: '',
      multipleSelection: [],
      dialogFormVisible_check: false,
      dialogForm_check: {
        shjg: "",
        clyj: "",
      },
      rules_check: {
        shjg: [
          {required: true, message: "请选择审核结果", trigger: "change"},
        ],
        clyj: [{required: true, message: "请输入处理意见", trigger: "blur"}],
      },
      formLabelWidth: "120px",
      dialogFormVisible_downLoad: false,
      dialogForm_down: {
        shjg: "",
      },
      rules_down: {
        shjg: [
          {required: true, message: "请选择审核结果", trigger: "change"},
        ],
      },
      gwId: "",
      dialogFormVisible_upload: false,
      dialogForm_upload: {
        fj: "",
      },
      rules_upload: {
        fj: [{required: true, validator: validateLogo, trigger: "change"}],
      },
      appendixList: [],
      extraParameters: {
        api: "json",
        urltype: 2,
      },
      updateUrl: window.globalVariables.api + "upload/main/file",
      officeFixedUrl: "https://view.officeapps.live.com/op/view.aspx?src=",
      prefixPDFUrl:
          window.globalVariables.api + "/plugins/pdf.js/web/viewer2.html?file=",
      titlePngUrl: "",
      zhangUrl: "",
      transImgUrl: "",
      zhangSwitch: false,
      lastOne: false,
      curLcId: "",
      transfile: "",
      fullPathImgUrl: "",
      uploadLoading: false,
      dialogFormVisible_finalview: false,
      pdfPicturePath: "",
      finalSwitch: false,

      finalViewSwitch: false,
      finalLoading: false,

      initWidth: 0,//父元素的宽-自适应值
      initHeight: 0,//父元素的高-自适应值
      startclientX: 0,//元素拖拽距离浏览器的x的位置
      startclientY: 0,//元素拖拽距离浏览器的y的位置
      elLeft: 163,//元素的左偏移量
      elTop: 260,//元素的右偏移量

      currentImgW: 120,
      currentImgH: 120,

    };
  },
  mounted() {
    this.transId = this.$route.params.id;
    this.initData();
  },
  methods: {
    initData() {
      let transObj = {
        gw_id: this.transId,
      };
      common_detail(transObj)
          .then((res) => {
            if (res.code == "1") {
              this.singleData = res.data.one_info;
              this.tableData = res.data.one_info.shjl;
              this.uploadPdfImg = JSON.parse(res.data.one_info.gw_img_list);
            }
          })
          .catch((err) => {
            console.log(err);
          });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //提交dialog弹出
    myCheckDialog(item) {
      this.dialogForm_check = {
        shjg: "",
        clyj: "",
      };
      this.gwId = item.gw_id;
      this.curLcId = item.lc_id;
      //这里要判断下 登录的人和审核人是否是同一人
      let ShPerson = item.sh_user_id;
      let localPerson = user_id;
      if (ShPerson == localPerson) {
        //同一人
        this.dialogFormVisible_check = true;
        //判断是否是最后一个人审核
        let lastLcId = this.singleData.shjl.pop().lc_id;
        if (this.curLcId == lastLcId) {
          //最后一个人审核
          this.zhangSwitch = true;
          this.lastOne = true;
        } else {
          this.zhangSwitch = false;
          this.lastOne = false;
        }
      } else {
        this.$message({
          message: "请审核自己的项目",
          type: "error",
        });
        return;
      }
    },
    //审核关闭按钮事件
    closeCheckDialog() {
      this.dialogFormVisible_check = false;
      this.zhangSwitch = false;
      this.initData();
    },
    //审核dialog取消
    cancleCheck() {
      this.dialogFormVisible_check = false;
      this.zhangSwitch = false;
      this.initData();
    },
    //审核提交
    addFormSubmitCheck(formName) {
      let ifPDFurl = this.singleData.gw_ylfj_pdf;
      if (ifPDFurl) {//这里说明 已经上传了word 处于pdf预览
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.dialogForm_check.shjg == 3) {//审核不通过
              let transObj = {
                gw_id: this.gwId, //项目ID
                sh_status: this.dialogForm_check.shjg,
                sh_reason: this.dialogForm_check.clyj,
                file_url: "",
              };
              gw_check(transObj)
                  .then((res) => {
                    if (res.code == "1") {
                      this.$message({
                        message: res.msg,
                        type: "success",
                      });
                      this.initData();
                      this.dialogFormVisible_check = false;
                    } else {
                      this.$message({
                        message: res.msg,
                        type: "error",
                      });
                    }
                  })
                  .catch((err) => {
                    console.log(err);
                  });

            } else {//审核通过
              //弹出新的确认公文界面
              // this.readPdf(ifPDFurl);
              if (this.lastOne) {//最后一人审核
                this.dialogFormVisible_finalview = true;//弹出确认框
              } else {//不是最后一人 其他审核人同意
                let transObj = {
                  gw_id: this.gwId, //项目ID
                  sh_status: this.dialogForm_check.shjg,
                  sh_reason: this.dialogForm_check.clyj,
                  file_url: "",
                };
                gw_check(transObj)
                    .then((res) => {
                      if (res.code == "1") {
                        this.$message({
                          message: res.msg,
                          type: "success",
                        });
                        this.initData();
                        this.dialogFormVisible_check = false;
                      } else {
                        this.$message({
                          message: res.msg,
                          type: "error",
                        });
                      }
                    })
                    .catch((err) => {
                      console.log(err);
                    });
              }

            }
          }
        });
      } else {//这里是还没有上传word的时候处理的方法
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.dialogForm_check.shjg == 3) {//审核不通过
              let transObj = {
                gw_id: this.gwId, //项目ID
                sh_status: this.dialogForm_check.shjg,
                sh_reason: this.dialogForm_check.clyj,
                file_url: "",
              };
              gw_check(transObj)
                  .then((res) => {
                    if (res.code == "1") {
                      this.$message({
                        message: res.msg,
                        type: "success",
                      });
                      this.initData();
                      this.dialogFormVisible_check = false;
                    } else {
                      this.$message({
                        message: res.msg,
                        type: "error",
                      });
                    }
                  })
                  .catch((err) => {
                    console.log(err);
                  });
            } else {//没有上传Word且点击了通过
              html2canvas(this.$refs.imageDom, {
                allowTaint: true,
                useCORS: true,
                width: 794,
              }).then((canvas) => {
                var cans = canvas.toDataURL("image/jpeg", 1.0);
                this.transImgUrl = cans;
                let str = this.base64toFile(cans, "file");
                let formData = new FormData();
                //调用图片上传接口
                formData.append("filedata", str);
                formData.append("api", "json");
                formData.append("token", token);
                formData.append("urltype", "0");
                request({
                  url: "upload/main/file",
                  data: formData,
                  timeout: 1000 * 60,
                }).then((res) => {
                  if (res.code == "1") {
                    this.fullPathImgUrl = res.data.url;
                    let transObj = {
                      gw_id: this.gwId, //项目ID
                      sh_status: this.dialogForm_check.shjg,
                      sh_reason: this.dialogForm_check.clyj,
                      file_url: this.fullPathImgUrl,
                    };
                    gw_check(transObj)
                        .then((res) => {
                          if (res.code == "1") {
                            this.$message({
                              message: res.msg,
                              type: "success",
                            });
                            this.initData();
                            this.dialogFormVisible_check = false;
                          } else {
                            this.$message({
                              message: res.msg,
                              type: "error",
                            });
                          }
                        })
                        .catch((err) => {
                          console.log(err);
                        });
                  }
                });
              });
            }
          }
        })


      }
    },
    //最终预览-关闭按钮
    closeFinalDialog() {
      this.dialogFormVisible_finalview = false;
      this.finalSwitch = false;
      this.finalViewSwitch = false;
    },
    //最终预览-确定
    finalConfirmPosi() {
      this.finalLoading = true;
      let that = this;
      setTimeout(function () {
        that.finalSwitch = true;
      }, 100)
      html2canvas(this.$refs.finalimageDomOut, {
        allowTaint: true,
        useCORS: true,
        width: 794,
      }).then((canvas) => {
        var cans = canvas.toDataURL("image/jpeg", 1.0);
        // this.transImgUrl = cans;
        let str = this.base64toFile(cans, "file");
        let formData = new FormData();
        //调用图片上传接口
        formData.append("filedata", str);
        formData.append("api", "json");
        formData.append("token", token);
        formData.append("urltype", "0");
        request({
          url: "upload/main/file",
          data: formData,
          timeout: 1000 * 60,
        }).then((res) => {
          if (res.code == "1") {
            this.finalLoading = false;
            this.fullPathImgUrl = res.data.url;
            this.$message({
              message: "确认最终发文成功~",
              type: "success",
            });
            this.dialogFormVisible_finalview = false;
            //这里调用
            let transObj = {
              gw_id: this.gwId, //项目ID
              sh_status: this.dialogForm_check.shjg,
              sh_reason: this.dialogForm_check.clyj,
              file_url: this.fullPathImgUrl,
            };
            gw_check(transObj)
                .then((res) => {
                  if (res.code == "1") {
                    this.$message({
                      message: res.msg,
                      type: "success",
                    });
                    this.initData();
                    this.dialogFormVisible_check = false;
                  } else {
                    this.$message({
                      message: res.msg,
                      type: "error",
                    });
                  }
                })
                .catch((err) => {
                  console.log(err);
                });
          }
        })

      })

    },

    //base64转图片file
    base64toFile(data, fileName) {
      let dataArr = data.split(",");
      const byteString = atob(dataArr[1]);
      const options = {
        type: "image/jpeg",
        endings: "native",
      };
      const u8Arr = new Uint8Array(byteString.length);
      for (let i = 0; i < byteString.length; i++) {
        u8Arr[i] = byteString.charCodeAt(i);
      }
      return new File([u8Arr], fileName + ".jpg", options);
    },
    //下载-打开wps-office 弹窗
    downLoadFile() {
      this.dialogFormVisible_downLoad = true;
    },
    //下载提交
    addFormSubmitDownLoad(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let transObj = {
            api: "xml",
            gw_id: this.singleData.gw_id, //项目ID
          };
          gw_download(transObj)
              .then((res) => {
                if (res.code == "1") {
                  //后端下载模版处理
                  // this.downloadWord(this.singleData);
                  //前端处理
                  this.exportDoc()
                  // this.initData();
                  this.dialogFormVisible_downLoad = false;
                } else {
                  this.$message({
                    message: res.msg,
                    type: "error",
                  });
                }
              })
              .catch((err) => {
                console.log(err);
              });
        }
      });
    },
    // 下载(导出word)--后端处理(停用)
    downloadWord(item) {
      let gwId = item.gw_id;
      let transObj = {
        gw_id: gwId,
        export_word: 1, //1:word;2:pdf;
      };
      gw_expWord(transObj)
          .then((res) => {
            if (res.code == "1") {
              window.open(res.data.file_url, "_blank");
              this.$message({
                message: res.msg,
                type: "success",
              });
            } else {
              this.$message({
                message: res.msg,
                type: "error",
              });
            }
            console.log(res);
          })
          .catch((err) => {
            console.log(err);
          });
    },
    //导出页面为word
    exportDoc() {
      let singleData = this.singleData;
      switch (singleData.lb_id) {
        case "1":
          this.titlePngUrl = this.getAssetsImages("fileTitle1");
          this.zhangUrl = this.getAssetsImages("zhang1");
          break;
        case "2":
          this.titlePngUrl = this.getAssetsImages("fileTitle2");
          this.zhangUrl = this.getAssetsImages("zhang2");
          break;
        case "3":
          this.titlePngUrl = this.getAssetsImages("fileTitle3");
          this.zhangUrl = this.getAssetsImages("zhang3");
          break;
        case "4":
          this.titlePngUrl = this.getAssetsImages("fileTitle4");
          this.zhangUrl = this.getAssetsImages("zhang4");
          break;
        case "5":
          this.titlePngUrl = this.getAssetsImages("fileTitle5");
          this.zhangUrl = this.getAssetsImages("zhang5");
          break;
        case "6":
          this.titlePngUrl = this.getAssetsImages("fileTitle6");
          this.zhangUrl = this.getAssetsImages("zhang6");
          break;
      }
      let titlePngUrl = this.titlePngUrl;
      let zhangUrl = this.zhangUrl;

      let str = `
      <div class="titleHeader">
          <div style="text-align:center;">
            <img src="${singleData.gw_title_png}" style="width:100%;" alt="">
          </div>
          <div class="secPart" style="text-align: center;font-size: 16px;border-bottom: 3px solid red;margin-top: 50px;box-sizing: border-box;padding: 10px 0; border-bottom: 3px solid red;font-family: 仿宋_GB2312; font-size: 16pt;">${singleData.gw_zh}</div>
          <h3 style="text-align: center;margin-top:10px;margin-bottom:10px;font-family: 方正小标宋简体; font-size: 22pt;">${singleData.gw_title}</h3>
          <div >${singleData.gw_content}</div>
        </div>
        <div class="footerInfo" style="text-align: right;font-family: 仿宋_GB2312; font-size: 16pt;">
          <p>景宁畲族自治县教育局</p>
          <p>${singleData.fb_dateline}</p>
        </div>
        <div class="reaFooter" style="overflow:hidden;border-top: 1px solid #000;border-bottom: 1px solid #000;">
          <span class="reaFooter_left" style="width: 45%;text-align: left; font-family: 仿宋_GB2312; font-size: 16pt;float:left;">${singleData.gw_fqks_name}</span>
          <span class="reaFooter_right" style="width: 50%;text-align: right;font-family: 仿宋_GB2312; font-size: 16pt;float:right;">${singleData.fb_dateline}印发</span>
        </div>
      `;

      let htmlStr = `
      <!DOCTYPE html>
      <html lang="en">
        <body>
        <style type="text/css">
          @page{
            mso-page-border-surround-header:no;
            mso-page-border-surround-footer:no;
          }
          @page Section0{
              margin:104.9pt 73.7pt 99.2pt 79.4pt;
              size:595.3000pt 841.9000pt;
              layout-grid:15.6000pt;
              mso-header-margin:142.5500pt;
              mso-footer-margin:149.6000pt;
          }
          div.Section0{
            page:Section0;
          }
        </style>
          <div class="Section0">
           ${str}
          </div>

        </body>
      </html>
`;
      const node = htmlStr;
      const html = this.getModelHtml(node, this.singleData);
      const blob = new Blob([html], {
        type: "application/msword;charset=utf-8",
      });
      saveAs(blob, `${singleData.gw_title}.docx`);
    },
    getModelHtml(mhtml, row) {
      return `<!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">
      <head>
        <!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian><w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><w:BreakWrappedTables/><w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/><w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/><w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><m:mathPr><m:mathFont m:val="Cambria Math"/><m:brkBin m:val="before"/><m:brkBinSub m:val="--"/><m:smallFrac m:val="off"/><m:dispDef/><m:lMargin m:val="0"/> <m:rMargin m:val="0"/><m:defJc m:val="centerGroup"/><m:wrapIndent m:val="1440"/><m:intLim m:val="subSup"/><m:naryLim m:val="undOvr"/></m:mathPr></w:WordDocument></xml><![endif]-->

          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width,initial-scale=1.0">
          <title>${row.gw_title}</title>

      </head>
      <body>
          <div style="display: flex;justify-content: center;">
            ${mhtml}
          </div>
      </body>
      </html>`;
    },
    //上传
    uplozdFile() {
      this.dialogFormVisible_upload = true;
      this.appendixList = [];
    },
    //上传提交
    formSubmit_upload() {
      //这里要判断上传的是否为空文件
      if (this.appendixList.length == 0) {
        //传递的是空值
        this.$message({
          message: "无上传附件，请添加上传附件~",
          type: "error",
        });
        return;
      }
      this.uploadLoading = true;
      let transObj = {
        issubmit: 1,
        gw_id: this.transId,
        jdbg_gwgl_gw: {
          gw_ylfj: this.appendixList[0].url,
        },
      };
      common_edit(transObj)
          .then((res) => {
            if (res.code == "1") {
              this.uploadLoading = false;
              this.$message({
                message: res.msg,
                type: "success",
              });
              this.initData();
              this.dialogFormVisible_upload = false;
            }
          })
          .catch((err) => {
            console.log(err);
          });
    },
    /**附件上传网络请求*/
    appendixHttpRequest(param) {
      const {token} = useUserStore();
      let file = param.file;
      let formData = new FormData();
      formData.append("filedata", file);
      formData.append("api", this.extraParameters.api);
      formData.append("urltype", this.extraParameters.urltype);
      formData.append("token", token);
      //发起axios请求
      let that = this;
      that
          .$axios({
            method: "post",
            url: this.updateUrl,
            headers: {"Content-Type": "multipart/form-data"},
            data: formData,
          })
          .then((res) => {
            var response = res.data;
            if (response.code == "1") {
              this.appendixList = [];
              //单个上传后台返回的是相对地址
              let tempArr = {
                name: response.data.file_name,
                url: response.data.url,
              };
              //存入appendixList列表中
              this.appendixList.push(tempArr);
              this.dialogForm_upload.fj = this.appendixList;
              this.$message({
                message: response.msg,
                type: "success",
              });
            }
          })
          .catch((error) => {
            console.log(error);
          });
    },
    /**附件删除*/
    handleRemoveAppendix(file, fileList) {
      console.log(file, fileList);
      var fileName = file.name;
      this.appendixList = this.appendixList.filter(
          (item) => item.name !== fileName
      );
    },
    //跳转历史编辑记录
    toHisRecord(item) {
      let transId = this.singleData.gw_id;
      this.$router.push({
        name: "gwglxt_dbfw_lsbjjl",
        params: {id: transId},
      });
    },
    //盖章（停用）
    singin() {
      let transId = this.singleData.gw_id;
      this.$router.push({name: "gwglxt_dbfw_dzqz", params: {id: transId}});
    },
    // 初始化pdf插件（停用）
    readPdf(fileUrl) {
      pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker;
      let self = this;
      self.finalViewSwitch = true;
      self.pdfPicturePath = "";
      const loadingTask = PDFJS.getDocument(fileUrl);
      loadingTask.promise
          .then(function (pdf) {
            if (pdf) {
              // pdf 总页数
              const pageNum = pdf.numPages;
              for (let i = 1; i <= pageNum; i++) {
                // 生成每页 pdf 的 canvas
                const canvas = document.createElement("canvas");
                canvas.id = "pageNum" + i;
                // 将 canvas 添加到 dom 中,docView(存放canvas的div)
                self.$refs.finalimageDom.append(canvas);
                //getContext() 方法返回一个用于在画布上绘图的环境。
                const context = canvas.getContext("2d");
                self.openPage(pdf, i, context);
              }
              setTimeout(() => {
                self.exportImg(self);
              }, 1000);
            }
          })
          .catch(function (reason) {
            console.error("Error: " + reason);
          });
      // };
    },
    // pdf转成canvas（停用）
    openPage(pdfFile, pageNumber, context) {
      let scale = 2;
      let that = this;
      pdfFile.getPage(pageNumber).then(function (page) {
        // reference canvas via context
        const viewport = page.getViewport(scale);
        let canvas = context.canvas;
        canvas.width = viewport.width;
        canvas.height = viewport.height;
        canvas.style.width = "100%";
        canvas.style.height = "100%";
        let renderContext = {
          canvasContext: context,
          viewport: viewport,
        };
        page.render(renderContext);
        that.loading = false;
      });
      return;
    },
    // canvas转成图片（停用）
    exportImg(self) {
      this.finalSwitch = true;
      let canvaslist = document.querySelectorAll("canvas");
      for (let i = 0; i < canvaslist.length; i++) {
        // let canvas = document.getElementById("pageNum" + (i + 1));
        // // 将 canvas 转成 base64 格式的图片
        // let base64ImgSrc = (canvas as any).toDataURL("image/png")
        // const img = document.createElement("img")
        // img.setAttribute('class', 'pdf-img');
        // img.src = base64ImgSrc
        // img.style.width = '100%';
        // // 将图片挂载到 dom 中
        //   (self.$refs as any).docView.append(img);
        let canvasNode = document.getElementById("pageNum" + (i + 1));
        // 将 canvas 转成 base64 格式的图片
        this.pdfPicturePath = canvasNode.toDataURL("image/png");
      }
    },
    //网页转图片(base64->blob->file)
    generatePicture() {
      html2canvas(this.$refs.imageDom).then((img) => {
        this.transImgUrl = img.toDataURL("image/png", 1.0); //可将 canvas 转为 base64 格式 , 清晰度 0 - 1
        const dataArr = this.transImgUrl.split(",");
        const byteString = atob(dataArr[1]);
        const options = {
          type: "image/jpeg",
          endings: "native",
        };
        const u8Arr = new Uint8Array(byteString.length);
        for (let i = 0; i < byteString.length; i++) {
          u8Arr[i] = byteString.charCodeAt(i);
        }
        return new File([u8Arr], this.singleData.gw_title + ".jpg", options); //返回文件流

        // //将base64转换为blob
        // var arr = this.transImgUrl.split(','),
        // mime = arr[0].match(/:(.*?);/)[1],
        // bstr = atob(arr[1]),
        // n = bstr.length,
        // u8arr = new Uint8Array(n);
        // while (n--) {
        //     u8arr[n] = bstr.charCodeAt(n);
        // }
        // let theBlob=  new Blob([u8arr], { type: mime });
        //   //将blob转换为file
        // theBlob.lastModifiedDate = new Date();
        // theBlob.name = this.singleData.gw_title;
        // this.transfile = theBlob;
      });

      // let transBlob =this.dataURLtoBlob(this.transImgUrl);
      // this.transfile = this.blobToFile(transBlob, imgName);
    },
    //将base64转换为blob
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(","),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {type: mime});
    },
    //将blob转换为file
    blobToFile(theBlob, fileName) {
      theBlob.lastModifiedDate = new Date();
      theBlob.name = fileName;
      return theBlob;
    },
    //获取图片
    getAssetsImages(name) {
      // return new URL(`/app/jdbg/public/tempImg/${name}.png`, import.meta.url).href;
      return new URL(`/public/tempImg/${name}.png`, import.meta.url).href;
    },
    //拖拽事件的开始
    dragstart(e) {
      //
      this.initWidth = this.$refs.finalimageDomOut.clientWidth; // 拿到父元素宽
      this.initHeight = this.$refs.finalimageDomOut.clientHeight;

      this.startClientX = e.clientX;
      this.startClientY = e.clientY;
    },
    //拖拽进行
    dragOver(e) {
      let x = this.startClientX - e.clientX;
      let y = this.startClientY - e.clientY;
      this.elLeft += x;
      this.elTop += y;
    },
    //拖拽事件的完成
    dragend(e) {
      let x = this.startClientX - e.clientX;//这里指的偏移量
      let y = this.startClientY - e.clientY;
      //获取目前图片的大小
      // let currentImgW = document.querySelector('.lastZhang img').offsetWidth;
      // let currentImgH = document.querySelector('.lastZhang img').offsetHeight;

      let currentImgW = this.$refs.lastZhang.offsetWidth;
      let currentImgH = this.$refs.lastZhang.offsetHeight;
      let halfCurrentImgW = currentImgW / 2;
      let halfCurrentImgH = currentImgH / 2;

      /**
       * x:正值为往左拖动，负值为往右拖动
       * y:正值往上拖动，负值为向下拖动
       */
      if (x >= 0 && y >= 0) {//左上角拖动
        this.elLeft = this.elLeft + x + (halfCurrentImgW);
        this.elTop = this.elTop + y - (halfCurrentImgH);
      } else if (x >= 0 && y <= 0) {//左小角
        this.elLeft = this.elLeft + x + (halfCurrentImgW);
        this.elTop = this.elTop + y - (halfCurrentImgH);
      } else if (x <= 0 && y >= 0) {//右上角
        this.elLeft = this.elLeft + x + (halfCurrentImgW);
        this.elTop = this.elTop + y - (halfCurrentImgH);
      } else {//右小角
        this.elLeft = this.elLeft + x + (halfCurrentImgW);
        this.elTop = this.elTop + y - (halfCurrentImgH);
      }
    },

  },
};
</script>

<style lang="scss" scoped>
@import url("../../../../styles/documentOnlineRev.scss");

.vdr.active:before {
  display: none;
}

.topBut {
  display: flex;
  flex-direction: row;
  height: 70px;
  line-height: 70px;
  box-sizing: border-box;
  padding: 0 2% 0 0;
  border-bottom: 1px solid #000;
}

.topBut_left {
  width: 50%;
}

.topBut_right {
  flex: 1;
  text-align: right;
  font-size: 16px;
  font-weight: 400;
  color: #265cd4;
  cursor: pointer;
}

.fileShow {
  min-height: 300px;
  box-sizing: border-box;
  padding: 5% 0;
  font-family: "方正仿宋_GBK";
}

.specialD {
  width: 210mm;
  margin: 0 auto;
  box-sizing: border-box;
  padding: 84px 78px 20px 78px;
  // box-shadow: 0 0 2px #000; 
  overflow: hidden;
}

.ImgUrlShow {
  min-height: 400px;
  text-align: center;
}

.ImgUrlShow img {
  display: inline-block;
}

.onlineShow {
  min-height: 400px;
  text-align: center;
}

.posiR {
  position: relative;
}

.zhang {
  position: absolute;
  right: 10%;
  bottom: -50%;
  z-index: 13;
}

.lastZhang {
  position: absolute;
  right: 13%;
  bottom: 10%;
  z-index: 14;
  user-select: none;
}
</style>
