common-utils.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. App.namespace("App.common");
  2. $(function($, mod){
  3. var methods = {
  4. /**
  5. *创建富文本框
  6. *target 节点
  7. *callBackFn 回调,返回当前富文本框的实例
  8. **/
  9. createEditor : function(target, callBackFn){
  10. layui.use("wangEditor",function(){
  11. var E = layui.wangEditor;
  12. var _editor = new E(target);
  13. _editor.customConfig.uploadImgServer = App.getUrl("/static/file/uploadedit");
  14. _editor.customConfig.uploadFileName = 'image';
  15. _editor.customConfig.pasteFilterStyle = false;
  16. _editor.customConfig.uploadImgMaxLength = 5;
  17. _editor.customConfig.uploadImgMaxSize = 2 * 1024 * 1024 // 2M
  18. _editor.customConfig.uploadImgHooks = {
  19. // 上传超时
  20. timeout: function (xhr, editor) {
  21. layer.msg('上传超时!')
  22. },
  23. // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式,可使用该配置
  24. customInsert: function (insertImg, result, editor) {
  25. if (result.code == 0) {
  26. var url = result.resultList;
  27. url.forEach(function (e) {
  28. insertImg(App.getUrl("/static/file/"+e.id+"/showfile"));
  29. })
  30. } else {
  31. App.msg.error(result.msg);
  32. }
  33. }
  34. };
  35. _editor.customConfig.pasteTextHandle = function (pasteStr) {
  36. // content 即粘贴过来的内容(html 或 纯文本),可进行自定义处理然后返回
  37. if (pasteStr == '' && !pasteStr) return '';
  38. //处理的标签里的多余代码
  39. let reg = /<!--\[if\s+gte\s+mso\s+[0-9][0-9]?\]>(?:(?!<!\[endif\]-->)[\s\S])*<!\[endif\]-->/gi;
  40. pasteStr = pasteStr.replace(reg,"");
  41. pasteStr = pasteStr.replace(/<xml>[\s\S]*?<\/xml>/ig, '');
  42. pasteStr= pasteStr.replace('/(\\n|\\r| class=(")?Mso[a-zA-Z]+(")?)/g','');
  43. reg=new RegExp('<!--(.*?)-->','g');
  44. pasteStr=pasteStr.replace(reg,'');
  45. return pasteStr;
  46. };
  47. _editor.customConfig.customAlert = function (info) {
  48. App.msg.info(info);
  49. };
  50. _editor.create();
  51. if(callBackFn != 'undifined' && typeof callBackFn == 'function'){
  52. callBackFn(_editor);
  53. }
  54. })
  55. },
  56. /**
  57. * 创建图标选择器
  58. * target 节点
  59. * clickFn 点击回调
  60. * successFn 渲染成功后的回调
  61. * iconUrl 图标接口
  62. */
  63. createIconPicker : function(target, clickFn, successFn){
  64. layui.use('iconPickerFa', function () {
  65. var iconPickerFa = layui.iconPickerFa;
  66. iconPickerFa.render({
  67. // 选择器,推荐使用input
  68. elem: target,
  69. // fa 图标接口
  70. //url: _iconUrl,
  71. // 是否开启搜索:true/false,默认true
  72. search: true,
  73. // 是否开启分页:true/false,默认true
  74. page: true,
  75. // 每页显示数量,默认12
  76. limit: 12,
  77. // 点击回调
  78. click: function (data) {
  79. if(clickFn != undefined && typeof clickFn == 'function'){
  80. clickFn(data);
  81. }
  82. },
  83. // 渲染成功后的回调
  84. success: function (d) {
  85. if(successFn != undefined && typeof successFn == 'function'){
  86. successFn(d);
  87. }
  88. }
  89. });
  90. })
  91. },
  92. /**
  93. * 树结构表格
  94. */
  95. treeTable : function(obj, successFn, doneFn){
  96. layui.use('treetable', function () {
  97. var _treeTable = layui.treetable;
  98. _treeTable.render({
  99. treeColIndex: obj.treeColIndex || 1,
  100. treeSpid: obj.treeSpid,
  101. treeIdName: obj.treeIdName,
  102. treePidName: obj.treePidName,
  103. elem: obj.elem,
  104. url: obj.url,
  105. page: false,
  106. cols: obj.cols,
  107. done: function () {
  108. if(doneFn != undefined && typeof doneFn == 'function'){
  109. doneFn();
  110. }
  111. }
  112. });
  113. if(successFn != undefined && typeof successFn == 'function'){
  114. successFn(_treeTable);
  115. }
  116. });
  117. },
  118. /**
  119. * 树形下拉框
  120. */
  121. treeSelect : function(_elem, successFn, clickFn){
  122. layui.use('treeSelect', function () {
  123. var _treeSelect = layui.treeSelect;
  124. var $elem = $(_elem),
  125. _url = $elem.attr("url"),
  126. _method = $elem.attr("method"),
  127. _placeholder = $elem.attr("placeholder"),
  128. _search = $elem.attr("search") || false,
  129. _enable = $elem.attr("enableParent") || true,
  130. _layFilter = $elem.attr("lay-filter");
  131. _treeSelect.render({
  132. // 选择器
  133. elem: _elem,
  134. // 数据
  135. data: _url,
  136. // 异步加载方式:get/post,默认get
  137. type: _method,
  138. // 占位符
  139. placeholder: _placeholder,
  140. // 是否开启搜索功能:true/false,默认false
  141. search: _search,
  142. //树相关对应字段
  143. treeParam : {
  144. nameKey: $elem.attr("nameFiled") || "name",
  145. titleKey: $elem.attr("titleFiled") || "",
  146. idKey: $elem.attr("idFiled") || "id",
  147. pIdkey: $elem.attr("parentIdFiled"),
  148. rootPId: "",
  149. enable : JSON.parse(_enable) //开启父级树结构
  150. },
  151. // 点击回调
  152. click: function(d){
  153. _treeSelect.checkNode(_layFilter, d.current.id);
  154. if(clickFn != undefined && typeof clickFn == "function"){
  155. clickFn(d.current);
  156. }
  157. },
  158. // 加载完成后的回调函数
  159. success: function (d) {
  160. $elem.bind("input propertychange",function(){
  161. var layFilter = $(this).attr("lay-filter");
  162. var id = $(this).val();
  163. _treeSelect.checkNode(layFilter, id);
  164. });
  165. if(successFn != undefined && typeof successFn == "function"){
  166. successFn(_treeSelect);
  167. }
  168. }
  169. });
  170. });
  171. },
  172. /**
  173. * 省市县三级联动
  174. */
  175. layarea : function(_elem, areaData, changeFn, successFn){
  176. layui.use('layarea', function () {
  177. var _layarea = layui.layarea;
  178. if(areaData){
  179. _layarea = _layarea.render({
  180. elem : _elem,
  181. data : {
  182. province : areaData.province || "",
  183. city : areaData.city || "",
  184. county : areaData.county || ""
  185. },
  186. change : function(res){
  187. if(changeFn != undefined && typeof changeFn == 'function'){
  188. changeFn(res);
  189. }
  190. },
  191. success : function(res){
  192. if(successFn != undefined && typeof successFn == 'function'){
  193. successFn(res);
  194. }
  195. }
  196. });
  197. }else{
  198. _layarea.render({
  199. elem : _elem,
  200. change : function(res){
  201. if(changeFn != undefined && typeof changeFn == 'function'){
  202. changeFn(res);
  203. }
  204. },
  205. success : function(res){
  206. if(successFn != undefined && typeof successFn == 'function'){
  207. successFn(res);
  208. }
  209. }
  210. });
  211. }
  212. })
  213. },
  214. /**
  215. * 省市县三级联动加自填详情地址解析为省,市,县,详情地址
  216. * param 地址字符串
  217. * return {province-省, city-市, county-县, area-自填地址}
  218. */
  219. getAreaData : function(data){
  220. var areaData = {"province" : "", "city" : "", "county" : "", "area" : ""};
  221. if(data){
  222. var nativePlace = data.split("_");
  223. areaData.province = nativePlace[0];
  224. areaData.city = nativePlace[1];
  225. areaData.county = nativePlace[2];
  226. areaData.area = nativePlace.splice(3,nativePlace.length).join("_");
  227. }
  228. return areaData;
  229. },
  230. imgShow : function(fileId){
  231. return App.getUrl("/static/file/"+fileId+"/showfile");
  232. },
  233. tableSelect : function(_elem,paramData,fallBack){
  234. layui.use("tableSelect",function(){
  235. var ts = layui.tableSelect;
  236. ts.render({
  237. elem: _elem, //定义输入框input对象 必填
  238. checkedKey: 'id', //表格的唯一建值,非常重要,影响到选中状态 必填
  239. searchKey: paramData.searchKey, //搜索输入框的name值 默认keyword
  240. searchPlaceholder: paramData.searchPlaceholder, //搜索输入框的提示文字 默认关键词搜索
  241. height:'400', //自定义高度
  242. width:'300', //自定义宽度
  243. table: { //定义表格参数,与LAYUI的TABLE模块一致,只是无需再定义表格elem
  244. url:App.getUrl(paramData.url),
  245. cols: [
  246. paramData.table
  247. ]
  248. },
  249. done: function (elem, data) {
  250. //选择完后的回调,包含2个返回值 elem:返回之前input对象;data:表格返回的选中的数据 []
  251. //拿到data[]后 就按照业务需求做想做的事情啦~比如加个隐藏域放ID...
  252. if(fallBack != undefined && typeof fallBack == 'function'){
  253. fallBack(data);
  254. }
  255. }
  256. })
  257. });
  258. },
  259. uploadFile: function(target, url, params, beforeFunction, doneFunction, errorFunction) {
  260. layui.upload.render({
  261. elem: target,
  262. url: url, // 此处用的是第三方的 http 请求演示,实际使用时改成您自己的上传接口即可。
  263. acceptMime: params.acceptMime || 'image/png,image/jpg,image/jpeg',
  264. exts: params.exts || 'png|jpg|jpeg',
  265. multiple: params.multiple || false, //允许上传多个文件
  266. before: function (obj) {
  267. obj.preview(function(index, file, result) {
  268. if(beforeFunction != undefined && typeof beforeFunction == 'function'){
  269. beforeFunction(index, file, result);
  270. }
  271. });
  272. },
  273. done: function (res,index,upload) {
  274. if(res.success) {
  275. if(doneFunction != undefined && typeof doneFunction == 'function'){
  276. doneFunction(res);
  277. }
  278. }else {
  279. App.msg.warn("上传失败");
  280. if(errorFunction != undefined && typeof errorFunction == 'function') {
  281. errorFunction();
  282. }
  283. }
  284. }
  285. });
  286. },
  287. downFile: function(url,methodType, query,filename, errMsg) {
  288. App.showLoading();
  289. if(!methodType) {
  290. methodType = "GET";
  291. }
  292. if(query && methodType == "GET") {
  293. var params = "";
  294. for(var i in query) {
  295. params+= "&"+i+"="+query[i];
  296. }
  297. url += params.replace("&","?");
  298. }
  299. var req = new XMLHttpRequest();
  300. req.open(methodType, url, true);
  301. /*req.addEventListener("progress", function (evt) {
  302. if(evt.lengthComputable) {
  303. var percentComplete = evt.loaded / evt.total;
  304. console.log(percentComplete);
  305. }
  306. }, false);*/
  307. req.responseType = "blob";
  308. req.onreadystatechange = function () {
  309. if (req.readyState === 4) {
  310. if(req.status === 200) {
  311. App.closeLoading();
  312. if (typeof window.chrome !== 'undefined') {
  313. // Chrome version
  314. var link = top.document.createElement('a');
  315. link.href = window.URL.createObjectURL(req.response);
  316. link.download = filename;
  317. link.click();
  318. } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
  319. // IE version
  320. var blob = new Blob([req.response], { type: 'application/force-download' });
  321. window.navigator.msSaveBlob(blob, filename);
  322. } else {
  323. // Firefox version
  324. var file = new File([req.response], filename, { type: 'application/force-download' });
  325. window.open(URL.createObjectURL(file));
  326. }
  327. }else {
  328. App.closeLoading();
  329. App.msg.warn(errMsg||"下载失败");
  330. }
  331. }
  332. };
  333. if(methodType == "POST") {
  334. req.setRequestHeader("Content-type", "application/json");
  335. req.send(JSON.stringify(query));
  336. } else {
  337. req.send();
  338. }
  339. },
  340. imageWater: function(url, content, callBackFunction) {
  341. const img = new Image();
  342. img.src = url;
  343. img.crossOrigin = 'anonymous';
  344. img.onload = function () {
  345. // 创建canvas,并将创建的img绘制成canvas
  346. const canvas = document.createElement('canvas')
  347. canvas.width = img.width
  348. canvas.height = img.height
  349. const ctx = canvas.getContext('2d')
  350. ctx.drawImage(img, 0, 0);
  351. ctx.textAlign = 'left';
  352. ctx.textBaseline = 'top';
  353. ctx.font = '80px Microsoft Yahei'
  354. ctx.fillStyle = 'rgba(255, 255, 255, 0.5)'
  355. //ctx.rotate((Math.PI / 180) * 15)
  356. // 循环绘制水印
  357. // ctx.fillText(content, img.width - textX, img.height - textY)
  358. /*for (let i = 0; i < img.height / 120; i++) {
  359. for (let j = 0; j < img.width / 50; j++) {*/
  360. ctx.fillText(content, 200, 80, img.width)
  361. /*}
  362. }*/
  363. // 将绘制完成的canvas转换为base64的地址
  364. const base64Url = canvas.toDataURL()
  365. callBackFunction && callBackFunction(base64Url)
  366. }
  367. }
  368. };
  369. // ---------------成员方法定义---------------
  370. mod.utils = methods;
  371. }(jQuery, App.common))