<!-- @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;
                  height: 75vh;
                "
              >
                <!--                <el-button type="primary" @click="openWebOffic">打开</el-button>-->
                <div style="height: 76vh" id="WebOffice2015"></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="90px"
                    style="width: 320px; margin-top: 20px"
                    :model="outMessageParams"
                  >
                    <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: 320px"
                        :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
                        :disabled="isEdit"
                        v-model="outMessageParams.title"
                        placeholder="请输入文件标题"
                      ></el-input>
                    </el-form-item>
                    <el-form-item
                      label-width="90px"
                      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>
                            {{ item.name }}
                          </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="120px"
                    style="width: 320px"
                  >
                    <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: 320px"
                        @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: 320px"
                        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: 320px"
                        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>
                      <div style="margin-left: 4vw">
                        <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>
                    </div>
                    <!--   归档操作       -->
                    <div v-show="guidangBt">
                      <el-form-item label="档案分类: ">
                        <el-tree-select
                          style="width: 320px"
                          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="40%"
      @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="200"
          label="退回原因："
          placeholder="请输入退回原因"
        >
          <el-input v-model="returnMsg" style="width: 20vw" type="textarea" />
        </el-form-item>
      </el-form>
      <span
        style="position: relative; left: 28vw"
        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="30%"
      @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: 20vw"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <span
        style="position: relative; left: 18vw"
        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 { detectOS, initOffice } from "@/static/webOffice/KingiWebOffice2015";
import selectUser from "../../selectUser";
import dispatch from "@/views/flows/fwsp";
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import Cookies from "js-cookie";
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,
} 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 nodeValue = ref(null);
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 nType = ref(0);
const fujianList = ref([]);
const mkdir = ref("");
const isEdit = ref(true);
const showNotReason = ref(false);
///////////////
const input3 = ref("");
const liuzhuanData = ref([]);
const sendDownFile = ref([]);
const select = ref("");
/////////////////////
const hanldType = ref(null);
const selUserNames = ref("");
const dangansel = ref(false);
const uploadNot = 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 nowNode = ref(true);
const receivedData = ref(null);
const workId = ref(null);
const nowShow = ref(null);
const targetuuid = ref(null);
const uuid = ref(null);
const sendUrl = ref(null);
const NextStepNode = ref([]);
const flowDatas = ref({});
const selNextNode = ref(null);
const typeList = ref([]);
const tuurl = ref("");
const szFileName = 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",
});
const props = defineProps({
  ReceivedQiLinData: null,
  nowShow: null,
  hanldType: null,
});

let requestParams = getRequest(); //获取当前url地址
let WebOffice;
const onSubmit = (formEl) => {
  closePage(0);
  saveOffice2Web();
};
function closeDialog(done) {
  done();
}
function openWebOffic() {
  proxy.$nextTick(() => {
    WebDownLoadFile();
  });
}
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 openYbj() {
  ybjState.value = true;
  // closePage(0);
}
const uploadPdfFile = (response, file) => {
  console.log(response, file);
  outMessageParams.value.finalFileId = response.data.fileId;
};
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;
  });
}
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);
  dialogBack.value = false;
  proxy.$emit("closeViewLeave");

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

  proxy.$modal.closeLoading();
  webOfficeOBJ.value.CloseDocument();
}

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);
}
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.CloseDocument();
    dialogApproved.value = false;
    formData.value.reviewMsg = "";
    proxy.$emit("closeViewLeave");
  });
}
//获取退回界定啊
async function returnWorkNode() {
  let nData = await getReturnWorkNode(getJToken(), formData.value.workid);
  nodeData.value = nData;
}

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.CloseDocument();
      });
      proxy.$emit("closeViewLeave");
    } 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",
            });
            proxy.$emit("closeViewLeave");
            formData.value.reviewMsg = "";

            // msgValue.value = true;
          } else if (response.data.VarAcceptersName == "结束") {
            ElMessage({
              message: response.data.Message,
              type: "success",
            });
            proxy.$emit("closeViewLeave");
          } else {
            ElMessage({
              message: response.data.Message.replaceAll("@", ""),
              type: "success",
            });
          }
          proxy.$emit("closeViewLeave");
          proxy.$modal.closeLoading();
          webOfficeOBJ.value.CloseDocument();
        } else {
          proxy.$modal.msgError("发送失败");
          proxy.$emit("closeViewLeave");
        }
      });
    }
  }
}

/** 选择用户后进行下一步 */
function VBAShowRevisions(flg) {
  webOfficeOBJ.value.VBAShowRevisions(flg);
}
/** 查询归档类型列表 */
function getTypeList() {
  listType({}).then((response) => {
    typeList.value = proxy.handleTree(
      response.data,
      "archiveTypeId",
      "parentId"
    );
  });
}
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 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() {
  flowDatas.value.toNodeId = selNextNode.value;
  proxy.$refs["selectRef"].show1(flowDatas.value);
}

async function saveOffice2Web() {
  proxy.$modal.loading("正在提交中，请稍候...");

  //console.log(webOfficeOBJ.value.getFilePath() + webOfficeOBJ.value.FileName)
  console.log("保存文档到本地成功");
  //保存文件到本地
  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) {
        // alert(httpclient.ResponseText);
        var res = JSON.parse(httpclient.ResponseText);
        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();
              webOfficeOBJ.value.CloseDocument();
              proxy.$emit("closeViewLeave");
              proxy.$modal.closeLoading();
            } else {
              proxy.$modal.closeLoading();
              proxy.$modal.msgError("提交失败");
              webOfficeOBJ.value.CloseDocument();
              proxy.$emit("closeViewLeave");
            }
          });
        } else {
          proxy.$modal.closeLoading();
          proxy.$modal.msgError("保存文档到服务器失败");
          webOfficeOBJ.value.CloseDocument();
          proxy.$emit("closeViewLeave");
          return false;
        }
      }
    }
    httpclient.Close();
  }
}

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

function Load() {
  // 是否可编辑原信息
  getSelfParas(flowDatas.value.WorkID).then((res) => {
    console.log("是否可编辑原信息", res);
    if (res.data.SelfParas == "isEdit") {
      isEdit.value = false;
    }
    uploadNot.value = true;
    if (nowShow == "no") {
      isEdit.value = true;
      uploadNot.value = false;
    }
  });
  getOutMessageByWorkId(flowDatas.value.WorkID).then((response) => {
    if (response.code == "200") {
      outMessageParams.value = response.data;
      docFile.value = response.data.sendFile;
      if (outMessageParams.value.infoOpenType == "3") {
        showNotReason.value = true;
      }
      WebDownLoadFile();
      // initWebOffice();
    }
  });
  //chrome浏览器，HookEnabled设置为true，用于控件中和本地excel表格的焦点互相切换

  loadingWebLoad.value = false;
}
//作用：打开远程文件
function WebDownLoadFile() {
  loadingWebLoad.value = false;
  //   if (document.getElementById("WebOfficeId") != null) {
  webOfficeOBJ.value = document.getElementById("WebOffice");
  getInfo().then((res) => {
    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); //设置信创中间件加载文字编辑软件
      //以下属性必须设置，实始化iWebOffice
      webOfficeOBJ.value.FileName = Math.random() * 100000 + "Mytemplate.doc";
      webOfficeOBJ.value.ShowWindow = false; //显示/隐藏进度条
      webOfficeOBJ.value.EditType = "2"; //设置加载文档类型 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();
      proxy.$modal.closeLoading();
      var urlFile = outMessageParams.value.sendFile.url;
      var mResult = webOfficeOBJ.value.WebDownLoadFile(
        urlFile,
        "/tmp/test.doc"
      );
      szFileName.value = "/tmp/test.doc";

      if (mResult) {
        webOfficeOBJ.value.WebOpenLocalFile("/tmp/test.doc");
        //alert("成功");
      } else {
        //alert("失败");
      }
    } catch (e) {
      proxy.$modal.closeLoading();
    }
  });
}
function onCloseBtnClicked() {}

const onCloseBtnClicked1 = () => {};

function closePage(numf) {
  if (numf == undefined) {
    return;
  }
}

//获取所有可退回的节点
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() {
  proxy.$modal.loading("正在打开中...");
  nowNode.value = true;
  if (props.ReceivedQiLinData.FK_Node == "201") {
    nowNode.value = false;
  }

  // flowDatas.value.FK_Flow = getUrlParameter("FK_Flow");
  //是否展示 发送下一步
  hanldType.value = props.hanldType;
  nowShow.value = props.value;
  //档案查看
  // dangansel.value = getUrlParameter("dangan") == "true";
  formData.value = props.ReceivedQiLinData;

  formData.value.workid = formData.value.WorkID;
  flowDatas.value.WorkID = formData.value.WorkID;
  flowDatas.value.FK_Node = formData.value.FK_Node;
  flowDatas.value.FK_Flow = formData.value.FK_Flow;
  formData.value.optionName = formData.value.NodeName;
  //判断当前节点是不是最后一个.

  getLiuzhuanData();

  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;

  //获取iWebOffice2015控件对象，WebOffice.FuncExtModule是iWebOffice2015控件扩展接口对象
  //加载dom元素，获取 weboffice对象
  initOffice(document);

  setTimeout(function () {
    Load();
  }, 1000); //需要做一个延时，iWebOffice2015才能获取FuncExtModule扩展接口对象
}

// onMounted(async () => {
//   console.log("onMounted11");
//   OnReady();
//   window.addEventListener("beforeunload", beforeUnloadListener());
// });

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

function beforeUnloadListener() {
  // setCloseTabItemAs()
  // alert("111")
}
defineExpose({
  OnReady,
});
</script>

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