/** @format */

var WebOffice;
var obj;

/* 初始化对象 */
export function setObj(object) {
  obj = object;
  WebOffice = obj.FuncExtModule;
  return WebOffice;
}

//作用：退出iWebOffice
function UnLoad() {
  //WebOffice.Alert("关闭进程");
  try {
    var ret = WebOffice.WebClose();
  } catch (e) {
    //alert(e.description);
  }
}

export function GetUrlbasePath() {
  //获取当前网址，如： http://localhost:8080/ems/Pages/Basic/Person.jsp
  var curWwwPath = window.document.location.href;
  //获取主机地址之后的目录，如： /ems/Pages/Basic/Person.jsp
  var pathName = window.document.location.pathname;
  var pos = curWwwPath.indexOf(pathName);
  //获取主机地址，如： http://localhost:8080
  var localhostPath = curWwwPath.substring(0, pos);
  //获取带"/"的项目名，如：/ems
  var projectName = pathName.substring(0, pathName.substr(1).indexOf("/") + 1);
  //获取项目的basePath   http://localhost:8080/ems/
  var basePath = localhostPath + projectName + "/";
  return basePath;
}

//打开在线文档
export function WebOpenFile(fileUrl) {
  var urlPath = fileUrl;
  var szTempPath = obj.FileSystem.GetTempPath();
  var szFileName = szTempPath + "sample.doc";
  //先删除文件
  obj.FileSystem.DeleteFile(szFileName);
  //下载到本地
  WebOffice.WebDownLoadFile(urlPath, szFileName);
  //打开本地文件
  WebOffice.WebOpenLocalFile(szFileName);
}

//清稿套红
function clearRevisionAndtaohong() {
  var urlPath = GetUrlbasePath() + "/Document/Template1.doc";
  var szTempPath = obj.FileSystem.GetTempPath();
  var szFileName = szTempPath + "123.doc";
  var szTemplateName = szTempPath + "Template1.doc";

  //先删除源文件
  obj.FileSystem.DeleteFile(szFileName);
  //保存正文清理文档痕迹
  WebOffice.ClearRevisions();
  //保存当前打开的正文到本地
  WebOffice.WebSaveLocalFile(szFileName);
  //先删除源文件
  obj.FileSystem.DeleteFile(szTemplateName);
  //下载到模板文件到本地
  WebOffice.WebDownLoadFile(urlPath, szTemplateName);

  //打开模板文件
  WebOffice.WebOpenLocalFile(szTemplateName);
  obj.Activate(true);
  if (obj.ActiveDocument.Bookmarks.Exists("Content")) {
    //this.obj.ActiveDocument.Bookmarks(Position).Range.Select(); //测试
    setTimeout(
      obj.ActiveDocument.Application.Selection.GoTo(-1, 0, 0, "Content"),
      200
    );
  }
  obj.Activate(true);
  obj.ActiveDocument.Application.Selection.InsertFile(
    szFileName,
    "",
    false,
    false,
    false
  );
  WebOffice.WebSetBookmarks("book1", "此处测试填充书签1");
  WebOffice.WebSetBookmarks("book2", "此处测试填充书签2");
  WebOffice.WebSetBookmarks("book3", "此处测试填充书签3");
}

//创建新文档
export function createDocument() {
  WebOffice.FileType = ".doc"; //激活文档，防止调用控件接口没有文档对象

  WebOffice.CreateFile();
}

//打开本地文档(弹窗)

export function openLocalFile() {
  WebOffice.FileType = ".doc"; //激活文档，防止调用控件接口没有文档对象
  WebOffice.WebOpenLocal();
}

//保存本地文档(弹窗)
export function saveLocalFile() {
  WebOffice.WebSaveLocal();
}
//
// //保存本地文档(弹窗)
// export function saveToWebFile() {
//   WebOffice.WebSave();
// }
//保存本地文档(弹窗)
export function saveToWebFile(headert) {
  WebOffice.WebSave(headert, function (a) {});
}

//保护文档
function protectDocument() {
  WebOffice.WebSetProtect(true, "123456");
}

//解除保护
function unProtectDocument() {
  WebOffice.WebSetProtect(false, "123456");
}

//允许拷贝
function enableCopy() {
  WebOffice.CopyType = 1;
}

//禁止拷贝
function disableCopy() {
  WebOffice.CopyType = 0;
}

//打印文档
function printDocument() {
  WebOffice.WebOpenPrint();
}

//获取当前文档大小
function getCurFileSize() {
  var size = WebOffice.WebLocalFileSize();
  alert("当前文档大小：" + size + "byte");
}

//文档是否修改
function documentIsModify() {
  if (WebOffice.Modify) {
    alert("文档已修改");
  } else {
    alert("文档未修改");
  }
}

//文档是否为空白文档
function documentIsEmpty() {
  if (
    WebOffice.WebObject.Application.ActiveDocument.Characters.Count > 1 ||
    WebOffice.WebObject.Application.ActiveDocument.Shapes.Count >= 1
  ) {
    alert("当前文档不是空白文档");
  } else {
    alert("当前文档是空白文档");
  }
}

//显示痕迹
function ShowRevision() {
  WebOffice.WebShow(true);
}

//隐藏痕迹
function HideRevision() {
  WebOffice.WebShow(false);
}

//清理痕迹
function ClearRevision() {
  WebOffice.ClearRevisions();
}

//获取doc文件夹下的文件的绝对路径
function rel2Abs(path) {
  var _path = path;
  var locationStr = window.location.href.toString();

  var relative;
  while ((relative = _path.substring(0, _path.indexOf("/")))) {
    if (relative === ".") {
      // 遇到. path去掉最前面的./
      // 遇到.当前路径去掉/后面内容
      _path = _path.substring(_path.indexOf("/") + 1, _path.length);
      locationStr = locationStr.substring(0, locationStr.lastIndexOf("/"));
      locationStr = locationStr.substring(0, locationStr.lastIndexOf("/") + 1);
    } else if (relative === "..") {
      // 遇到.. path去掉最前面的../
      // 遇到.. 当前路径去掉/xxx,然后再去掉/后面的内容
      _path = _path.substring(_path.indexOf("/") + 1, _path.length);
      locationStr = locationStr.substring(0, locationStr.lastIndexOf("/"));
      locationStr = locationStr.substring(0, locationStr.lastIndexOf("/") + 1);
    } else {
      break;
    }
  }
  var index1 = locationStr.indexOf("%");
  if (index1 > 0) {
    //将获取的地址中的编码转成中文
    var index2 = locationStr.lastIndexOf("%");
    var cc = locationStr.substring(index1, index2 + 3);
    var bb = decodeURIComponent(cc);
    locationStr = locationStr.replace(cc, bb);
  }
  var result = locationStr + _path;
  result = result.substring(7); //去掉地址中的file://
  path = result;
  return result;
}

//插入一个书签
function insertBookmark() {
  var BMarksName = "test";
  var BMarksValue = "测试新增书签";
  if (
    !WebOffice.WebObject.Application.ActiveDocument.BookMarks.Exists(BMarksName)
  ) {
    //判断是否存在该书签
    var BMVLength = BMarksValue.length;
    WebOffice.WebObject.Application.Selection.TypeText(BMarksValue); //插入内容
    WebOffice.WebObject.Application.Selection.MoveLeft(
      (Unit = 1),
      (Count = BMVLength)
    );
    var StartR = WebOffice.WebObject.Application.Selection.Start;
    var EndR = WebOffice.WebObject.Application.Selection.Start + BMVLength;
    WebOffice.WebObject.Application.ActiveDocument.Range(
      (Start = StartR),
      (End = EndR)
    ).Select();
    WebOffice.WebObject.Application.ActiveDocument.Bookmarks.Add(BMarksName); //添加书签
  }
}

//设置书签内容
function setBookmarkValue() {
  WebOffice.WebSetBookMarks("test", "测试设置书签");
  return;
  /*var BMarksName = "test";
	var BMarksValue = "测试设置书签";
    try {
			if (WebOffice.WebObject.Application.ActiveDocument.BookMarks.Exists(BMarksName)) {// 判断是否存在该书签
				var vRange = WebOffice.WebObject.Application.ActiveDocument.Bookmarks.Item(BMarksName).Range;
				vRange.text = BMarksValue;
				WebOffice.WebObject.Application.ActiveDocument.Bookmarks.Add(BMarksName, vRange);
			}
		} catch (e) {
			this.Status = "名称为<" + BMarksName + ">的书签在文档中不存在";
			return false;
		}*/
}

//隐藏书签
function hideBookmark() {
  var Bookmarks = WebOffice.WebObject.Application.ActiveDocument.BookMarks;
  var bookname = "test";
  if (Bookmarks.Exists(bookname)) {
    var range = Bookmarks.Item(bookname).Range;
    range.Select();
    range.Select();
    WebOffice.WebObject.Application.Selection.Font.Hidden = true;
  }
}

//显示书签
function showBookmark() {
  var Bookmarks = WebOffice.WebObject.Application.ActiveDocument.BookMarks;
  var bookname = "test";
  if (Bookmarks.Exists(bookname)) {
    var range = Bookmarks.Item(bookname).Range;
    range.Select();
    WebOffice.WebObject.Application.Selection.Font.Hidden = false;
  }
}

//锁定书签
function protectBookmark() {
  var Bookmarks = WebOffice.WebObject.Application.ActiveDocument.BookMarks;
  var bookname = "test";
  if (Bookmarks.Exists(bookname)) {
    var range = Bookmarks.Item(bookname).Range;
    range.Select();
    var cc;
    cc = WebOffice.WebObject.Application.ActiveDocument.ContentControls.Add(
      1,
      range
    );
    cc.Type = 1;
    cc.Title = "wuhui";
    cc.LockContents = true;
    cc.LockContentControl = true;
  }
}
//显示书签
function unProtectBookmark() {
  var ControlCount =
    WebOffice.WebObject.Application.ActiveDocument.ContentControls.Count;
  for (var i = ControlCount; i >= 1; i--) {
    if (
      WebOffice.WebObject.Application.ActiveDocument.ContentControls.Item(i)
        .Title == "wuhui"
    ) {
      WebOffice.WebObject.Application.ActiveDocument.ContentControls.Item(
        i
      ).LockContentControl = false;
      WebOffice.WebObject.Application.ActiveDocument.ContentControls.Item(
        i
      ).Delete();
    }
  }
}

//定位书签
function locateBookmark() {
  var bookname = "test";
  if (
    WebOffice.WebObject.Application.ActiveDocument.Bookmarks.Exists(bookname)
  ) {
    WebOffice.WebObject.Application.ActiveDocument.Bookmarks.Item(
      bookname
    ).Select();
  } else {
    alert("书签不存在！");
  }
}

//获取书签内容
function getBookmarkValue() {
  var bookmarkvalue = WebOffice.WebGetBookMarks("test");
  alert("书签内容:" + bookmarkvalue);
  /*var bookmarkvalue;
	var Bookmarks = WebOffice.WebObject.Application.ActiveDocument.BookMarks;
	var bookname = "test";
	if(Bookmarks.Exists(bookname))
	{
		var range = Bookmarks.Item(bookname).Range;
		bookmarkvalue = range.Text;
		alert("书签内容:" + bookmarkvalue);
	}*/
}

//书签插入文档内容
function insertFile() {
  var Bookmarks = WebOffice.WebObject.Application.ActiveDocument.Bookmarks;
  var bookname = "test";
  if (Bookmarks.Exists(bookname)) {
    var range = Bookmarks.Item(bookname).Range;
    var filePath = rel2Abs("./doc/001.doc");
    range.InsertFile(filePath);
  }
}

//书签插入图片
function insertPicture() {
  var Bookmarks = WebOffice.WebObject.Application.ActiveDocument.Bookmarks;
  var bookname = "test";
  if (Bookmarks.Exists(bookname)) {
    WebOffice.WebObject.Application.ActiveDocument.Bookmarks.Item(
      bookname
    ).Select();
    var filePath = rel2Abs("./doc/001.jpg");
    WebOffice.insertPicture(filePath);
  }
}

//删除指定书签
function deleteBookmark() {
  var bookmarks = WebOffice.WebObject.Application.ActiveDocument.Bookmarks;
  if (bookmarks.Exists("test")) {
    var bookname = bookmarks.Item("test");
    bookname.Delete();
  }
}

//判断书签是否存在
function bookmarkIsExists() {
  var bookmarks = WebOffice.WebObject.Application.ActiveDocument.Bookmarks;
  if (bookmarks.Exists("test")) {
    alert("书签存在");
  } else {
    alert("书签不存在");
  }
}

//高亮显示书签内容
function highlightBookmark() {
  var Bookmarks = WebOffice.WebObject.Application.ActiveDocument.Bookmarks;
  var bookname = "test";
  if (Bookmarks.Exists(bookname)) {
    var range = Bookmarks.Item(bookname).Range;
    range.HighlightColorIndex = 7;
  }
}

//设置书签内容中部分文字的格式
function setBookmarkFormat() {
  var Bookmarks = WebOffice.WebObject.Application.ActiveDocument.Bookmarks;
  var bookname = "test";
  var strText = "测试";
  if (Bookmarks.Exists(bookname)) {
    var range = Bookmarks.Item(bookname).Range;
    range.Select();
    if (
      WebOffice.WebObject.Application.Selection.Find.Execute(
        strText,
        false,
        false,
        false,
        false,
        false,
        true,
        0,
        false,
        "",
        false
      )
    ) {
      WebOffice.WebObject.Application.Selection.Range.Font.Name = "黑体";
      WebOffice.WebObject.Application.Selection.Range.Font.Size = 28;
      WebOffice.WebObject.Application.Selection.Range.Font.Color = 255;
    }
  }
}

//设置表格底纹
function setTableTexture() {
  var filePath = GetUrlbasePath() + "samples/iWebOfficeApp_VUE/src/doc/5.doc"; //rel2Abs("./doc/5.doc");
  var localfile = "d:\\123test.doc";
  WebOffice.WebDownLoadFile(filePath, localfile);
  WebOffice.WebOpenLocalFile(localfile);
  WebOffice.WebObject.Application.Selection.Tables.Item(1).Shading.Texture = 0;
  WebOffice.WebObject.Application.Selection.Tables.Item(
    1
  ).Shading.ForegroundPatternColor = -16777216;
  WebOffice.WebObject.Application.Selection.Tables.Item(
    1
  ).Shading.BackgroundPatternColor = 255;
}

//设置表格单元格底纹
function setTableUnitTexture() {
  var filePath = GetUrlbasePath() + "samples/iWebOfficeApp_VUE/src/doc/2.doc"; //rel2Abs("./doc/5.doc");
  var localfile = "d:\\234test.doc";
  WebOffice.WebDownLoadFile(filePath, localfile);
  WebOffice.WebOpenLocalFile(localfile);
  var mytable = WebOffice.WebObject.Application.ActiveDocument.Tables.Item(1);
  mytable.Cell(1, 1).Select(); //选中单元格
  WebOffice.WebObject.Application.Selection.Cells.Shading.Texture = 0;
  WebOffice.WebObject.Application.Selection.Cells.Shading.ForegroundPatternColor =
    -16777216;
  WebOffice.WebObject.Application.Selection.Cells.Shading.BackgroundPatternColor = 255;
}

//拆分表格
function splitCell() {
  var filePath = GetUrlbasePath() + "samples/iWebOfficeApp_VUE/src/doc/5.doc"; //rel2Abs("./doc/5.doc");
  var localfile = "d:\\345test.doc";
  WebOffice.WebDownLoadFile(filePath, localfile);
  WebOffice.WebOpenLocalFile(localfile);
  var mytable = WebOffice.WebObject.Application.ActiveDocument.Tables.Item(1);
  mytable.Cell(1, 1).Select();
  WebOffice.WebObject.Application.Selection.Cells.Split(1, 2, false);
}

//合并列
function mergeRow() {
  var filePath =
    GetUrlbasePath() + "samples/iWebOfficeApp_VUE/src/doc/mergerow.doc"; //rel2Abs("./doc/5.doc");
  var localfile = "d:\\456test.doc";
  WebOffice.WebDownLoadFile(filePath, localfile);
  WebOffice.WebOpenLocalFile(localfile);
  var fptableMerge =
    WebOffice.WebObject.Application.ActiveDocument.Tables.Item(1);
  WebOffice.WebObject.Application.ActiveDocument.Range(
    fptableMerge.Cell(3, 2).Range.Start,
    fptableMerge.Cell(6, 3).Range.End
  ).Select();
  WebOffice.WebObject.Application.Selection.Cells.Merge();
}
//删除表格
function deleteCell() {
  var filePath =
    GetUrlbasePath() + "samples/iWebOfficeApp_VUE/src/doc/deletetable.doc"; //rel2Abs("./doc/5.doc");
  var localfile = "d:\\567test.doc";
  WebOffice.WebDownLoadFile(filePath, localfile);
  WebOffice.WebOpenLocalFile(localfile);
  var mytable = WebOffice.WebObject.Application.ActiveDocument.Tables.Item(1);
  mytable.Cell(1, 32).Delete();
  mytable.Cell(2, 32).Delete();
  mytable.Cell(3, 32).Delete();
  mytable.Cell(4, 33).Delete();
  mytable.Cell(5, 33).Delete();
  mytable.Cell(6, 33).Delete();
  mytable.Cell(7, 33).Delete();
  mytable.Cell(8, 33).Delete();
}

//关闭控件
export function OnUnLoad() {
  WebOffice.WebClose();
}

function FlushCodeInfo(tips, code) {
  document.getElementById("shuoming").innerText = tips;
  document.getElementById("daima").innerText = code;
  // flush code style
  // layui.code({
  //     title: 'JavaScript'
  //     , about: false      //剔除关于
  // });
}

// function CreateFunction(tips, func, args) {
//     return function() {
//         FlushCodeInfo(tips, func.toString());
//     }
// }

//var _CreateFile = new CreateFunction("创建新文档", CreateFile, []);

function callAlert(tip, functionName) {
  //根据函数名得到函数类型
  var func = eval(functionName);
  //alert(func);
  FlushCodeInfo(tip, func);
}
