<!-- @format -->

<template>
  <el-dialog
    title="收文"
    :close-on-click-modal="false"
    :before-close="dcolse"
    :destroy-on-close="true"
    v-model="visible"
    width="83%"
    :fullscreen="fullscreen"
    top="2vh"
    append-to-body
  >
    <div
      @click="Enlarge"
      style="float: right; position: relative; top: -60px; right: 30px"
    >
      <el-icon><FullScreen /></el-icon>
    </div>
    <div
      @click="Enlarge1"
      style="float: right; position: relative; top: -60px; right: 50px"
    >
      <el-icon><Minus /></el-icon>
    </div>
    <div class="app-container" style="margin-top: -45px">
      <el-row :gutter="20" style="min-height: 82vh; max-height: 90vh">
        <el-col
          :span="18"
          style="background-color: #9ca1a7; margin-top: 10px; padding: 20px"
        >
          <iframe
            style="overflow: scroll; width: 100%; height: 100%"
            :src="iframeSrc"
            ref="iframeRef"
          >
          </iframe>
        </el-col>
        <el-col :span="3">
          <el-form
            ref="receivedFormRef"
            label-width="105px"
            :disabled="isAllowed"
            style="width: 20vw"
            :rules="rules"
            :model="receivedParams"
          >
            <el-form-item label="紧急程度:" prop="emergencyDegree">
              <el-select
                style="width: 350px"
                v-model="receivedParams.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="来文标题:" prop="title">
              <el-input
                style="width: 400px"
                v-model="receivedParams.title"
                placeholder="请输入来文标题"
              ></el-input>
            </el-form-item>
            <el-form-item label="来文单位:" prop="sender">
              <!-- <el-input
                v-model="receivedParams.sender"
                placeholder="请输入来文单位"
              ></el-input> -->

              <el-input
                style="width: 20vw"
                v-model="receivedParams.sender"
                placeholder="请选择或输入来文单位"
                class="input-with-select"
              >
                <template #append>
                  <el-select
                    placement="bottom-start"
                    v-model="outUnit1"
                    placeholder="选择"
                    @change="changeSelect"
                    style="width: 78px"
                  >
                    <el-option
                      v-for="item in lw_unit"
                      :key="item.value"
                      :label="item.label"
                      :value="item.label"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-input>

              <!--            <el-link type="primary" :onclick="openLwUnit">选择</el-link>-->
            </el-form-item>
            <!--          <el-form-item label="来文内容:" prop="content">
            <el-input
                :rows="2"
                type="textarea"
                v-model="receivedParams.content"
                placeholder="请输入来文内容"
            ></el-input>
          </el-form-item>-->
            <el-form-item label="来文日期:" prop="sendTime">
              <el-date-picker
                style="width: 350px"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                v-model="receivedParams.sendTime"
                type="date"
                placeholder="请输入来文日期"
                size="defalut"
              />
            </el-form-item>
            <el-form-item label="流水号: " prop="serial">
              <el-input
                v-model="receivedParams.serial"
                placeholder="请输入流水号"
              ></el-input>
            </el-form-item>

            <el-form-item label="文件类型: " prop="receiveType">
              <el-select
                v-model="receivedParams.receiveType"
                placeholder="请选择文件类型"
                style="width: 350px"
              >
                <el-option
                  v-for="dict in sw_open_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                  >{{ dict.label }}</el-option
                >
              </el-select>
            </el-form-item>

            <el-form-item label="文件字号:" prop="documentNum">
              <!-- <el-input
                v-model="receivedParams.documentNum"
                placeholder="请选择文件字号"
              ></el-input> -->
              <!-- <el-select
                placement="bottom-start"
                v-model="receivedParams.documentNum"
                placeholder="请选择文件字号"
                style="width: 350px"
              >
                <el-option
                  v-for="item in receive_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                >
                </el-option>
              </el-select> -->
              <el-input
                v-model="receivedParams.documentNum"
                placeholder="请选择或输入文件字号"
              >
                <template #append>
                  <el-select
                    placement="bottom-start"
                    v-model="selectWordNum"
                    placeholder="选择"
                    @change="changeSelect1"
                    style="width: 78px"
                  >
                    <el-option
                      v-for="item in receive_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.label"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="上传正文:">
              <el-upload
                style="max-width: 300px"
                class="upload-pdf"
                ref="sendFileUpload"
                :action="upload.url"
                :headers="upload.headers"
                :disabled="isAllowed"
                multiple
                accept=".pdf"
                :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-upload
                ref="fujianUpload"
                v-model:file-list="fujianList"
                :action="upload.url"
                :headers="upload.headers"
                :on-success="uploadFuJianFiles"
                :disabled="isAllowed"
                multiple
              >
                <el-button type="primary">点击上传附件</el-button>
              </el-upload>
            </el-form-item>

            <!-- <el-form-item label="拟办意见:" prop="remark">
              <el-input
                :rows="2"
                type="textarea"
                v-model="receivedParams.remark"
                placeholder="请输入拟办意见"
              ></el-input>
            </el-form-item> -->
            <el-form-item label="是否需要反馈:" prop="">
              <el-radio-group v-model="receivedParams.isFeedback" class="ml-4">
                <el-radio label="1" size="large">是</el-radio>
                <el-radio label="0" size="large">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              v-if="receivedParams.isFeedback == '1'"
              label="反馈时限:"
              prop=""
            >
              <el-date-picker
                style="width: 350px"
                :picker-options="disabledDate"
                v-model="receivedParams.closeTime"
                type="datetime"
                placeholder="请选择反馈时限"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                @change="handle"
              />
              <!-- <el-date-picker
                v-model="receivedParams.closeTime"
                type="datetime"
                placeholder="Pick a Date"
                format="YYYY/MM/DD HH:mm:ss"
              /> -->
            </el-form-item>

            <el-form-item>
              <el-button
                :loading="loadingWebLoad"
                @click="onSubmit(receivedFormRef)"
                type="primary"
                >提交</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>

<script setup name="viewPdf">
import { getToken } from "@/utils/auth";
const { proxy } = getCurrentInstance();
import { onMounted, reactive, ref } from "vue";
import { saveReceived } from "@/api/office/received";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
const { lw_unit } = proxy.useDict("lw_unit");
const { sw_open_type } = proxy.useDict("sw_open_type");
import { Base64 } from "js-base64";
const router = useRouter();
const route = useRoute();
const key = computed(() => {
  return route.path + Math.random();
});
const iframeSrc = ref("");
const value2 = ref("");
const selectWordNum = ref([]);
const input3 = ref("");
const pdfUrl = ref("");
const defaultTime = new Date(2000, 1, 1, 12, 0, 0);
const dialogApproved = ref(false);
const visible = ref(false);
const isAllowed = ref(false);
const outUnit1 = ref([]);
const { urgent_type } = proxy.useDict("urgent_type");
const { receive_type } = proxy.useDict("receive_type");
const radio1 = ref("0");
//////////////////////////////
const date = ref(new Date());

const disabledDate = ref((time) => {
  return time.getTime() < Date.now() - 1 * 24 * 3600 * 1000;
});

onMounted(() => {
  if (receivedParams.value.closeTime < Date.now()) {
    receivedParams.value.closeTime = new Date();
  }

  // else if (receivedParams.value.closeTime == '' || receivedParams.value.closeTime == null || receivedParams.value.closeTime == undefined) {
  //   return;
  // }
});
function notApproved() {
  dialogApproved.value = true;
  closePage(0);
}
function handle() {
  var startAt = (new Date(receivedParams.value.closeTime) * 1000) / 1000;

  if (startAt < Date.now()) {
    let formatDate;
    formatDate = new Date();
    formatDate =
      formatDate.getFullYear() +
      "-" +
      (formatDate.getMonth() + 1 > 9
        ? formatDate.getMonth() + 1
        : "0" + (formatDate.getMonth() + 1)) +
      "-" +
      (formatDate.getDate() > 9
        ? formatDate.getDate()
        : "0" + formatDate.getDate()) +
      "  " +
      (formatDate.getHours() > 9
        ? formatDate.getHours()
        : "0" + formatDate.getHours()) +
      ":" +
      (formatDate.getMinutes() > 9
        ? formatDate.getMinutes()
        : "0" + formatDate.getMinutes()) +
      ":" +
      (formatDate.getSeconds() > 9
        ? formatDate.getSeconds()
        : "0" + formatDate.getSeconds());
    receivedParams.value.closeTime = formatDate;
  }
}
function changeSelect1(val) {
  if (receivedParams.value.documentNum != "") {
    receivedParams.value.documentNum = val;
  } else {
    receivedParams.value.documentNum = val;
  }
  selectWordNum.value = "";
}
/** 查询参数列表 */
function show(type) {
  visible.value = true;
  receivedParams.value.offcialType = type;
  setTimeout(() => {
    proxy.$refs.receivedFormRef.resetFields();
  }, 200);
}
const loadingWebLoad = ref(false);
let pdfDoc = null;
const pdfPages = ref(0);
const sendDownFile = ref([]);
const fujianList = ref([]);
const fullscreen = ref(true);
const receivedFormRef = ref(false);
const dcolse = (done) => {
  iframeSrc.value = "";
  pdfPages.value = 0;
  sendDownFile.value = [];
  receivedFormRef.value = false;
  restForm();
  proxy.$refs["fujianUpload"].clearFiles();
  proxy.$refs["sendFileUpload"].clearFiles();
  done();
};
function restForm() {
  receivedParams.value = {
    title: null, //来文标题
    offcialType: null, //来文标题
    sender: "", //单位
    sendTime: null, //时间
    serial: null, //流水号
    // documentNum: null, //字号
    emergencyDegree: null, //紧急程度
    sendDownFileId: null, //下发文件
    receiveFileId: null, //收文原件
    fujianFileList: [], //附件信息
    isFeedback: "0",
    closeTime: null,
    documentNum: "",
  };
}

const data = reactive({
  upload: {
    // 设置上传的请求头部
    headers: { Authorization: "Bearer " + getToken() },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + "/system/file/fileupload",
  },
  formData: {},
  receivedParams: {
    title: null, //来文标题
    offcialType: null, //来文标题
    sender: "", //单位
    sendTime: null, //时间
    serial: null, //流水号
    // documentNum: null, //字号
    emergencyDegree: null, //紧急程度
    sendDownFileId: null, //下发文件
    receiveFileId: null, //收文原件
    fujianFileList: [], //附件信息
    isFeedback: "0",
    closeTime: null,
    documentNum: "",
  },
  rules: {
    title: [
      {
        required: true,
        message: "来文标题不能为空",
        trigger: "blur",
      },
    ],
    sender: [
      {
        required: true,
        message: "来文单位不能为空",
        trigger: ["blur", "change"],
      },
    ],
    sendTime: [
      {
        required: true,
        message: "来文时间不能为空",
        trigger: "blur",
      },
    ],
    serial: [
      {
        required: true,
        message: "流水号不能为空",
        trigger: "blur",
      },
    ],
    documentNum: [
      {
        required: true,
        message: "字号不能为空",
        trigger: ["change", "blur"],
      },
    ],
    receiveType: [
      {
        required: true,
        message: "请选择文件类型",
        trigger: "blur",
      },
    ],
    emergencyDegree: [
      {
        required: true,
        message: "请选择紧急程度",
        trigger: "change",
      },
    ],
  },
});
const { formData, upload, receivedParams, rules } = toRefs(data);

function openLwUnit() {}
function Enlarge() {
  fullscreen.value = true;
}
function Enlarge1() {
  fullscreen.value = false;
}
//pdf
// 上传前
function before_upload(file) {
  // 截取上传文件的后缀名
  let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
  console.log(fileType);
  // 判断文件名的类型，允许多种就判断多个
  if (fileType == "pdf") {
    console.log(file);
  } else {
    ElMessage.error("文件类型必须为pdf格式");
    // 返回false 就不会执行上传操作了
    return false;
  }
  // 判断多个
  // if (!["pdf", "doc", "docx"].includes(fileType)) {
  //    ElMessage.error("文件类型必须为pdf格式");
  //    return false;
  // }
}

// // 上传
// function  UploadImage(param) {
//     let formData = new FormData()
//     formData.append('file', param.file)
//     // 调用自己的后端接口上传文件到服务器
//     getUpload(formData).then((res)=>{
//     if (res.code === 1) {
//         ElMessage.success(res.msg)
//         this.contract_file.push({
//             name: res.data.name,
//             url: res.data.url
//         })
//     } else {
//         ElMessage.error(res.msg)
//     }
//    })

// }

// // 删除上传的文件
// function handleRemove(flie, fileList) {
//   this.contract_file = fileList;
// }

const onSubmit = (formEl) => {
  if (!formEl) return;
  if (receivedParams.value.sendDownFileId == null) {
    ElMessage({
      message: "请先上传正文",
      type: "warning",
    });
    return;
  }
  if (receivedParams.value.isFeedback != "1") {
    receivedParams.value.closeTime = "";
  }
  formEl.validate(async (valid, fields) => {
    if (valid) {
      proxy.$modal.loading("提交中，请稍候！");
      loadingWebLoad.value = true;
      // receivedParams.yOffcialReceiveFileList =  fujianList.value.map((element) => {
      //   return {"offcialReceiveId":null, fileId: element.response.data.fileId };
      // });
      for (let i = 0; i < fujianList.value.length; i++) {
        receivedParams.value.fujianFileList.push({
          fileId: fujianList.value[i].response.data.fileId,
        });
      }
      saveReceived(receivedParams.value).then((response) => {
        if (response.code == 200) {
          if (response.data.VarAcceptersName != "") {
            ElMessage({
              message:
                "已发送到" +
                response.data.VarToNodeName +
                "节点，接收人：" +
                response.data.VarAcceptersName,
              type: "success",
            });
          } else {
            ElMessage({
              message: response.data.Message.replaceAll("@", ""),
              type: "success",
            });
          }
          //清空表单数据
          pdfPages.value = 0;
          sendDownFile.value = [];
          receivedFormRef.value = false;
          restForm();
          proxy.$refs["fujianUpload"].clearFiles();
          proxy.$refs["sendFileUpload"].clearFiles();
          iframeSrc.value = "";
          loadingWebLoad.value = false;
          visible.value = false;
        } else {
          loadingWebLoad.value = false;
          visible.value = false;
        }
        proxy.$modal.closeLoading();
      });
    }
  });
};
function changeSelect(val) {
  if (receivedParams.value.sender != "") {
    receivedParams.value.sender += "," + val;
  } else {
    receivedParams.value.sender = val;
  }
  outUnit1.value = "";
}
const uploadFuJianFiles = (response, file) => {};
const uploadPdfFile = (response, file) => {
  if (response.code == "200") {
    ElMessage({ message: "上传成功", type: "success" });
    sendDownFile.value = [];
    sendDownFile.value.push(response.data);
    receivedParams.value.sendDownFileId = response.data.fileId;
    pdfUrl.value = response.data.url;
    // proxy.$refs["pdfViewRef"].loadFile(pdfUrl.value);
    var url = pdfUrl.value;
    var b64Encoded = Base64.encode(url);
    iframeSrc.value =
      import.meta.env.VITE_APP_KKFILE2 +
      encodeURIComponent(b64Encoded) +
      "&officePreviewType=pdf";
  } else {
    ElMessage({ message: "上传失败：" + response.msg, type: "error" });
  }
};

defineExpose({
  show,
});
</script>
<style>
.el-dialog:not(.is-fullscreen) {
  margin-top: 2vh !important;
}
</style>
