<!-- @format -->

<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24">
        <el-tabs type="border-card" class="demo-tabs">
          <el-tab-pane>
            <template #label>
              <span class="custom-tabs-label" @click="openWebOffic()">
                <el-icon>
                  <Document />
                </el-icon>
                <span>基本信息</span>
              </span>
            </template>
            <el-row :gutter="24">
              <el-col
                :span="18"
                style="
                  background-color: #9ca1a7;
                  margin-top: 10px;
                  padding: 5px;
                "
              >
                <!--                <el-button type="primary" @click="openWebOffic">打开</el-button>-->
                <div
                  style="height: 85vh; min-height: 800px"
                  class="iWebOfficeDom"
                  ref="iWebOfficeDom"
                ></div>
              </el-col>
              <el-col :span="6">
                <div
                  style="
                    border: 1px solid #9ca1a7;
                    padding: 25px 30px 10px 0px;
                    height: 85.5vh;
                    overflow: auto;
                    border-radius: 5px;
                    margin-top: 10px;
                  "
                >
                  <el-form
                    label-width="110px"
                    style="width: 22vw; margin-top: 10px"
                    :model="outMessageParams"
                  >
                    <!-- <el-button @click="ShowToolBar" type="primary"
                    >ShowToolBar</el-button
                  >
                  <el-button @click="ShowMenu" type="primary"
                    >ShowMenu</el-button
                  >
                  <el-button @click="ShowTitleBar" type="primary"
                    >ShowTitleBar</el-button
                  >
                  <el-button @click="ShowToolBars" type="primary"
                    >ShowToolBars</el-button
                  >
                  <el-button @click="ShowStatusBar" type="primary"
                    >ShowStatusBar</el-button
                  > -->
                    <el-form-item label="发文单位:" prop="outUnit">
                      <el-input
                        :disabled="isEdit"
                        v-model="outMessageParams.outUnit"
                        placeholder="请输入发文单位"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="承办单位:" prop="undertakerUnit">
                      <el-input
                        :disabled="isEdit"
                        v-model="outMessageParams.undertakerUnit"
                        placeholder="请输入承办单位"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="主送单位:" prop="mainUnit">
                      <el-input
                        placeholder="请输入主送单位"
                        type="textarea"
                        v-model="outMessageParams.mainUnit"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="抄送单位:" prop="copyUnit">
                      <el-input
                        placeholder="请输入抄送单位"
                        type="textarea"
                        v-model="outMessageParams.copyUnit"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="拟办人:" prop="draftedName">
                      <el-input
                        :disabled="isEdit"
                        v-model="outMessageParams.draftedName"
                        placeholder="请输入拟办人"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="拟稿日期:" prop="draftedTime">
                      <el-date-picker
                        style="width: 100%"
                        :disabled="isEdit"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                        v-model="outMessageParams.draftedTime"
                        type="date"
                        placeholder="请输入来文日期"
                        size="defalut"
                      />
                    </el-form-item>
                    <el-form-item label="文件标题:" prop="title">
                      <el-input
                        type="textarea"
                        :disabled="isEdit"
                        v-model="outMessageParams.title"
                        placeholder="请输入文件标题"
                      ></el-input>
                    </el-form-item>
                    <el-form-item
                      label-width="120px"
                      v-show="hanldType != true"
                      label="文件字号:"
                      prop="title"
                    >
                      <el-input
                        v-model="outMessageParams.wordNum"
                        placeholder="请输入文件字号"
                      ></el-input>
                    </el-form-item>

                    <el-form-item label="附件列表:">
                      <el-upload
                        v-if="uploadNot"
                        style="width: 100%"
                        ref="fujianUpload"
                        v-model:file-list="fujianList"
                        :action="upload.url"
                        :headers="upload.headers"
                        :on-success="uploadFuJianFiles"
                        @handleRemove="romveFile"
                        multiple
                      >
                        <el-button type="primary">点击上传附件</el-button>
                      </el-upload>
                      <div></div>
                      <el-link
                        style="display: inline"
                        v-for="(
                          item, index
                        ) in outMessageParams.messageFileList"
                        :key="index"
                        type="primary"
                      >
                        <div v-if="item != null">
                          <div
                            style="display: inline-block"
                            @click="openFujianFile(item.url, item.name)"
                          >
                            <el-icon class="el-icon--left">
                              <Document />
                            </el-icon>
                            <span
                              style="
                                display: inline-block;
                                margin-left: 5px;
                                overflow: hidden;
                                white-space: nowrap;
                                text-overflow: ellipsis;
                                width: 9vw;
                                height: 18px;
                                line-height: 18px;
                              "
                            >
                              {{ item.name }}</span
                            >
                          </div>
                          <el-popconfirm
                            v-if="!isEdit"
                            @confirm="confirmEvent(item, index)"
                            @cancel="cancelEvent"
                            title="确认删除该文件吗?"
                          >
                            <template #reference>
                              <span
                                @click="delFile(item, index)"
                                style="
                                  display: inline-block;
                                  margin-top: 5px;
                                  margin-left: 10px;
                                "
                                ><el-icon><Close /></el-icon
                              ></span>
                            </template>
                          </el-popconfirm>
                        </div>
                      </el-link>
                    </el-form-item>
                    <el-form-item v-if="dangansel" label="最终文件:">
                      <el-link
                        v-model="outMessageParams.finalFile"
                        type="primary"
                        @click="
                          openFujianFile(
                            outMessageParams.finalFile.url,
                            outMessageParams.finalFile.name
                          )
                        "
                      >
                        <el-icon class="el-icon-left">
                          <Document />
                        </el-icon>
                        {{ outMessageParams.finalFile.name }}
                      </el-link>
                    </el-form-item>
                  </el-form>

                  <el-form
                    v-show="hanldType"
                    label-width="110px"
                    style="width: 22vw"
                  >
                    <el-form-item label="文件字号: " prop="title">
                      <el-input
                        v-model="outMessageParams.wordNum"
                        placeholder="请输入文件字号"
                      ></el-input>
                    </el-form-item>

                    <el-form-item label="信息公开类型:">
                      <el-select
                        style="width: 100%"
                        @change="changeSelect2"
                        v-model="outMessageParams.infoOpenType"
                        placeholder="请选择信息公开类型"
                      >
                        <el-option
                          v-for="item in sw_open_type"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item v-if="showNotReason" label="不公开理由:">
                      <el-select
                        style="width: 100%"
                        v-model="outMessageParams.noOpenReason"
                        placeholder="请选择不公开理由"
                      >
                        <el-option
                          v-for="item in no_open_reason"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item v-if="nowNode" label="下一步节点: ">
                      <el-select
                        style="width: 100%"
                        v-model="selNextNode"
                        placeholder="请选择下一步节点"
                      >
                        <el-option
                          v-for="item in NextStepNode"
                          :key="item.NodeID"
                          :label="item.Name"
                          :value="item.NodeID"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>

                    <!--  发送到下一步操作         -->
                    <div v-show="guidangBt != true">
                      <el-form-item
                        v-if="nowNode"
                        label="审核意见: "
                        prop="reviewMsg"
                      >
                        <el-input
                          type="textarea"
                          :rows="2"
                          placeholder="请输入审核意见"
                          v-model="formData.reviewMsg"
                        ></el-input>
                      </el-form-item>
                      <!-- <el-form-item style="width: 360px" label=" "> -->
                      <div
                        style="
                          margin-left: 30px;
                          align-items: center;
                          text-align: center;
                        "
                      >
                        <el-button
                          :loading="loadingWebLoad"
                          :disabled="false"
                          @click="sendNext"
                          type="primary"
                          >提交
                        </el-button>
                        <el-button
                          style="display: inline-block"
                          v-if="nowNode"
                          @click="sendBack"
                          type="danger"
                          >退回
                        </el-button>
                        <el-button
                          style="display: inline-block"
                          v-if="nowNode"
                          @click="notApproved"
                          type="warning"
                          >不予审批
                        </el-button>
                      </div>

                      <!-- </el-form-item> -->
                    </div>
                    <!--   归档操作       -->
                    <div v-show="guidangBt">
                      <el-form-item label="档案分类: ">
                        <el-tree-select
                          style="width: 100%"
                          v-model="guidangData.typeId"
                          :data="typeList"
                          :props="{
                            value: 'archiveTypeId',
                            label: 'name',
                            children: 'children',
                          }"
                          value-key="archiveTypeId"
                          placeholder="请选择档案分类"
                        />
                      </el-form-item>
                      <el-form-item label="打印份数: ">
                        <el-input
                          type="number"
                          placeholder="请输入打印份数"
                          v-model="guidangData.printNum"
                        ></el-input>
                      </el-form-item>

                      <el-form-item label="正式文件:">
                        <el-upload
                          class="upload-pdf"
                          ref="sendFileUpload"
                          :action="upload.url"
                          :headers="upload.headers"
                          multiple
                          :limit="1"
                          :before-upload="before_upload"
                          :on-success="uploadPdfFile"
                          :file-list="sendDownFile"
                        >
                          <el-button type="primary">上传</el-button>
                        </el-upload>
                      </el-form-item>

                      <!-- <el-form-item label="密级">
                  <el-select
                    v-model="guidangData.levels"
                    placeholder="请选择密级"
                  >
                    <el-option
                      v-for="dict in archive_levels"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item> -->
                      <el-form-item label=" ">
                        <el-button
                          :disabled="false"
                          @click="sendNext1"
                          type="primary"
                          >归档
                        </el-button>
                      </el-form-item>
                    </div>
                  </el-form>
                </div>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="流转记录">
            <template #label>
              <span class="custom-tabs-label">
                <el-icon>
                  <Promotion />
                </el-icon>
                <span>流转记录</span>
              </span>
            </template>
            <!-- <iframe :src="tuurl" width="100%" height="500px"></iframe> -->
            <div>
              <el-table border :data="liuzhuanData" style="width: 100%">
                <el-table-column
                  align="center"
                  label="序号"
                  width="200"
                  type="index"
                >
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="NDFromT"
                  label="	节点名称"
                  width="220"
                >
                </el-table-column>
                <el-table-column
                  align="center"
                  width="200"
                  prop="ActionTypeText"
                  label="办理状态"
                >
                </el-table-column>
                <el-table-column align="center" prop="EmpFromT" label="办理人">
                </el-table-column>
                <el-table-column align="center" prop="SDT" label="到达时间">
                </el-table-column>
                <el-table-column align="center" prop="RDT" label="处理时间">
                </el-table-column>

                <el-table-column
                  align="center"
                  prop="ActionType22"
                  label="审核意见"
                >
                  <template #default="scope">
                    <div v-if="scope.row.ActionType == 2">
                      退回原因：{{ scope.row.Msg }}
                    </div>
                    <div v-else-if="scope.row.ActionType == 3">
                      移交原因：{{ scope.row.Msg }}
                    </div>
                    <div v-else-if="scope.row.ActionType22 != undefined">
                      <div v-for="item in scope.row.ActionType22" :key="item">
                        <!-- <div></div> -->
                        <div>{{ item.Msg }}</div>
                      </div>
                    </div>
                    <div v-else>{{ scope.row.Msg }}</div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          <!--   v-hasPermi="['lc:sw:ybj']"       -->
          <el-tab-pane label="发文审批笺">
            <template #label>
              <span class="custom-tabs-label">
                <el-icon>
                  <SetUp />
                </el-icon>
                <span>发文审批笺</span>
              </span></template
            >
            <div style="text-align: center">
              发文审批笺
              <el-button
                type="primary"
                icon="view"
                style="margin-left: 5px"
                @click="openYbj"
                >预览</el-button
              >
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <select-user
      ref="selectRef"
      @ok="handleQuery"
      @closeDialogf="closePage"
    ></select-user>
    <!-- 退回 -->
    <el-dialog
      title="退回"
      v-model="dialogBack"
      width="600px"
      @close="closePage(1)"
    >
      <el-form>
        <el-form-item label-width="150" label="退回节点：">
          <el-select
            v-model="nodeValue"
            placeholder="请选择退回节点信息"
            style="width: 200px"
          >
            <el-option
              v-for="item in nodeData"
              :key="item.No"
              :label="item.Name"
              :value="item.No"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label-width="150"
          label="退回原因："
          placeholder="请输入退回原因"
        >
          <el-input v-model="returnMsg" style="width: 300px" type="textarea" />
        </el-form-item>
      </el-form>
      <span
        style="position: relative; left: 400px"
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogBack = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 不予审批 -->
    <el-dialog
      title="不予审批"
      v-model="dialogApproved"
      width="500px"
      @close="closePage(1)"
    >
      <el-form>
        <!-- <el-form-item label-width="200" label="退回节点：">
          <el-select
            v-model="nodeValue"
            placeholder="请选择退回节点信息"
            style="width: 240px"
          >
            <el-option
              v-for="item in nodeData"
              :key="item.No"
              :label="item.Name"
              :value="item.No"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label-width="100" label="原因：">
          <el-input
            placeholder="请输入不予审批原因"
            v-model="formData.reviewMsg"
            style="width: 300px"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <span
        style="position: relative; left: 300px"
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogApproved = false">取 消</el-button>
        <el-button type="primary" @click="submitNotApproved">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="阅办笺"
      width="60%"
      v-model="ybjState"
      :before-close="closeDialog"
    >
      <dispatch ref="dispatchRef" :data="outMessageParams"></dispatch>
    </el-dialog>
  </div>
</template>

<script setup>
import selectUser from "../../selectUser";
import dispatch from "@/views/flows/fwsp";
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import Cookies from "js-cookie";
import { LoadStr } from "@/plugins/iWebOffice2015";
import WebOffice2015 from "@/static/webOffice/WebOffice";
import {
  getRequest,
  GetUrlbase,
  getUrlParameter,
} from "../../../official/hookFunction";
import {
  generNextStepNode,
  judgeNode,
  generNextStepAllNode,
  sendFlowToNext,
  getWfGenerWorkList,
  getSelfParas,
} from "@/api/liucheng";
import {
  leave,
  getLeave,
  getReturnWorkNode,
  WorkProgressBar,
  NodeReturnWork,
} from "@/api/clocking/leave";
import {
  saveOutMessage,
  updateMessage,
  getOutMessageByWorkId,
  delFileList,
} from "@/api/office/message";
import { uploadFile, base64toBlob } from "@/api/system/oafile";
import { saveArchive } from "@/api/archive/archive";
import { ElMessage, ElMessageBox } from "element-plus";

import { getJToken, getToken } from "@/utils/auth";
import { getInfo } from "@/api/login";
import { listType } from "@/api/archive/type";

const { proxy } = getCurrentInstance();

const { archive_levels } = proxy.useDict("archive_levels");
const { sw_open_type } = proxy.useDict("sw_open_type");
const { no_open_reason } = proxy.useDict("no_open_reason");
const WebOfficeStr = LoadStr();
const nodeValue = ref(null);
const fujianList = ref([]);
const returnMsg = ref(null);
const dialogBack = ref(false);
const dialogApproved = ref(false);
const msgValue = ref(true);
const ybjState = ref(false);
const nodeData = ref([]);
const valDate = ref(null);
const showNotReason = ref(false);

///////////////
const input3 = ref("");
const liuzhuanData = ref([]);
const select = ref("");
/////////////////////
const hanldType = ref(true);
const selUserNames = ref("");
const dangansel = ref(false);
const iWebOfficeDom = ref(null); //获取他的dom
const openFileState = ref(false);
const loadingWebLoad = ref(false);
const isAllowed = ref(true);
const outMessageFormRef = ref(false);
const guidangBt = ref(false);
const isEndNodeFlg = ref(false);
const uploadNot = ref(false);
const nowNode = ref(true);
const receivedData = ref(null);
const workId = ref(null);
const targetuuid = ref(null);
const uuid = ref(null);
const NextStepNode = ref([]);
const flowDatas = ref({});
const selNextNode = ref(null);
const typeList = ref([]);
const isEdit = ref(true);
const fileLists = ref([]);
const sendDownFile = ref([]);
const tuurl = ref("");
const nowShow = ref("");
const szFileName = ref("");
const reviewMsg = ref("");
const baseUrl = ref(import.meta.env.VITE_APP_BASE_API);
const urgentDict = ref([]);
const docFile = ref({});
const data = reactive({
  outMessageParams: {
    title: null, //来文标题
    outUnit: null, //发文单位
    draftedTime: null, //时间
    draftedName: null, //拟稿人
    undertakerUnit: null, //承办单位
    sendFileId: null, //下发文件
    outMessageId: "",
    copyUnit: null,
    mainUnit: null,
  },
  formData: {
    reviewMsg: "同意",
    optionName: null,
    toNodeId: null,
    users: null,
    workid: null,
  },
  guidangData: {
    archiveNo: null,
    workId: null,
    archiveFormNo: null,
    printNum: null,
    levels: null,
    typeId: null,
    name: null,
  },
});

const rules = reactive({
  reviewMsg: [
    {
      required: true,
      message: "审核信息不能为空",
      trigger: "blur",
    },
  ],
});
const { outMessageParams, formData, guidangData } = toRefs(data);
const webOfficeOBJ = ref(null);
const upload = reactive({
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/file/fileupload",
});

let requestParams = getRequest(); //获取当前url地址
let WebOffice;
const onSubmit = (formEl) => {
  closePage(0);
  saveOffice2Web();
};
function confirmEvent(item, index) {
  console.log(item);
  delFileList(item.fileId).then((res) => {
    console.log(res);
    proxy.$message({
      type: "success",
      message: "删除成功",
    });
    outMessageParams.value.messageFileList.splice(index, 1);
  });
}
//删除附件
function delFile(item, index) {}
function closeDialog(done) {
  done();
}
///////////////////////////////////////////////
const uploadFuJianFiles = (response, file) => {};
function ShowToolBar() {
  webOfficeOBJ.value.ShowToolBar = 0;
  webOfficeOBJ.value.WebRefresh();
  console.log("111");
}
function ShowMenu() {
  webOfficeOBJ.value.ShowMenu = "1";
}
function ShowTitleBar(mValue) {
  webOfficeOBJ.value.ShowTitleBar = mValue;
}
function ShowToolBars(mValue) {
  webOfficeOBJ.value.ShowToolBars = false;
  webOfficeOBJ.value.WebRefresh();
  console.log("111");
}
function ShowStatusBar(mValue) {
  webOfficeOBJ.value.ShowStatusBar = mValue;
}
///////////////////////////////////////
function openWebOffic() {
  // webOfficeOBJ.value.obj.HidePlugin(1);
  setTimeout(function () {
    webOfficeOBJ.value.WebOpenLocalFile(szFileName.value);
  }, 200);
}
function openYbj() {
  ybjState.value = true;
  // closePage(0);
}
function changeSelect2(val) {
  showNotReason.value = false;
  if (val == "不予公开") {
    showNotReason.value = true;
  } else {
    showNotReason.value = false;
  }
}
function getLiuzhuanData() {
  getWfGenerWorkList(getJToken(), formData.value.workid).then((res) => {
    liuzhuanData.value = res.trackList;
    console.log("liuzhuanData", liuzhuanData.value);
  });
}
function submitNotApproved() {
  proxy.$modal.loading();
  if (formData.value.reviewMsg == "") {
    proxy.$message.error("请输入不予审批原因");
    return;
  }

  formData.value.toNodeId = 204;
  sendFlowToNext(formData.value).then((response) => {
    ElMessage({
      message:
        "已发送到" +
        response.data.VarToNodeName +
        "节点，接收人：" +
        response.data.VarAcceptersName,
      type: "success",
    });
    proxy.$modal.closeLoading();
    ////////关闭文件，释放资源
    webOfficeOBJ.value.WebClose();
    dialogApproved.value = false;
    formData.value.reviewMsg = "";
    setTimeout(function () {
      SendMsgB();
      var setting = window.Setting;
      setting.CloseWindow();
    }, 2000);
  });
}
//tuihui
async function submitNodeBack() {
  proxy.$modal.loading("正在退回，请稍候...");
  if (nodeValue.value == null) {
    proxy.$message.error("请选择退回节点信息");
    proxy.$modal.closeLoading();
    return;
  }
  if (returnMsg.value == null) {
    proxy.$message.error("请输入退回原因");
    proxy.$modal.closeLoading();
    return;
  }
  closePage(0);
  let res = await NodeReturnWork(
    formData.value.workid,
    nodeValue.value,
    returnMsg.value
  );
  proxy.$message.success(res);

  // proxy.$emit("closeViewLeave");

  nodeValue.value = null;
  returnMsg.value = null;
  valDate.value = null;
  selNextNode.value = null;

  proxy.$modal.closeLoading();
  webOfficeOBJ.value.WebClose();
  setTimeout(function () {
    SendMsgB();
    var setting = window.Setting;
    setting.CloseWindow();
  }, 2000);
}

async function openFujianFile(url, name) {
  const files = await proxy.$download.downloadUrlFile(url, name);
  proxy.$download.saveAs(
    new Blob([files], { type: "text/plain;charset=UTF-8" }),
    name
  );
  // window.open(url, "_blank");
}
function sendBack() {
  returnWorkNode();
  dialogBack.value = true;
  closePage(0);
}
function notApproved() {
  dialogApproved.value = true;
  formData.value.reviewMsg = "";

  closePage(0);
}
//获取退回界定啊
async function returnWorkNode() {
  let nData = await getReturnWorkNode(getJToken(), formData.value.workid);
  nodeData.value = nData;
}

function SendMsgB(msg) {
  var sendmsg = {
    action: "invoke",
    content: encodeURIComponent(msgValue.value),
  };
  // let msgs = JSON.parse(JSON.stringify(sendmsg));
  // console.log("JSON.stringify(sendmsg)", JSON.parse(JSON.stringify(sendmsg)));
  _sendMsg("(" + JSON.stringify(sendmsg) + ")");
}
//给A页面发送消息
function _sendMsg(msg) {
  let urlString =
    "http://127.0.0.1:9588/SendMsg?targetid=" + uuid.value + "&msg=" + msg;
  fetch(urlString, { method: "GET" })
    .then((data) => {
      var jsonobj = eval(data);
    })
    .catch((err) => {});
}
async function reSendFlowToNext() {
  if (dialogBack.value) {
    submitNodeBack();
  } else {
    if (guidangBt.value) {
      guidangData.value.archiveFormNo = flowDatas.value.FK_Flow;
      guidangData.value.workId = workId.value;
      let { archiveRes } = await saveArchive(guidangData.value);
    }
    //如果市最后一个节点则执行 完成
    if (isEndNodeFlg.value) {
      generNextStepAllNode(
        flowDatas.value.FK_Flow,
        flowDatas.value.WorkID,
        "",
        getJToken()
      ).then((res) => {
        ElMessage({
          message: "当前工作已结束",
          type: "success",
        });
        proxy.$modal.closeLoading();
        ////////关闭文件，释放资源
        webOfficeOBJ.value.WebClose();
        setTimeout(function () {
          SendMsgB();
          var setting = window.Setting;
          setting.CloseWindow();
        }, 2000);
      });
    } else {
      sendFlowToNext(formData.value).then((response) => {
        if (response.code == 200) {
          if (
            response.data.VarAcceptersName != "" &&
            response.data.VarAcceptersName != "结束"
          ) {
            ElMessage({
              message:
                "已发送到" +
                response.data.VarToNodeName +
                "节点，接收人：" +
                response.data.VarAcceptersName,
              type: "success",
            });
            // msgValue.value = true;
            SendMsgB();
          } else if (response.data.VarAcceptersName == "结束") {
            ElMessage({
              message: response.data.Message,
              type: "success",
            });
            SendMsgB();
          } else {
            ElMessage({
              message: response.data.Message.replaceAll("@", ""),
              type: "success",
            });
            SendMsgB();
          }
          proxy.$modal.closeLoading();
          webOfficeOBJ.value.WebClose();
          setTimeout(function () {
            SendMsgB();
            var setting = window.Setting;
            setting.CloseWindow();
          }, 2000);
        } else {
          proxy.$modal.msgError("发送失败");
        }
      });
    }
  }
}

/** 选择用户后进行下一步 */
function VBAShowRevisions(flg) {
  webOfficeOBJ.value.VBAShowRevisions(flg);
}
/** 查询归档类型列表 */
function getTypeList() {
  listType({}).then((response) => {
    typeList.value = proxy.handleTree(
      response.data,
      "archiveTypeId",
      "parentId"
    );
    console.log(typeList.value);
  });
}
function colsedialog() {}

function handleQuery(selUsers) {
  formData.value.users = selUsers;
  if (selUsers != undefined && selUsers != "") {
    onSubmit();
  }
}

/** 表单重置 */
function reset() {
  formData.value = {
    reviewMsg: null,
    optionName: null,
    toNodeId: null,
    users: null,
    workid: null,
  };
  NextStepNode.value = [];
  flowDatas.value = {};
  selNextNode.value = "";
  // selUserNames.value = "";
}

//点击发送到下一步
const sendNext = () => {
  if (fujianList.value.length != 0) {
    for (let i = 0; i < fujianList.value.length; i++) {
      outMessageParams.value.messageFileList.push({
        fileId: fujianList.value[i].response.data.fileId,
      });
    }
  }

  if (formData.value.reviewMsg == "") {
    closePage(0);
    ElMessageBox.alert("请填写审核意见", "提示", {
      type: "warning",
      confirmButtonText: "确定",
      callback: (action) => {
        closePage(1);
      },
    });
    return;
  }
  formData.value.toNodeId = selNextNode.value;
  let DeliveryWay = "";
  //查看当前是选择的那个节点
  NextStepNode.value.forEach((item, index) => {
    if (item.NodeID == selNextNode.value) {
      DeliveryWay = item.DeliveryWay;
    }
  });

  //判断当前节点是哪一个节点
  //DeliveryWay 3:绑定人员计算
  if (DeliveryWay == "3") {
    onSubmit();
  }
  //4:由发送人选择发送
  else if (DeliveryWay == "4" || DeliveryWay == "1" || DeliveryWay == "9") {
    openSelectUser();
    return;
  } else {
    onSubmit();
  }
};
const uploadPdfFile = (response, file) => {
  console.log(response, file);
  outMessageParams.value.finalFileId = response.data.fileId;
};

const sendNext1 = () => {
  if (formData.value.reviewMsg == "") {
    closePage(0);
    ElMessageBox.alert("请填写审核意见", "提示", {
      type: "warning",
      confirmButtonText: "确定",
      callback: (action) => {
        closePage(1);
      },
    });
    return;
  }
  if (selNextNode.value == null) {
    closePage(0);
    proxy.$modal.msgError("请选择下一步节点");
    return;
  }
  // if (
  //   guidangData.value.archiveNo == "" ||
  //   guidangData.value.archiveNo == null ||
  //   guidangData.value.archiveNo == undefined
  // ) {
  //   closePage(0);
  //   proxy.$modal.msgError("请输入档案编号");
  //   return;
  // }
  if (
    guidangData.value.typeId == "" ||
    guidangData.value.typeId == null ||
    guidangData.value.typeId == undefined
  ) {
    closePage(0);
    proxy.$modal.msgError("请选择档案分类");
    return;
  }
  if (
    guidangData.value.printNum == "" ||
    guidangData.value.printNum == null ||
    guidangData.value.printNum == undefined
  ) {
    closePage(0);
    proxy.$modal.msgError("请输入打印份数");
    return;
  }
  formData.value.toNodeId = selNextNode.value;
  let DeliveryWay = "";
  //查看当前是选择的那个节点
  NextStepNode.value.forEach((item, index) => {
    if (item.NodeID == selNextNode.value) {
      DeliveryWay = item.DeliveryWay;
    }
  });

  // 判断当前节点是哪一个节点
  // DeliveryWay 3:绑定人员计算
  if (DeliveryWay == "3") {
    onSubmit();
  }
  //4:由发送人选择发送
  else if (DeliveryWay == "4" || DeliveryWay == "1" || DeliveryWay == "9") {
    openSelectUser();
    return;
  } else {
    onSubmit();
  }
};

/** 打开授权用户表弹窗 */
function openSelectUser() {
  webOfficeOBJ.value.obj.HidePlugin(0);
  flowDatas.value.toNodeId = selNextNode.value;
  console.log("11111", flowDatas.value);
  proxy.$refs["selectRef"].show1(flowDatas.value);
}

async function saveOffice2Web() {
  proxy.$modal.loading("正在提交中，请稍候...");
  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 formData1 = new FormData();
    formData1.append("file", myfff, webOfficeOBJ.value.FileName);
    uploadFile(formData1).then((res) => {
      if (res.code == 200) {
        //设置修订痕迹记录用户
        // webOfficeOBJ.value.VBASetUserName(webOfficeOBJ.value.OfficeUserName);
        // console.log("文件保存文档到服务器成功");
        outMessageParams.value.sendFileId = res.data.fileId;
        loadingWebLoad.value = true;

        updateMessage(outMessageParams.value).then((response) => {
          if (response.code == 200) {
            loadingWebLoad.value = false;
            // proxy.$modal.msgSuccess("提交成功");
            reSendFlowToNext();
          } else {
            proxy.$modal.closeLoading();
            proxy.$modal.msgError("提交失败");
          }
        });
      } else {
        proxy.$modal.closeLoading();
        proxy.$modal.msgError("保存文档到服务器失败");
        return false;
      }
    });
  } else {
    proxy.$modal.closeLoading();
    alert("保存文档失败");
    return false;
  }
}

const handlePreview = () => {};
const handleRemove = () => {};

function Load() {
  tuurl.value =
    Cookies.get("jFontIp") +
    "/WF/Port.htm?DoWhat=OneWork2&WorkID=" +
    flowDatas.value.WorkID +
    "&FK_Flow=" +
    flowDatas.value.FK_Flow +
    "&Token=" +
    getJToken();
  // 是否可编辑原信息
  getSelfParas(flowDatas.value.WorkID).then((res) => {
    console.log("是否可编辑原信息", res);
    if (res.data.SelfParas == "isEdit") {
      isEdit.value = false;
    }
    uploadNot.value = true;
    if (nowShow.value == "no") {
      isEdit.value = true;
      uploadNot.value = false;
    }
  });

  getOutMessageByWorkId(workId.value).then((response) => {
    console.log("response", response);
    if (response.code == "200") {
      outMessageParams.value = response.data;
      docFile.value = response.data.sendFile;

      if (outMessageParams.value.infoOpenType == "3") {
        showNotReason.value = true;
      }
      initWebOffice();
    }
  });
  //chrome浏览器，HookEnabled设置为true，用于控件中和本地excel表格的焦点互相切换

  loadingWebLoad.value = false;
}

function onCloseBtnClicked() {}

const onCloseBtnClicked1 = () => {};

function closePage(numf) {
  if (numf == undefined) {
    return;
  }
  if (webOfficeOBJ.value != null) {
    webOfficeOBJ.value.obj.HidePlugin(numf);
  }
}

function initWebOffice() {
  getInfo().then((res) => {
    // console.log("res", res);
    // outMessageParams.value.draftedName = res.user.userName;
    console.log("outMessageParams", outMessageParams.value);
    // try{
    //   webOfficeOBJ.value.WebUrl = GetUrlbase()+upload.url;
    //webOfficeOBJ.value.RecordID = "1551950618511";  //RecordID:本文档记录编号
    webOfficeOBJ.value.UserName = res.user.nickName;
    webOfficeOBJ.value.FileName = Math.random() * 100000 + "Mytemplate.doc";
    webOfficeOBJ.value.FileType = "." + docFile.value.extension; //FileType:文档类型  .doc  .xls
    webOfficeOBJ.value.ShowWindow = false; //显示/隐藏进度条
    webOfficeOBJ.value.EditType = "2"; //设置加载文档类型 0 锁定文档，1无痕迹模式，2带痕迹模式
    //显示菜单
    webOfficeOBJ.value.ShowMenuBar(false);
    //显示工具栏
    webOfficeOBJ.value.ShowToolBars(true);
    //显示标题状态栏
    webOfficeOBJ.value.ShowTitleBar(true);
    // webOfficeOBJ.value.ShowCustomToolbar(true);
    // console.log(webOfficeOBJ)
    //设置编辑域名称
    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.HookEnabled();

    //获取临时文件路径
    var szTempPath = webOfficeOBJ.value.obj.FileSystem.GetTempPath();
    szFileName.value = szTempPath + Math.random() * 100000 + "sample.doc";
    //先删除文件
    webOfficeOBJ.value.FileType = ".doc";
    webOfficeOBJ.value.WebDelFile(szFileName.value);
    //下载到本地
    webOfficeOBJ.value.DownloadToFileEx(docFile.value.url, szFileName.value);
    //打开本地文件
    webOfficeOBJ.value.WebOpenLocalFile(szFileName.value);
    webOfficeOBJ.value.WebShow(1);
    //设置修订痕迹记录用户
    webOfficeOBJ.value.VBASetUserName(webOfficeOBJ.value.UserName);
    // 根据FileType设置的扩展名来创建对应的空白文档

    // }
    // catch(e){
    //   console.log("catch");
    //   console.log(e.description);
    // }
  });
}

//获取所有可退回的节点
const allreturnWork = () => {
  getReturnWorkNode().then((reData) => {
    reWorkNode.value = reData;
  });
};
//退回
const returnWork = () => {
  let reData = {
    workid: flowDatas.value.WorkID,
    returnToNodeID: "",
    returnMsg: "",
    token: getJToken(),
  };
  node_ReturnWork().then((reData) => {
    ElMessage({
      message: "退回成功",
      type: "success",
    });
    colsedialog();
  });
};
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
  targetuuid.value = getUrlParameter("targetid");
  uuid.value = getUrlParameter("id");
  document.title = "发文HideVerison";
  workId.value = getUrlParameter("workId");
  formData.value.workid = getUrlParameter("workId");
  flowDatas.value.WorkID = getUrlParameter("workId");
  flowDatas.value.FK_Node = getUrlParameter("FK_Node");
  formData.value.optionName = getUrlParameter("NodeName");
  nowShow.value = getUrlParameter("nowShow");
  getLiuzhuanData();
  nowNode.value = true;
  if (flowDatas.value.FK_Node == "201") {
    nowNode.value = false;
  }

  flowDatas.value.FK_Flow = getUrlParameter("FK_Flow");
  //是否展示 发送下一步
  hanldType.value = getUrlParameter("hanldType") == "true";
  //档案查看
  dangansel.value = getUrlParameter("dangan") == "true";
  //判断当前节点是不是最后一个.
  if (hanldType.value) {
    if (
      formData.value.optionName.indexOf("归档") != -1 ||
      flowDatas.value.FK_Node == "204"
    ) {
      getTypeList();
      formData.value.reviewMsg = "归档";
      guidangBt.value = true;
    }
    judgeNode(flowDatas.value.FK_Node, getJToken()).then((nres) => {
      if (nres.msg == "Y") {
        NextStepNode.value.push({ NodeID: 0, Name: "结束" });
        isEndNodeFlg.value = true;
        selNextNode.value = NextStepNode.value[0].NodeID;
      } else {
        //获取下个节点
        generNextStepAllNode(
          flowDatas.value.FK_Flow,
          flowDatas.value.WorkID,
          "",
          getJToken()
        ).then((res) => {
          NextStepNode.value = res;
          selNextNode.value = NextStepNode.value[0].NodeID;
        });
      }
    });
  }
  loadingWebLoad.value = true;
  iWebOfficeDom.value.innerHTML = WebOfficeStr;
  OnReady();
  window.addEventListener("beforeunload", beforeUnloadListener());
});

onBeforeUnmount(() => {
  window.removeEventListener("beforeunload", beforeUnloadListener());
});

function beforeUnloadListener() {
  // setCloseTabItemAs()
  // alert("111")
}
</script>

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