<!-- @format -->

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="17" style="height: 100vh; margin-top: 1px">
        <!--        <el-button
              @click="closePage()"
              type="primary" >关闭页面
          </el-button>-->
        <!--        <el-button
              :loading="openFileState"
              @click="openLocalFile()"
              type="primary" >打印预览
          </el-button>-->
        <div style="height: 95vh" id="WebOffice2015"></div>
      </el-col>

      <el-col :span="7">
        <div
          style="
            border: 1px solid #9ca1a7;
            padding: 25px 30px 10px 0px;
            height: 95.2vh;
            overflow: auto;
            border-radius: 5px;
          "
        >
          <el-form
            ref="outMessageFormRef"
            label-width="120px"
            style="width: 350px"
            :rules="rules"
            :model="outMessageParams"
          >
            <el-form-item label="">
              <el-button
                :loading="openFileState"
                @click="openLocalFile()"
                type="primary"
                >打开本地文档
              </el-button>
            </el-form-item>
            <el-form-item label="发文单位:" prop="outUnit">
              <el-input
                v-model="outMessageParams.outUnit"
                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 fw_unit"
                      :key="item.value"
                      :label="item.label"
                      :value="item.label"
                    >
                    </el-option>
                  </el-select>
                </template> -->
              </el-input>
              <!-- <el-input
                v-model="outMessageParams.outUnit"
                placeholder="请输入发文单位"
              ></el-input>
               <el-select
                v-model="outMessageParams.outUnit"
                filterable
                allow-create
                default-first-option
                placeholder="请选择/输入发文单位"
                @change="selectBlur($event)"
              >
                <el-option
                  v-for="item in fw_unit"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select> -->
            </el-form-item>
            <el-form-item label="承办单位:" prop="undertakerUnit">
              <!-- <el-input
                v-model="outMessageParams.undertakerUnit"
                placeholder="请输入承办单位"
              ></el-input> -->
              <!-- <el-tree-select
                style="width: 350px"
                v-model="outMessageParams.undertakerUnit"
                :data="optionsUnit"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="id"
                placeholder="请选择承办单位"
                check-strictly
              /> -->
              <el-input
                v-model="outMessageParams.undertakerUnit"
                placeholder="请输入承办单位"
              ></el-input>
              <!-- <el-select
                v-model="outMessageParams.undertakerUnit"
                filterable
                allow-create
                default-first-option
                placeholder="请输入承办单位"
              >
                <el-option
                  v-for="item in optionsUnit"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select> -->
            </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
                type="textarea"
                placeholder="请输入抄送单位"
                v-model="outMessageParams.copyUnit"
              ></el-input>
            </el-form-item>
            <el-form-item label="拟办人:" prop="draftedName">
              <el-input
                v-model="outMessageParams.draftedName"
                placeholder="请输入拟办人"
              ></el-input>
            </el-form-item>
            <el-form-item label="拟稿日期:" prop="draftedTime">
              <el-date-picker
                style="width: 350px"
                v-model="outMessageParams.draftedTime"
                type="date"
                placeholder="请选择拟稿日期"
                size="defalut"
              />
            </el-form-item>
            <el-form-item label="文件标题: " prop="title">
              <el-input
                v-model="outMessageParams.title"
                placeholder="请输入文件标题"
              ></el-input>
            </el-form-item>
            <el-form-item label="文件字号: " prop="wordNum">
              <!-- <el-select
                placement="bottom-start"
                v-model="outMessageParams.wordNum"
                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
                disabled
                v-model="outMessageParams.wordNum"
                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-select
                style="width: 350px"
                @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: 350px"
                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 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>
              <el-button
                :loading="loadingWebLoad"
                @click="onSubmit(outMessageFormRef)"
                type="primary"
                >提交</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import Cookies from "js-cookie";
import { detectOS, initOffice } from "@/static/webOffice/KingiWebOffice2015";
import { getRequest, GetUrlbase, getUrlParameter } from "../hookFunction";
import { getInfo } from "@/api/login";
import { saveOutMessage } from "@/api/office/message";
import { uploadFile, base64toBlob } from "@/api/system/oafile";
import { getToken } from "@/utils/auth";
import { ElMessage } from "element-plus";
import { Iphone } from "@element-plus/icons-vue";
const { proxy } = getCurrentInstance();
import {
  changeUserStatus,
  listUser,
  resetUserPwd,
  delUser,
  getUser,
  updateUser,
  addUser,
  deptTreeSelect,
} from "@/api/system/user";
const { fw_unit } = proxy.useDict("fw_unit");
const { receive_type } = proxy.useDict("receive_type");
const { sw_open_type } = proxy.useDict("sw_open_type");
const { no_open_reason } = proxy.useDict("no_open_reason");
const props = defineProps({
  fkData: "",
});
const fujianList = ref([]);
const WebOfficeId = ref(null); //获取他的dom
const openFileState = ref(false);
const loadingWebLoad = ref(false);
const outMessageFormRef = ref(false);
const input3 = ref("");
const nType = ref(0);
const strFileName = ref();
const isNewDocument = ref(false);
const Slid = ref("");
const inputArr = ref([]);
const baseUrl = ref(import.meta.env.VITE_APP_BASE_API);
const urgentDict = ref([]);
const showNotReason = ref(false);
const docFileUrl = ref("");
const outUnit1 = ref([]);
const selectWordNum = ref([]);
const WebOffice = ref({});
const isAllowed = ref(false);
const optionsUnit = ref([]);
const mkdir = ref("");
const outMessageParams = reactive({
  title: null, //来文标题
  outUnit: "", //发文单位
  draftedTime: null, //时间
  draftedName: null, //拟稿人
  undertakerUnit: null, //承办单位
  sendFileId: null, //下发文件
  content: null, //下发文件
  params: {},
  wordNum: "",
  messageFileList: [],
});
const webOfficeOBJ = ref(null);
const upload = reactive({
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/file/fileupload",
});

const rules = reactive({
  title: [
    {
      required: true,
      message: "发文标题不能为空",
      trigger: "blur",
    },
  ],
  wordNum: [
    {
      required: true,
      message: "文件字号不能为空",
      trigger: "blur",
    },
  ],
  outUnit: [
    {
      required: true,
      message: "发文单位不能为空",
      trigger: "blur",
    },
  ],
  draftedTime: [
    {
      required: true,
      message: "拟稿时间不能为空",
      trigger: "blur",
    },
  ],
  draftedName: [
    {
      required: true,
      message: "拟稿人不能为空",
      trigger: "blur",
    },
  ],
  undertakerUnit: [
    {
      required: true,
      message: "承办单位不能为空",
      trigger: "blur",
    },
  ],
});
let requestParams = getRequest(); //获取当前url地址

// http://192.168.3.213:9000/public/20230916/2346eada103c4badb9a6970078a6a446.docx
const onSubmit = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      proxy.$modal.loading("正在提交，请稍候...");
      //保存文件到服务器中
      let uf = await saveOffice2Web();
    }
  });
};
const testfunc = () => {
  webOfficeOBJ.value.CloseDocument();

  // SaveDocumentTo2015Server();
};
const testfunc1 = () => {
  webOfficeOBJ.value.close();

  // SaveDocumentTo2015Server();
};

//保存文档到服务器
const SaveDocumentTo2015Server = () => {
  // //保存文件到本地
  // 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);
  // if (httpclient.Open(1, "http://192.168.3.213:81"+upload.url, false)) {
  //   if (httpclient.Send()) {
  //     if (httpclient.Status == 200) {
  //       alert(httpclient.ResponseText)
  //       var res = JSON.parse(httpclient.ResponseText)
  //       alert(res.msg)
  //     }
  //   }
  //   httpclient.Close();
  // }
};

const uploadFuJianFiles = (response, file) => {};

function saveOffice2Web() {
  //console.log(webOfficeOBJ.value.getFilePath() + webOfficeOBJ.value.FileName)
  //保存文件到本地
  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) {
        var res = JSON.parse(httpclient.ResponseText);
        if (res.code == 200) {
          //console.log("文件保存文档到服务器成功");
          outMessageParams.sendFileId = res.data.fileId;
          loadingWebLoad.value = true;
          //附件上传
          for (let i = 0; i < fujianList.value.length; i++) {
            outMessageParams.messageFileList.push({
              fileId: fujianList.value[i].response.data.fileId,
            });
          }
          outMessageParams.params["fk_flow"] = props.fkData;
          saveOutMessage(outMessageParams).then((response) => {
            if (response.code == 200) {
              loadingWebLoad.value = false;
              ElMessage({
                message:
                  "提交成功！已发送到" +
                  response.data.VarToNodeName +
                  "节点，接收人：" +
                  response.data.VarAcceptersName,
                type: "success",
              });
              setTimeout(function () {
                proxy.$modal.closeLoading();
                webOfficeOBJ.value.CloseDocument();

                proxy.$emit("change1");
              }, 2000);
              outMessageParams.mainUnit = null;
              outMessageParams.copyUnit = null;
              outMessageParams.draftedTime = null;
              outMessageParams.title = null;
              outMessageParams.wordNum = null;
              outMessageParams.infoOpenType = null;
              outMessageParams.noOpenReason = null;
              fujianList.value = [];
            } else {
              proxy.$modal.closeLoading();
              proxy.$modal.msgError("提交失败");
            }
          });
        } else {
          proxy.$modal.closeLoading();
          proxy.$modal.msgError("保存文档到服务器失败");

          return false;
        }
      }
    }
    httpclient.Close();
  }
}
// const selectBlur = (e) => {
//   if (e.target.value) {
//     // 不在表单的时候不需要判断，也不需要isname字段
//     this.fawen.push(e.target.value).join(",");
//     console.log("68698", this.fawen);
//   } else {
//   }
// };
function changeSelect(val) {
  if (outMessageParams.outUnit != "") {
    outMessageParams.outUnit += "," + val;
  } else {
    outMessageParams.outUnit = val;
  }
  outUnit1.value = "";
}
function changeSelect2(val) {
  showNotReason.value = false;
  if (val == "3") {
    showNotReason.value = true;
  } else {
    showNotReason.value = false;
  }
}
function changeSelect1(val) {
  if (outMessageParams.wordNum != "") {
    outMessageParams.wordNum = val;
  } else {
    outMessageParams.wordNum = val;
  }
  selectWordNum.value = "";
}
const handlePreview = () => {};
const handleRemove = () => {};

//作用：载入iWebOffice信创版控件
function Load_ZUKK() {
  loadingWebLoad.value = false;
  //   if (document.getElementById("WebOfficeId") != null) {
  webOfficeOBJ.value = document.getElementById("WebOffice");
  getInfo().then((res) => {
    outMessageParams.draftedName = res.user.nickName;
    outMessageParams.undertakerUnit = res.user.dept.deptName;
    outMessageParams.outUnit = res.user.dept.deptName;
    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); //设置信创中间件加载文字编辑软件
      //alert("weburl");
      //以下属性必须设置，实始化iWebOffice
      webOfficeOBJ.value.FileName = Math.random() * 100000 + "Mytemplate.doc";
      webOfficeOBJ.value.ShowWindow = false; //显示/隐藏进度条
      webOfficeOBJ.value.EditType = "1"; //设置加载文档类型 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(); ////iWebOffice信创版控件，打开该文档    交互OfficeServer  调出文档OPTION="LOADFILE"    调出模板OPTION="LOADTEMPLATE"     <参考技术文档>
      //alert(ret);
      if (ret) {
        proxy.$modal.closeLoading();
        // alert(webOfficeOBJ.value.Status);
        //StatusMsg(WebOffice.Status);
      }
    } catch (e) {
      proxy.$modal.closeLoading();
      //alert(e.description);                                   //显示出错误信息
    }
  });
}

//作用：显示操作状态
function StatusMsg(mString) {
  webform.StatusBar.value = mString;
}
function openLocalFile() {
  openFileState.value = true;
  setTimeout(() => {
    openFileState.value = false;
  }, 1000);
  webOfficeOBJ.value.FileType = ".doc"; //激活文档，防止调用控件接口没有文档对象
  var app = webOfficeOBJ.value.KGGetObject("Application");
  var IsYozoOffice = webOfficeOBJ.value.WebApplication(".eio");
  if (IsYozoOffice) {
    app.Dialogs.Item(80).Show2();
  } else {
    var filename = app.ShowLocalDocumentDialog();
    // alert(filename);
    if (filename == "" || filename == null || filename == "undefined") {
      return;
    } else {
      var aa = webOfficeOBJ.value.openDocument(filename, false);
    }
  }
}
function changeFkFlow(fk) {
  outMessageParams.params["fk_flow"] = fk;
}
function closePage() {
  // webOfficeOBJ.value.WebShow(false);
}

function optionSection() {
  deptTreeSelect().then((response) => {
    optionsUnit.value = response.data;
  });
}

function OnReady() {
  proxy.$modal.loading("正在打开中...");
  //获取iWebOffice2015控件对象，WebOffice.FuncExtModule是iWebOffice2015控件扩展接口对象
  //加载dom元素，获取 weboffice对象
  initOffice(document);
  setTimeout(function () {
    Load_ZUKK();
  }, 1000); //需要做一个延时，iWebOffice2015才能获取FuncExtModule扩展接口对象
}
onMounted(async () => {
  //修改页面title
  outMessageParams.params["fk_flow"] = props.fkData;
  loadingWebLoad.value = true;
  OnReady();
});
optionSection();

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

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