api.js 45 KB

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