api.js 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057
  1. // 加密 sha1 md5
  2. var encrypt = require('./encrypt.js');
  3. // 缓存
  4. var cache = require('./cache.js');
  5. // 数学精确计算
  6. var math = require('./math.js');
  7. // 腾讯位置服务
  8. var qqMap = require("./qqmap-wx-jssdk");
  9. // 二维码
  10. var qrCode = require("./weapp.qrcode.min");
  11. module.exports = {
  12. /**
  13. * 小程序基本配置
  14. */
  15. config: {
  16. name: '船百知',
  17. debug: false, //开发模式true,生产环境改为false;
  18. version: 'xcx',
  19. baseUrl: 'https://ship.shipcc.cn',
  20. qqMap: false,
  21. loading: false
  22. },
  23. /**
  24. * sha1加密
  25. * @param str
  26. * @param raw 加密方式 1str_sha1 0hex_sha1
  27. */
  28. sha1: function(str, raw) {
  29. return encrypt.sha1(str, raw);
  30. },
  31. /**
  32. * md5加密
  33. * @param str
  34. */
  35. md5: function(str) {
  36. return encrypt.md5(str);
  37. },
  38. /**
  39. * 缓存
  40. */
  41. cache: cache,
  42. /**
  43. * 数字精确计算
  44. */
  45. math: math,
  46. /**
  47. * 腾讯地图
  48. */
  49. qqMap: qqMap,
  50. /**
  51. * 消息提示
  52. * @param title
  53. * @param icon:success,error,loading,none
  54. * @param success
  55. * @param time
  56. * @param mask
  57. */
  58. info: function(title, icon, success, time, mask) {
  59. if (typeof icon == 'function') {
  60. success = icon;
  61. icon = "none";
  62. }
  63. title = title == undefined ? "系统繁忙" : title;
  64. icon = icon == undefined ? "none" : icon;
  65. time = time == undefined ? 1000 : time;
  66. mask = mask == undefined ? true : mask;
  67. uni.showToast({
  68. title: title,
  69. icon: icon,
  70. mask: mask,
  71. duration: time,
  72. success: setTimeout(function() {
  73. success && success()
  74. }, time)
  75. });
  76. },
  77. /**
  78. * 确认提示框
  79. * @param {Object} content
  80. * @param {Object} success
  81. * @param {Object} cancel
  82. * @param {Object} confirmText
  83. * @param {Object} cancelText
  84. */
  85. modal: function(content, success, cancel, confirmText, cancelText) {
  86. let opt = {};
  87. opt.title = this.config.name;
  88. opt.content = content;
  89. // 默认不显示取消
  90. opt.showCancel = false;
  91. if (typeof cancel == 'function' || (typeof cancel == 'boolean' && cancel)) {
  92. opt.showCancel = true;
  93. } else if (typeof cancel == 'string') {
  94. cancelText = confirmText;
  95. confirmText = cancel;
  96. }
  97. if (!this.isEmpty(confirmText)) {
  98. opt.confirmText = confirmText;
  99. }
  100. if (!this.isEmpty(cancelText)) {
  101. opt.cancelText = cancelText;
  102. opt.showCancel = true;
  103. }
  104. opt.success = function(res) {
  105. if (res.confirm) {
  106. success && success();
  107. } else if (res.cancel) {
  108. typeof cancel == 'function' && cancel();
  109. }
  110. };
  111. uni.showModal(opt);
  112. },
  113. /**
  114. * loading 提示框
  115. * @param title
  116. */
  117. loading: function(title) {
  118. var that = this;
  119. title = typeof title == 'string' ? title : "加载中...";
  120. !that.config.loading && uni.showLoading({
  121. title: title,
  122. mask: true,
  123. success: function() {
  124. that.config.loading = true;
  125. }
  126. });
  127. },
  128. /**
  129. * 关闭loading 提示框
  130. */
  131. closeLoading: function() {
  132. var that = this;
  133. that.config.loading && uni.hideLoading({
  134. noConflict: true,
  135. success: function() {
  136. that.config.loading = false;
  137. }
  138. });
  139. },
  140. /**
  141. * 判断登录
  142. * @param {Object} type 0不跳转登录 1跳转登录
  143. * @param {Object} success
  144. */
  145. login: function(type, success) {
  146. if (typeof type == 'function') {
  147. success = type;
  148. type = 1;
  149. } else if (typeof type == 'undefined') {
  150. type = 1;
  151. }
  152. var that = this;
  153. /* var userInfo = this.getUserInfo();
  154. if (this.isEmpty(userInfo)) {
  155. if (type == 1) {
  156. that.info('请先登录', function() {
  157. var pages = getCurrentPages();
  158. var route = pages[pages.length - 1].route;
  159. // if (route != 'pages/login/choose') {
  160. // that.jump('/pages/login/choose');
  161. // }
  162. });
  163. }
  164. return false;
  165. } */
  166. // return success && success(userInfo) || userInfo;
  167. return success
  168. },
  169. /**
  170. * 页面跳转
  171. * @param url
  172. * @param type
  173. */
  174. jump: function(url, type, params) {
  175. var that = this;
  176. if (that.isEmpty(url) && type !== -1) return false;
  177. if (url === -1) {
  178. var delta = type || 1;
  179. type = url;
  180. } else if (type === -1) {
  181. var delta = 1;
  182. if (params && params.delta) {
  183. delta = params.delta;
  184. }
  185. }
  186. type = type || 0, //默认0
  187. params = params || {};
  188. if (that.isEmpty(params)) {
  189. cache.remove('jump_data');
  190. } else {
  191. cache.set('jump_data', params);
  192. }
  193. switch (type) {
  194. case -1:
  195. //关闭当前页面,返回上一页面或多级页面 delta:1 返回层数
  196. setTimeout(function() {
  197. uni.navigateBack({
  198. delta: delta
  199. });
  200. }, 800);
  201. return;
  202. case 0:
  203. //保留当前页面,跳转到应用内的某个页面,使用uni.navigateBack可以返回到原页面
  204. uni.navigateTo({
  205. url: url
  206. });
  207. return;
  208. case 1:
  209. //关闭当前页面,跳转到应用内的某个页面
  210. uni.redirectTo({
  211. url: url
  212. });
  213. return;
  214. case 2:
  215. //关闭所有页面,打开到应用内的某个页面
  216. uni.reLaunch({
  217. url: url
  218. });
  219. return;
  220. case 3:
  221. //跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面
  222. uni.switchTab({
  223. url: url
  224. });
  225. return;
  226. default:
  227. return false;
  228. }
  229. },
  230. /**
  231. * 数据请求
  232. */
  233. req: function(option, onsuccess, onerror, oncomplete) {
  234. if (option == 'undefined') return false;
  235. this.loading()
  236. // console.log('请求',option);
  237. var that = this,
  238. config = {
  239. sign: false, //是否签名数据
  240. load: false, //是否显示loading提示
  241. login: false, //是否需要登录
  242. url: false,
  243. data: option.data,
  244. header: {
  245. 'content-type': 'application/json',
  246. 'api-token': uni.getStorageSync('token').token?uni.getStorageSync('token').token:'',
  247. 'api-name': 'wxapp'
  248. },
  249. method: option.method?option.method:'GET',
  250. dataType: 'json',
  251. success: function(res) { //通讯成功
  252. that.jslog('请求:' + option.url);
  253. that.jslog(res.data);
  254. that.closeLoading()
  255. //获取返回数据
  256. res = res.data;
  257. //如果存在回调,优先执行回调函数
  258. if (onsuccess) {
  259. if (onsuccess(res) === false) {
  260. return;
  261. }
  262. }
  263. if (typeof(res) == 'object') {
  264. // (res.info && res.info != 'success') && that.info(res.info);
  265. /* if (res.status == 98) { //未登录或账号不存在
  266. cache.remove('user_info');
  267. that.login();
  268. } else if (res.status == 99) { //token验证失败
  269. cache.remove('token');
  270. } */
  271. if(res.code == 401) {
  272. that.info(res.info)
  273. setTimeout(function() {
  274. that.jump('/pages/login/password_login')
  275. }, 2000)
  276. }
  277. if(res.code == 0) {
  278. that.info(res.info)
  279. if(!uni.getStorageSync('token')) {
  280. // that.jump('/pages/login/password_login')
  281. }
  282. // setTimeout(function() {
  283. // that.jump('/pages/login/password_login')
  284. // }, 2000)
  285. }
  286. } else {
  287. // that.modal('接口异常');
  288. }
  289. },
  290. fail: function(res) { //通讯失败
  291. that.closeLoading()
  292. that.jslog('请求:' + option.url);
  293. that.jslog(res);
  294. onerror && onerror();
  295. },
  296. complete: function(res) { //通讯完成
  297. option.load && that.closeLoading();
  298. oncomplete && oncomplete();
  299. }
  300. };
  301. option.data && (option.data = option.data);
  302. if (option.url) {
  303. option.url = that.config.baseUrl + option.url;
  304. } else {
  305. return false;
  306. }
  307. option = that.extend({}, config, option);
  308. if (option.login && !that.login()) {
  309. return false;
  310. }
  311. // if (!option.data.submit) {
  312. // option.data.submit = 'yes';
  313. // }
  314. if (option.sign) {
  315. that.getsign(option.data, function(res) {
  316. option.data = res;
  317. option.load && that.loading(option.load);
  318. uni.request(option);
  319. })
  320. } else {
  321. option.load && that.loading(option.load);
  322. uni.request(option);
  323. }
  324. },
  325. /*
  326. * 规格重置
  327. */
  328. resetspec: function(spec) {
  329. var name = "已选:"
  330. if(spec.includes('::')) {
  331. var temp = spec.split(';;')
  332. console.log(temp);
  333. for(var i=0;i<temp.length;i++) {
  334. var temp2 = temp[i].split('::')
  335. name += temp2[1] + ';'
  336. }
  337. } else {
  338. name = name + spec
  339. }
  340. return name
  341. },
  342. /**
  343. * 获取一个Token,登录成功请清空
  344. * @param {function} callback :回调函数
  345. */
  346. gettoken: function(callback) {
  347. var that = this,
  348. token = cache.get('token'),
  349. timestamp = Date.parse(new Date()) / 1000;
  350. // 10分钟缓冲
  351. if (token && token.date_expire > (timestamp + 600)) return callback({
  352. status: 1,
  353. data: token
  354. });
  355. var uuid = that.uuid(),
  356. //clientid=that.getClientId(),
  357. uid = that.getUserInfo('id', 0);
  358. uni.request({
  359. url: that.config.baseUrl + 'token',
  360. data: {
  361. uuid: uuid,
  362. uid: uid,
  363. timestamp: timestamp
  364. }, //clientid:clientid
  365. timeout: 10000, //超时时间设置为10秒
  366. success: function(res) {
  367. var res = res.data;
  368. if (res.status == 1) {
  369. cache.set('token', res.data);
  370. }
  371. return callback(res);
  372. },
  373. complete: function(res) {
  374. that.jslog('获取token:' + res);
  375. }
  376. });
  377. },
  378. /**
  379. * 数据签名
  380. * @param {string} data:要签名的数据
  381. * @param {function} onsuccess:成功回调函数
  382. * @param {function} onerror:失败回调函数
  383. */
  384. getsign: function(param, onsuccess, onerror) {
  385. var that = this,
  386. arr = [];
  387. param._sign_uuid = that.uuid();
  388. param._sign_uid = that.getUserInfo('id', 0);
  389. param._timestamp = Date.parse(new Date()) / 1000;
  390. param._version = that.config.version;
  391. that.gettoken(function(res) {
  392. if (res.status == 1) {
  393. param._sign_token = res.data.token;
  394. for (var i in param) {
  395. if (!that.isEmpty(param[i], true)) {
  396. arr.push(i + '=' + param[i]);
  397. }
  398. }
  399. arr.sort();
  400. param._sign = encrypt.sha1(arr.join('&') + res.data.token).toUpperCase();
  401. return onsuccess(param);
  402. } else {
  403. return onerror && onerror(res.info) || that.info(res.info);
  404. }
  405. });
  406. },
  407. /**
  408. * 格式化参数(password加密)
  409. * @param {string} query:参数
  410. */
  411. formatparam: function(query) {
  412. var json = {};
  413. if (typeof(query) == 'object') {
  414. for (var i in query) {
  415. if (i.indexOf('password') > -1) {
  416. query[i] = encrypt.md5(encrypt.sha1(query[i]));
  417. }
  418. }
  419. return query;
  420. } else {
  421. var vars = query.split('&');
  422. for (var i = 0; i < vars.length; i++) {
  423. var pair = vars[i].split('=');
  424. if (pair[0].indexOf('password') != -1) {
  425. pair[1] = encrypt.md5(encrypt.sha1(pair[1]));
  426. } else {
  427. pair[1] = pair[1];
  428. }
  429. if (typeof json[pair[0]] === 'undefined') {
  430. json[pair[0]] = pair[1];
  431. } else if (typeof json[pair[0]] === 'string') {
  432. var arr = [json[pair[0]], pair[1]];
  433. json[pair[0]] = arr;
  434. } else {
  435. json[pair[0]].push(pair[1]);
  436. }
  437. }
  438. return json;
  439. }
  440. },
  441. /**
  442. * 判断是否数组
  443. *
  444. * 1. 通过object类型的副属性class判断,
  445. * 其中函数的class是Function,结果是[object Function]
  446. * 普通的对象是Object,结果是[object Object]
  447. * Object.prototype.toString.call(arr) === '[object Array]'
  448. * 2. 通过原型去判断
  449. * arr.constructor === Array
  450. * Array.prototype.isPrototypeOf(arr)
  451. * arr.__proto__ === Array.prototype
  452. * Object.getPrototypeOf(arr) === Array.prototype
  453. * arr instanceof Array
  454. * 3. es6新增方法
  455. * Array.isArray(arr)
  456. */
  457. isArray: function(arr) {
  458. return arr && typeof(arr) == 'object' && Object.prototype.toString.call(arr) === '[object Array]';
  459. },
  460. /**
  461. * 否判断指定参数是否是一个纯粹的对象
  462. * 所谓"纯粹的对象",就是通过"{}"或"new Object"创建的,不包括数组等对象
  463. *
  464. * 1. 通过object类型的副属性class判断
  465. * Object.prototype.toString.call(obj) === '[object Object]'
  466. * 2. 通过原型去判断
  467. * obj.constructor === Object
  468. * obj instanceof Object(数组也是对象,所以 arr instanceof Object 也为true)
  469. * 3. typeof
  470. * typeof obj(除了{},null和[]也是'object')
  471. */
  472. isPlainObject: function(obj) {
  473. if (Object.getPrototypeOf) {
  474. return obj && typeof(obj) == 'object' && Object.getPrototypeOf(obj) == Object.prototype;
  475. } else {
  476. return obj && typeof(obj) == 'object' && Object.prototype.toString.call(obj) == "[object Object]" &&
  477. !obj.length;
  478. }
  479. },
  480. /**
  481. * 获取对象大小
  482. * @param object
  483. */
  484. getLength: function(object) {
  485. return Object.keys(object).length
  486. },
  487. /**
  488. * 判断两个Json(纯粹)对象是否一样
  489. * @param objA
  490. * @param objB
  491. */
  492. compareJsonObj: function(objA, objB) {
  493. if (!this.isPlainObject(objA) || !this.isPlainObject(objB)) return false; //判断类型是否正确
  494. return this.compareObj(objA, objB); //默认为true
  495. },
  496. /**
  497. * 判断两个对象是否一样
  498. * @param objA
  499. * @param objB
  500. * @param flag
  501. */
  502. compareObj: function(objA, objB, flag) {
  503. if (this.getLength(objA) != this.getLength(objB)) return false;
  504. flag = flag || true;
  505. for (var key in objA) {
  506. if (!flag) //flag为false,则跳出整个循环
  507. break;
  508. if (!objB.hasOwnProperty(key)) { //是否有自身属性,而不是继承的属性
  509. flag = false;
  510. break;
  511. }
  512. if (!this.isArray(objA[key])) { //子级不是数组时,比较属性值
  513. if (this.isPlainObject(objA[key])) {
  514. if (this.isPlainObject(objB[key])) {
  515. if (!flag) //这里跳出循环是为了不让递归继续
  516. break;
  517. flag = this.compareObj(objA[key], objB[key], flag);
  518. } else {
  519. flag = false;
  520. break;
  521. }
  522. } else {
  523. if (String(objB[key]) != String(objA[key])) { //排除数字比较的类型差异
  524. flag = false;
  525. break;
  526. }
  527. }
  528. } else {
  529. if (!this.isArray(objB[key])) {
  530. flag = false;
  531. break;
  532. }
  533. var oA = objA[key],
  534. oB = objB[key];
  535. if (oA.length != oB.length) {
  536. flag = false;
  537. break;
  538. }
  539. for (var k in oA) {
  540. if (!flag) //这里跳出循环是为了不让递归继续
  541. break;
  542. flag = this.compareObj(oA[k], oB[k], flag);
  543. }
  544. }
  545. }
  546. return flag;
  547. },
  548. /**
  549. * 将一个或多个对象的内容合并到目标对象
  550. * @param Object target 目标对象,其他对象的成员属性将被附加到该对象上
  551. * @param Object target 目标对象,第一个被合并的对象
  552. * @param Object target 目标对象,第二个被合并的对象
  553. */
  554. extend: Object.assign || function(target, source, deep) {
  555. for (key in source) {
  556. if (deep && (this.isPlainObject(source[key]) || this.isArray(source[key]))) {
  557. if (this.isPlainObject(source[key]) && !this.isPlainObject(target[key])) {
  558. target[key] = {};
  559. }
  560. if (this.isArray(source[key]) && !this.isArray(target[key])) {
  561. target[key] = [];
  562. }
  563. this.extend(target[key], source[key], deep);
  564. } else if (source[key] !== undefined) {
  565. target[key] = source[key];
  566. }
  567. }
  568. return target;
  569. },
  570. /**
  571. * 判断一个对象是否为空
  572. * @param {string} string:要判断的参数
  573. * @param {string} is_zero:是否要判断'0'
  574. */
  575. isEmpty: function(string, is_zero = false) {
  576. if (is_zero && string === '0') {
  577. return true;
  578. }
  579. // 0 == '',false == '',[] == ''
  580. if (string == '' || string == null || typeof(string) == 'undefined' || string == 'undefined') {
  581. return true;
  582. }
  583. // 对象 和 数组
  584. if (typeof(string) == 'object') {
  585. return this.getLength(string) ? false : true;
  586. }
  587. return false;
  588. },
  589. /**
  590. * 为客户端生成一个唯一的uuid
  591. */
  592. uuid: function() {
  593. var uuid,
  594. random = function() {
  595. return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  596. };
  597. uuid = cache.get('uuid');
  598. if (!uuid) {
  599. uuid = encrypt.sha1(random() + random() + '-' + random() + '-' + random() + '-' + random() + '-' +
  600. random() + random() + random());
  601. cache.set('uuid', uuid);
  602. }
  603. return uuid;
  604. },
  605. /**
  606. * 获取设备唯一标识
  607. */
  608. getClientId: function() {
  609. //获取客户端ID
  610. var clientid = cache.get('client_id');
  611. if (clientid) return clientid;
  612. //TODO::
  613. },
  614. /**
  615. * 获取用户登录信息
  616. * @param k 键值
  617. * @param d 入没有返回的默认值
  618. */
  619. getUserInfo: function(k, d) {
  620. if (d == 'undefined') {
  621. d = 0;
  622. }
  623. var userInfo = cache.get('user_info');
  624. if (this.isEmpty(userInfo)) {
  625. return d;
  626. } else {
  627. if (typeof k == 'undefined') {
  628. return userInfo;
  629. } else {
  630. if (typeof userInfo[k] == 'undefined') {
  631. return d;
  632. } else {
  633. return userInfo[k];
  634. }
  635. }
  636. }
  637. },
  638. /**
  639. * 查找指定值的元素在数组中第一次出现的位置
  640. * 查找指定键的值的元素在二维数组中第一次出现的位置
  641. * @param arr 数组
  642. * @param val 要查找的值
  643. * @param key 二维数组元素的值对应的键
  644. */
  645. indexOf: function(arr, val, key) {
  646. if (this.isEmpty(arr) || this.isEmpty(val)) return -1;
  647. if (typeof key == 'undefined') {
  648. for (let i = 0; i < arr.length; i++) {
  649. if (arr[i] == val) {
  650. return i;
  651. }
  652. }
  653. } else {
  654. for (let i = 0; i < arr.length; i++) {
  655. if (arr[i][key] == val) {
  656. return i;
  657. }
  658. }
  659. }
  660. return -1;
  661. },
  662. /**
  663. * (批量)删除数组中指定值的元素
  664. * (批量)删除二维数组中指定键的值的元素
  665. * @param {Object} arr (二维)数组
  666. * @param {Object} vals 值(数组)
  667. * @param {Object} key 值(数组)组对应的键
  668. */
  669. removeItemByVals: function(arr, vals, key) {
  670. var that = this;
  671. if (this.isEmpty(arr) || this.isEmpty(vals)) return arr;
  672. if (this.isArray(vals)) {
  673. //!倒序删除
  674. if (typeof key == 'undefined') {
  675. for (let i = arr.length - 1; i >= 0; i--) {
  676. let index = that.indexOf(vals, arr[i]);
  677. if (index > -1) {
  678. arr.splice(i, 1);
  679. }
  680. }
  681. } else {
  682. for (let i = arr.length - 1; i >= 0; i--) {
  683. let index = that.indexOf(vals, arr[i][key]);
  684. if (index > -1) {
  685. arr.splice(i, 1);
  686. }
  687. }
  688. }
  689. } else {
  690. let index = this.indexOf(arr, vals, key);
  691. if (index > -1) {
  692. arr.splice(index, 1);
  693. }
  694. }
  695. return arr;
  696. },
  697. /**
  698. * 批量删除数组中指定键的元素
  699. * @param {Object} arr 数组
  700. * @param {Object} indexs 序号(数组)
  701. */
  702. removeItemByIndex: function(arr, indexs) {
  703. var that = this;
  704. if (this.isEmpty(arr) || this.isEmpty(indexs)) return arr;
  705. if (this.isArray(indexs)) {
  706. //!倒序删除
  707. for (let i = arr.length - 1; i >= 0; i--) {
  708. let index = that.indexOf(indexs, i);
  709. if (index > -1) {
  710. arr.splice(i, 1);
  711. }
  712. }
  713. } else {
  714. arr.splice(indexs, 1);
  715. }
  716. return arr;
  717. },
  718. /**
  719. * 返回数组中某个单一列的值
  720. */
  721. array_column: function(arr, key) {
  722. if (this.isEmpty(arr)) return arr;
  723. if (this.isEmpty(key)) return [];
  724. var vals = [];
  725. arr.forEach(item => {
  726. vals.push(item[key]);
  727. });
  728. return vals;
  729. },
  730. /**
  731. * 对象按照key排序
  732. * @param {Object} arr
  733. */
  734. array_ksort: function(arr) {
  735. let sorted = {},
  736. keys = Object.keys(arr);
  737. keys.sort();
  738. keys.forEach((key) => {
  739. sorted[key] = arr[key];
  740. })
  741. return sorted;
  742. },
  743. /**
  744. * 数组按元素(指定键值)排序
  745. * @param {Object} arr
  746. * @param {Object} key
  747. * @param {Object} sort asc desc
  748. */
  749. array_vsort: function(arr, key, sort) {
  750. if (this.isEmpty(arr)) return arr;
  751. key = key || '';
  752. sort = sort || 'asc';
  753. if (key == '') {
  754. return arr.sort();
  755. } else {
  756. if (sort == 'asc') {
  757. return arr.sort(function(a, b) {
  758. return a[key] - b[key];
  759. });
  760. } else {
  761. return arr.sort(function(a, b) {
  762. return b[key] - a[key];
  763. });
  764. }
  765. }
  766. },
  767. /**
  768. * 日期时间格式化
  769. * @param {Object} date 日期对象
  770. */
  771. formatDate: function({
  772. value = '',
  773. mode = ''
  774. }) {
  775. var date = value
  776. var that = this;
  777. if(that.isEmpty(date,true)) {
  778. date = new Date();
  779. } else {
  780. if (typeof date == 'number') {
  781. date = new Date(parseInt(date));
  782. } else if (typeof date == 'string') {
  783. date = new Date(date);
  784. }
  785. }
  786. var value1 = ''
  787. let Y = date.getFullYear();
  788. let M = +(date.getMonth()+1 < 10 ? '0' +(date.getMonth()+1) : date.getMonth()+1) ;
  789. let D = date.getDate();
  790. let h = date.getHours();
  791. let m = date.getMinutes();
  792. let s = date.getSeconds();
  793. if(mode == 'year-month') {
  794. value1 = Y+ '-'+ M
  795. } else {
  796. value1 = Y+ '-'+M+ '-'+D
  797. }
  798. return value1
  799. },
  800. /**
  801. * 日期时间格式化
  802. * @param {Object} date 日期对象
  803. * @param {Object} type 增加加的时间间隔:y年 q季度(3个月) m月 d天
  804. * @param {Object} number 增加的时间间隔的个数
  805. * @param {Object} format 格式化样式
  806. */
  807. formatDate1: function({
  808. date = '',
  809. type = 'y',
  810. number = 0,
  811. format = 'Y-m-d'
  812. }) {
  813. var that = this;
  814. if (that.isEmpty(date, true)) {
  815. date = new Date();
  816. } else {
  817. if (typeof date == 'number') {
  818. date = new Date(parseInt(date) * 1000);
  819. } else if (typeof date == 'string') {
  820. date = new Date(date);
  821. }
  822. }
  823. date = that.addDate(type, number, date);
  824. var zero = function(value) {
  825. if (value < 10) {
  826. return '0' + value;
  827. }
  828. return value;
  829. },
  830. year = date.getFullYear(),
  831. month = zero(date.getMonth() + 1),
  832. day = zero(date.getDate());
  833. // hour = zero(date.getHours()),
  834. // minite = zero(date.getMinutes()),
  835. // second = zero(date.getSeconds());
  836. return format.replace(/Y|m|d/ig, function(matches) {
  837. return ({
  838. Y: year,
  839. m: month,
  840. d: day,
  841. // H: hour,
  842. // i: minite,
  843. // s: second,
  844. })[matches];
  845. });
  846. },
  847. /**
  848. * 日期时间计算
  849. * addDate(type,number,date)
  850. * @param {Object} type 增加的时间间隔:y年 q季度(3个月) m月 d天
  851. * @param {Object} number 增加的时间间隔的个数
  852. * @param {Object} date 开始日期对象
  853. * @return {type} 新的日期对象
  854. * var now = new Date();
  855. * var newDate = addDate( "d", 5, now);
  856. */
  857. addDate: function(type, number, date) {
  858. switch (type) {
  859. case "y": {
  860. date.setFullYear(date.getFullYear() + number);
  861. return date;
  862. break;
  863. }
  864. case "q": {
  865. date.setMonth(date.getMonth() + number * 3);
  866. return date;
  867. break;
  868. }
  869. case "m": {
  870. date.setMonth(date.getMonth() + number);
  871. return date;
  872. break;
  873. }
  874. case "w": {
  875. date.setDate(date.getDate() + number * 7);
  876. return date;
  877. break;
  878. }
  879. case "d": {
  880. date.setDate(date.getDate() + number);
  881. return date;
  882. break;
  883. }
  884. case "h": {
  885. date.setHours(date.getHours() + number);
  886. return date;
  887. break;
  888. }
  889. case "m": {
  890. date.setMinutes(date.getMinutes() + number);
  891. return date;
  892. break;
  893. }
  894. case "s": {
  895. date.setSeconds(date.getSeconds() + number);
  896. return date;
  897. break;
  898. }
  899. default: {
  900. date.setDate(date.getDate() + number);
  901. return date;
  902. break;
  903. }
  904. }
  905. },
  906. /**
  907. * 二维码操作
  908. * @param {Object} canvas 图片路径
  909. * @param {Object} action 操作类型
  910. * qrcode:绘制二维码(根据内容data)
  911. * scan:扫描二维码
  912. * @param {Object} canvas 绘制二维码canvasID
  913. * @param {Object} data 绘制二维码内容
  914. * @param {Object} camera 扫描二维码是否只使用相机
  915. * @param {Object} success 成功回调
  916. * @param {Object} error 失败回调
  917. */
  918. qrCodeOperat({
  919. action = 'qrcode',
  920. canvas,
  921. data,
  922. camera = false,
  923. success,
  924. error
  925. }) {
  926. var that = this;
  927. switch (action) {
  928. case 'qrcode':
  929. qrCode({
  930. width: 180,
  931. height: 180,
  932. x: 20,
  933. y: 20,
  934. canvasId: canvas,
  935. text: data,
  936. });
  937. break;
  938. case 'scan':
  939. uni.scanCode({
  940. onlyFromCamera: camera,
  941. success(res) {
  942. if (res.errMsg == 'scanCode:ok') {
  943. // 二维码内容 res.result
  944. success && success(res.result);
  945. } else {
  946. error && error(res);
  947. }
  948. },
  949. fail(res) {
  950. if (res.errMsg != 'scanCode:fail cancel') {
  951. error && error(res);
  952. }
  953. }
  954. });
  955. break;
  956. default:
  957. that.modal('请明确二维码操作类型');
  958. }
  959. },
  960. /**
  961. * 图片操作
  962. * @param {Object} path 图片路径
  963. * @param {Object} action 操作类型
  964. * choose:选择图片
  965. * upload:图片上传
  966. * info:图片信息
  967. * read:读取图片(base64)
  968. * write:保存图片(base64)
  969. * down:下载图片
  970. * save:保存图片(临时路径)
  971. * preview:图片预览
  972. * @param {Object} data 保存图片:图片base64内容(不带 data:image/png;base64,),
  973. * 图片预览:图片数组
  974. * @param {Object} fileName 保存图片的名称
  975. * @param {Object} menu 图片预览:是否显示长按菜单
  976. * @param {Object} count 图片选择:默认图片选择数量
  977. * @param {Object} success 成功回调
  978. * @param {Object} error 失败回调
  979. */
  980. imageOperat({
  981. action = 'choose',
  982. path,
  983. fileName = 'write',
  984. data,
  985. count = 1,
  986. menu = true,
  987. success,
  988. error
  989. }) {
  990. var that = this;
  991. if (action == 'choose') {
  992. uni.chooseImage({
  993. count: count,
  994. sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
  995. sourceType: ['camera', 'album'], //相册选择、使用相机
  996. success: (e) => {
  997. e.tempFilePaths.forEach((item) => {
  998. success && success(item);
  999. });
  1000. },
  1001. fail(e) {
  1002. error && error(e);
  1003. }
  1004. });
  1005. } else if (action == 'upload') {
  1006. uni.uploadFile({
  1007. url: that.config.baseUrl + '/api/Publics/uploadLocality',
  1008. filePath: path,
  1009. name: 'upfile',
  1010. /* header: {
  1011. 'content-type': 'multipart/form-data'
  1012. }, */
  1013. formData: {
  1014. // uid: that.getUserInfo('id', 0)
  1015. file: path
  1016. },
  1017. success(e) {
  1018. console.log(e)
  1019. let res = JSON.parse(e.data);
  1020. if (res.status == 1) {
  1021. success && success(res);
  1022. } else {
  1023. error && error({
  1024. errMsg: res.info
  1025. });
  1026. }
  1027. },
  1028. fail(e) {
  1029. error && error(e);
  1030. }
  1031. });
  1032. } else if (action == 'info') {
  1033. uni.getImageInfo({
  1034. src: path,
  1035. success(e) {
  1036. if (e.errMsg == 'getImageInfo:ok') {
  1037. //e.height e.width e.type
  1038. success && success(e);
  1039. } else {
  1040. error && error(e);
  1041. }
  1042. },
  1043. fail(e) {
  1044. error && error(e);
  1045. }
  1046. });
  1047. } else if (action == 'read') {
  1048. uni.getFileSystemManager().readFile({
  1049. filePath: path,
  1050. encoding: 'base64',
  1051. position: 0,
  1052. success(e) {
  1053. if (e.errMsg == 'readFile:ok') {
  1054. //let img = 'data:image/png;base64,' + e.data.replace(/[\r\n]/g, "");
  1055. success && success(e);
  1056. } else {
  1057. error && error(e);
  1058. }
  1059. },
  1060. fail(e_t) {
  1061. error && error(e);
  1062. }
  1063. });
  1064. } else if (action == 'write') {
  1065. let filePath = `${uni.env.USER_DATA_PATH}/${fileName}.png`;
  1066. uni.getFileSystemManager().writeFile({
  1067. filePath: filePath,
  1068. data: data,
  1069. encoding: 'base64',
  1070. success(e) {
  1071. if (e.errMsg == 'writeFile:ok') {
  1072. success && success(filePath);
  1073. } else {
  1074. error && error(e);
  1075. }
  1076. },
  1077. fail(e) {
  1078. console.log(e);
  1079. error && error(e);
  1080. }
  1081. });
  1082. } else if (action == 'down') {
  1083. uni.downloadFile({
  1084. url: path,
  1085. success(e) {
  1086. if (e.errMsg === 'downloadFile:ok') {
  1087. //e.tempFilePath
  1088. success && success(e);
  1089. } else {
  1090. error && error(e);
  1091. }
  1092. },
  1093. fail(e) {
  1094. error && error(e);
  1095. }
  1096. })
  1097. } else if (action == 'save') {
  1098. let filePath = `${uni.env.USER_DATA_PATH}/${fileName}.png`;
  1099. uni.getFileSystemManager().saveFile({
  1100. tempFilePath: path,
  1101. filePath: filePath,
  1102. success(e) {
  1103. if (e.errMsg == 'saveFile:ok') {
  1104. success && success(filePath);
  1105. } else {
  1106. error && error(e);
  1107. }
  1108. },
  1109. fail(e) {
  1110. console.log(e);
  1111. error && error(e);
  1112. }
  1113. });
  1114. } else if (action == 'preview') {
  1115. uni.previewImage({
  1116. currnet: path,
  1117. urls: data,
  1118. showmenu: menu
  1119. });
  1120. }
  1121. },
  1122. /**
  1123. * 视频操作
  1124. */
  1125. viedoOperat({
  1126. action = 'choose',
  1127. count = 1, //上传视频的个数
  1128. mediaType = ['video'], //限制上传的类型为video
  1129. sourceType = ['album', 'camera'], //视频选择来源
  1130. maxDuration = 58, //拍摄限制时间
  1131. camera = 'back', //采用后置摄像头
  1132. filePath,
  1133. path,
  1134. size = 20,
  1135. success,
  1136. error
  1137. }) {
  1138. var that = this
  1139. if (action == 'choose') {
  1140. uni.chooseMedia({
  1141. count: count,
  1142. mediaType: mediaType,
  1143. sourceType: sourceType,
  1144. maxDuration: maxDuration,
  1145. camera: camera,
  1146. success(e) {
  1147. console.log(e)
  1148. if (e.errMsg == 'chooseMedia:ok') {
  1149. e.tempFiles.forEach((item) => {
  1150. let sel_size = parseFloat(item.size / 1024 / 1024).toFixed(1)
  1151. if (sel_size > size) {
  1152. let beyongSize = sel_size - size //获取视频超出限制大小的数量
  1153. that.info("上传的视频大小超限,超出" + beyongSize + "MB,请重新上传!")
  1154. error && error();
  1155. } else {
  1156. success && success(item);
  1157. }
  1158. });
  1159. } else {
  1160. error && error(e);
  1161. }
  1162. },
  1163. fail(e) {
  1164. console.log(e);
  1165. error && error(e);
  1166. }
  1167. })
  1168. }
  1169. //压缩视频
  1170. if (action == 'compress') {
  1171. uni.compressVideo({
  1172. quality: 'high',
  1173. src: filePath,
  1174. success(e) {
  1175. console.log(e)
  1176. if (e.errMsg == 'compressVideo:ok') {
  1177. // e.tempFiles.forEach((item) => {
  1178. success && success(e);
  1179. // });
  1180. } else {
  1181. error && error(e);
  1182. }
  1183. },
  1184. fail(e) {
  1185. console.log(e);
  1186. error && error(e);
  1187. }
  1188. })
  1189. }
  1190. },
  1191. /**
  1192. * 位置服务
  1193. * @param {Object} action 操作类型
  1194. * getLocation: 获取当前的地理位置、速度
  1195. * openLocation: 使用微信内置地图查看位置
  1196. * chooseLocation: 打开地图选择位置
  1197. * choosePoi: 打开 POI 列表选择位置
  1198. * getLatLng: 获取指定地址经纬度
  1199. * getAreaCode: 根据经纬度获取区划信息
  1200. * getDistance: 计算2个经纬度之间的距离
  1201. * @param {Object} type 返回坐标类型: wgs84返回gps坐标,gcj02 返回可用于 uni.openLocation 的坐标
  1202. * @param {Object} address 查询地址: '北京市海淀区彩和坊路海淀西大街74号'
  1203. * @param {Object} from 计算距离起点坐标,默认当前位置
  1204. * {latitude: 0, longitude: 0}
  1205. * @param {Object} to 计算距离终点坐标
  1206. * [{latitude: 0, longitude: 0}]
  1207. * @param {Object} success 成功回调
  1208. * @param {Object} error 失败回调
  1209. */
  1210. locationOperat({
  1211. action = 'getLocation',
  1212. type = 'gcj02',
  1213. address,
  1214. from = '',
  1215. to,
  1216. success,
  1217. error
  1218. }) {
  1219. var that = this;
  1220. if (action == 'getLocation') {
  1221. uni.getLocation({
  1222. type: type,
  1223. success(e) {
  1224. if (e.errMsg == 'getLocation:ok') {
  1225. success && success(e);
  1226. } else {
  1227. error && error(e);
  1228. }
  1229. },
  1230. fail(e) {
  1231. error && error(e);
  1232. }
  1233. });
  1234. } else if (action == 'openLocation') {
  1235. var {
  1236. latitude,
  1237. longitude
  1238. } = from;
  1239. uni.openLocation({
  1240. latitude: latitude,
  1241. longitude: longitude,
  1242. success(e) {
  1243. if (e.errMsg == 'openLocation:ok') {
  1244. success && success(e);
  1245. } else {
  1246. error && error(e);
  1247. }
  1248. },
  1249. fail(e) {
  1250. error && error(e);
  1251. }
  1252. });
  1253. } else if (action == 'chooseLocation') {
  1254. var {
  1255. latitude = '',
  1256. longitude = ''
  1257. } = from;
  1258. uni.chooseLocation({
  1259. latitude: latitude,
  1260. longitude: longitude,
  1261. success(e) {
  1262. if (e.errMsg == 'chooseLocation:ok') {
  1263. success && success(e);
  1264. } else {
  1265. error && error(e);
  1266. }
  1267. },
  1268. fail(e) {
  1269. error && error(e);
  1270. }
  1271. });
  1272. } else if (action == 'choosePoi') {
  1273. var {
  1274. latitude = '',
  1275. longitude = ''
  1276. } = from;
  1277. uni.choosePoi({
  1278. success(e) {
  1279. if (e.errMsg == 'choosePoi:ok') {
  1280. success && success(e);
  1281. } else {
  1282. error && error(e);
  1283. }
  1284. },
  1285. fail(e) {
  1286. error && error(e);
  1287. }
  1288. });
  1289. } else if (action == 'getLatLng') {
  1290. new qqMap({
  1291. key: that.config.qqMapKey
  1292. }).geocoder({
  1293. address: address,
  1294. success(e) {
  1295. if (e.status == 0 && e.message == 'query ok') {
  1296. success && success(e.result);
  1297. } else {
  1298. error && error(e);
  1299. }
  1300. },
  1301. fail(e) {
  1302. error && error(e);
  1303. }
  1304. });
  1305. } else if (action == 'getAreaCode') {
  1306. new qqMap({
  1307. key: that.config.qqMapKey
  1308. }).reverseGeocoder({
  1309. success(e) {
  1310. if (e.status == 0 && e.message == 'query ok') {
  1311. success && success(e.result);
  1312. } else {
  1313. error && error(e);
  1314. }
  1315. },
  1316. fail(e) {
  1317. error && error(e);
  1318. }
  1319. });
  1320. } else if (action == 'getDistanceApi') {
  1321. new qqMap({
  1322. key: that.config.qqMapKey
  1323. }).calculateDistance({
  1324. from: from, //若起点有数据则采用起点坐标,若为空默认当前地址
  1325. to: to,
  1326. success(e) {
  1327. if (e.status == 0 && e.message == 'query ok') {
  1328. success && success(e.result.elements);
  1329. } else {
  1330. error && error(e);
  1331. }
  1332. },
  1333. fail(e) {
  1334. error && error(e);
  1335. }
  1336. });
  1337. } else if (action == 'getDistanceMath') { // 返回KM
  1338. var {
  1339. latitude: lat1 = '',
  1340. longitude: lng1 = ''
  1341. } = from;
  1342. if (lat1 == '' && lng1 == '') {
  1343. return 0;
  1344. }
  1345. var {
  1346. latitude: lat2 = '',
  1347. longitude: lng2 = ''
  1348. } = to;
  1349. var toRad = function(d) {
  1350. return d * Math.PI / 180;
  1351. };
  1352. var dis = 0;
  1353. var deltaLng = toRad(lng1) - toRad(lng2);
  1354. var radLat1 = toRad(lat1);
  1355. var radLat2 = toRad(lat2);
  1356. var deltaLat = radLat1 - radLat2;
  1357. var dis = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(deltaLat / 2), 2) + Math.cos(radLat1) * Math.cos(
  1358. radLat2) * Math.pow(Math.sin(deltaLng / 2), 2)));
  1359. return that.math.toFixed(dis * 6378.137, 2); // km
  1360. }
  1361. },
  1362. /**
  1363. * 过滤emoji
  1364. * @param {Object} str
  1365. */
  1366. filterEmoji: function(str) {
  1367. return str.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, '');
  1368. },
  1369. /**
  1370. * 打印对象
  1371. * @param obj
  1372. */
  1373. jslog: function(obj) {
  1374. this.config.debug && console.log(JSON.stringify(obj));
  1375. },
  1376. /**
  1377. * form表单数据校验
  1378. * @param value
  1379. * @param rule
  1380. */
  1381. formCheck: function(value, rule, error) {
  1382. // return false
  1383. var that = this;
  1384. var regs = {
  1385. required: [
  1386. /[\s\S]+/,
  1387. '必填项不能为空',
  1388. ],
  1389. english: [
  1390. /^[a-zA-Z]+$/,
  1391. '必填项只能由大小写字母组成',
  1392. ],
  1393. mobile: [
  1394. /^1[3|4|5|7|8|9][0-9]\d{4,8}$/,
  1395. '请输入正确的手机号',
  1396. ],
  1397. phone: [
  1398. /^(\d{3,4}-?)?\d{7,9}$/g,
  1399. '请输入正确的电话号码',
  1400. ],
  1401. email: [
  1402. /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
  1403. '请输入正确的电子邮箱'
  1404. ],
  1405. url: [
  1406. /(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/,
  1407. '请输入正确的链接'
  1408. ],
  1409. number: [
  1410. /^\d+$/,
  1411. '必填项只能填数字'
  1412. ],
  1413. code4: [
  1414. /^\d{4}$/,
  1415. '请输入正确的手机验证码'
  1416. ],
  1417. code6: [
  1418. /^\d{6}$/,
  1419. '请输入正确的手机验证码'
  1420. ],
  1421. captcha4: [
  1422. /^[0-9a-zA-Z]{4}$/,
  1423. '请输入正确的图片验证码'
  1424. ],
  1425. date: [
  1426. /^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/,
  1427. '请输入正确的日期格式'
  1428. ],
  1429. identity: [
  1430. /(^\d{15}$)|(^\d{17}(x|X|\d)$)/,
  1431. '请输入正确的身份证号'
  1432. ],
  1433. username: [
  1434. /^[a-zA-Z0-9\u4e00-\u9fa5-_\.]{2,12}$/,
  1435. '请输入正确的帐号(只能包含中文、英文、数字、下划线等字符)'
  1436. ],
  1437. password: [
  1438. /^\w{6,16}$/,
  1439. '请输入正确的密码(6-16位数字,字母或符号)'
  1440. ],
  1441. passwords: [
  1442. /^[a-zA-Z]+\w{5,12}$/,
  1443. '请输入正确的密码(以字母开头,长度在6-12之间)'
  1444. ],
  1445. pwd: [
  1446. /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]{6,12}$/,
  1447. '请输入正确的密码(6-12位数字+字母组合)'
  1448. ],
  1449. invite: [
  1450. /^[0-9a-zA-Z]{10}$/,
  1451. '邀请码为8位数字或字母组合'
  1452. ],
  1453. truename: [
  1454. /^[\u4e00-\u9fa5]{2,4}$/,
  1455. '请输入正确的真实姓名(2-4个汉字)'
  1456. ],
  1457. money: [
  1458. /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/,
  1459. '请输入正确的金额'
  1460. ]
  1461. };
  1462. var reg = regs[rule];
  1463. if (that.isEmpty(reg)) {
  1464. return true;
  1465. } else {
  1466. if (value == '' || !RegExp(reg[0]).test(value)) {
  1467. that.info(error || reg[1]);
  1468. return false;
  1469. }
  1470. return true;
  1471. }
  1472. },
  1473. /****************************************************/
  1474. /**
  1475. *获取系统信息
  1476. * @param label 获取系统的某一项信息
  1477. * screenWidth 屏幕宽度,
  1478. * screenHeight 屏幕高度,单位px
  1479. * windowWidth 单位px可使用窗口宽度,单位px
  1480. * windowHeight 可使用窗口高度,单位px
  1481. * statusBarHeight 状态栏的高度,单位px
  1482. * menuButton:右上角胶囊按钮的布局位置信息,坐标信息以屏幕左上角为原点
  1483. * width 宽度,单位:px
  1484. * height 高度,单位:px
  1485. * top 上边界坐标,单位:px
  1486. * right 右边界坐标,单位:px
  1487. * bottom 下边界坐标,单位:px
  1488. * left 左边界坐标,单位:px
  1489. */
  1490. getSystemInfo(success) {
  1491. // 获取系统状态栏信息
  1492. uni.getSystemInfo({
  1493. success: (res) => {
  1494. if (res.errMsg == 'getSystemInfo:ok') {
  1495. res.menuButton = uni.getMenuButtonBoundingClientRect();
  1496. success && success(res);
  1497. } else {
  1498. that.modal('获取系统信息失败:' + res.errMsg);
  1499. }
  1500. },
  1501. fail: (res) => {
  1502. that.modal('获取系统信息失败:' + res.errMsg);
  1503. }
  1504. });
  1505. },
  1506. /**
  1507. * 检查登录
  1508. */
  1509. getSessionKey: function(success) {
  1510. let that = this;
  1511. let data = {};
  1512. data.openid = cache.get('open_id');
  1513. data.session_key = cache.get('session_key');
  1514. // 都存在
  1515. if (!that.isEmpty(data.session_key) && !that.isEmpty(data.openid)) {
  1516. uni.checkSession({
  1517. success() {
  1518. success && success(data);
  1519. },
  1520. fail() {
  1521. cache.remove('open_id');
  1522. cache.remove('session_key');
  1523. that.getOpenId(success);
  1524. }
  1525. });
  1526. } else {
  1527. cache.remove('open_id');
  1528. cache.remove('session_key');
  1529. that.getOpenId(success);
  1530. }
  1531. },
  1532. /**
  1533. * 获取openid
  1534. * @param success
  1535. */
  1536. getOpenId: function(success, error) {
  1537. var that = this;
  1538. that.loading();
  1539. uni.login({
  1540. success: (e) => {
  1541. that.req({
  1542. url: 'public/getOpenid',
  1543. data: {
  1544. code: e.code
  1545. },
  1546. login: false,
  1547. load: false
  1548. }, function(res) {
  1549. if (res.status == 1) {
  1550. cache.set('open_id', res.data.openid);
  1551. cache.set('session_key', res.data.session_key);
  1552. success && success(res.data);
  1553. } else {
  1554. that.modal('微信登录失败:' + res.info, function() {
  1555. error && error();
  1556. });
  1557. return false;
  1558. }
  1559. }, function() {}, function() {
  1560. that.closeLoading();
  1561. });
  1562. },
  1563. fail: (e) => {
  1564. that.closeLoading();
  1565. that.modal('微信登录失败:' + e.errMsg, function() {
  1566. error && error();
  1567. });
  1568. }
  1569. });
  1570. },
  1571. /**
  1572. * 登录
  1573. * @param {Object} data
  1574. * @param {Object} success
  1575. * @param {Object} error
  1576. */
  1577. doLogin: function(data, success, error) {
  1578. var that = this;
  1579. data.loginsubmit = 'yes';
  1580. this.req({
  1581. url: 'account/login',
  1582. data: data,
  1583. login: false
  1584. }, function(res) {
  1585. if (res.status == 1) {
  1586. cache.set('user_info', res.data);
  1587. success && success(res.data);
  1588. } else {
  1589. error && error(res);
  1590. }
  1591. });
  1592. },
  1593. /**
  1594. * 注册
  1595. * @param {Object} data
  1596. * @param {Object} success
  1597. * @param {Object} error
  1598. */
  1599. doRegist: function(data, success, error) {
  1600. var that = this;
  1601. data.registsubmit = 'yes';
  1602. this.req({
  1603. url: 'account/register',
  1604. data: data,
  1605. login: false
  1606. }, function(res) {
  1607. if (res.status == 1) {
  1608. cache.set('user_info', res.data);
  1609. success && success(res.data);
  1610. } else {
  1611. error && error(res);
  1612. }
  1613. });
  1614. },
  1615. /**
  1616. * 查询是否注册
  1617. * @param {Object} success
  1618. * @param {Object} error
  1619. */
  1620. checkRegist: function(success, error) {
  1621. var that = this;
  1622. that.getSessionKey(function(data) {
  1623. that.req({
  1624. url: 'account/checkRegist',
  1625. data: {
  1626. open_id: data.openid,
  1627. registsubmit: 'yes'
  1628. },
  1629. login: false,
  1630. load: false
  1631. }, function(res) {
  1632. if (res.status == 1) {
  1633. success && success();
  1634. } else {
  1635. error && error();
  1636. }
  1637. });
  1638. });
  1639. },
  1640. /**
  1641. * 获取会员信息
  1642. * @param {Object} success
  1643. * @param {Object} error
  1644. */
  1645. getMemberInfo: function(success, error) {
  1646. var that = this;
  1647. this.req({
  1648. url: 'center/getMemberInfo',
  1649. load: false
  1650. }, function(res) {
  1651. if (res.status == 1) {
  1652. cache.set('user_info', res.data);
  1653. success && success(res.data);
  1654. } else {
  1655. error && error(res);
  1656. }
  1657. });
  1658. },
  1659. /**
  1660. * 获取用户微信资料
  1661. * @param success
  1662. */
  1663. getUserProfile: function(success, error) {
  1664. var that = this;
  1665. that.loading('获取微信信息中...');
  1666. uni.getUserProfile({
  1667. lang: 'zh_CN',
  1668. desc: '用于完善会员资料',
  1669. success: (res) => {
  1670. if (res.errMsg == 'getUserProfile:ok') {
  1671. // 过滤掉emoji
  1672. res.userInfo.nickName = that.filterEmoji(res.userInfo.nickName);
  1673. success(res.userInfo);
  1674. } else {
  1675. that.modal('获取微信信息失败:' + res.errMsg, function() {
  1676. error && error(res);
  1677. });
  1678. }
  1679. },
  1680. fail: (res) => {
  1681. that.modal('获取微信信息失败:' + res.errMsg, function() {
  1682. console.log(res)
  1683. error && error(res);
  1684. });
  1685. },
  1686. complete: () => {
  1687. that.closeLoading();
  1688. }
  1689. });
  1690. },
  1691. /**
  1692. * 获取配置信息
  1693. * @param success
  1694. */
  1695. getConfigInfo: function({
  1696. source = 'system',
  1697. label = '',
  1698. success
  1699. }) {
  1700. this.req({
  1701. url: 'public/configInfo',
  1702. data: {
  1703. source: source,
  1704. label: label
  1705. },
  1706. login: false,
  1707. load: false
  1708. }, function(res) {
  1709. success(res.data);
  1710. });
  1711. },
  1712. /**
  1713. * 获取微信手机号
  1714. * @param e
  1715. * @param success
  1716. */
  1717. getMobile: function(e, success) {
  1718. var that = this;
  1719. that.getSessionKey(function(data) {
  1720. if (e.detail.errMsg == 'getPhoneNumber:ok') {
  1721. that.req({
  1722. url: 'public/getMobile',
  1723. data: {
  1724. encryptedData: e.detail.encryptedData,
  1725. iv: e.detail.iv,
  1726. sessionKey: data.session_key
  1727. },
  1728. login: false
  1729. }, function(res) {
  1730. if (res.status == 1) {
  1731. success(res.data);
  1732. } else {
  1733. that.modal('获取手机号失败' + res.info);
  1734. return false;
  1735. }
  1736. });
  1737. } else {
  1738. that.modal('获取手机号失败' + e.detail.errMsg);
  1739. }
  1740. });
  1741. },
  1742. /**
  1743. * 拨打电话
  1744. * @param mobile
  1745. */
  1746. makeCall: function(mobile) {
  1747. uni.makePhoneCall({
  1748. phoneNumber: mobile
  1749. });
  1750. },
  1751. /**
  1752. * 修改页面标题
  1753. * @param title
  1754. */
  1755. changeNavBarTitle: function(title) {
  1756. uni.setNavigationBarTitle({
  1757. title: title
  1758. });
  1759. },
  1760. /**
  1761. * 检查版本更新
  1762. */
  1763. checkUpdate: function() {
  1764. if (uni.canIUse('getUpdateManager')) {
  1765. const updateManager = uni.getUpdateManager()
  1766. updateManager.onCheckForUpdate(function(res) {
  1767. if (res.hasUpdate) {
  1768. updateManager.onUpdateReady(function() {
  1769. uni.showModal({
  1770. title: '更新提示',
  1771. content: '新版本已经准备好,是否重启应用?',
  1772. success: function(res) {
  1773. if (res.confirm) {
  1774. updateManager.applyUpdate()
  1775. }
  1776. }
  1777. })
  1778. })
  1779. updateManager.onUpdateFailed(function() {
  1780. uni.showModal({
  1781. title: '已经有新版本了~',
  1782. content: '新版本已经上线啦~,请您删除当前小程序,重新搜索打开~'
  1783. })
  1784. })
  1785. }
  1786. })
  1787. } else {
  1788. uni.showModal({
  1789. title: '提示',
  1790. content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
  1791. })
  1792. }
  1793. },
  1794. /**
  1795. * html转义
  1796. * @param {object} str    //需要转义内容
  1797. * @param {object} success  
  1798. */
  1799. escape2Html(str, success) {
  1800. var arrEntities = {
  1801. 'lt': '<',
  1802. 'gt': '>',
  1803. 'nbsp': ' ',
  1804. 'amp': '&',
  1805. 'quot': '"'
  1806. };
  1807. return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function(all, t) {
  1808. return arrEntities[t];
  1809. }).replace(/<section/g, '<div').replace(/<u>/g, '').replace(/<u style="">/g, '').replace(/<\/u>/g, '');
  1810. },
  1811. /**
  1812. * 分享信息
  1813. */
  1814. shareInfo: function() {
  1815. var that = this;
  1816. var userInfo = cache.get('user_info');
  1817. if (!that.isEmpty(userInfo) && !that.isEmpty(userInfo.serial)) {
  1818. var path = `/pages/index/index?invite_code=${userInfo.serial}`;
  1819. } else {
  1820. var path = '/pages/index/index';
  1821. }
  1822. return {
  1823. title: that.config.name,
  1824. path: path,
  1825. // imageUrl: '/image/iconimg/login.png'
  1826. };
  1827. },
  1828. /**
  1829. * 检测是否收藏
  1830. * @param {object} id //检测是否收藏的商品id
  1831. * @param {object} success
  1832. */
  1833. checkStore(id, key, success) {
  1834. var that = this
  1835. var shopStore = cache.get(key);
  1836. if (that.isEmpty(shopStore)) {
  1837. success && success(false)
  1838. } else {
  1839. var have = 0
  1840. for (let i in shopStore) {
  1841. var d = shopStore[i];
  1842. if (d.id == id) {
  1843. // 有收藏
  1844. have = 1
  1845. success && success(true)
  1846. break;
  1847. }
  1848. if (have == 0) {
  1849. // 无收藏
  1850. success && success(false)
  1851. }
  1852. }
  1853. }
  1854. },
  1855. /**
  1856. * 收藏缓存
  1857. * @param {object} id //需要收藏或取消的商品id
  1858. * @param {object} success
  1859. */
  1860. changeStore(data, key, success) {
  1861. var shopStore = cache.get(key);
  1862. var that = this
  1863. var p = {}
  1864. p = data
  1865. if (that.isEmpty(shopStore)) {
  1866. var shopStore = []
  1867. shopStore.push(p);
  1868. cache.set(key, shopStore);
  1869. success && success('收藏成功')
  1870. } else {
  1871. var have = 0
  1872. for (let i in shopStore) {
  1873. var d = shopStore[i];
  1874. console.log(d, data)
  1875. if (d.id == data.id && d.table == data.table) {
  1876. // 有的话取消收藏
  1877. have = 1
  1878. shopStore.splice(i, 1);
  1879. cache.set(key, shopStore);
  1880. success && success('取消成功')
  1881. break;
  1882. }
  1883. }
  1884. if (have == 0) {
  1885. // 没有的话收藏
  1886. shopStore.push(p);
  1887. cache.set(key, shopStore);
  1888. success && success('收藏成功')
  1889. }
  1890. }
  1891. },
  1892. /****************************************************/
  1893. /**
  1894. * 获取购物车信息,设置导航红点信息
  1895. * @param index 设置信息 tabBar 序号
  1896. */
  1897. getshopcar: function(success) {
  1898. var shopCar_list = cache.get('shop_car');
  1899. if (this.isEmpty(shopCar_list)) {
  1900. uni.hideTabBarRedDot({ //隐藏 tabBar 某一项的右上角文本
  1901. index: 2, //第几个 tabBar,从左边 0 算起
  1902. success: function() {
  1903. success && success(0);
  1904. }
  1905. });
  1906. } else {
  1907. var len = this.getLength(shopCar_list);
  1908. uni.setTabBarBadge({ //为 tabBar 某一项的右上角添加文本
  1909. index: 2, //第几个 tabBar,从左边 0 算起
  1910. text: String(len), //右上角添加的文本
  1911. success: function() {
  1912. success && success(len);
  1913. }
  1914. });
  1915. }
  1916. },
  1917. /**
  1918. * 上拉刷新加载数据
  1919. * @param {object} type
  1920. * @param {object} page
  1921. * @param {object} succes
  1922. */
  1923. onReachFoot: function(url, data, succes) {
  1924. //type=1时请求找工作
  1925. if (url) {
  1926. this.req({
  1927. url: url,
  1928. data: data
  1929. }, function(res) {
  1930. if (res.status == 1) {
  1931. succes && succes(res.data);
  1932. }
  1933. })
  1934. } else {
  1935. succes && success(false)
  1936. }
  1937. },
  1938. /**
  1939. * 电话聊天控制
  1940. * @param price 价格
  1941. * @param mobile 手机号
  1942. * @param work_id 工作或求职id
  1943. * @param {String} type 类型,work招工,worker求职
  1944. * @param {String} buy_type 购买类型 pirce电话,chat_price聊天
  1945. * @param send_id 被购买的用户id
  1946. * @param send_name 被购买的名字
  1947. */
  1948. /* makeCall(price, mobile, work_id, type, buy_type, send_id, send_name = '') {
  1949. var that = this
  1950. that.modal('将自动使用会员次数或东豆进行抵扣', function(params) {
  1951. that.req({
  1952. url: 'center/MobileOrMessage',
  1953. data: {
  1954. price: price,
  1955. mobile: mobile,
  1956. work_id: work_id,
  1957. type: type,
  1958. buy_type: buy_type,
  1959. send_id: send_id,
  1960. send_name: send_name
  1961. }
  1962. }, function(params) {
  1963. if (params.status == 1) {
  1964. if (buy_type == 'price') {
  1965. uni.makePhoneCall({
  1966. phoneNumber: mobile,
  1967. })
  1968. } else {
  1969. that.jump('/pages/chat/chat?id=' + send_id + '&nickname=' + send_name)
  1970. }
  1971. }
  1972. if (params.status == 2) {
  1973. }
  1974. })
  1975. }, true)
  1976. }, */
  1977. /**
  1978. * 微信小程序防抖
  1979. * @param func 防抖事件
  1980. * @param wait 阻止时间
  1981. */
  1982. debounce: function(func, wait) {
  1983. let timeout;
  1984. return function() {
  1985. console.log('防抖事件:' + func, '防抖时间:' + wait)
  1986. let context = this
  1987. let args = arguments
  1988. let later = () => {
  1989. timeout = null
  1990. func.apply(context, args)
  1991. }
  1992. clearTimeout(timeout)
  1993. timeout = setTimeout(later, wait)
  1994. }
  1995. }
  1996. }