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