api.js 47 KB

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