util.js 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192
  1. const Promise = require('./es6-promise.js');
  2. // 保留两位小数
  3. var filters = {
  4. toFix: function (value) {
  5. value = parseInt(value)
  6. return value.toFixed(2) // 此处2为保留两位小数,保留几位小数,这里写几
  7. }
  8. }
  9. module.exports = {
  10. filters,
  11. // amapFile: require('amap-wx.js'),
  12. config: require('config.js'),
  13. // 以空格开始或结束的字符串
  14. trim: function (str) {
  15. return str.replace(/^\s+/, "").replace(/\s+$/, "");
  16. },
  17. // 所有存在空格的字符串
  18. spaceTrim: function (str) {
  19. return str.replace(/\s+/g, "")
  20. },
  21. // 通过宝贝币匹配会员等级
  22. getCoinLevel(coinNum) {
  23. let data = {};
  24. this.config.coin_level.forEach((el, i) => {
  25. if (el.min_num <= coinNum && coinNum < el.max_num) {
  26. data.levelName = el.levelName;
  27. data.index = i;
  28. data.level = el.level;
  29. data.time = el.time || 0;
  30. }
  31. });
  32. return data;
  33. },
  34. toMoney: function (str, s) {
  35. if (str === undefined) return str;
  36. var nums = str.toString().substr(0, 1) == '-' ? true : false,
  37. num = 0;
  38. str = str.toString().replace(/[^\d.]/g, "").split(".");
  39. str.length = 2, s = s || "", num = ((str[0] || 0) * 1000 / 1000).toString();
  40. str[1] = str[1] || 0;
  41. str[1] = Number("0." + str[1]).toString().substring(2, 4);
  42. if (str[1].length < 2) {
  43. for (var i = str[1].length; i < 2; i++) {
  44. str[1] += "0";
  45. }
  46. }
  47. for (var i = 0, j = Math.floor((num.length - (1 + i)) / 3); i < j; i++) {
  48. num = num.substring(0, num.length - (4 * i + 3)) + s + num.substring(num.length - (4 * i + 3));
  49. }
  50. str[0] = num;
  51. return (nums ? "-" : "") + str.join(".");
  52. },
  53. getRequestURL: function (query) {
  54. return this.config.apiServer + query + '.do';
  55. },
  56. // 一次性订阅信息(待完善数组) cancel————取消授权是否依旧执行
  57. requestMsg(tmplIds, cancel) {
  58. let arr = [];
  59. if (!this.isEmpty(tmplIds)) {
  60. if (Array.isArray(tmplIds)) {
  61. arr = tmplIds;
  62. }
  63. if (typeof tmplIds == 'string') {
  64. arr.push(tmplIds)
  65. }
  66. }
  67. return new Promise((resolve, reject) => {
  68. wx.requestSubscribeMessage({
  69. tmplIds: arr,
  70. success: (res) => {
  71. if (res[arr[0]] === 'accept') {
  72. resolve()
  73. }
  74. if (res[arr[0]] === "reject" && cancel) {
  75. resolve()
  76. }
  77. },
  78. fail(err) {
  79. reject()
  80. }
  81. })
  82. })
  83. },
  84. // 获取物品清单(副文本)
  85. getGoodstext(id) {
  86. let that = this;
  87. return new Promise((resolve, reject) => {
  88. that.ajax({
  89. func: 'ebusiness/listItems',
  90. data: {
  91. aid: id
  92. },
  93. load: false
  94. }, res => {
  95. if (res.code == 0) {
  96. resolve(res.data)
  97. }
  98. })
  99. })
  100. },
  101. // 获取物品清单(商品列表)
  102. getGoodsList(id) {
  103. let that = this;
  104. return new Promise((resolve, reject) => {
  105. that.ajax({
  106. func: 'ebusiness/recommend',
  107. data: {
  108. aid: id
  109. },
  110. load: false
  111. }, res => {
  112. if (res.code == 0) {
  113. resolve(res.data)
  114. }
  115. })
  116. })
  117. },
  118. // 获取阿里云图片信息
  119. getImageInfo(url) {
  120. return new Promise((resolve, reject) => {
  121. wx.getImageInfo({
  122. src: url,
  123. success: (result) => {
  124. if (result.errMsg == "getImageInfo:ok") {
  125. resolve(result.width + '*' + result.height)
  126. } else {
  127. reject('')
  128. }
  129. },
  130. fail: (res) => {
  131. reject('')
  132. },
  133. })
  134. })
  135. },
  136. // 获取物品推荐
  137. getGoodsRecommend(id) {
  138. let that = this;
  139. return new Promise((resolve, reject) => {
  140. that.ajax({
  141. func: 'ebusiness/checkExistItems',
  142. data: {
  143. aid: id
  144. },
  145. load: false
  146. }, res => {
  147. if (res.code == 0) {
  148. resolve(res.data)
  149. }
  150. })
  151. })
  152. },
  153. // 获取用户信息
  154. getUserInfo() {
  155. let that = this,
  156. loginuser = wx.getStorageSync("WXuserInfo") ? true : false;
  157. return new Promise(function (resolve, reject) {
  158. if (loginuser) {
  159. that.ajax({
  160. func: 'v2/user/info',
  161. load: false
  162. }, res => {
  163. if (res.code == 0) {
  164. resolve(res.data);
  165. } else {
  166. reject(res.reason);
  167. }
  168. });
  169. } else {
  170. reject(false);
  171. }
  172. })
  173. },
  174. // 获取用户佣金信息
  175. stat() {
  176. let that = this;
  177. return new Promise(function (resolve, reject) {
  178. that.ajax({
  179. func: 'v2/user/stat',
  180. load: false
  181. }, res => {
  182. if (res.code == 0) {
  183. resolve(res.data);
  184. }
  185. });
  186. })
  187. },
  188. // 获取上一页地址
  189. getPrePageRoute() {
  190. let pages = getCurrentPages(); //页面对象
  191. let prevpage = pages[pages.length - 2]; //上一个页面对象
  192. return prevpage.route;
  193. },
  194. navigator: function (url) {
  195. let app = getApp();
  196. if (app.globalData.userInfo) {
  197. wx.navigateTo({
  198. url: url
  199. })
  200. } else {
  201. // 静默登录
  202. this.silentLogin().then(res => {
  203. wx.navigateTo({
  204. url: url
  205. })
  206. })
  207. }
  208. },
  209. isTimeLeng(val) {
  210. var s = val.toString();
  211. return s.length == 1 ? "0" + val : val;
  212. },
  213. showTips(msg, time) {
  214. wx.showToast({
  215. title: msg,
  216. icon: 'none',
  217. mask: true,
  218. duration: time || 2000
  219. });
  220. },
  221. // 对比时间是否已过期
  222. timeContrast(time) {
  223. if (!this.isEmpty(time) && time > 0) {
  224. let now = new Date().getTime();
  225. return (time - now >= 0 ? true : false);
  226. }
  227. },
  228. base64Encode: function (str) {
  229. str = this.utf16to8(str);
  230. var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  231. var out, i, len;
  232. var c1, c2, c3;
  233. len = str.length;
  234. i = 0;
  235. out = "";
  236. while (i < len) {
  237. c1 = str.charCodeAt(i++) & 0xff;
  238. if (i == len) {
  239. out += base64EncodeChars.charAt(c1 >> 2);
  240. out += base64EncodeChars.charAt((c1 & 0x3) << 4);
  241. out += "==";
  242. break;
  243. }
  244. c2 = str.charCodeAt(i++);
  245. if (i == len) {
  246. out += base64EncodeChars.charAt(c1 >> 2);
  247. out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
  248. out += base64EncodeChars.charAt((c2 & 0xF) << 2);
  249. out += "=";
  250. break;
  251. }
  252. c3 = str.charCodeAt(i++);
  253. out += base64EncodeChars.charAt(c1 >> 2);
  254. out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
  255. out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
  256. out += base64EncodeChars.charAt(c3 & 0x3F);
  257. }
  258. return out;
  259. },
  260. base64Decode(str) {
  261. var base64DecodeChars = new Array(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);
  262. var c1, c2, c3, c4;
  263. var i, len, out;
  264. len = str.length;
  265. i = 0;
  266. out = "";
  267. while (i < len) {
  268. /* c1 */
  269. do {
  270. c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
  271. }
  272. while (i < len && c1 == -1);
  273. if (c1 == -1)
  274. break;
  275. /* c2 */
  276. do {
  277. c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
  278. }
  279. while (i < len && c2 == -1);
  280. if (c2 == -1)
  281. break;
  282. out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
  283. /* c3 */
  284. do {
  285. c3 = str.charCodeAt(i++) & 0xff;
  286. if (c3 == 61)
  287. return out;
  288. c3 = base64DecodeChars[c3];
  289. }
  290. while (i < len && c3 == -1);
  291. if (c3 == -1)
  292. break;
  293. out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));
  294. /* c4 */
  295. do {
  296. c4 = str.charCodeAt(i++) & 0xff;
  297. if (c4 == 61)
  298. return out;
  299. c4 = base64DecodeChars[c4];
  300. }
  301. while (i < len && c4 == -1);
  302. if (c4 == -1)
  303. break;
  304. out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
  305. }
  306. return this.utf8to16(out);
  307. },
  308. utf8to16(str) {
  309. var out, i, len, c;
  310. var char2, char3;
  311. out = "";
  312. len = str.length;
  313. i = 0;
  314. while (i < len) {
  315. c = str.charCodeAt(i++);
  316. switch (c >> 4) {
  317. case 0:
  318. case 1:
  319. case 2:
  320. case 3:
  321. case 4:
  322. case 5:
  323. case 6:
  324. case 7:
  325. // 0xxxxxxx
  326. out += str.charAt(i - 1);
  327. break;
  328. case 12:
  329. case 13:
  330. // 110x xxxx 10xx xxxx
  331. char2 = str.charCodeAt(i++);
  332. out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
  333. break;
  334. case 14:
  335. // 1110 xxxx10xx xxxx10xx xxxx
  336. char2 = str.charCodeAt(i++);
  337. char3 = str.charCodeAt(i++);
  338. out += String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0));
  339. break;
  340. }
  341. }
  342. return out;
  343. },
  344. utf16to8: function (str) {
  345. var out, i, len, c;
  346. out = "";
  347. len = str.length;
  348. for (i = 0; i < len; i++) {
  349. c = str.charCodeAt(i);
  350. if ((c >= 0x0001) && (c <= 0x007F)) {
  351. out += str.charAt(i);
  352. } else
  353. if (c > 0x07FF) {
  354. out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
  355. out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
  356. out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
  357. } else {
  358. out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
  359. out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
  360. }
  361. }
  362. return out;
  363. },
  364. formatDate: function (date, format, isFormat) {
  365. isFormat = isFormat != undefined ? isFormat : true;
  366. // date = new Date(date.replace(/-/g, "/"));
  367. date = typeof date == "string" ?
  368. new Date(date.replace(/-/g, "/")) :
  369. new Date(date);
  370. var format = format || "yyyy-MM-dd hh:mm:ss",
  371. o = {
  372. "M+": date.getMonth() + 1,
  373. "d+": date.getDate(),
  374. "h+": date.getHours(),
  375. "m+": date.getMinutes(),
  376. "s+": date.getSeconds(),
  377. "q+": Math.floor((date.getMonth() + 3) / 3),
  378. "S": date.getMilliseconds()
  379. };
  380. if (/(y+)/.test(format)) {
  381. format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length))
  382. }
  383. for (var k in o) {
  384. if (new RegExp("(" + k + ")").test(format)) {
  385. format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
  386. }
  387. }
  388. if (isFormat) {
  389. return new Date(format.replace(/-/g, "/"));
  390. } else {
  391. return format;
  392. }
  393. },
  394. decode: function (value, args) {
  395. var result = value;
  396. if (arguments.length > 0) {
  397. if (arguments.length == 1) {
  398. result = args;
  399. } else {
  400. for (var i = 1; i < arguments.length; i = i + 2) {
  401. if (arguments[i] != undefined) {
  402. if (arguments[i + 1] != undefined) {
  403. if (result == arguments[i]) {
  404. result = arguments[i + 1];
  405. break;
  406. }
  407. } else {
  408. result = arguments[i];
  409. }
  410. }
  411. }
  412. }
  413. }
  414. return result;
  415. },
  416. urlDecode: function (data, key) {
  417. if (data == null) return '';
  418. var t = typeof (data);
  419. if (t == 'string' || t == 'number' || t == 'boolean') {
  420. data = decodeURI(data);
  421. } else {
  422. for (var i in data) {
  423. data[i] = decodeURI(data[i]);
  424. }
  425. }
  426. return data;
  427. },
  428. toParam: function (param, key, encode) {
  429. if (param == null) return '';
  430. var paramStr = '';
  431. var t = typeof (param);
  432. if (t == 'string' || t == 'number' || t == 'boolean') {
  433. paramStr += '&' + key + '=' + ((encode == null || encode) ? decodeURI(param) : param);
  434. } else {
  435. for (var i in param) {
  436. var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
  437. paramStr += this.toParam(param[i], k, encode);
  438. }
  439. }
  440. return paramStr;
  441. },
  442. isPhone: function (phone) {
  443. return typeof (phone) != "undefined" && (phone.length != 11 || !(/^1[3|4|5|6|7|8|9][0-9]{9}/.test(phone)));
  444. },
  445. delData: function (data, filed, val) {
  446. var newArr = new Array();
  447. for (var i = 0; i < data.length; i++) {
  448. var j = data[i];
  449. if (j[filed] != val) {
  450. newArr.push(j);
  451. }
  452. }
  453. return newArr;
  454. },
  455. formatUnixtimestamp: function (inputTime) {
  456. var date = new Date(inputTime);
  457. var y = date.getFullYear();
  458. var m = date.getMonth() + 1;
  459. m = m < 10 ? ('0' + m) : m;
  460. var d = date.getDate();
  461. d = d < 10 ? ('0' + d) : d;
  462. var h = date.getHours();
  463. h = h < 10 ? ('0' + h) : h;
  464. var minute = date.getMinutes();
  465. var second = date.getSeconds();
  466. minute = minute < 10 ? ('0' + minute) : minute;
  467. second = second < 10 ? ('0' + second) : second;
  468. return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
  469. },
  470. formatMonth: function (begin, end) {
  471. let that = this;
  472. var arr = [],
  473. unixDb = begin - 24 * 60 * 60 * 1000,
  474. unixDe = end - 24 * 60 * 60 * 1000;
  475. for (var k = unixDb; k <= unixDe;) {
  476. k = k + 24 * 60 * 60 * 1000;
  477. var time = {
  478. text: that.formatDate(that.formatUnixtimestamp(k), 'MM月dd日', false),
  479. value: that.formatDate(that.formatUnixtimestamp(k), 'yyyy-MM-dd', false),
  480. active: (that.getNowFormatDate("yyyy-MM-dd") == that.formatDate(that.formatUnixtimestamp(k), 'yyyy-MM-dd', false) ? 1 : 0)
  481. };
  482. arr.push(time);
  483. }
  484. return arr;
  485. },
  486. getNowFormatDate: function (format) {
  487. format = format || "yyyy-MM-dd";
  488. return this.formatDate(this.formatUnixtimestamp(new Date().getTime()), format, false);
  489. },
  490. datedifference: function (sDate1, sDate2, compareSec) { //compareSec ——是否比较至秒级 true-是 -false 否
  491. var dateSpan, tempDate, iDays;
  492. sDate1 = Date.parse(sDate1);
  493. sDate2 = Date.parse(sDate2);
  494. dateSpan = sDate2 - sDate1;
  495. dateSpan = Math.abs(dateSpan);
  496. iDays = compareSec ? dateSpan / 1000 : Math.floor(dateSpan / (24 * 3600 * 1000));
  497. return iDays;
  498. },
  499. isEmpty: function (obj) {
  500. var s = obj == null || obj == undefined ? "" : obj.toString().replace(/^\s+/, "").replace(/\s+$/, "");
  501. return s.length == 0;
  502. },
  503. isObjEmpty: function (obj) {
  504. for (var prop in obj) {
  505. if (obj.hasOwnProperty(prop))
  506. return false;
  507. }
  508. return true;
  509. },
  510. defaultIdcard: function (data) {
  511. if (typeof (data) == "undefined") {
  512. return "";
  513. }
  514. var self = this;
  515. for (var i in data) {
  516. data[i]['cardTypeStr'] = self.cardType(data[i]['cardType']);
  517. if (!self.isObjEmpty(data[i]['parent'])) {
  518. data[i]['parent']['cardTypeStr'] = self.cardType(data[i]['parent']['cardType']);
  519. }
  520. }
  521. return data;
  522. },
  523. cardType: function (cardType) {
  524. cardType = typeof (cardType) == "undefined" ? 0 : parseInt(cardType);
  525. return this.config.cardTypeArr[cardType];
  526. },
  527. identityCodeValid: function (code, str) {
  528. str = str.toUpperCase();
  529. if (parseInt(code) == 0) {
  530. var city = {
  531. 11: "北京",
  532. 12: "天津",
  533. 13: "河北",
  534. 14: "山西",
  535. 15: "内蒙古",
  536. 21: "辽宁",
  537. 22: "吉林",
  538. 23: "黑龙江 ",
  539. 31: "上海",
  540. 32: "江苏",
  541. 33: "浙江",
  542. 34: "安徽",
  543. 35: "福建",
  544. 36: "江西",
  545. 37: "山东",
  546. 41: "河南",
  547. 42: "湖北 ",
  548. 43: "湖南",
  549. 44: "广东",
  550. 45: "广西",
  551. 46: "海南",
  552. 50: "重庆",
  553. 51: "四川",
  554. 52: "贵州",
  555. 53: "云南",
  556. 54: "西藏 ",
  557. 61: "陕西",
  558. 62: "甘肃",
  559. 63: "青海",
  560. 64: "宁夏",
  561. 65: "新疆",
  562. 71: "台湾",
  563. 81: "香港",
  564. 82: "澳门",
  565. 91: "国外 "
  566. };
  567. if (!/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(str)) {
  568. return false;
  569. } else if (!city[str.substr(0, 2)]) {
  570. return false;
  571. } else {
  572. str = str.split('');
  573. //∑(ai×Wi)(mod 11)
  574. //加权因子
  575. var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
  576. //校验位
  577. var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
  578. var sum = 0;
  579. var ai = 0;
  580. var wi = 0;
  581. for (var i = 0; i < 17; i++) {
  582. ai = str[i];
  583. wi = factor[i];
  584. sum += ai * wi;
  585. }
  586. var last = parity[sum % 11];
  587. if (parity[sum % 11] != str[17]) {
  588. return false;
  589. }
  590. }
  591. return true;
  592. } else {
  593. return !this.isEmpty(str);
  594. }
  595. },
  596. getSex(psidno) {
  597. var sexno;
  598. if (psidno.length == 18) {
  599. sexno = psidno.substring(16, 17);
  600. } else if (psidno.length == 15) {
  601. sexno = psidno.substring(14, 15);
  602. }
  603. return sexno % 2;
  604. },
  605. ages(str) {
  606. var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
  607. if (r == null) return "成人";
  608. var d = new Date(r[1], r[3] - 1, r[4]);
  609. if (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4]) {
  610. var Y = new Date().getFullYear();
  611. var M = new Date().getMonth() + 1;
  612. var D = new Date().getDate();
  613. return Y - r[1] > 18 || (Y - r[1] == 18 && M - r[3] > 0) || (Y - r[1] == 18 && M - r[3] == 0 && D - r[4] >= 0) ? "成人" : "儿童"
  614. }
  615. return "成人";
  616. },
  617. getAge: function (strBirthday) {
  618. var returnAge, strBirthdayArr = strBirthday.split("-"),
  619. birthYear = strBirthdayArr[0],
  620. birthMonth = strBirthdayArr[1],
  621. birthDay = strBirthdayArr[2],
  622. d = new Date(),
  623. nowYear = d.getFullYear(),
  624. nowMonth = d.getMonth() + 1,
  625. nowDay = d.getDate();
  626. if (nowYear == birthYear) {
  627. returnAge = 0; //同年 则为0岁
  628. } else {
  629. var ageDiff = nowYear - birthYear; //年之差
  630. if (ageDiff > 0) {
  631. if (nowMonth == birthMonth) {
  632. var dayDiff = nowDay - birthDay; //日之差
  633. if (dayDiff < 0) {
  634. returnAge = ageDiff - 1;
  635. } else {
  636. returnAge = ageDiff;
  637. }
  638. } else {
  639. var monthDiff = nowMonth - birthMonth; //月之差
  640. if (monthDiff < 0) {
  641. returnAge = ageDiff - 1;
  642. } else {
  643. returnAge = ageDiff;
  644. }
  645. }
  646. } else {
  647. returnAge = -1; //返回-1 表示出生日期输入错误 晚于今天
  648. }
  649. }
  650. return parseInt(returnAge); //返回周岁年龄
  651. },
  652. // 渠道创建记录
  653. getChannelMsg(channel) {
  654. let that = this;
  655. return new Promise(function (resolve, reject) {
  656. that.ajax({
  657. func: "user/channel/browhistory",
  658. data: {
  659. channelId: channel
  660. }
  661. }, function (res) {
  662. if (res.code == 0) {
  663. resolve(res);
  664. } else {
  665. reject(res);
  666. }
  667. });
  668. })
  669. },
  670. uploadFile(url, files, data = {}, isCall = false) {
  671. let that = this;
  672. return new Promise(function (resolve, reject) {
  673. that.ajax({
  674. func: url,
  675. data: data
  676. }, (res) => {
  677. if (res.code == 0) {
  678. let oss = res.data,
  679. photoArrsm = '';
  680. if (files.indexOf('http://tmp/') != -1) {
  681. photoArrsm = oss.dir + files.replace('http://tmp/', "");
  682. }
  683. if (files.indexOf('wxfile://') != -1) {
  684. photoArrsm = oss.dir + files.replace('wxfile://', "");
  685. }
  686. let formData = {
  687. 'key': photoArrsm,
  688. 'policy': oss.policy,
  689. 'OSSAccessKeyId': oss.accessid,
  690. 'success_action_status': '200', //让服务端返回200,不然,默认会返回204
  691. 'signature': oss.signature
  692. }
  693. if (isCall) formData.callback = oss.callback;
  694. setTimeout(() => {
  695. console.log(that.config.ossImgPath);
  696. const uploadTask = wx.uploadFile({
  697. url: that.config.ossImgPath,
  698. formData: formData,
  699. name: 'file',
  700. filePath: files,
  701. header: {
  702. 'content-type': 'application/json'
  703. },
  704. method: 'post',
  705. success: (res) => {
  706. if (res.statusCode == 200) {
  707. resolve({
  708. code: 0,
  709. uploadTask: uploadTask,
  710. url: that.config.ossImgPath + photoArrsm
  711. });
  712. } else {
  713. reject({
  714. code: -1,
  715. reason: '上传失败,请重新上传。'
  716. });
  717. }
  718. },
  719. fail(info) {
  720. reject({
  721. code: -1,
  722. reason: '上传失败,请重新上传。'
  723. });
  724. }
  725. });
  726. }, 1000);
  727. } else
  728. that.showTips(res.reason);
  729. })
  730. });
  731. },
  732. sendMessage: function (options, callBack) {
  733. console.log(options.key);
  734. if (typeof options != "object") return false;
  735. options.vid = ".code";
  736. var timer;
  737. this.ajax({
  738. func: "sendmcode",
  739. data: {
  740. phone: options['phone'],
  741. "type": options.type,
  742. key: options.key
  743. },
  744. load: options['load'] ? options['load'] : false,
  745. method: "POST",
  746. }, function (res) {
  747. if (res.code == 0) {
  748. btnTimer(options, function (text) {
  749. res.text = text;
  750. callBack(res);
  751. });
  752. } else {
  753. callBack(res);
  754. }
  755. });
  756. function btnTimer(options, callBack) {
  757. console.log(options.time);
  758. var i = options.time;
  759. timer = setInterval(function () {
  760. if (i == 0) {
  761. callBack(i);
  762. clearInterval(timer);
  763. } else {
  764. callBack(i);
  765. i--;
  766. }
  767. }, 1000);
  768. }
  769. },
  770. // 微信支付
  771. WXPay(data, aid, title, alone, method) {
  772. let that = this,
  773. app = getApp(),
  774. userInfo = app.globalData.userInfo;
  775. data.applet = '1';
  776. data.tradeType = 'JSAPI';
  777. data.openid = userInfo.socialUid;
  778. console.log(data);
  779. return new Promise(function (resolve, reject) {
  780. that.ajax({
  781. func: "weixin/npre", //获取微信支付所需信息
  782. data: data,
  783. load: true,
  784. title: '请求中'
  785. // method:'POST'
  786. }, function (res) {
  787. if (res.code == 0) {
  788. let datas = res.data;
  789. wx.requestPayment({
  790. 'timeStamp': datas.timestamp,
  791. 'nonceStr': datas.nonce_str,
  792. 'package': datas.package,
  793. 'signType': datas.signType,
  794. 'paySign': datas.sign,
  795. 'success': function (result) {
  796. that.payResultWait(datas.orderid)
  797. wx.reportAnalytics('order_pay', {
  798. aid: aid,
  799. title: title,
  800. });
  801. resolve({
  802. orderid: datas.orderid,
  803. tradeChannelWeixin: res.tradeChannelWeixin,
  804. btype: data.btype
  805. });
  806. //CMBC --民生支付
  807. },
  808. 'fail': function (result) {
  809. wx.showModal({
  810. title: '提示',
  811. content: '订单有5分钟的支付时间,超时后将自动取消订单,确定暂不支付?',
  812. confirmText: '继续支付',
  813. cancelText: '暂不支付',
  814. confirmColor: '#ee3a43',
  815. success: function (res) {
  816. if (res.confirm) {
  817. data.orderid = datas.orderid;
  818. if (data.btype == 2) {
  819. data.btype = 0;
  820. }
  821. that.WXPay(data, aid, title, alone).then((orderid) => {
  822. var pages = getCurrentPages()
  823. var currentPage = pages[pages.length - 2];
  824. if (currentPage.route == "pages/product/activity/index" || currentPage.route == "pages/order/index/order" || currentPage.route == "pages/order/detail/index") {
  825. let info = [];
  826. info.push('orderid=' + orderid)
  827. info.push('alone=' + alone)
  828. info.push('btype=' + data.btype)
  829. if (data.btype == 1) {
  830. info.push('presellOpen=' + method)
  831. } else if (data.btype == 2) {
  832. info.push('presellStatus=' + method)
  833. } else {
  834. info.push('presellOpen=' + method)
  835. }
  836. // wx.navigateTo({
  837. // url: '/pages/order/success/index?orderid=' + orderid + '&alone=' + alone + '&presellOpen='+method+'&btype='+data.btype
  838. // });
  839. wx.navigateTo({
  840. url: '/pages/order/success/index?' + info.join('&')
  841. });
  842. }
  843. })
  844. } else if (res.cancel) {
  845. // if(!that.isEmpty(data.orderid)){
  846. // that.ajax({
  847. // func: 'order/pay/cancel',
  848. // data: { "oldOrderid": data.orderid, "orderid": datas.orderid },
  849. // load: false
  850. // }, function (res) {
  851. // reject(res);
  852. // });
  853. // }else {
  854. // reject(res);
  855. // }
  856. var pages = getCurrentPages()
  857. var currentPage = pages[pages.length - 1]
  858. if (currentPage.route == "pages/product/buy/index") {
  859. let info = 'orderid=' + datas.orderid + '&otype=1';
  860. if (data.btype == 1) {
  861. info = method == 0 ? (info + '&presellStatus=0') : (info + '&presellStatus=1')
  862. } else if (data.btype == 2) {
  863. info = info + '&presellStatus=' + method
  864. } else if (data.btype == 0) {
  865. info = info + '&presellStatus=0'
  866. } else if (data.btype == 3) {
  867. info = info + '&presellStatus=0'
  868. }
  869. wx.navigateTo({
  870. url: '/pages/order/detail/index?' + info
  871. })
  872. }
  873. if (currentPage.route == 'pages/product/balancePayment/balancePayment') {
  874. let info = 'orderid=' + datas.orderid + '&otype=1' + '&presellStatus=2'
  875. wx.navigateTo({
  876. url: '/pages/order/detail/index?' + info
  877. })
  878. }
  879. }
  880. }
  881. })
  882. }
  883. })
  884. } else {
  885. reject(res);
  886. }
  887. });
  888. });
  889. },
  890. ajax: function (options, success) {
  891. let app = getApp(),
  892. that = this;
  893. options.data = typeof (options.data) != "undefined" ? options.data : {};
  894. options.load = typeof (options.load) == "undefined" ? false : options.load;
  895. options.title = typeof (options.title) == "undefined" ? false : options.title;
  896. options.method = typeof (options.method) == "undefined" ? "GET" : options.method;
  897. if (options.load && options.title) {//评价相关接口调用弹窗避免重复调用
  898. wx.showLoading({
  899. title: options.title,
  900. mask: true
  901. });
  902. } else if (options.load) {
  903. wx.showLoading({
  904. title: '加载中…'
  905. });
  906. }
  907. for (let key in options.data) {
  908. if (options.data[key] === 'undefined') {
  909. options.data[key] = '';
  910. }
  911. }
  912. options.data['city'] = options.data['city'] || "永康" || "";
  913. options.data['platform'] = 1;
  914. // options.data['lat'] = app.globalData.city.latitude || "";
  915. // options.data['lng'] = app.globalData.city.longitude || "";
  916. options.data['rid'] = app.globalData.userInfo ? app.globalData.userInfo['rid'] : "";
  917. options.data['channel'] = options.data['channel'] || "applet";
  918. options.contentType = typeof (options.contentType) == "undefined" ? "application/json" : options.contentType;
  919. console.log(options.data, 7878)
  920. wx.request({
  921. url: this.getRequestURL(options.func),
  922. data: options.data,
  923. method: options.method,
  924. header: {
  925. "content-type": options.contentType
  926. },
  927. success(res) {
  928. options.load ? wx.hideLoading() : "";
  929. if (res.statusCode == 200) {
  930. if (res.data.code == 1004 || res.data.code == 1005) {
  931. wx.removeStorageSync("WXuserInfo");
  932. wx.removeStorageSync("nps")
  933. app.globalData.userInfo = null;
  934. if (res.data.code == 1004) {
  935. wx.navigateTo({
  936. url: '/pages/home/login'
  937. });
  938. }
  939. return false;
  940. }
  941. typeof (success) == "function" ? success(res.data) : "";
  942. } else {
  943. that.showTips("网络请求失败。");
  944. typeof (success) == "function" ? success(res) : "";
  945. }
  946. }
  947. });
  948. },
  949. // loadCity: function (callback, type) {
  950. // var self = this;
  951. // ({
  952. // type: 'wgs84',
  953. // success: function (res) {
  954. // var myAmapFun = new self.amapFile.AMapWX({
  955. // key: "4048819e3a45aa1cbac417a4e45f44aa"
  956. // }); // oldKey —— bae2697f5d1a1e5db9dd855e7cd083bf
  957. // myAmapFun.getRegeo({
  958. // location: res.longitude + ',' + res.latitude,
  959. // success: function (data) {
  960. // data[0]['regeocodeData']['addressComponent']['latitude'] = res.latitude;
  961. // data[0]['regeocodeData']['addressComponent']['longitude'] = res.longitude;
  962. // if (typeof (data[0]['regeocodeData']['addressComponent']['city']) == "object") {
  963. // data[0]['regeocodeData']['addressComponent']['city'] = data[0]['regeocodeData']['addressComponent']['city'].join("");
  964. // }
  965. // data[0]['regeocodeData']['addressComponent']['city'] = self.isEmpty(data[0]['regeocodeData']['addressComponent']['city']) ? data[0]['regeocodeData']['addressComponent']['province'] : data[0]['regeocodeData']['addressComponent']['city'];
  966. // data[0]['regeocodeData']['addressComponent']['city'] = data[0]['regeocodeData']['addressComponent']['city'].replace("市", "");
  967. // self.businessCity().then(function (citys) {
  968. // let getCity = wx.getStorageSync("city") || {};
  969. // if (citys.includes(data[0]['regeocodeData']['addressComponent']['city']) || !self.isObjEmpty(getCity)) {
  970. // if (!self.isObjEmpty(getCity) && type == undefined) data[0]['regeocodeData']['addressComponent'] = getCity;
  971. // typeof (callback) == "function" ? callback({
  972. // code: 0,
  973. // data: data[0]['regeocodeData']['addressComponent'],
  974. // msg: "省市获取成功。"
  975. // }): "";
  976. // } else {
  977. // typeof (callback) == "function" ? callback({
  978. // code: 2,
  979. // data: data[0]['regeocodeData']['addressComponent'],
  980. // msg: "省市获取失败。"
  981. // }): "";
  982. // }
  983. // });
  984. // },
  985. // });
  986. // },
  987. // fail: function (info) {
  988. // typeof (callback) == "function" ? callback({
  989. // code: 1,
  990. // data: {
  991. // city: "未知城市"
  992. // },
  993. // msg: "省市获取失败。"
  994. // }): "";
  995. // }
  996. // });
  997. // },
  998. // 支付成功后调用(不做回调处理)
  999. payResultWait(orderid) {
  1000. let that = this;
  1001. that.ajax({
  1002. func: 'weixin/order/result/wait',
  1003. data: {
  1004. orderid: orderid
  1005. },
  1006. load: false
  1007. }, function (res) { });
  1008. },
  1009. businessCity() {
  1010. let that = this;
  1011. return new Promise(function (resolve, reject) {
  1012. that.ajax({
  1013. func: 'city_list',
  1014. load: false
  1015. }, function (res) {
  1016. if (res.code == 0) {
  1017. resolve(res.data.city);
  1018. } else {
  1019. reject();
  1020. }
  1021. });
  1022. });
  1023. },
  1024. refreshCount() {
  1025. let that = this,
  1026. app = getApp();
  1027. if (app != undefined && !that.isObjEmpty(app.globalData.userInfo)) {
  1028. that.ajax({
  1029. func: "user/stat_info",
  1030. load: false
  1031. }, function (res) {
  1032. if (res.data) {
  1033. let userInfo = app.globalData.userInfo;
  1034. userInfo['membered'] = res.data.membered;
  1035. userInfo['babyCoin'] = that.toMoney(res.data.coin, ",");
  1036. res.data.score = Math.round(res.data.score);
  1037. userInfo['role'] = that.userRole(res.data.score);
  1038. userInfo['roleType'] = res.data.roleType || 'normal';
  1039. userInfo['roleTypeDisable'] = res.data.roleTypeDisable || 0;
  1040. userInfo['score'] = res.data.score;
  1041. userInfo['weixin'] = res.data.weixin || 0;
  1042. app.globalData.userInfo = userInfo;
  1043. wx.setStorageSync("WXuserInfo", userInfo);
  1044. }
  1045. });
  1046. }
  1047. },
  1048. userRole: function (val) {
  1049. var that = this,
  1050. str = that.config.userRole[0];
  1051. for (let i = 0; i < that.config.userRole.length; i++) {
  1052. if (parseFloat(val) >= parseFloat(that.config.userRole[i].startPoint) && (that.config.userRole[i].endPoint == undefined || parseFloat(val) <= parseFloat(that.config.userRole[i].endPoint))) {
  1053. str = that.config.userRole[i];
  1054. }
  1055. }
  1056. return str;
  1057. },
  1058. // 完成宝贝币任务
  1059. finishCoinTask(taskId, onlyCoin) {
  1060. let that = this;
  1061. return new Promise(function (resolve, reject) {
  1062. that.ajax({
  1063. func: "v2/user_coin/task/pass",
  1064. data: {
  1065. taskId: taskId
  1066. },
  1067. method: "POST",
  1068. load: false
  1069. }, function (res) {
  1070. if (res.code == 0) {
  1071. if (onlyCoin) {
  1072. resolve(res.data)
  1073. } else {
  1074. let text = '恭喜你完成任务,获得' + res.data + '枚宝贝币'
  1075. resolve(text)
  1076. }
  1077. } else {
  1078. resolve(res.reason)
  1079. }
  1080. });
  1081. })
  1082. },
  1083. // 通过小程序码进入的获取活动aid
  1084. codeGetAid(aid) {
  1085. let that = this;
  1086. return new Promise(function (resolve, reject) {
  1087. that.ajax({
  1088. func: "v2/article/aid",
  1089. data: {
  1090. "aid": aid
  1091. }
  1092. }, function (res) {
  1093. if (res.code == 0) {
  1094. resolve(res)
  1095. } else {
  1096. reject(res)
  1097. }
  1098. });
  1099. })
  1100. },
  1101. promise: function () {
  1102. var that = this,
  1103. app = getApp();
  1104. return new Promise(function (resolve, reject) {
  1105. // that.loadCity(function (res) {
  1106. // let city = app.globalData.city;
  1107. // if (res.code == 0) { //获取地址成功
  1108. // app.globalData.locationCity = res.data.city;
  1109. // if (!that.isObjEmpty(city) && res.data.city != city.city && app.globalData.path == 'pages/index/index') {
  1110. // wx.hideLoading();
  1111. // wx.showModal({
  1112. // title: "温馨提示",
  1113. // content: "自动定位地理位置为“" + res.data.city + "”,是否切换到“" + res.data.city + "”?",
  1114. // success: function (d) {
  1115. // if (d.confirm) {
  1116. // app.globalData.previous = city.city;
  1117. // app.globalData.city = res.data;
  1118. // wx.setStorageSync("city", app.globalData.city);
  1119. // resolve(true)
  1120. // } else {
  1121. // resolve(true)
  1122. // }
  1123. // }
  1124. // });
  1125. // } else {
  1126. // app.globalData.city = res.data;
  1127. // wx.setStorageSync("city", app.globalData.city);
  1128. // resolve(true)
  1129. // }
  1130. // } else if (res.code == 1 || res.code == 2) { //获取地址失败
  1131. // if (that.isObjEmpty(city) || res.code == 2) { //全局地址为空
  1132. // var e = getCurrentPages(),
  1133. // url = (e.length <= 0 ? "/pages/index/index" : "/" + (e[e.length - 1].route));
  1134. // reject('reject');
  1135. // app.globalData.city = {};
  1136. // wx.removeStorageSync("city");
  1137. // wx.redirectTo({
  1138. // url: '/pages/city/list?query=selectCity&url=' + url
  1139. // });
  1140. // } else { //全局地址city['city']存在
  1141. // resolve(true)
  1142. // }
  1143. // }
  1144. that.refreshCount();
  1145. // });
  1146. })
  1147. },
  1148. // 静默登录
  1149. silentLogin() {
  1150. let that = this;
  1151. let app = getApp();
  1152. return new Promise(function (resolve, reject) {
  1153. wx.login({
  1154. success: res => {
  1155. let it = {};
  1156. it.version = "applet_v1.0.0";
  1157. it.code = res.code;
  1158. it.target = 'challengerhome';
  1159. that.ajax({
  1160. func: "applet_login",
  1161. data: it
  1162. }, function (data) {
  1163. if (data.code == 0) {
  1164. // 第一次登录未注册
  1165. if (data.data.firstLogin == 1) {
  1166. wx.navigateTo({
  1167. url: '/pages/home/login',
  1168. });
  1169. reject()
  1170. } else {
  1171. data.data.role = that.userRole(Math.round(data.data.score));
  1172. // 强制退出登录
  1173. data.data.VERSION = 9
  1174. wx.setStorageSync("WXuserInfo", data.data);
  1175. app.globalData.userInfo = data.data
  1176. resolve()
  1177. }
  1178. } else {
  1179. that.showTips(data.reason);
  1180. }
  1181. });
  1182. }
  1183. });
  1184. })
  1185. }
  1186. }