sa.js 40 KB

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