<!-- @format -->

<template>
  <el-dialog
    title="收文"
    :close-on-click-modal="false"
    :before-close="dcolse"
    :destroy-on-close="true"
    v-model="visible"
    width="1600px"
    top="2vh"
    append-to-body
  >
    <div class="app-container" style="margin-top: -45px">
      <el-row>
        <el-col :span="10"> </el-col>
      </el-row>
      <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>
        </el-col>
        <el-col :span="7">
          <el-form
            ref="receivedFormRef"
            label-width="105px"
            :disabled="isAllowed"
            style="width: 350px"
            :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 mail_state"
                  :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 sw_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="documentNum">
              <el-input
                v-model="receivedParams.documentNum"
                placeholder="请输入文件字号"
              ></el-input>
            </el-form-item>

            <el-form-item label="上传正文:">
              <el-upload
                class="upload-pdf"
                ref="sendFileUpload"
                :action="upload.url"
                :headers="upload.headers"
                :disabled="isAllowed"
                accept=".pdf"
                multiple
                :limit="1"
                :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
                :picker-options="option"
                style="width: 350px"
                v-model="receivedParams.closeTime"
                type="datetime"
                placeholder="请选择反馈时限"
                :shortcuts="shortcuts"
                @change="handle"
              />
            </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 PdfViewer from "@/components/PdfViewer";
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 { sw_unit } = proxy.useDict("sw_unit");

const router = useRouter();
const route = useRoute();
const key = computed(() => {
  return route.path + Math.random();
});
const value2 = ref("");
const input3 = ref("");
const pdfUrl = ref("");
const visible = ref(false);
const isAllowed = ref(false);
const outUnit1 = ref([]);
const { mail_state } = proxy.useDict("mail_state");
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();
  }
});

function handle() {
  var startAt = (new Date(receivedParams.value.closeTime) * 1000) / 1000;
  if (startAt < Date.now()) {
    receivedParams.value.closeTime = new Date();
  }
}
/** 查询参数列表 */
function show(type) {
  visible.value = true;
  receivedParams.value.offcialType = type;
}
const loadingWebLoad = ref(false);
let pdfDoc = null;
const pdfPages = ref(0);
const sendDownFile = ref([]);
const fujianList = ref([]);

const receivedFormRef = ref(false);
const dcolse = (done) => {
  pdfPages.value = 0;
  sendDownFile.value = [];
  receivedFormRef.value = false;
  restForm();
  proxy.$refs["fujianUpload"].clearFiles();
  proxy.$refs["sendFileUpload"].clearFiles();
  done();
};
function restForm() {
  //console.log("清空表单")
  receivedParams.value = {
    title: null, //来文标题
    offcialType: null, //来文标题
    sender: "", //单位
    sendTime: null, //时间
    serial: null, //流水号
    documentNum: null, //字号
    emergencyDegree: null, //紧急程度
    sendDownFileId: null, //下发文件
    receiveFileId: null, //收文原件
    fujianFileList: [], //附件信息
    isFeedback: "0",
    closeTime: null,
  };
}

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,
  },
  rules: {
    title: [
      {
        required: true,
        message: "来文标题不能为空",
        trigger: "blur",
      },
    ],
    sender: [
      {
        required: true,
        message: "来文单位不能为空",
        trigger: "blur",
      },
    ],
    sendTime: [
      {
        required: true,
        message: "来文时间不能为空",
        trigger: "blur",
      },
    ],
    serial: [
      {
        required: true,
        message: "流水号不能为空",
        trigger: "blur",
      },
    ],
    documentNum: [
      {
        required: true,
        message: "字号不能为空",
        trigger: "blur",
      },
    ],
    emergencyDegree: [
      {
        required: true,
        message: "请选择紧急程度",
        trigger: "blur",
      },
    ],
  },
});
const { formData, upload, receivedParams, rules } = toRefs(data);

function openLwUnit() {}

const onSubmit = (formEl) => {
  if (!formEl) return;
  if (receivedParams.value.sendDownFileId == null) {
    ElMessage({
      message: "请先上传正文",
      type: "warning",
    });
    return;
  }
  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();

          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);
  } else {
    ElMessage({ message: "上传失败：" + response.msg, type: "error" });
  }
};

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