sa.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508
  1. // =========================== sa对象封装一系列工具方法 ===========================
  2. var sa = {
  3. version: '2.4.3',
  4. update_time: '2020-10-2',
  5. info: '新增双击layer标题处全屏'
  6. };
  7. // =========================== 当前环境配置 =======================================
  8. (function() {
  9. // 公司开发环境
  10. var cfg_dev = {
  11. api_url: 'http://127.0.0.1:8080', // 所有ajax请求接口父地址
  12. // api_url: 'http://192.168.88.34:8080',
  13. web_url: 'http://www.baidu.com' // 此项目前台地址 (此配置项非必须)
  14. }
  15. // 服务器测试环境
  16. var cfg_test = {
  17. api_url: 'https://pco.aseanbusiness.cn/pro',
  18. web_url: 'http://www.baidu.com'
  19. }
  20. // 正式生产环境
  21. var cfg_prod = {
  22. api_url: 'https://dxkaa1.gxbtka.com/pro',
  23. web_url: 'http://www.baidu.com'
  24. }
  25. sa.cfg = cfg_dev; // 最终环境 , 上线前请选择正确的环境
  26. })();
  27. // =========================== ajax的封装 =======================================
  28. (function() {
  29. sa.ajaxNoLayer = function(url, data, success200, cfg) {
  30. // 如果是简写模式(省略了data参数)
  31. if (typeof data === 'function') {
  32. cfg = success200;
  33. success200 = data;
  34. data = {};
  35. }
  36. // 默认配置
  37. var defaultCfg = {
  38. baseUrl: (url.indexOf('http') === 0 ? '' : sa.cfg.api_url), // 父url,拼接在url前面
  39. sleep: 0, // 休眠n毫秒处理回调函数
  40. type: 'post', // 默认请求类型
  41. success200: success200, // code=200, 代表成功
  42. }
  43. // 将调用者的配置和默认配置合并
  44. cfg = sa.extendJson(cfg, defaultCfg);
  45. // 开始请求ajax
  46. return $.ajax({
  47. url: cfg.baseUrl + url,
  48. type: cfg.type,
  49. data: data,
  50. dataType: 'json',
  51. beforeSend: function(xhr) {
  52. xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  53. // 追加token
  54. if (localStorage.tokenName) {
  55. xhr.setRequestHeader(localStorage.tokenName, localStorage.tokenValue);
  56. }
  57. },
  58. success: function(res) {
  59. if (cfg['success' + res.code] != undefined) {
  60. return cfg['success' + res.code](res);
  61. }
  62. },
  63. });
  64. };
  65. sa.ajaxNoLoading = function(url, data, success200, cfg) {
  66. // 如果是简写模式(省略了data参数)
  67. if (typeof data === 'function') {
  68. cfg = success200;
  69. success200 = data;
  70. data = {};
  71. }
  72. // 默认配置
  73. var defaultCfg = {
  74. baseUrl: (url.indexOf('http') === 0 ? '' : sa.cfg.api_url), // 父url,拼接在url前面
  75. sleep: 0, // 休眠n毫秒处理回调函数
  76. type: 'post', // 默认请求类型
  77. success200: success200, // code=200, 代表成功
  78. success500: function(res) { // code=500, 代表失败
  79. let msg = res.msg;
  80. if (msg === '操作超时') {
  81. window.parent.location.href = '../../login.html';
  82. return;
  83. }
  84. return layer.alert('失败:' + res.msg);
  85. },
  86. success403: function(res) { // code=403, 代表权限不足
  87. return layer.alert("权限不足," + res.msg, {
  88. icon: 5
  89. });
  90. },
  91. success401: function(res) { // code=401, 代表未登录
  92. return layer.confirm("您当前暂未登录,是否立即登录?", {}, function() {
  93. layer.closeAll();
  94. return sa.$page.openLogin(cfg.login_url);
  95. });
  96. },
  97. success405: function(res) { // code=401, 代表未登录
  98. window.parent.location.href = '../../login.html';
  99. },
  100. errorfn: function(xhr, type, errorThrown) { // ajax发生异常时的默认处理函数
  101. if (xhr.status == 0) {
  102. return layer.alert('无法连接到服务器,请检查网络');
  103. }
  104. return layer.alert("异常:" + JSON.stringify(xhr));
  105. },
  106. complete: function(xhr, ts) { // 成功失败都会执行
  107. }
  108. }
  109. // 将调用者的配置和默认配置合并
  110. cfg = sa.extendJson(cfg, defaultCfg);
  111. // 开始请求ajax
  112. return $.ajax({
  113. url: cfg.baseUrl + url,
  114. type: cfg.type,
  115. data: data,
  116. dataType: 'json',
  117. // xhrFields: {
  118. // withCredentials: true // 携带跨域cookie
  119. // },
  120. // crossDomain: true,
  121. beforeSend: function(xhr) {
  122. xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  123. // 追加token
  124. if (localStorage.tokenName) {
  125. xhr.setRequestHeader(localStorage.tokenName, localStorage.tokenValue);
  126. }
  127. },
  128. success: function(res) {
  129. setTimeout(function() {
  130. // 如果相应的处理函数存在
  131. if (cfg['success' + res.code] != undefined) {
  132. return cfg['success' + res.code](res);
  133. }
  134. layer.alert('未知状态码:' + JSON.stringify(res));
  135. }, cfg.sleep);
  136. },
  137. error: function(xhr, type, errorThrown) {
  138. setTimeout(function() {
  139. sa.hideLoading();
  140. return cfg.errorfn(xhr, type, errorThrown);
  141. }, cfg.sleep);
  142. },
  143. complete: cfg.complete
  144. });
  145. };
  146. /** 对ajax的再封装, 这个ajax假设你的接口会返回以下格式的内容
  147. {
  148. "code": 200,
  149. "msg": "ok",
  150. "data": []
  151. }
  152. 如果返回的不是这个格式, 你可能需要改动一下源码, 要么改动服务端适应此ajax, 要么改动这个ajax适应你的服务端
  153. * @param {Object} url 请求地址
  154. * @param {Object} data 请求参数
  155. * @param {Object} success200 当返回的code码==200时的回调函数
  156. * @param {Object} 其它配置,可配置项有:
  157. {
  158. msg: '', // 默认的提示文字 填null为不提示
  159. type: 'get', // 设定请求类型 默认post
  160. baseUrl: '', // ajax请求拼接的父路径 默认取 sa.cfg.api_url
  161. sleep: 0, // ajax模拟的延时毫秒数, 默认0
  162. success500: fn, // code码等于500时的回调函数 (一般代表服务器错误)
  163. success403: fn, // code码等于403时的回调函数 (一般代表无权限)
  164. success401: fn, // code码等于401时的回调函数 (一般代表未登录)
  165. errorfn: fn, // ajax发生错误时的回调函数 (一般是ajax请求本身发生了错误)
  166. complete: fn, // ajax无论成功还是失败都会执行的回调函数
  167. }
  168. */
  169. sa.ajax = function(url, data, success200, cfg) {
  170. // 如果是简写模式(省略了data参数)
  171. if (typeof data === 'function') {
  172. cfg = success200;
  173. success200 = data;
  174. data = {};
  175. }
  176. // 默认配置
  177. var defaultCfg = {
  178. msg: '努力加载中...', // 提示语
  179. baseUrl: (url.indexOf('http') === 0 ? '' : sa.cfg.api_url), // 父url,拼接在url前面
  180. sleep: 0, // 休眠n毫秒处理回调函数
  181. type: 'post', // 默认请求类型
  182. success200: success200, // code=200, 代表成功
  183. success500: function(res) { // code=500, 代表失败
  184. let msg = res.msg;
  185. console.log(msg);
  186. if (msg === '操作超时') {
  187. window.parent.location.href = '../../login.html';
  188. return;
  189. }
  190. return layer.alert('失败:' + res.msg);
  191. },
  192. success403: function(res) { // code=403, 代表权限不足
  193. return layer.alert("权限不足," + res.msg, {
  194. icon: 5
  195. });
  196. },
  197. success401: function(res) { // code=401, 代表未登录
  198. return layer.confirm("您当前暂未登录,是否立即登录?", {}, function() {
  199. layer.closeAll();
  200. return sa.$page.openLogin(cfg.login_url);
  201. });
  202. },
  203. errorfn: function(xhr, type, errorThrown) { // ajax发生异常时的默认处理函数
  204. if (xhr.status == 0) {
  205. return layer.alert('无法连接到服务器,请检查网络');
  206. }
  207. if(xhr.responseText.indexOf('code=405')>0){
  208. window.parent.location.href = '../../login.html';
  209. return;
  210. }
  211. return layer.alert("异常:" + JSON.stringify(xhr));
  212. },
  213. complete: function(xhr, ts) { // 成功失败都会执行
  214. }
  215. }
  216. // 将调用者的配置和默认配置合并
  217. cfg = sa.extendJson(cfg, defaultCfg);
  218. // 开始显示loading图标
  219. if (cfg.msg != null) {
  220. sa.loading(cfg.msg);
  221. }
  222. // 开始请求ajax
  223. return $.ajax({
  224. url: cfg.baseUrl + url,
  225. type: cfg.type,
  226. data: data,
  227. dataType: 'json',
  228. // xhrFields: {
  229. // withCredentials: true // 携带跨域cookie
  230. // },
  231. // crossDomain: true,
  232. beforeSend: function(xhr) {
  233. xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  234. // 追加token
  235. if (localStorage.tokenName) {
  236. xhr.setRequestHeader(localStorage.tokenName, localStorage.tokenValue);
  237. }
  238. },
  239. success: function(res) {
  240. setTimeout(function() {
  241. sa.hideLoading();
  242. // 如果相应的处理函数存在
  243. if (cfg['success' + res.code] != undefined) {
  244. return cfg['success' + res.code](res);
  245. }
  246. layer.alert('未知状态码:' + JSON.stringify(res));
  247. }, cfg.sleep);
  248. },
  249. error: function(xhr, type, errorThrown) {
  250. setTimeout(function() {
  251. sa.hideLoading();
  252. return cfg.errorfn(xhr, type, errorThrown);
  253. }, cfg.sleep);
  254. },
  255. complete: cfg.complete
  256. });
  257. };
  258. // 模拟一个ajax
  259. // 请注意: 本模板中所有ajax请求调用的均为此模拟函数
  260. sa.ajax2 = function(url, data, success200, cfg) {
  261. // 如果是简写模式(省略了data参数)
  262. if (typeof data === 'function') {
  263. cfg = success200;
  264. success200 = data;
  265. data = {};
  266. }
  267. // 几个默认配置
  268. cfg = cfg || {};
  269. cfg.baseUrl = (url.indexOf('http') === 0 ? '' : sa.cfg.api_url); // 父url,拼接在url前面
  270. // 设定一个默认的提示文字
  271. if (cfg.msg == undefined || cfg.msg == null || cfg.msg == '') {
  272. cfg.msg = '正在努力加载...';
  273. }
  274. // 默认延时函数
  275. if (cfg.sleep == undefined || cfg.sleep == null || cfg.sleep == '' || cfg.sleep == 0) {
  276. cfg.sleep = 600;
  277. }
  278. // 默认的模拟数据
  279. cfg.res = cfg.res || {
  280. code: 200,
  281. msg: 'ok',
  282. data: []
  283. }
  284. // 开始loding
  285. sa.loading(cfg.msg);
  286. // 模拟ajax的延时
  287. setTimeout(function() {
  288. sa.hideLoading(); // 隐藏掉转圈圈
  289. success200(cfg.res);
  290. }, cfg.sleep)
  291. };
  292. })();
  293. // =========================== 封装弹窗相关函数 =======================================
  294. (function() {
  295. var me = sa;
  296. if (window.layer) {
  297. layer.ready(function() {});
  298. }
  299. // tips提示文字
  300. me.msg = function(msg, cfg) {
  301. msg = msg || '操作成功';
  302. layer.msg(msg, cfg);
  303. };
  304. // 操作成功的提示
  305. me.ok = function(msg) {
  306. msg = msg || '操作成功';
  307. layer.msg(msg, {
  308. anim: 0,
  309. icon: 1
  310. });
  311. }
  312. me.ok2 = function(msg) {
  313. msg = msg || '操作成功';
  314. layer.msg(msg, {
  315. anim: 0,
  316. icon: 6
  317. });
  318. }
  319. // 操作失败的提示
  320. me.error = function(msg) {
  321. msg = msg || '操作失败';
  322. layer.msg(msg, {
  323. anim: 6,
  324. icon: 2
  325. });
  326. }
  327. me.error2 = function(msg) {
  328. msg = msg || '操作失败';
  329. layer.msg(msg, {
  330. anim: 6,
  331. icon: 5
  332. });
  333. }
  334. // alert弹窗 [text=提示文字, okFn=点击确定之后的回调函数]
  335. me.alert = function(text, okFn) {
  336. // 开始弹窗
  337. layer.alert(text, function(index) {
  338. layer.close(index);
  339. if (okFn) {
  340. okFn();
  341. }
  342. });
  343. };
  344. // 询问框 [text=提示文字, okFn=点击确定之后的回调函数]
  345. me.confirm = function(text, okFn) {
  346. layer.confirm(text, {}, function(index) {
  347. layer.close(index);
  348. if (okFn) {
  349. okFn();
  350. }
  351. }.bind(this));
  352. };
  353. // 输入框 [title=提示文字, okFn=点击确定后的回调函数, formType=输入框类型(0=文本,1=密码,2=多行文本域) 可省略, value=默认值 可省略 ]
  354. me.prompt = function(title, okFn, formType, value) {
  355. layer.prompt({
  356. title: title,
  357. formType: formType,
  358. value: value
  359. }, function(pass, index) {
  360. layer.close(index);
  361. if (okFn) {
  362. okFn(pass);
  363. }
  364. });
  365. }
  366. // 打开loading
  367. me.loading = function(msg) {
  368. layer.closeAll(); // 开始前先把所有弹窗关了
  369. return layer.msg(msg, {
  370. icon: 16,
  371. shade: 0.3,
  372. time: 1000 * 20,
  373. skin: 'ajax-layer-load'
  374. });
  375. };
  376. // 隐藏loading
  377. me.hideLoading = function() {
  378. layer.closeAll();
  379. };
  380. // ============== 一些常用弹窗 =====================
  381. // 大窗显示一个图片
  382. // 参数: src=地址、w=宽度(默认80%)、h=高度(默认80%)
  383. me.showImage = function(src, w, h) {
  384. w = w || '80%';
  385. h = h || '80%';
  386. var content = '<div style="height: 100%; overflow: hidden !important;">' +
  387. '<img src="' + src + ' " style="width: 100%; height: 100%;" />' +
  388. '</div>';
  389. layer.open({
  390. type: 1,
  391. title: false,
  392. shadeClose: true,
  393. closeBtn: 0,
  394. area: [w, h], //宽高
  395. content: content
  396. });
  397. }
  398. // 预览一组图片
  399. // srcList=图片路径数组(可以是json样,也可以是逗号切割式), index=打开立即显示哪张(可填下标, 也可填写src路径)
  400. me.showImageList = function(srcList, index) {
  401. // 如果填的是个string
  402. srcList = srcList || [];
  403. if (typeof srcList === 'string') {
  404. try {
  405. srcList = JSON.parse(srcList);
  406. } catch (e) {
  407. try {
  408. srcList = srcList.split(','); // 尝试字符串切割
  409. } catch (e) {
  410. srcList = [];
  411. }
  412. }
  413. }
  414. // 如果填的是路径
  415. index = index || 0;
  416. if (typeof index === 'string') {
  417. index = srcList.indexOf(index);
  418. index = (index == -1 ? 0 : index);
  419. }
  420. // 开始展示
  421. var arr_list = [];
  422. srcList.forEach(function(item) {
  423. arr_list.push({
  424. alt: '左右键切换',
  425. pid: 1,
  426. src: item,
  427. thumb: item
  428. })
  429. })
  430. layer.photos({
  431. photos: {
  432. title: '',
  433. id: new Date().getTime(),
  434. start: index,
  435. data: arr_list
  436. },
  437. anim: 5 //0-6的选择,指定弹出图片动画类型,默认随机(请注意,3.0之前的版本用shift参数)
  438. });
  439. }
  440. // 显示一个iframe
  441. // 参数: 标题,地址,宽,高 , 点击遮罩是否关闭, 默认false
  442. me.showIframe = function(title, url, w, h, shadeClose) {
  443. // 参数修正
  444. w = w || '95%';
  445. h = h || '95%';
  446. shadeClose = (shadeClose === undefined ? false : shadeClose);
  447. // 弹出面板
  448. var index = layer.open({
  449. type: 2,
  450. title: title, // 标题
  451. shadeClose: shadeClose, // 是否点击遮罩关闭
  452. maxmin: true, // 显示最大化按钮
  453. shade: 0.8, // 遮罩透明度
  454. scrollbar: false, // 屏蔽掉外层的滚动条
  455. moveOut: true, // 是否可拖动到外面
  456. area: [w, h], // 大小
  457. content: url, // 传值
  458. // 解决拉伸或者最大化的时候,iframe高度不能自适应的问题
  459. resizing: function(layero) {
  460. solveLayerBug(index);
  461. }
  462. });
  463. // 解决拉伸或者最大化的时候,iframe高度不能自适应的问题
  464. $('#layui-layer' + index + ' .layui-layer-max').click(function() {
  465. setTimeout(function() {
  466. solveLayerBug(index);
  467. }, 200)
  468. })
  469. }
  470. me.showView = me.showIframe;
  471. // 显示一个iframe, 底部按钮方式
  472. // 参数: 标题,地址,点击确定按钮执行的代码(在子窗口执行),宽,高
  473. me.showIframe2 = function(title, url, evalStr, w, h) {
  474. // 参数修正
  475. w = w || '95%';
  476. h = h || '95%';
  477. // 弹出面板
  478. var index = layer.open({
  479. type: 2,
  480. title: title, // 标题
  481. closeBtn: (title ? 1 : 0), // 是否显示关闭按钮
  482. btn: ['确定', '取消'],
  483. shadeClose: false, // 是否点击遮罩关闭
  484. maxmin: true, // 显示最大化按钮
  485. shade: 0.8, // 遮罩透明度
  486. scrollbar: false, // 屏蔽掉外层的滚动条
  487. moveOut: true, // 是否可拖动到外面
  488. area: [w, h], // 大小
  489. content: url, // 传值
  490. // 解决拉伸或者最大化的时候,iframe高度不能自适应的问题
  491. resizing: function(layero) {
  492. },
  493. yes: function(index, layero) {
  494. var iframe = document.getElementById('layui-layer-iframe' + index);
  495. var iframeWindow = iframe.contentWindow;
  496. iframeWindow.eval(evalStr);
  497. }
  498. });
  499. }
  500. // 当前iframe关闭自身 (在iframe中调用)
  501. me.closeCurrIframe = function() {
  502. try {
  503. var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
  504. parent.layer.close(index); //再执行关闭
  505. } catch (e) {
  506. //TODO handle the exception
  507. }
  508. }
  509. me.closeCurrView = me.closeCurrIframe;
  510. //执行一个函数, 解决layer拉伸或者最大化的时候,iframe高度不能自适应的问题
  511. function solveLayerBug(index) {
  512. var selected = '#layui-layer' + index;
  513. var height = $(selected).height();
  514. var title_height = $(selected).find('.layui-layer-title').height();
  515. $(selected).find('iframe').css('height', (height - title_height) + 'px');
  516. }
  517. // 监听回车事件,达到回车关闭弹窗的效果
  518. if (window.$) {
  519. $(document).on('keydown', function() {
  520. if (event.keyCode === 13 && $(".layui-layer-btn0").length == 1 && !window.is_not_watch_enter &&
  521. $(this).find('.layui-layer-input').length == 0) {
  522. $(".layui-layer-btn0").click();
  523. return false;
  524. }
  525. });
  526. }
  527. })();
  528. // =========================== 常用util函数封装 =======================================
  529. (function() {
  530. // 超级对象
  531. var me = sa;
  532. // =========================== 常用util函数封装 =======================================
  533. if (true) {
  534. // 从url中查询到指定参数值
  535. me.p = function(name, defaultValue) {
  536. var query = window.location.search.substring(1);
  537. var vars = query.split("&");
  538. for (var i = 0; i < vars.length; i++) {
  539. var pair = vars[i].split("=");
  540. if (pair[0] == name) {
  541. return pair[1];
  542. }
  543. }
  544. return (defaultValue == undefined ? null : defaultValue);
  545. }
  546. me.q = function(name, defaultValue) {
  547. var query = window.location.search.substring(1);
  548. var vars = query.split("&");
  549. for (var i = 0; i < vars.length; i++) {
  550. var pair = vars[i].split("=");
  551. if (pair[0] == name) {
  552. return pair[1];
  553. }
  554. }
  555. return (defaultValue == undefined ? null : defaultValue);
  556. }
  557. // 判断一个变量是否为null
  558. // 返回true或false,如果return_obj有值,则在true的情况下返回return_obj
  559. me.isNull = function(obj, return_obj) {
  560. var flag = [null, undefined, '', 'null', 'undefined'].indexOf(obj) != -1;
  561. if (return_obj === undefined) {
  562. return flag;
  563. } else {
  564. if (flag) {
  565. return return_obj;
  566. } else {
  567. return obj;
  568. }
  569. }
  570. }
  571. // 将时间戳转化为指定时间
  572. // way:方式(1=年月日,2=年月日时分秒)默认1, 也可以指定格式:yyyy-MM-dd HH:mm:ss
  573. me.forDate = function(inputTime, way) {
  574. if (me.isNull(inputTime) == true) {
  575. return "";
  576. }
  577. var date = new Date(inputTime);
  578. var y = date.getFullYear();
  579. var m = date.getMonth() + 1;
  580. m = m < 10 ? ('0' + m) : m;
  581. var d = date.getDate();
  582. d = d < 10 ? ('0' + d) : d;
  583. var h = date.getHours();
  584. h = h < 10 ? ('0' + h) : h;
  585. var minute = date.getMinutes();
  586. var second = date.getSeconds();
  587. minute = minute < 10 ? ('0' + minute) : minute;
  588. second = second < 10 ? ('0' + second) : second;
  589. var ms = date.getMilliseconds();
  590. way = way || 1;
  591. // way == 1 年月日
  592. if (way === 1) {
  593. return y + '-' + m + '-' + d;
  594. }
  595. // way == 1 年月日时分秒
  596. if (way === 2) {
  597. return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
  598. }
  599. // way == 具体格式 标准格式: yyyy-MM-dd HH:mm:ss
  600. if (typeof way == 'string') {
  601. return way.replace("yyyy", y).replace("MM", m).replace("dd", d).replace("HH", h).replace("mm",
  602. minute).replace("ss", second).replace("ms", ms);
  603. }
  604. return y + '-' + m + '-' + d;
  605. };
  606. // 时间日期
  607. me.forDatetime = function(inputTime) {
  608. return me.forDate(inputTime, 2);
  609. }
  610. // 将时间转化为 个性化 如:3小时前,
  611. // d1 之于 d2 ,d2不填则默认取当前时间
  612. me.forDate2 = function(d, d2) {
  613. var hou = "前";
  614. if (d == null || d == '') {
  615. return '';
  616. }
  617. if (d2 == null || d2 == '') {
  618. d2 = new Date();
  619. }
  620. d2 = new Date(d2).getTime();
  621. var timestamp = new Date(d).getTime() - 1000;
  622. var mistiming = Math.round((d2 - timestamp) / 1000);
  623. if (mistiming < 0) {
  624. mistiming = 0 - mistiming;
  625. hou = '后'
  626. }
  627. var arrr = ['年', '月', '周', '天', '小时', '分钟', '秒'];
  628. var arrn = [31536000, 2592000, 604800, 86400, 3600, 60, 1];
  629. for (var i = 0; i < arrn.length; i++) {
  630. var inm = Math.floor(mistiming / arrn[i]);
  631. if (inm != 0) {
  632. return inm + arrr[i] + hou;
  633. }
  634. }
  635. }
  636. // 综合以上两种方式,进行格式化
  637. // 小于24小时的走forDate2,否则forDat
  638. me.forDate3 = function(d, way) {
  639. if (d == null || d == '') {
  640. return '';
  641. }
  642. var cha = new Date().getTime() - new Date(d).getTime();
  643. cha = (cha > 0 ? cha : 0 - cha);
  644. if (cha < (86400 * 1000)) {
  645. return me.forDate2(d);
  646. }
  647. return me.forDate(d, way);
  648. }
  649. // 返回时间差, 此格式数组:[x, x, x, 天, 时, 分, 秒]
  650. me.getSJC = function(small_time, big_time) {
  651. var date1 = new Date(small_time); //开始时间
  652. var date2 = new Date(big_time); //结束时间
  653. var date3 = date2.getTime() - date1.getTime(); //时间差秒
  654. //计算出相差天数
  655. var days = Math.floor(date3 / (24 * 3600 * 1000));
  656. //计算出小时数
  657. var leave1 = date3 % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
  658. var hours = Math.floor(leave1 / (3600 * 1000));
  659. //计算相差分钟数
  660. var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
  661. var minutes = Math.floor(leave2 / (60 * 1000));
  662. //计算相差秒数
  663. var leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
  664. var seconds = Math.round(leave3 / 1000);
  665. // 返回数组
  666. return [0, 0, 0, days, hours, minutes, seconds];
  667. }
  668. // 将日期,加上指定天数
  669. me.dateAdd = function(d, n) {
  670. var s = new Date(d).getTime();
  671. s += 86400000 * n;
  672. return new Date(s);
  673. }
  674. // 转化json,出错返回默认值
  675. me.JSONParse = function(obj, default_obj) {
  676. try {
  677. return JSON.parse(obj) || default_obj;
  678. } catch (e) {
  679. return default_obj || {};
  680. }
  681. }
  682. // 截取指定长度字符,默认50
  683. me.maxLength = function(str, length) {
  684. length = length || 50;
  685. if (!str) {
  686. return "";
  687. }
  688. return (str.length > length) ? str.substr(0, length) + ' ...' : str;
  689. },
  690. // 过滤掉标签
  691. me.text = function(str) {
  692. if (!str) {
  693. return "";
  694. }
  695. return str.replace(/<[^>]+>/g, "");
  696. }
  697. // 为指定集合的每一项元素添加上is_update属性
  698. me.listAU = function(list) {
  699. list.forEach(function(ts) {
  700. ts.is_update = false;
  701. })
  702. return list;
  703. }
  704. // 获得一段文字中所有图片的路径
  705. me.getSrcList = function(str) {
  706. try {
  707. var imgReg = /<img.*?(?:>|\/>)/gi; //匹配图片(g表示匹配所有结果i表示区分大小写)
  708. var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i; //匹配src属性
  709. var arr = str.match(imgReg); // 图片数组
  710. var srcList = [];
  711. for (var i = 0; i < arr.length; i++) {
  712. var src = arr[i].match(srcReg);
  713. srcList.push(src[1]);
  714. }
  715. return srcList;
  716. } catch (e) {
  717. return [];
  718. }
  719. }
  720. // 无精度损失的乘法
  721. me.accMul = function(arg1, arg2) {
  722. var m = 0,
  723. s1 = arg1.toString(),
  724. s2 = arg2.toString(),
  725. t;
  726. t = s1.split(".");
  727. // 判断有没有小数位,避免出错
  728. if (t[1]) {
  729. m += t[1].length
  730. }
  731. t = s2.split(".");
  732. if (t[1]) {
  733. m += t[1].length
  734. }
  735. return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
  736. }
  737. // 正则验证是否为手机号
  738. me.isTel = function(str) {
  739. str = str + '';
  740. if ((/^1[345678]\d{9}$/.test(str)) || (/0\d{2,3}-\d{7,8}/.test(str))) {
  741. return true;
  742. }
  743. return false;
  744. }
  745. me.isCarNo = function(str) {
  746. str = str + '';
  747. let reg =
  748. /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/
  749. if (reg.test(str)) {
  750. return true;
  751. }
  752. return false;
  753. }
  754. me.isNum = function(str) {
  755. str = str + '';
  756. if ((/^[0-9]*$/.test(str)) || (/^[0-9]+(.[0-9]{1})?$/.test(str))) {
  757. return true;
  758. }
  759. return false;
  760. }
  761. me.isEmail = function(str) {
  762. str = str + '';
  763. if ((/^[A-Za-z0-9_-\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(str))) {
  764. return true;
  765. }
  766. return false;
  767. }
  768. me.isTaxId = function(str) {
  769. str = str + '';
  770. if ((/^[A-Z0-9]{15}$|^[A-Z0-9]{18}$|^[A-Z0-9]{20}$/.test(str))) {
  771. return true;
  772. }
  773. return false;
  774. }
  775. // 产生随机字符串
  776. me.randomString = function(len) {
  777. len = len || 32;
  778. var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  779. /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  780. var maxPos = $chars.length;
  781. var str = '';
  782. for (i = 0; i < len; i++) {
  783. str += $chars.charAt(Math.floor(Math.random() * maxPos));
  784. }
  785. return str;
  786. }
  787. // 刷新页面
  788. me.f5 = function() {
  789. location.reload();
  790. }
  791. // 动态加载js
  792. me.loadJS = function(src, onload) {
  793. var script = document.createElement("script");
  794. script.setAttribute("type", "text/javascript");
  795. script.src = src;
  796. script.onload = onload;
  797. document.body.appendChild(script);
  798. }
  799. // 产生随机数字
  800. me.randomNum = function(min, max) {
  801. return parseInt(Math.random() * (max - min + 1) + min, 10);
  802. }
  803. // 打开页面
  804. me.open = function(url) {
  805. window.open(url);
  806. }
  807. // == if 结束
  808. }
  809. // =========================== 数组操作 =======================================
  810. if (true) {
  811. // 从数组里获取数据,根据指定数据
  812. me.getArrayField = function(arr, prop) {
  813. var propArr = [];
  814. for (var i = 0; i < arr.length; i++) {
  815. propArr.push(arr[i][prop]);
  816. }
  817. return propArr;
  818. }
  819. // 从数组里获取数据,根据指定数据
  820. me.arrayGet = function(arr, prop, value) {
  821. for (var i = 0; i < arr.length; i++) {
  822. if (arr[i][prop] == value) {
  823. return arr[i];
  824. }
  825. }
  826. return null;
  827. }
  828. // 正则验证是否为手机号
  829. me.isPhone = function(str) {
  830. str = str + '';
  831. if ((/^1[3456789]\d{9}$/.test(str))) {
  832. return true;
  833. }
  834. return false;
  835. }
  836. // 从数组删除指定记录
  837. me.arrayDelete = function(arr, item) {
  838. if (item instanceof Array) {
  839. for (let i = 0; i < item.length; i++) {
  840. let ite = item[i];
  841. let index = arr.indexOf(ite);
  842. if (index > -1) {
  843. arr.splice(index, 1);
  844. }
  845. }
  846. } else {
  847. var index = arr.indexOf(item);
  848. if (index > -1) {
  849. arr.splice(index, 1);
  850. }
  851. }
  852. }
  853. // 从数组删除指定id的记录
  854. me.arrayDeleteById = function(arr, id) {
  855. var item = me.arrayGet(arr, 'id', id);
  856. me.arrayDelete(arr, item);
  857. }
  858. // 将数组B添加到数组A的开头
  859. me.unshiftArray = function(arrA, arrB) {
  860. if (arrB) {
  861. arrB.reverse().forEach(function(ts) {
  862. arrA.unshift(ts);
  863. })
  864. }
  865. return arrA;
  866. }
  867. // 将数组B添加到数组A的末尾
  868. me.pushArray = function(arrA, arrB) {
  869. if (arrB) {
  870. arrB.forEach(function(ts) {
  871. arrA.push(ts);
  872. })
  873. }
  874. return arrA;
  875. }
  876. // == if 结束
  877. }
  878. // =========================== 浏览器相关 =======================================
  879. if (true) {
  880. // set cookie 值
  881. me.setCookie = function setCookie(cname, cvalue, exdays) {
  882. exdays = exdays || 30;
  883. var d = new Date();
  884. d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  885. var expires = "expires=" + d.toGMTString();
  886. document.cookie = cname + "=" + escape(cvalue) + "; " + expires + "; path=/";
  887. }
  888. // get cookie 值
  889. me.getCookie = function(objName) {
  890. var arrStr = document.cookie.split("; ");
  891. for (var i = 0; i < arrStr.length; i++) {
  892. var temp = arrStr[i].split("=");
  893. if (temp[0] == objName) {
  894. return unescape(temp[1])
  895. };
  896. }
  897. return "";
  898. }
  899. // 复制指定文本
  900. me.copyText = function(str) {
  901. var oInput = document.createElement('input');
  902. oInput.value = str;
  903. document.body.appendChild(oInput);
  904. oInput.select(); // 选择对象
  905. document.execCommand("Copy"); // 执行浏览器复制命令
  906. oInput.className = 'oInput';
  907. oInput.style.display = 'none';
  908. }
  909. // jquery序列化表单增强版: 排除空值
  910. me.serializeNotNull = function(selected) {
  911. var serStr = $(selected).serialize();
  912. return serStr.split("&").filter(function(str) {
  913. return !str.endsWith("=")
  914. }).join("&");
  915. }
  916. // 将cookie序列化为k=v形式
  917. me.strCookie = function() {
  918. return document.cookie.replace(/; /g, "&");
  919. }
  920. // 回到顶部
  921. me.goTop = function() {
  922. function smoothscroll() {
  923. var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
  924. if (currentScroll > 0) {
  925. window.requestAnimationFrame(smoothscroll);
  926. window.scrollTo(0, currentScroll - (currentScroll / 5));
  927. }
  928. };
  929. smoothscroll();
  930. }
  931. // == if 结束
  932. }
  933. // =========================== javascript对象操作 =======================================
  934. if (true) {
  935. // 去除json对象中的空值
  936. me.removeNull = function(obj) {
  937. var newObj = {};
  938. if (obj != undefined && obj != null) {
  939. for (var key in obj) {
  940. if (obj[key] === undefined || obj[key] === null || obj[key] === '') {
  941. //
  942. } else {
  943. newObj[key] = obj[key];
  944. }
  945. }
  946. }
  947. return newObj;
  948. }
  949. // JSON 浅拷贝, 返回拷贝后的obj
  950. me.copyJSON = function(obj) {
  951. if (obj === null || obj === undefined) {
  952. return obj;
  953. };
  954. var new_obj = {};
  955. for (var key in obj) {
  956. new_obj[key] = obj[key];
  957. }
  958. return new_obj;
  959. }
  960. // json合并, 将 defaulet配置项 转移到 user配置项里 并返回 user配置项
  961. me.extendJson = function(userOption, defaultOption) {
  962. if (!userOption) {
  963. return defaultOption;
  964. };
  965. for (var key in defaultOption) {
  966. if (userOption[key] === undefined) {
  967. userOption[key] = defaultOption[key];
  968. } else if (userOption[key] == null) {
  969. } else if (typeof userOption[key] == "object") {
  970. me.extendJson(userOption[key], defaultOption[key]); //深度匹配
  971. }
  972. }
  973. return userOption;
  974. }
  975. // == if 结束
  976. }
  977. // =========================== 本地集合存储 =======================================
  978. if (true) {
  979. // 获取指定key的list
  980. me.keyListGet = function(key) {
  981. try {
  982. var str = localStorage.getItem('LIST_' + key);
  983. if (str == undefined || str == null || str == '' || str == 'undefined' || typeof(JSON.parse(
  984. str)) == 'string') {
  985. //alert('key' + str);
  986. str = '[]';
  987. }
  988. return JSON.parse(str);
  989. } catch (e) {
  990. return [];
  991. }
  992. },
  993. me.keyListSet = function(key, list) {
  994. localStorage.setItem('LIST_' + key, JSON.stringify(list));
  995. },
  996. me.keyListHas = function(key, item) {
  997. var arr2 = me.keyListGet(key);
  998. return arr2.indexOf(item) != -1;
  999. },
  1000. me.keyListAdd = function(key, item) {
  1001. var arr = me.keyListGet(key);
  1002. arr.push(item);
  1003. me.keyListSet(key, arr);
  1004. },
  1005. me.keyListRemove = function(key, item) {
  1006. var arr = me.keyListGet(key);
  1007. var index = arr.indexOf(item);
  1008. if (index > -1) {
  1009. arr.splice(index, 1);
  1010. }
  1011. me.keyListSet(key, arr);
  1012. }
  1013. // == if 结束
  1014. }
  1015. // =========================== 对sa-admin的优化 =======================================
  1016. if (true) {
  1017. // 封装element-ui的导出表格
  1018. // 参数:选择器(默认.data-count),fileName=导出的文件名称
  1019. me.exportExcel = function(select, fileName) {
  1020. // 声明函数
  1021. let exportExcel_fn = function(select, fileName) {
  1022. // 赋默认值
  1023. select = select || '.data-table';
  1024. fileName = fileName || 'table.xlsx';
  1025. // 开始导出
  1026. let wb = XLSX.utils.table_to_book(document.querySelector(select)); // 这里就是表格
  1027. let sheet = wb.Sheets.Sheet1; // 单元表
  1028. try {
  1029. // 强改宽度
  1030. sheet['!cols'] = sheet['!cols'] || [];
  1031. let thList = document.querySelector(select).querySelectorAll(
  1032. '.el-table__header-wrapper tr th');
  1033. for (var i = 0; i < thList.length; i++) {
  1034. // 如果是多选框
  1035. if (thList[i].querySelector('.el-checkbox')) {
  1036. sheet['!cols'].push({
  1037. wch: 5
  1038. }); // 强改宽度
  1039. continue;
  1040. }
  1041. sheet['!cols'].push({
  1042. wch: 15
  1043. }); // 强改宽度
  1044. }
  1045. // 强改高度
  1046. sheet['!rows'] = sheet['!rows'] || [];
  1047. let trList = document.querySelector(select).querySelectorAll(
  1048. '.el-table__body-wrapper tbody tr');
  1049. for (var i = 0; i < trList.length + 1; i++) {
  1050. sheet['!rows'].push({
  1051. hpx: 20
  1052. }); // 强改高度
  1053. }
  1054. } catch (e) {
  1055. console.err(e);
  1056. }
  1057. // 开始制作并输出
  1058. let wbout = XLSX.write(wb, {
  1059. bookType: 'xlsx',
  1060. bookSST: true,
  1061. type: 'array'
  1062. });
  1063. // 点击
  1064. let blob = new Blob([wbout], {
  1065. type: 'application/octet-stream'
  1066. });
  1067. const a = document.createElement("a")
  1068. a.href = URL.createObjectURL(blob)
  1069. a.download = fileName // 这里填保存成的文件名
  1070. a.click()
  1071. URL.revokeObjectURL(a.href)
  1072. a.remove();
  1073. sa.hideLoading();
  1074. }
  1075. sa.loading('正在导出...');
  1076. // 判断是否首次加载
  1077. if (window.XLSX) {
  1078. return exportExcel_fn(select, fileName);
  1079. } else {
  1080. me.loadJS('https://unpkg.com/xlsx@0.16.6/dist/xlsx.core.min.js', function() {
  1081. return exportExcel_fn(select, fileName);
  1082. });
  1083. }
  1084. }
  1085. // 刷新表格高度, 请务必在所有表格高度发生变化的地方调用此方法
  1086. me.f5TableHeight = function() {
  1087. Vue.nextTick(function() {
  1088. if ($('.el-table.data-table .el-table__body-wrapper table').length == 0) {
  1089. return;
  1090. }
  1091. var _f5Height = function() {
  1092. var height = $('.el-table .el-table__body-wrapper table').height();
  1093. height = height == 0 ? 60 : height;
  1094. // 判断是否有滚动条
  1095. var tw = $('.el-table .el-table__body-wrapper').get(0);
  1096. if (tw.scrollWidth > tw.clientWidth) {
  1097. height = height + 16;
  1098. }
  1099. if ($('.el-table .el-table__body-wrapper table td').width() == 0) {
  1100. return;
  1101. }
  1102. // 设置高度
  1103. $('.el-table .el-table__body-wrapper').css('min-height', height);
  1104. $('.el-table .el-table__body-wrapper').css('max-height', height);
  1105. };
  1106. setTimeout(_f5Height, 0)
  1107. setTimeout(_f5Height, 200)
  1108. })
  1109. }
  1110. // 在表格查询的页面,监听input回车事件,提交查询
  1111. me.onInputEnter = function(app) {
  1112. Vue.nextTick(function() {
  1113. app = app || window.app;
  1114. document.querySelectorAll('.el-form').forEach(function(item) {
  1115. item.onkeydown = function(e) {
  1116. var theEvent = e || window.event;
  1117. var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
  1118. if (code == 13) {
  1119. var target = e.target || e.srcElement;
  1120. if (target.tagName.toLowerCase() == "input") {
  1121. app.p.pageNo = 1;
  1122. app.f5();
  1123. }
  1124. }
  1125. }
  1126. })
  1127. })
  1128. }
  1129. // 如果value为true,则抛出异常
  1130. me.check = function(value, errorMsg) {
  1131. if (value === true) {
  1132. throw {
  1133. type: 'sa-error',
  1134. msg: errorMsg
  1135. };
  1136. }
  1137. }
  1138. // 如果value为null,则抛出异常
  1139. me.checkNull = function(value, errorMsg) {
  1140. if (me.isNull(value)) {
  1141. throw {
  1142. type: 'sa-error',
  1143. msg: errorMsg
  1144. };
  1145. }
  1146. }
  1147. me.checkPhone = function(str, errorMsg) {
  1148. str = str + '';
  1149. if (!(/^1[3456789]\d{9}$/.test(str))) {
  1150. throw {
  1151. type: 'sa-error',
  1152. msg: errorMsg
  1153. };
  1154. }
  1155. }
  1156. me.checkEmptyArray=function(value,errorMsg){
  1157. if(!value||value.length===0){
  1158. throw {
  1159. type: 'sa-error',
  1160. msg: errorMsg
  1161. };
  1162. }
  1163. }
  1164. // 监听窗口变动
  1165. if (!window.onresize) {
  1166. window.onresize = function() {
  1167. try {
  1168. me.f5TableHeight();
  1169. } catch (e) {
  1170. // console.log(e);
  1171. }
  1172. }
  1173. }
  1174. // 双击layer标题处全屏
  1175. if (window.$) {
  1176. $(document).on('mousedown', '.layui-layer-title', function(e) {
  1177. // console.log('单击中');
  1178. if (window.layer_title_last_click_time) {
  1179. var cz = new Date().getTime() - window.layer_title_last_click_time;
  1180. if (cz < 250) {
  1181. $(this).parent().find('.layui-layer-max').click();
  1182. }
  1183. }
  1184. window.layer_title_last_click_time = new Date().getTime();
  1185. })
  1186. }
  1187. // == if 结束
  1188. }
  1189. })();
  1190. // =========================== $sys 有关当前系统的方法 一般不能复制到别的项目中用 =======================================
  1191. (function() {
  1192. // 超级对象
  1193. var me = {};
  1194. sa.$sys = me;
  1195. // ======================= 登录相关 ============================
  1196. // 写入当前已登陆用户信息
  1197. me.setCurrUser = function(currUser) {
  1198. localStorage.setItem('currUser', JSON.stringify(currUser));
  1199. }
  1200. // 获得当前已登陆用户信息
  1201. me.getCurrUser = function() {
  1202. var user = localStorage.getItem("currUser");
  1203. if (user == undefined || user == null || user == 'null' || user == '' || user == '{}' || user.length <
  1204. 10) {
  1205. user = {
  1206. id: '0',
  1207. username: '未登录'
  1208. }
  1209. } else {
  1210. user = JSON.parse(user);
  1211. }
  1212. return user;
  1213. }
  1214. // 如果未登录,则强制跳转到登录
  1215. me.checkLogin = function(not_login_url) {
  1216. if (me.getCurrUser().id == 0) {
  1217. location.href = not_login_url || '../../login.html';
  1218. throw '未登录,请先登录';
  1219. }
  1220. }
  1221. // 同上, 只不过是以弹窗的形式显示未登录
  1222. me.checkLoginTs = function(not_login_url) {
  1223. if (me.getCurrUser().id == 0) {
  1224. sa.$page.openLogin(not_login_url || '../../login.html');
  1225. throw '未登录,请先登录';
  1226. }
  1227. }
  1228. // ========================= 权限验证 =========================
  1229. // 定义key
  1230. var pcode_key = 'permission_code';
  1231. // 写入当前会话的权限码集合
  1232. sa.setAuth = function(codeList) {
  1233. sa.keyListSet(pcode_key, codeList);
  1234. }
  1235. // 清除当前会话的权限码集合
  1236. sa.clearAuth = function() {
  1237. sa.keyListSet(pcode_key, []);
  1238. }
  1239. // 检查当前会话是否拥有一个权限码, 返回true和false
  1240. sa.isAuth = function(pcode) {
  1241. return sa.keyListHas(pcode_key, pcode);
  1242. }
  1243. // 检查当前会话是否拥有一个权限码, 如果没有, 则跳转到无权限页面
  1244. // 注意: 非二级目录页面请注意调整路径问题
  1245. sa.checkAuth = function(pcode, not_pcode_url) {
  1246. var is_have = sa.keyListHas(pcode_key, pcode);
  1247. if (is_have == false) {
  1248. location.href = not_pcode_url || '../../sa-view/error-page/403.html';
  1249. throw '暂无权限: ' + pcode;
  1250. }
  1251. }
  1252. // 同上, 只不过是以弹窗的形式显示出来无权限来
  1253. sa.checkAuthTs = function(pcode, not_pcode_url) {
  1254. var is_have = sa.keyListHas(pcode_key, pcode);
  1255. if (is_have == false) {
  1256. var url = not_pcode_url || '../../sa-view/error-page/403.html';
  1257. layer.open({
  1258. type: 2,
  1259. title: false, // 标题
  1260. shadeClose: true, // 是否点击遮罩关闭
  1261. shade: 0.8, // 遮罩透明度
  1262. scrollbar: false, // 屏蔽掉外层的滚动条
  1263. closeBtn: false,
  1264. area: ['700px', '600px'], // 大小
  1265. content: url // 传值
  1266. });
  1267. throw '暂无权限: ' + pcode;
  1268. }
  1269. }
  1270. // ======================= 配置相关 ============================
  1271. // 写入配置信息
  1272. me.setAppCfg = function(cfg) {
  1273. if (typeof cfg != 'string') {
  1274. cfg = JSON.stringify(cfg);
  1275. }
  1276. localStorage.setItem('app_cfg', cfg);
  1277. }
  1278. // 获取配置信息
  1279. me.getAppCfg = function() {
  1280. var app_cfg = sa.JSONParse(localStorage.getItem('app_cfg'), {}) || {};
  1281. return app_cfg;
  1282. }
  1283. })();
  1284. // =========================== $page 跳页面相关 避免一次变动,到处乱改 =======================================
  1285. (function() {
  1286. // 超级对象
  1287. var me = {};
  1288. sa.$page = me;
  1289. // 打开登录页面
  1290. me.openLogin = function(login_url) {
  1291. layer.open({
  1292. type: 2,
  1293. // title: '登录',
  1294. title: false,
  1295. closeBtn: false,
  1296. shadeClose: true,
  1297. shade: 0.8,
  1298. // area: ['90%', '100%'],
  1299. area: ['70%', '80%'],
  1300. // area: ['450px', '360px'],
  1301. resize: false,
  1302. content: login_url || '../../login.html'
  1303. });
  1304. }
  1305. // 打开admin信息界面
  1306. me.openAdminInfo = function(id, username) {
  1307. var title = username + ' - 账号详情';
  1308. if (username === undefined) {
  1309. title = '账号详情';
  1310. }
  1311. sa.showIframe(title, '../sp-admin/admin-info.html?id=' + id, '700px', '600px');
  1312. }
  1313. })();
  1314. // 如果是sa_admin环境
  1315. window.sa_admin = window.sa_admin || parent.sa_admin || top.sa_admin;
  1316. window.saAdmin = window.sa_admin;
  1317. // 如果当前是Vue环境, 则挂在到 Vue 示例
  1318. if (window.Vue) {
  1319. // 全局的 sa 对象
  1320. Vue.prototype.sa = window.sa;
  1321. Vue.prototype.sa_admin = window.sa_admin;
  1322. Vue.prototype.saAdmin = window.saAdmin;
  1323. // 表单校验异常捕获
  1324. Vue.config.errorHandler = function(err, vm) {
  1325. if (err.type == 'sa-error') {
  1326. return sa.error(err.msg);
  1327. }
  1328. throw err;
  1329. }
  1330. // Element-UI 全局组件样式
  1331. Vue.prototype.$ELEMENT = {
  1332. size: 'mini',
  1333. zIndex: 3000
  1334. };
  1335. // 加载全局组件 (注意路径问题)
  1336. // if(window.httpVueLoader && window.loadComponent !== false) {
  1337. // Vue.component("sa-item", httpVueLoader('../../sa-frame/com/sa-item.vue'));
  1338. // Vue.component("sa-td", httpVueLoader('../../sa-frame/com/sa-td.vue'));
  1339. // }
  1340. }
  1341. // 对外开放, 在模块化时解开此注释
  1342. // export default sa;