<!-- @format -->

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="17">
        <div style="height: 77vh" id="WebOffice2015"></div>
      </el-col>
      <el-col :span="7">
        <el-tabs type="border-card" class="demo-tabs">
          <el-tab-pane>
            <template #label>
              <span style="display: flex" class="custom-tabs-label">
                <el-icon style="margin-top: 13px"><Document /></el-icon>
                <span
                  style="
                    display: inline-block;
                    padding-bottom: 10px;
                    margin-left: 3px;
                  "
                  >文件概况</span
                >
              </span>
            </template>
            <el-form
              ref="receivedFormRef"
              label-width="105px"
              style="width: 20vw; height: 87.5vh"
              :rules="rules"
              :model="ywJournalPublishParams"
            >
              <el-form-item label="">
                <el-button
                  :loading="openFileState"
                  @click="openLocalFile()"
                  type="primary"
                  >打开本地文档
                </el-button>
              </el-form-item>
              <el-form-item label="投稿人处室:" prop="deptName">
                <el-input
                  disabled
                  v-model="ywJournalPublishParams.deptName"
                  placeholder="请输入投稿人处室"
                ></el-input>
              </el-form-item>
              <el-form-item label="投稿人姓名:" prop="userName">
                <el-input
                  disabled
                  v-model="ywJournalPublishParams.userName"
                  placeholder=" 请输入投稿人姓名"
                ></el-input>
              </el-form-item>
              <el-form-item label="论文名称:" prop="paperName">
                <el-input
                  v-model="ywJournalPublishParams.paperName"
                  placeholder="请输入论文名称"
                ></el-input>
              </el-form-item>
              <el-form-item label="期刊级别:" prop="journalLevel">
                <el-input
                  v-model="ywJournalPublishParams.journalLevel"
                  placeholder="请输入期刊级别"
                ></el-input>
              </el-form-item>
              <el-form-item label="发表期刊的年、卷、期:" prop="journalNumber">
                <el-input
                  style="margin: 15px 0"
                  v-model="ywJournalPublishParams.journalNumber"
                  placeholder="请输入发表期刊的年、卷、期"
                ></el-input>
              </el-form-item>
              <el-form-item label="版面费金额:" prop="layoutFees">
                <el-input
                  v-model="ywJournalPublishParams.layoutFees"
                  placeholder="请输入版面费金额"
                  :formatter="
                    (value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
                  "
                  :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
                  ><template #append>元</template></el-input
                >
              </el-form-item>
              <!--              <el-form-item label="报销金额:" prop="eliminateMoney">
                <el-input
                    v-model="ywJournalPublishParams.eliminateMoney"
                    placeholder="请输入报销金额"
                    :formatter="(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                    :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
                ><template #append>元</template></el-input>
              </el-form-item>-->
              <el-form-item label="登记日期:" prop="registrationDate">
                <el-date-picker
                  style="width: 20vw"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  v-model="ywJournalPublishParams.registrationDate"
                  type="date"
                  placeholder="请选择登记日期"
                  size="defalut"
                />
              </el-form-item>
              <el-form-item label="添加附件:">
                <el-upload
                  ref="fujianUpload"
                  v-model:file-list="fujianList"
                  :action="upload.url"
                  :headers="upload.headers"
                  :on-success="uploadFuJianFiles"
                  :disabled="isAllowed"
                  multiple
                >
                  <el-button type="primary">点击上传附件</el-button>
                </el-upload>
              </el-form-item>

              <el-form-item>
                <div style="margin: 0 auto">
                  <el-button
                    style="padding: 8px 35px"
                    :loading="loadingWebLoad"
                    @click="onSubmit(receivedFormRef)"
                    type="primary"
                    >提交</el-button
                  >
                </div>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <select-user
      ref="selectRef"
      @ok="handleQuery"
      @closeDialogf="closePage(1)"
    ></select-user>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import Cookies from "js-cookie";
import { detectOS, initOffice } from "@/static/webOffice/KingiWebOffice2015";

// import WebOffice2015 from "../../../static/webOffice/WebOffice";
import { getRequest, GetUrlbase, getUrlParameter } from "../hookFunction";
import { getInfo } from "@/api/login";
import { startPublish } from "@/api/office/publish";
import { uploadFile, base64toBlob } from "@/api/system/oafile";
import { getToken } from "@/utils/auth";
import { ElMessage } from "element-plus";
const { proxy } = getCurrentInstance();

const fujianList = ref([]);
const WebOfficeId = ref(null); //获取他的dom
const openFileState = ref(false);
const loadingWebLoad = ref(false);
const outMessageFormRef = ref(false);
const mkdir = ref("");
const nType = ref(0);
const baseUrl = ref(import.meta.env.VITE_APP_BASE_API);
const urgentDict = ref([]);
const docFileUrl = ref("");
const WebOffice = ref({});

const receivedFormRef = ref(false);
const ywJournalPublishParams = reactive({
  userId: null,
  paperName: "",
  journalLevel: "",
  journalNumber: "",
  layoutFees: "",
  registrationDate: "",
  eliminateTime: "",
  eliminateMoney: "",
  sendFileId: "",
  fujianFileList: [],
  params: {},
});
const webOfficeOBJ = ref(null);
const upload = reactive({
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/file/fileupload",
});
const props = defineProps({
  paperDataQiLin: "",
});
const uploadFuJianFiles = (response, file) => {};
const rules = reactive({
  deptName: [{ required: true, message: "请输入投稿人处室", trigger: "blur" }],
  paperName: [{ required: true, message: "请输入论文名称", trigger: "blur" }],
  journalLevel: [
    { required: true, message: "请输入期刊级别", trigger: "blur" },
  ],
  layoutFees: [
    { required: true, message: "请输入版面费金额", trigger: "blur" },
  ],
  // eliminateMoney: [{ required: true, message: "请输入报销金额", trigger: "blur" }],
  registrationDate: [
    { required: true, message: "请输入登记日期", trigger: "blur" },
  ],
  journalNumber: [
    {
      required: true,
      message: "请输入发表期刊的，年，卷，期",
      trigger: "blur",
    },
  ],
});
let requestParams = getRequest(); //获取当前url地址
// http://192.168.3.213:9000/public/20230916/2346eada103c4badb9a6970078a6a446.docx
const onSubmit = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      proxy.$modal.loading("正在提交，请稍候...");
      //保存文件到服务器中
      let uf = await saveOffice2Web();
    }
  });
};

function saveOffice2Web() {
  //console.log(webOfficeOBJ.value.getFilePath() + webOfficeOBJ.value.FileName)
  //保存文件到本地
  var FileName = "/tmp/" + Math.round(Math.random() * 100000000) + ".doc";
  webOfficeOBJ.value.saveAs(FileName);
  var httpclient = webOfficeOBJ.value.Http;
  httpclient.SetRequestHeader("Authorization", "Bearer " + getToken());
  httpclient.AddFile("file", FileName);
  let baseurl = window.location.href.split("/")[2];
  if (httpclient.Open(1, "http://" + baseurl + upload.url, false)) {
    if (httpclient.Send()) {
      if (httpclient.Status == 200) {
        var res = JSON.parse(httpclient.ResponseText);
        if (res.code == 200) {
          //console.log("文件保存文档到服务器成功");
          ywJournalPublishParams.sendFileId = res.data.fileId;
          for (let i = 0; i < fujianList.value.length; i++) {
            ywJournalPublishParams.fujianFileList.push({
              fileId: fujianList.value[i].response.data.fileId,
            });
          }
          loadingWebLoad.value = true;
          startPublish(ywJournalPublishParams).then((response) => {
            if (response.code == 200) {
              loadingWebLoad.value = false;
              proxy.$modal.msgSuccess(
                "已发送到" +
                  response.data.VarToNodeName +
                  "节点，接收人：" +
                  response.data.VarAcceptersName
              );
              setTimeout(function () {
                proxy.$modal.closeLoading();
                webOfficeOBJ.value.CloseDocument();
                proxy.$emit("change1");
              }, 2000);
              ywJournalPublishParams.paperName = null;
              ywJournalPublishParams.journalLevel = null;
              ywJournalPublishParams.journalNumber = null;
              ywJournalPublishParams.layoutFees = null;
              ywJournalPublishParams.registrationDate = null;
              fujianList.value = [];
              ywJournalPublishParams.fujianFileList = [];
            } else {
              proxy.$modal.closeLoading();
              proxy.$modal.msgError("提交失败");
            }
          });
        } else {
          proxy.$modal.closeLoading();
          proxy.$modal.msgError("保存文档到服务器失败");

          return false;
        }
      }
    }
    httpclient.Close();
  }
}

//作用：载入iWebOffice信创版控件
function Load_ZUKK() {
  loadingWebLoad.value = false;
  //   if (document.getElementById("WebOfficeId") != null) {
  webOfficeOBJ.value = document.getElementById("WebOffice");
  getInfo().then((res) => {
    ywJournalPublishParams.userName = res.user.nickName;
    ywJournalPublishParams.deptName = res.user.dept.deptName;
    webOfficeOBJ.value.UserName = res.user.nickName;
    try {
      var OSType = detectOS();
      if (OSType.indexOf("Win") > -1) {
        return false;
      }

      var strFileType = ".doc";
      //alert(strFileType);

      if (strFileType == ".doc" || strFileType == ".docx") {
        nType.value = 1; //WPS文字编辑软件
        //nType = 14;    //永中Office文字编辑软件
      } else if (strFileType == ".xls" || strFileType == ".xlsx") {
        nType.value = 12; //WPS文字编辑软件

        //nType = 15;    //永中Office文字编辑软件
      } else if (strFileType == ".wps") {
        nType.value = 1;
      } else if (strFileType == ".et") {
        nType.value = 12;
      } else if (strFileType == ".ppt" || strFileType == ".pptx") {
        nType.value = 13; //WPS文字编辑软件

        //nType = 16;    //永中Office文字编辑软件
      } else if (strFileType == ".ofd") {
        nType.value = 3; //数科ofd阅读器
      }

      webOfficeOBJ.value.setPluginType(nType.value); //设置信创中间件加载文字编辑软件
      //alert("weburl");
      //以下属性必须设置，实始化iWebOffice
      webOfficeOBJ.value.FileName = Math.random() * 100000 + "Mytemplate.doc";
      webOfficeOBJ.value.ShowWindow = false; //显示/隐藏进度条
      webOfficeOBJ.value.EditType = "1"; //设置加载文档类型 0 锁定文档，1无痕迹模式，2带痕迹模式
      mkdir.value = "/media/greatwall/D盘/iweboffice/file/";
      var mkd = webOfficeOBJ.value.WebMkDirectory(mkdir.value); //创建临时目录用于控件下载文档到此目录

      if (mkd) {
        webOfficeOBJ.value.WebSetTmpPath(mkdir.value); //设置控件下载文档到本地的临时目录
      }

      webOfficeOBJ.value.MaxFileSize = 4 * 1024; //最大的文档大小控制，默认是8M，现在设置成4M。
      var ret = webOfficeOBJ.value.CreateFile(); ////iWebOffice信创版控件，打开该文档    交互OfficeServer  调出文档OPTION="LOADFILE"    调出模板OPTION="LOADTEMPLATE"     <参考技术文档>
      //alert(ret);
      if (ret) {
        proxy.$modal.closeLoading();
        // alert(webOfficeOBJ.value.Status);
        //StatusMsg(WebOffice.Status);
      }
    } catch (e) {
      proxy.$modal.closeLoading();
      //alert(e.description);                                   //显示出错误信息
    }
  });
}

const handlePreview = () => {};
const handleRemove = () => {};
// function Load() {
//   //chrome浏览器，HookEnabled设置为true，用于控件中和本地excel表格的焦点互相切换
//   initOffice();
//   loadingWebLoad.value = false;
// }
function openLocalFile() {
  openFileState.value = true;
  setTimeout(() => {
    openFileState.value = false;
  }, 1000);
  webOfficeOBJ.value.FileType = ".doc"; //激活文档，防止调用控件接口没有文档对象
  // webOfficeOBJ.value.WebOpenLocal();
  var app = webOfficeOBJ.value.KGGetObject("Application");
  var IsYozoOffice = webOfficeOBJ.value.WebApplication(".eio");
  if (IsYozoOffice) {
    app.Dialogs.Item(80).Show2();
  } else {
    var filename = app.ShowLocalDocumentDialog();
    if (filename == "" || filename == null || filename == "undefined") {
      return;
    } else {
      var aa = webOfficeOBJ.value.openDocument(filename, false);
    }
  }
}
function closePage() {
  // webOfficeOBJ.value.WebShow(false);
}

function OnReady() {
  proxy.$modal.loading("正在打开中...");
  initOffice(document);
  setTimeout(function () {
    Load_ZUKK();
  }, 1000); //需要做一个延时，iWebOffice2015才能获取FuncExtModule扩展接口对象
}
onMounted(async () => {
  //修改页面title
  ywJournalPublishParams.params["fk_flow"] = props.paperDataQiLin;
  loadingWebLoad.value = true;

  OnReady();
});

defineExpose({
  Load_ZUKK,
});
</script>

<style lang="scss" scoped>
.iWebOfficeDom {
  height: 950px;
}
</style>
