api.js 46 KB

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