<!-- @format -->

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="18">
        <!--        <el-button
            @click="closePage()"
            type="primary" >关闭页面
        </el-button>-->
        <!--        <el-button
            :loading="openFileState"
            @click="openLocalFile()"
            type="primary" >打印预览
        </el-button>-->
        <div class="iWebOfficeDom" ref="iWebOfficeDom"></div>
      </el-col>
      <el-col :span="6">
        <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: 23vw"
            :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: 100%"
                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: 75px"
                  >
                    <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: 100%"
                @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: 100%"
                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 { LoadStr } from "@/plugins/iWebOffice2015";
import WebOffice2015 from "../../../static/webOffice/WebOffice";
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 WebOfficeStr = LoadStr();
const fujianList = ref([]);
const iWebOfficeDom = ref(null); //获取他的dom
const openFileState = ref(false);
const loadingWebLoad = ref(false);
const outMessageFormRef = ref(false);
const showNotReason = ref(false);
const input3 = ref("");
const inputArr = ref([]);
const baseUrl = ref(import.meta.env.VITE_APP_BASE_API);
const urgentDict = ref([]);
const docFileUrl = ref("");
const outUnit1 = ref([]);
const selectWordNum = ref([]);
const isAllowed = ref(false);
const optionsUnit = ref([]);
const outMessageParams = reactive({
  title: null, //来文标题
  outUnit: "", //发文单位
  draftedTime: null, //时间
  draftedName: null, //拟稿人
  undertakerUnit: null, //承办单位
  sendFileId: null, //下发文件
  content: null, //下发文件
  params: {},
  wordNum: "",
  messageFileList: [],
  mainUnit: null,
  copyUnit: null,
});
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地址
let WebOffice;
// http://192.168.3.213:9000/public/20230916/2346eada103c4badb9a6970078a6a446.docx
const onSubmit = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      webOfficeOBJ.value.obj.HidePlugin(0);
      proxy.$modal.loading("正在提交，请稍候...");

      //保存文件到服务器中
      let uf = await saveOffice2Web();
    }
  });
};
const uploadFuJianFiles = (response, file) => {};
function saveOffice2Web() {
  let fileName = webOfficeOBJ.value.getFilePath() + webOfficeOBJ.value.FileName;
  var res = webOfficeOBJ.value.WebSaveLocalFile(fileName);
  if (res == 0) {
    var officeobj = webOfficeOBJ.value.obj;
    var base64file = officeobj.File2Base64Text(fileName);
    var myfff = base64toBlob(base64file);
    var formData = new FormData();
    formData.append("file", myfff, webOfficeOBJ.value.FileName);
    uploadFile(formData).then((res) => {
      if (res.code == 200) {
        webOfficeOBJ.value.WebClose();
        //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,
          });
        }
        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();
              var setting = window.Setting;
              setting.CloseWindow();
            }, 2200);
          } else {
            proxy.$modal.closeLoading();
            proxy.$modal.msgError("提交失败");
            setTimeout(function () {
              webOfficeOBJ.value.obj.HidePlugin(1);
            }, 2200);
          }
        });
      } else {
        proxy.$modal.closeLoading();
        proxy.$modal.msgError("保存文档到服务器失败");
        setTimeout(function () {
          webOfficeOBJ.value.obj.HidePlugin(1);
        }, 1000);
        return false;
      }
    });
  } else {
    webOfficeOBJ.value.obj.HidePlugin(1);
    proxy.$modal.closeLoading();
    alert("保存文档失败");
    return false;
  }
}
// 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 = () => {};
function Load() {
  //chrome浏览器，HookEnabled设置为true，用于控件中和本地excel表格的焦点互相切换
  initWebOffice();
  loadingWebLoad.value = false;
}
function openLocalFile() {
  openFileState.value = true;
  setTimeout(() => {
    openFileState.value = false;
  }, 1000);
  webOfficeOBJ.value.FileType = ".doc"; //激活文档，防止调用控件接口没有文档对象
  webOfficeOBJ.value.WebOpenLocal();
}
function closePage() {
  // webOfficeOBJ.value.WebShow(false);
}

function optionSection() {
  deptTreeSelect().then((response) => {
    optionsUnit.value = response.data;
  });
}
function initWebOffice() {
  var date = new Date();
  outMessageParams.draftedTime = date;
  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;
    //console.log(GetUrlbase())
    // try{
    //   webOfficeOBJ.value.WebUrl = GetUrlbase()+upload.url;
    //webOfficeOBJ.value.RecordID = "1551950618511";  //RecordID:本文档记录编号
    // webOfficeOBJ.value.UserName = "XXX";
    webOfficeOBJ.value.FileName = Math.random() * 100000 + "Mytemplate.doc";
    webOfficeOBJ.value.FileType = ".doc"; //FileType:文档类型  .doc  .xls
    webOfficeOBJ.value.ShowWindow = false; //显示/隐藏进度条
    webOfficeOBJ.value.EditType = "1"; //设置加载文档类型 0 锁定文档，1无痕迹模式，2带痕迹模式
    // webOfficeOBJ.value.ShowMenu = 1;
    // webOfficeOBJ.value.ShowToolBar = 1;
    webOfficeOBJ.value.ShowMenuBar(false);
    webOfficeOBJ.value.ShowToolBars(true);
    // //console.log(webOfficeOBJ)
    webOfficeOBJ.value.SetCaption(
      webOfficeOBJ.value.UserName + " 正在编辑文档"
    ); // 设置控件标题栏标题文本信息
    //参数顺序依次为：控件标题栏颜色、自定义菜单开始颜色、自定义工具栏按钮开始颜色、自定义工具栏按钮结束颜色、
    //自定义工具栏按钮边框颜色、自定义工具栏开始颜色、控件标题栏文本颜色（默认值为：0x000000）
    if (!webOfficeOBJ.value.Skin("blue")) {
      // alert(webOfficeOBJ.value.Status);
    }
    //设置控件皮肤
    if (webOfficeOBJ.value.WebOpen()) {
      // StatusMsg(WebOfficeObj.Status);
    }
    // webOfficeOBJ.value.AppendMenu("1","打开本地文件(&L)");
    // webOfficeOBJ.value.AppendMenu("2","保存本地文件(&S)");
    // webOfficeOBJ.value.AppendMenu("3","-");
    // webOfficeOBJ.value.AppendMenu("4","打印预览(&C)");
    // webOfficeOBJ.value.AppendMenu("5","退出打印预览(&E)");
    // webOfficeOBJ.value.AddCustomMenu();
    webOfficeOBJ.value.HookEnabled();
    webOfficeOBJ.value.CreateFile(); // 根据FileType设置的扩展名来创建对应的空白文档
    // }
    // catch(e){
    //   //console.log("catch");
    //   //console.log(e.description);
    // }
  });
}

function OnReady() {
  //获取iWebOffice2015控件对象，WebOffice.FuncExtModule是iWebOffice2015控件扩展接口对象
  WebOffice = document.getElementById("WebOffice2015");
  webOfficeOBJ.value = new WebOffice2015();
  webOfficeOBJ.value.setObj(WebOffice);

  setTimeout(function () {
    Load();
  }, 1000); //需要做一个延时，iWebOffice2015才能获取FuncExtModule扩展接口对象
}
onMounted(async () => {
  //修改页面title
  document.title = "发文HideVerison";
  outMessageParams.params["fk_flow"] = getUrlParameter("fk_flow");
  loadingWebLoad.value = true;
  iWebOfficeDom.value.innerHTML = WebOfficeStr;
  OnReady();
});
optionSection();
</script>

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