util.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  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. app.globalData.userInfo = null;
  933. if (res.data.code == 1004) {
  934. wx.navigateTo({
  935. url: '/pages/home/login'
  936. });
  937. }
  938. return false;
  939. }
  940. typeof (success) == "function" ? success(res.data) : "";
  941. } else {
  942. that.showTips("网络请求失败。");
  943. typeof (success) == "function" ? success(res) : "";
  944. }
  945. }
  946. });
  947. },
  948. // loadCity: function (callback, type) {
  949. // var self = this;
  950. // ({
  951. // type: 'wgs84',
  952. // success: function (res) {
  953. // var myAmapFun = new self.amapFile.AMapWX({
  954. // key: "4048819e3a45aa1cbac417a4e45f44aa"
  955. // }); // oldKey —— bae2697f5d1a1e5db9dd855e7cd083bf
  956. // myAmapFun.getRegeo({
  957. // location: res.longitude + ',' + res.latitude,
  958. // success: function (data) {
  959. // data[0]['regeocodeData']['addressComponent']['latitude'] = res.latitude;
  960. // data[0]['regeocodeData']['addressComponent']['longitude'] = res.longitude;
  961. // if (typeof (data[0]['regeocodeData']['addressComponent']['city']) == "object") {
  962. // data[0]['regeocodeData']['addressComponent']['city'] = data[0]['regeocodeData']['addressComponent']['city'].join("");
  963. // }
  964. // data[0]['regeocodeData']['addressComponent']['city'] = self.isEmpty(data[0]['regeocodeData']['addressComponent']['city']) ? data[0]['regeocodeData']['addressComponent']['province'] : data[0]['regeocodeData']['addressComponent']['city'];
  965. // data[0]['regeocodeData']['addressComponent']['city'] = data[0]['regeocodeData']['addressComponent']['city'].replace("市", "");
  966. // self.businessCity().then(function (citys) {
  967. // let getCity = wx.getStorageSync("city") || {};
  968. // if (citys.includes(data[0]['regeocodeData']['addressComponent']['city']) || !self.isObjEmpty(getCity)) {
  969. // if (!self.isObjEmpty(getCity) && type == undefined) data[0]['regeocodeData']['addressComponent'] = getCity;
  970. // typeof (callback) == "function" ? callback({
  971. // code: 0,
  972. // data: data[0]['regeocodeData']['addressComponent'],
  973. // msg: "省市获取成功。"
  974. // }): "";
  975. // } else {
  976. // typeof (callback) == "function" ? callback({
  977. // code: 2,
  978. // data: data[0]['regeocodeData']['addressComponent'],
  979. // msg: "省市获取失败。"
  980. // }): "";
  981. // }
  982. // });
  983. // },
  984. // });
  985. // },
  986. // fail: function (info) {
  987. // typeof (callback) == "function" ? callback({
  988. // code: 1,
  989. // data: {
  990. // city: "未知城市"
  991. // },
  992. // msg: "省市获取失败。"
  993. // }): "";
  994. // }
  995. // });
  996. // },
  997. // 支付成功后调用(不做回调处理)
  998. payResultWait(orderid) {
  999. let that = this;
  1000. that.ajax({
  1001. func: 'weixin/order/result/wait',
  1002. data: {
  1003. orderid: orderid
  1004. },
  1005. load: false
  1006. }, function (res) { });
  1007. },
  1008. businessCity() {
  1009. let that = this;
  1010. return new Promise(function (resolve, reject) {
  1011. that.ajax({
  1012. func: 'city_list',
  1013. load: false
  1014. }, function (res) {
  1015. if (res.code == 0) {
  1016. resolve(res.data.city);
  1017. } else {
  1018. reject();
  1019. }
  1020. });
  1021. });
  1022. },
  1023. refreshCount() {
  1024. let that = this,
  1025. app = getApp();
  1026. if (app != undefined && !that.isObjEmpty(app.globalData.userInfo)) {
  1027. that.ajax({
  1028. func: "user/stat_info",
  1029. load: false
  1030. }, function (res) {
  1031. if (res.data) {
  1032. let userInfo = app.globalData.userInfo;
  1033. userInfo['membered'] = res.data.membered;
  1034. userInfo['babyCoin'] = that.toMoney(res.data.coin, ",");
  1035. res.data.score = Math.round(res.data.score);
  1036. userInfo['role'] = that.userRole(res.data.score);
  1037. userInfo['roleType'] = res.data.roleType || 'normal';
  1038. userInfo['roleTypeDisable'] = res.data.roleTypeDisable || 0;
  1039. userInfo['score'] = res.data.score;
  1040. userInfo['weixin'] = res.data.weixin || 0;
  1041. app.globalData.userInfo = userInfo;
  1042. wx.setStorageSync("WXuserInfo", userInfo);
  1043. }
  1044. });
  1045. }
  1046. },
  1047. userRole: function (val) {
  1048. var that = this,
  1049. str = that.config.userRole[0];
  1050. for (let i = 0; i < that.config.userRole.length; i++) {
  1051. if (parseFloat(val) >= parseFloat(that.config.userRole[i].startPoint) && (that.config.userRole[i].endPoint == undefined || parseFloat(val) <= parseFloat(that.config.userRole[i].endPoint))) {
  1052. str = that.config.userRole[i];
  1053. }
  1054. }
  1055. return str;
  1056. },
  1057. // 完成宝贝币任务
  1058. finishCoinTask(taskId, onlyCoin) {
  1059. let that = this;
  1060. return new Promise(function (resolve, reject) {
  1061. that.ajax({
  1062. func: "v2/user_coin/task/pass",
  1063. data: {
  1064. taskId: taskId
  1065. },
  1066. method: "POST",
  1067. load: false
  1068. }, function (res) {
  1069. if (res.code == 0) {
  1070. if (onlyCoin) {
  1071. resolve(res.data)
  1072. } else {
  1073. let text = '恭喜你完成任务,获得' + res.data + '枚宝贝币'
  1074. resolve(text)
  1075. }
  1076. } else {
  1077. resolve(res.reason)
  1078. }
  1079. });
  1080. })
  1081. },
  1082. // 通过小程序码进入的获取活动aid
  1083. codeGetAid(aid) {
  1084. let that = this;
  1085. return new Promise(function (resolve, reject) {
  1086. that.ajax({
  1087. func: "v2/article/aid",
  1088. data: {
  1089. "aid": aid
  1090. }
  1091. }, function (res) {
  1092. if (res.code == 0) {
  1093. resolve(res)
  1094. } else {
  1095. reject(res)
  1096. }
  1097. });
  1098. })
  1099. },
  1100. promise: function () {
  1101. var that = this,
  1102. app = getApp();
  1103. return new Promise(function (resolve, reject) {
  1104. // that.loadCity(function (res) {
  1105. // let city = app.globalData.city;
  1106. // if (res.code == 0) { //获取地址成功
  1107. // app.globalData.locationCity = res.data.city;
  1108. // if (!that.isObjEmpty(city) && res.data.city != city.city && app.globalData.path == 'pages/index/index') {
  1109. // wx.hideLoading();
  1110. // wx.showModal({
  1111. // title: "温馨提示",
  1112. // content: "自动定位地理位置为“" + res.data.city + "”,是否切换到“" + res.data.city + "”?",
  1113. // success: function (d) {
  1114. // if (d.confirm) {
  1115. // app.globalData.previous = city.city;
  1116. // app.globalData.city = res.data;
  1117. // wx.setStorageSync("city", app.globalData.city);
  1118. // resolve(true)
  1119. // } else {
  1120. // resolve(true)
  1121. // }
  1122. // }
  1123. // });
  1124. // } else {
  1125. // app.globalData.city = res.data;
  1126. // wx.setStorageSync("city", app.globalData.city);
  1127. // resolve(true)
  1128. // }
  1129. // } else if (res.code == 1 || res.code == 2) { //获取地址失败
  1130. // if (that.isObjEmpty(city) || res.code == 2) { //全局地址为空
  1131. // var e = getCurrentPages(),
  1132. // url = (e.length <= 0 ? "/pages/index/index" : "/" + (e[e.length - 1].route));
  1133. // reject('reject');
  1134. // app.globalData.city = {};
  1135. // wx.removeStorageSync("city");
  1136. // wx.redirectTo({
  1137. // url: '/pages/city/list?query=selectCity&url=' + url
  1138. // });
  1139. // } else { //全局地址city['city']存在
  1140. // resolve(true)
  1141. // }
  1142. // }
  1143. that.refreshCount();
  1144. // });
  1145. })
  1146. },
  1147. // 静默登录
  1148. silentLogin() {
  1149. let that = this;
  1150. let app = getApp();
  1151. return new Promise(function (resolve, reject) {
  1152. wx.login({
  1153. success: res => {
  1154. let it = {};
  1155. it.version = "applet_v1.0.0";
  1156. it.code = res.code;
  1157. it.target = 'challengerhome';
  1158. that.ajax({
  1159. func: "applet_login",
  1160. data: it
  1161. }, function (data) {
  1162. if (data.code == 0) {
  1163. // 第一次登录未注册
  1164. if (data.data.firstLogin == 1) {
  1165. wx.navigateTo({
  1166. url: '/pages/home/login',
  1167. });
  1168. reject()
  1169. } else {
  1170. data.data.role = that.userRole(Math.round(data.data.score));
  1171. // 强制退出登录
  1172. data.data.VERSION = 9
  1173. wx.setStorageSync("WXuserInfo", data.data);
  1174. app.globalData.userInfo = data.data
  1175. resolve()
  1176. }
  1177. } else {
  1178. that.showTips(data.reason);
  1179. }
  1180. });
  1181. }
  1182. });
  1183. })
  1184. }
  1185. }