<!-- @format -->
<!-- 收文 -->
<template>
  <el-dialog
    ref="swDialog"
    :title="dialogTitle"
    :close-on-click-modal="false"
    @close="colsedialog"
    @opened="openSW"
    :destroy-on-close="true"
    v-model="visible"
    width="1600px"
    top="2vh"
    append-to-body
  >
    <div class="app-container" style="margin-top: -45px">
      <el-row :gutter="20" style="max-height: 800px">
        <el-col
          :span="17"
          style="background-color: #9ca1a7; margin-top: 10px; padding: 20px"
        >
          <PdfViewer
            ref="pdfViewRef"
            :key="$route.fullPath"
            :current-page="pdfPages"
            :src="pdfUrl"
          ></PdfViewer>
          <!-- <iframe :src="pdfUurl" frameborder="0"></iframe> -->
        </el-col>
        <el-col :span="7">
          <el-tabs type="border-card" class="demo-tabs">
            <el-tab-pane>
              <template #label>
                <span class="custom-tabs-label">
                  <el-icon><Document /></el-icon>
                  <span>基本信息</span>
                </span>
              </template>
              <el-form
                ref="receivedFormRef"
                label-width="90px"
                :disabled="isAllowed"
                style="width: 300px"
                :rules="rules"
                :model="receiverData"
              >
                <el-form-item label=":" prop="title">
                  <el-input
                    v-model="receiverData.title"
                    placeholder="请输入来文标题"
                  ></el-input>
                </el-form-item>
                <el-form-item label="来文单位:" prop="sender">
                  <el-input
                    v-model="receiverData.sender"
                    placeholder="请输入来文单位"
                  ></el-input>
                </el-form-item>
                <el-form-item label="来文日期:" prop="sendTime">
                  <el-date-picker
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    v-model="receiverData.sendTime"
                    type="date"
                    placeholder="请输入来文日期"
                    size="defalut"
                  />
                </el-form-item>
                <el-form-item label="流水号: " prop="serial">
                  <el-input
                    v-model="receiverData.serial"
                    placeholder="请输入流水号"
                  ></el-input>
                </el-form-item>
                <el-form-item label="文件字号:" prop="documentNum">
                  <el-input
                    v-model="receiverData.documentNum"
                    placeholder="请输入文件字号"
                  ></el-input>
                </el-form-item>
                <el-form-item label="紧急程度:" prop="emergencyDegree">
                  <el-select
                    v-model="receiverData.emergencyDegree"
                    placeholder="请输入紧急程度"
                  >
                    <el-option
                      v-for="dict of urgent_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="附件列表:">
                  <el-link
                    v-for="(item, index) in fujianList"
                    :key="index"
                    type="primary"
                    @click="openFujianFile(item.url)"
                  >
                    <el-icon class="el-icon--left">
                      <Document />
                    </el-icon>
                    {{ item.name }}
                  </el-link>
                </el-form-item>
              </el-form>
              <el-form
                v-show="hanldType"
                label-width="90px"
                style="width: 300px"
              >
                <el-form-item label="下一步节点:">
                  <el-select
                    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 label="审核意见:">
                    <el-input
                      type="textarea"
                      :rows="2"
                      placeholder="请输入审核意见"
                      v-model="formData.reviewMsg"
                    />
                  </el-form-item>
                  <el-form-item v-if="feedback" label="反馈时限:">
                    <div style="font-size: 15px">
                      {{ parseTime(closeTime) }}
                    </div>
                  </el-form-item>
                  <el-form-item v-if="feedback" label="反馈文件:">
                    <el-upload
                      ref="fujianUpload"
                      v-model:file-list="fujianList1"
                      :action="upload.url"
                      :headers="upload.headers"
                      :on-success="uploadFuJianFiles1"
                      multiple
                    >
                      <el-button type="primary">点击上传附件</el-button>
                    </el-upload>
                  </el-form-item>
                  <el-form-item>
                    <template v-if="fileBackFile.length !== 0">
                      <el-link
                        type="primary"
                        v-for="(item, index) in fileBackFile"
                        :key="index"
                        @click="openUrl(item.yfile.url)"
                      >
                        <el-icon><Document></Document></el-icon>
                        {{ item.yfile.name }}
                      </el-link>
                    </template>
                  </el-form-item>

                  <el-form-item label="">
                    <el-button
                      :loading="loadingWebLoad"
                      :disabled="false"
                      @click="sendNext"
                      type="primary"
                      >提交
                    </el-button>
                    <el-button
                      v-if="nodeInfo"
                      :disabled="false"
                      @click="sendBack"
                      type="danger"
                      >退回
                    </el-button>
                  </el-form-item>
                </div>
                <!--   归档操作       -->
                <div v-show="guidangBt">
                  <!-- <el-form-item label="档案编号: ">
                    <el-input
                      placeholder="请输入档案编号"
                      v-model="guidangData.archiveNo"
                    ></el-input>
                  </el-form-item> -->
                  <!--
                              <el-form-item label="档案份数: "  >
                                <el-input
                                    placeholder="请输入档案编号"
                                    v-model="guidangData.archiveNum"></el-input>
                              </el-form-item>-->
                  <el-form-item label="档案分类: ">
                    <el-tree-select
                      v-model="guidangData.typeId"
                      :data="typeList"
                      :props="{
                        value: 'archiveTypeId',
                        label: 'name',
                        children: 'children',
                        disabled: (data) => {
                          return data.children !== undefined ? true : false;
                        },
                      }"
                      value-key="archiveTypeId"
                      placeholder="请选择档案分类"
                      check-strictly
                    />
                  </el-form-item>
                  <el-form-item label="打印份数: ">
                    <el-input
                      placeholder="请输入打印份数"
                      v-model="guidangData.printNum"
                    ></el-input>
                  </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="sendNext"
                      type="primary"
                      >归档
                    </el-button>
                  </el-form-item>
                </div>
              </el-form>
            </el-tab-pane>
            <el-tab-pane>
              <template #label>
                <span class="custom-tabs-label">
                  <el-icon><Promotion /></el-icon>
                  <span>流转记录</span>
                </span>
              </template>
              <iframe :src="tuurl" width="100%" height="500px"></iframe>
            </el-tab-pane>
            <el-tab-pane label="收文阅办笺" v-hasPermi="['lc:sw:ybj']">
              <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>
    </div>
    <select-user
      ref="selectRef"
      @ok="handleQuery"
      @closeDialogf="closeSelUser"
    ></select-user>
    <!-- 退回 -->
    <el-dialog title="退回" v-model="dialogBack" width="40%">
      <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="submitNodeBack">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="阅办笺" v-model="ybjState">
      <incoming-message ref="incomRef" :id="receiverData.id"></incoming-message>
    </el-dialog>
  </el-dialog>
</template>

<script setup name="viewPdfer">
import PdfViewer from "@/components/PdfViewer";
import selectUser from "../../selectUser";
import { getToken } from "@/utils/auth";
import { listType } from "@/api/archive/type";

const { that, proxy } = getCurrentInstance();
import { onMounted, reactive, ref, nextTick } from "vue";
import { saveReceived } from "@/api/office/received";
import { useRoute, useRouter } from "vue-router";
import {
  generNextStepNode,
  generNextStepAllNode,
  judgeNode,
  sendFlowToNext,
  node_ReturnWork,
  receive,
} from "@/api/liucheng";
import {
  leave,
  getLeave,
  getReturnWorkNode,
  WorkProgressBar,
  NodeReturnWork,
} from "@/api/clocking/leave";
import { ElMessage, ElMessageBox } from "element-plus";
import { getJToken } from "@/utils/auth";
import { saveArchive } from "@/api/archive/archive";

import incomingMessage from "@/views/incomingMessages";

import Cookies from "js-cookie";

const { archive_levels } = proxy.useDict("archive_levels");

const router = useRouter();
const route = useRoute();
const key = computed(() => {
  return route.path + Math.random();
});
const print = ref({
  id: "printContent", //这里的id就是上面我们的打印区域id，实现指哪打哪
  // popTitle: '配置页眉标题', // 打印配置页上方的标题
  // extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  // preview: false, // 是否启动预览模式，默认是false
  // previewTitle: '预览的标题', // 打印预览的标题
  // previewPrintBtnLabel: '预览结束，开始打印', // 打印预览的标题下方的按钮文本，点击可进入打印
  // zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
  // previewBeforeOpenCallback() { //console.log('正在加载预览窗口！'); }, // 预览窗口打开之前的callback
  // previewOpenCallback() { //console.log('已经加载完预览窗口，预览打开了！') }, // 预览窗口打开时的callback
  // beforeOpenCallback() { //console.log('开始打印之前！') }, // 开始打印之前的callback
  // openCallback() { //console.log('执行打印了！') }, // 调用打印时的callback
  // closeCallback() { //console.log('关闭了打印工具！') }, // 关闭打印的callback(无法区分确认or取消)
  // clickMounted() { //console.log('点击v-print绑定的按钮了！') },
});

const pdfUrl = ref("");
const pdfUurl = ref(null);
const nodeInfo = ref(true);
const visible = ref(false);
const isAllowed = ref(true);
const { mail_state } = proxy.useDict("urgent_type");

const nodeValue = ref(null);
const returnMsg = ref(null);
const dialogBack = ref(false);
const feedback = ref(false);
const nodeData = ref([]);
const valDate = ref(null);
const closeTime = ref(null);
const loadingWebLoad = ref(false);
let pdfDoc = null;
const pdfPages = ref(0);
const sendDownFile = ref([]);
const fileBackFile = ref([]);
// const incoming = ref("/incomingMessages");
const NextStepNode = ref([]);
const fujianList = ref([]);
const fujianList1 = ref([]);
const dialogTitle = ref("收文");
const hanldType = ref(false);
const guidangBt = ref(false);
const ybjState = ref(false);
const isEndNodeFlg = ref(false);
const selUserNames = ref("");
const tuurl = ref("");
const selNextNode = ref("");
const typeList = ref([]);
const receiverData = ref({});
//可退回的节点
const reWorkNode = ref({});

/** 查询归档类型列表 */
function getTypeList() {
  listType({}).then((response) => {
    typeList.value = proxy.handleTree(
      response.data,
      "archiveTypeId",
      "parentId"
    );
  });
}

const data = reactive({
  upload: {
    // 设置上传的请求头部
    headers: { Authorization: "Bearer " + getToken() },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + "/system/file/fileupload",
  },
  formData: {
    reviewMsg: "同意",
    optionName: null,
    toNodeId: null,
    users: null,
    workid: null,
  },
  receivedParams: {
    title: null, //来文标题
    sender: null, //单位
    sendTime: null, //时间
    serial: null, //流水号
    documentNum: null, //字号
    emergencyDegree: null, //紧急程度
    sendDownFileId: null, //下发文件
    receiveFileId: null, //收文原件
    fujianFileList: [], //附件信息
  },
  guidangData: {
    archiveNo: null,
    workId: null,
    archiveFormNo: null,
    printNum: null,
    levels: null,
    typeId: null,
    name: null,
  },
});
const { formData, upload, receivedParams, rules, guidangData } = toRefs(data);

const receivedFormRef = ref(false);
const flowDatas = ref({});
const emit = defineEmits(["guanbi"]);

function openYbj() {
  ybjState.value = true;
}

function closeSelUser() {}

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

async function submitNodeBack() {
  if (nodeValue.value == null) {
    proxy.$message.error("请选择退回节点信息");
    return;
  }
  if (returnMsg.value == null) {
    proxy.$message.error("请输入退回原因");
    return;
  }
  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;
  colsedialog();
}

function sendBack() {
  dialogBack.value = true;
  // closePage(0);
  returnWorkNode();
}

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

const dcolse = (done) => {
  pdfPages.value = 0;
  pdfUrl.value = "";
  sendDownFile.value = [];
  fujianList.value = [];
  fujianList1.value = [];
  receivedFormRef.value = false;
  loadingWebLoad.value = false;
  emit("guanbi");
  done();
};
const colsedialog = () => {
  pdfPages.value = 0;
  pdfUrl.value = "";
  sendDownFile.value = [];
  fujianList.value = [];
  fujianList1.value = [];
  receivedFormRef.value = false;
  visible.value = false;
  loadingWebLoad.value = false;
  reset();
  emit("guanbi");
};

/** 查询参数列表 */
function showdetal2(recdata, flowData, type) {
  if (recdata.feedbackFileList !== undefined) {
    fileBackFile.value = recdata.feedbackFileList;
    // for (let i = 0; i < recdata.feedbackFileList.length; i++) {
    //   receiverData.value.feedbackFileList.push({
    //     fileId: recdata.feedbackFileList[i].yfile.fileId,
    //     userName: recdata.feedbackFileList[i].yfile.createBy,
    //   });
    // }
  }

  feedback.value = false;
  if (recdata.isFeedback == "1") {
    feedback.value = true;
    closeTime.value = recdata.closeTime;
  }
  nodeInfo.value = true;
  if (flowData.NodeName == "创建收文") {
    nodeInfo.value = false;
  }
  visible.value = true;
  if (recdata.sendFile != null) {
    pdfUrl.value = recdata.sendFile.url;
  }
  for (let i in recdata.fujianFileList) {
    fujianList.value.push(recdata.fujianFileList[i].yfile);
  }
  // receiverData.value.feedbackFileList
  receiverData.value = recdata;
  hanldType.value = type;
  formData.value.workid = flowData.WorkID;
  formData.value.optionName = flowData.NodeName;
  flowDatas.value = flowData;
  dialogTitle.value = flowData.NodeName;
  nextTick(() => {
    if (pdfUrl.value != null && pdfUrl.value != "") {
      proxy.$refs["pdfViewRef"].loadFile(pdfUrl.value);
    }
  });
  tuurl.value =
    Cookies.get("jFontIp") +
    "/WF/Port.htm?DoWhat=OneWork2&WorkID=" +
    flowData.WorkID +
    "&FK_Flow=" +
    flowData.FK_Flow +
    "&Token=" +
    getJToken();
  //判断当前节点是不是最后一个.
  judgeNode(flowDatas.value.FK_Node, getJToken()).then((nres) => {
    if (nres.msg == "Y") {
      NextStepNode.value.push({ NodeID: 0, Name: "结束" });
      isEndNodeFlg.value = true;
    } else {
      //获取下个节点.
      generNextStepAllNode(
        flowDatas.value.FK_Flow,
        flowDatas.value.WorkID,
        "",
        getJToken()
      ).then((res) => {
        NextStepNode.value = res;
        selNextNode.value = NextStepNode.value[0].NodeID;
      });
    }
  });

  if (
    formData.value.optionName == "归档打印" ||
    formData.value.optionName == "赋文号归档"
  ) {
    getTypeList();
    formData.value.reviewMsg = "归档";
    guidangBt.value = true;
  }
}

/** 选择用户后进行下一步 */
function handleQuery(selUsers) {
  formData.value.users = selUsers;
  if (selUsers != undefined && selUsers != "") {
    onSubmit();
  }
}

function openFujianFile(url) {
  window.open(url, "_blank");
}
function openUrl(url) {
  window.open(url, "_blank");
}

const openSW = () => {};

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

//点击提交
const onSubmit = async () => {
  loadingWebLoad.value = true;
  //反馈文件
  receiverData.value.feedbackFileList = [];
  for (let i = 0; i < fileBackFile.value.length; i++) {
    if (fileBackFile.value[i].yfile.length !== 0) {
      receiverData.value.feedbackFileList.push({
        fileId: fileBackFile.value[i].fileId,
        userName: fileBackFile.value[i].yfile.createBy,
      });
    }
  }
  for (let i = 0; i < fujianList1.value.length; i++) {
    receiverData.value.feedbackFileList.push({
      fileId: fujianList1.value[i].response.data.fileId,
      userName: fujianList1.value[i].response.data.createBy,
    });
  }
  if (guidangBt.value) {
    guidangData.value.archiveFormNo = flowDatas.value.FK_Flow;
    guidangData.value.workId = flowDatas.value.WorkID;
    let { archiveRes } = await saveArchive(guidangData.value);
  }
  // 如果市最后一个节点则执行 完成
  if (isEndNodeFlg.value) {
    generNextStepAllNode(
      flowDatas.value.FK_Flow,
      flowDatas.value.WorkID,
      "",
      getJToken()
    ).then((res) => {
      ElMessage({
        message: "当前工作已结束",
        type: "success",
      });
      colsedialog();
    });
  } else {
    //todo 调用修改接口 修改
    receive(receiverData.value).then((response) => {});
    // receiverData.value.feedbackFileList = [];
    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",
          });
        } else if (response.data.VarAcceptersName == "结束") {
          ElMessage({
            message: response.data.Message,
            type: "success",
          });
        } else {
          ElMessage({
            message: response.data.Message.replaceAll("@", ""),
            type: "success",
          });
        }
        colsedialog();
        loadingWebLoad.value = false;
      } else {
        loadingWebLoad.value = false;
        colsedialog();
      }
      loadingWebLoad.value = false;
    });
  }
};

function openRetrunWork() {}

//退回
const returnWork = () => {
  let reData = {
    workid: flowDatas.value.WorkID,
    returnToNodeID: "",
    returnMsg: "",
    token: getJToken(),
  };
  node_ReturnWork().then((reData) => {
    ElMessage({
      message: "退回成功",
      type: "success",
    });
    colsedialog();
  });
};

//点击发送到下一步
const sendNext = () => {
  if (formData.value.reviewMsg == "" || formData.value.reviewMsg == null) {
    ElMessageBox.alert("请填写审核意见", "提示", {
      confirmButtonText: "确定",
      type: "warning",
    });
    return;
  }
  formData.value.toNodeId = selNextNode.value;
  let DeliveryWay = "";
  //查看当前是选择的那个节点
  NextStepNode.value.forEach((item, index) => {
    if (item.NodeID == selNextNode.value) {
      DeliveryWay = item.DeliveryWay;
    }
  });
  // return;
  // //console.log(selNextNode.value)
  //判断当前节点是哪一个节点
  //DeliveryWay 3:绑定人员计算
  if (DeliveryWay == "3") {
    onSubmit();
  }
  //4:由发送人选择发送
  else if (DeliveryWay == "4") {
    openSelectUser();
    return;
  } else {
    onSubmit();
  }
};

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