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