<!-- @format -->

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="18">
        <div class="iWebOfficeDom" ref="iWebOfficeDom"></div>
      </el-col>
      <el-col :span="6">
        <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>

              <div style="text-align: center; margin-top: 5vh">
                <el-button
                  style="padding: 8px 35px"
                  :loading="loadingWebLoad"
                  @click="onSubmit(receivedFormRef)"
                  type="primary"
                  >提交</el-button
                >
              </div>
            </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 { LoadStr } from "@/plugins/iWebOffice2015";
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 WebOfficeStr = LoadStr();
const iWebOfficeDom = ref(null); //获取他的dom
const openFileState = ref(false);
const loadingWebLoad = ref(false);
const outMessageFormRef = ref(false);

const baseUrl = ref(import.meta.env.VITE_APP_BASE_API);
const urgentDict = ref([]);
const docFileUrl = 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 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地址
let WebOffice;
// http://192.168.3.213:9000/public/20230916/2346eada103c4badb9a6970078a6a446.docx
const onSubmit = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      webOfficeOBJ.value.obj.HidePlugin(0);
      proxy.$modal.loading("正在提交，请稍候...");
      //保存文件到服务器中
      let uf = await saveOffice2Web();
    }
  });
};

function saveOffice2Web() {
  let fileName = webOfficeOBJ.value.getFilePath() + webOfficeOBJ.value.FileName;
  var res = webOfficeOBJ.value.WebSaveLocalFile(fileName);
  if (res == 0) {
    var officeobj = webOfficeOBJ.value.obj;
    var base64file = officeobj.File2Base64Text(fileName);
    var myfff = base64toBlob(base64file);
    var formData = new FormData();
    formData.append("file", myfff, webOfficeOBJ.value.FileName);
    uploadFile(formData).then((res) => {
      if (res.code == 200) {
        webOfficeOBJ.value.WebClose();
        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();
              var setting = window.Setting;
              setting.CloseWindow();
            }, 2500);
          } else {
            proxy.$modal.closeLoading();
            proxy.$modal.msgError("提交失败");
            setTimeout(function () {
              webOfficeOBJ.value.obj.HidePlugin(1);
            }, 2000);
          }
        });
      } else {
        proxy.$modal.closeLoading();
        proxy.$modal.msgError("保存文档到服务器失败");
        setTimeout(function () {
          webOfficeOBJ.value.obj.HidePlugin(1);
        }, 2000);
        return false;
      }
    });
  } else {
    webOfficeOBJ.value.obj.HidePlugin(1);
    proxy.$modal.closeLoading();
    alert("保存文档失败");
    return false;
  }
}

const handlePreview = () => {};
const handleRemove = () => {};
function Load() {
  //chrome浏览器，HookEnabled设置为true，用于控件中和本地excel表格的焦点互相切换
  initWebOffice();
  loadingWebLoad.value = false;
}
function openLocalFile() {
  openFileState.value = true;
  setTimeout(() => {
    openFileState.value = false;
  }, 1000);
  webOfficeOBJ.value.FileType = ".doc"; //激活文档，防止调用控件接口没有文档对象
  webOfficeOBJ.value.WebOpenLocal();
}
function closePage() {
  // webOfficeOBJ.value.WebShow(false);
}

function initWebOffice() {
  getInfo().then((res) => {
    ywJournalPublishParams.userName = res.user.nickName;
    ywJournalPublishParams.userId = res.user.userId;
    ywJournalPublishParams.deptName = res.user.dept.deptName;
    webOfficeOBJ.value.UserName = res.user.nickName;
    // try{
    //   webOfficeOBJ.value.WebUrl = GetUrlbase()+upload.url;
    //webOfficeOBJ.value.RecordID = "1551950618511";  //RecordID:本文档记录编号
    // webOfficeOBJ.value.UserName = "XXX";
    webOfficeOBJ.value.FileName = Math.random() * 100000 + "Mytemplate.doc";
    webOfficeOBJ.value.FileType = ".doc"; //FileType:文档类型  .doc  .xls
    webOfficeOBJ.value.ShowWindow = false; //显示/隐藏进度条
    webOfficeOBJ.value.EditType = "1"; //设置加载文档类型 0 锁定文档，1无痕迹模式，2带痕迹模式
    // webOfficeOBJ.value.ShowMenu = 1;
    // webOfficeOBJ.value.ShowToolBar = 1;
    webOfficeOBJ.value.ShowMenuBar(false);
    webOfficeOBJ.value.ShowToolBars(true);
    webOfficeOBJ.value.SetCaption(
      webOfficeOBJ.value.UserName + " 正在编辑文档"
    ); // 设置控件标题栏标题文本信息
    //参数顺序依次为：控件标题栏颜色、自定义菜单开始颜色、自定义工具栏按钮开始颜色、自定义工具栏按钮结束颜色、
    //自定义工具栏按钮边框颜色、自定义工具栏开始颜色、控件标题栏文本颜色（默认值为：0x000000）
    if (!webOfficeOBJ.value.Skin("blue")) {
      // alert(webOfficeOBJ.value.Status);
    }
    //设置控件皮肤
    if (webOfficeOBJ.value.WebOpen()) {
      // StatusMsg(WebOfficeObj.Status);
    }
    // webOfficeOBJ.value.AppendMenu("1","打开本地文件(&L)");
    // webOfficeOBJ.value.AppendMenu("2","保存本地文件(&S)");
    // webOfficeOBJ.value.AppendMenu("3","-");
    // webOfficeOBJ.value.AppendMenu("4","打印预览(&C)");
    // webOfficeOBJ.value.AppendMenu("5","退出打印预览(&E)");
    // webOfficeOBJ.value.AddCustomMenu();
    webOfficeOBJ.value.HookEnabled();
    webOfficeOBJ.value.CreateFile(); // 根据FileType设置的扩展名来创建对应的空白文档
    // }
    // catch(e){
    //   //console.log("catch");
    //   //console.log(e.description);
    // }
  });
}

function OnReady() {
  //获取iWebOffice2015控件对象，WebOffice.FuncExtModule是iWebOffice2015控件扩展接口对象
  WebOffice = document.getElementById("WebOffice2015");
  webOfficeOBJ.value = new WebOffice2015();
  webOfficeOBJ.value.setObj(WebOffice);

  setTimeout(function () {
    Load();
  }, 1000); //需要做一个延时，iWebOffice2015才能获取FuncExtModule扩展接口对象
}
onMounted(async () => {
  //修改页面title
  document.title = "发表学术论文审批HideVerison";
  ywJournalPublishParams.params["fk_flow"] = getUrlParameter("fk_flow");
  loadingWebLoad.value = true;
  iWebOfficeDom.value.innerHTML = WebOfficeStr;
  OnReady();
});
</script>

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