index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. import regeneratorRuntime, { async } from './runtime';
  2. import './polyfill'
  3. import api from './api.js'
  4. import extend from './util.js'
  5. import {
  6. md5
  7. } from './md5.js'
  8. let app = null;
  9. setTimeout(_ => app = getApp())
  10. const getcitycode = (province, city) => {
  11. let code = '',
  12. clist = citycode.find(x => x["省"] == province.replace(/.$/, ''))
  13. if (clist && clist["市"]) {
  14. let c = clist["市"].find(x => x["市名"] == city.replace(/.$/, ''))
  15. if (c) code = c['编码']
  16. }
  17. return code;
  18. }
  19. const pvw = doc => {
  20. wx.showLoading({
  21. title: '文件加载中...',
  22. mask: true
  23. })
  24. wx.downloadFile({
  25. url: doc,
  26. success: ({
  27. tempFilePath: filePath
  28. }) => {
  29. wx.openDocument({
  30. filePath
  31. })
  32. },
  33. fail: _ => showTip("文件下载失败"),
  34. complete: () => {
  35. wx.hideLoading()
  36. }
  37. })
  38. }
  39. function pvw_native({
  40. currentTarget: {
  41. dataset: {
  42. doc
  43. }
  44. }
  45. }) {
  46. pvw(doc)
  47. }
  48. const formatTime = date => {
  49. const year = date.getFullYear()
  50. const month = date.getMonth() + 1
  51. const day = date.getDate()
  52. const hour = date.getHours()
  53. const minute = date.getMinutes()
  54. const second = date.getSeconds()
  55. return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  56. }
  57. const formatNumber = n => {
  58. n = n.toString()
  59. return n[1] ? n : '0' + n
  60. }
  61. function getHello() {
  62. let now = new Date(),
  63. hour = now.getHours(),
  64. hello;
  65. if (hour < 6) {
  66. hello = "凌晨好";
  67. } else if (hour < 9) {
  68. hello = "早上好!";
  69. } else if (hour < 12) {
  70. hello = "上午好!";
  71. } else if (hour < 14) {
  72. hello = "中午好!";
  73. } else if (hour < 17) {
  74. hello = "下午好!";
  75. } else if (hour < 19) {
  76. hello = "傍晚好!";
  77. } else if (hour < 22) {
  78. hello = "晚上好!";
  79. } else {
  80. hello = "夜里好!";
  81. }
  82. return hello;
  83. }
  84. function getCurrentDate() {
  85. var date = new Date();
  86. var year = date.getFullYear();
  87. var month = date.getMonth() + 1;
  88. var day = date.getDate();
  89. var hour = date.getHours();
  90. var minute = date.getMinutes();
  91. if (month >= 1 && month <= 9) {
  92. month = "0" + month;
  93. }
  94. if (day >= 0 && day <= 9) {
  95. day = "0" + day;
  96. }
  97. if (hour >= 0 && hour <= 9) {
  98. hour = "0" + hour;
  99. }
  100. if (minute >= 0 && minute <= 9) {
  101. minute = "0" + minute;
  102. }
  103. var data = {
  104. date: year + '-' + month + '-' + day,
  105. time: hour + ':' + minute
  106. }
  107. return data;
  108. }
  109. //时间判断
  110. function getApplyTime(time) {
  111. var timeStamp = time.replace('T', ' ');
  112. timeStamp = new Date(timeStamp.replace(/-/g, '/')).getTime();
  113. var timeStampNow = new Date().getTime();
  114. var str = (timeStampNow - timeStamp) / 1000 / 60;
  115. var applyTime = '';
  116. var newDate = new Date(time.replace('T', ' '));
  117. if (str <= 1) {
  118. applyTime = '1分钟前';
  119. }
  120. if (str > 1 && str < 60) {
  121. applyTime = parseInt(str) + '分钟前';
  122. }
  123. if (str >= 60 && str < 60 * 24) {
  124. applyTime = parseInt(str / 60) + '小时前';
  125. }
  126. if (str >= 60 * 24 && str <= 60 * 24 * 2) {
  127. applyTime = '昨天';
  128. }
  129. if (str > 60 * 24 * 2 && str <= 60 * 24 * 5) {
  130. applyTime = parseInt(str / 60 / 24) + '天前';
  131. }
  132. if (str > 60 * 24 * 5 && str <= 60 * 24 * 365) {
  133. applyTime = time.slice(5, 10);
  134. }
  135. if (str > 60 * 24 * 365) {
  136. applyTime = time.slice(0, 10);
  137. }
  138. return applyTime;
  139. }
  140. function navigate(url, t) {
  141. if (!url) return;
  142. app.globalData.url_param = param2Obj(url)
  143. return new Promise(success => {
  144. if (t) return wx[t]({
  145. url,
  146. success
  147. })
  148. wx.navigateTo({
  149. url,
  150. success,
  151. fail: _ => wx.redirectTo({
  152. url,
  153. success,
  154. fail: _ => wx.switchTab({
  155. url,
  156. success
  157. })
  158. })
  159. })
  160. })
  161. };
  162. function navigate_native({
  163. currentTarget: {
  164. dataset: {
  165. url,
  166. t
  167. }
  168. }
  169. }) {
  170. return navigate(url, t)
  171. }
  172. function navigate_auth_native({
  173. currentTarget: {
  174. dataset: {
  175. url,
  176. t
  177. }
  178. }
  179. }) {
  180. return _auth()._err || navigate(url, t)
  181. }
  182. function showTip(title) {
  183. wx.showToast({
  184. title,
  185. icon: 'none'
  186. })
  187. }
  188. function telephone_native({
  189. currentTarget: {
  190. dataset: {
  191. num: phoneNumber
  192. }
  193. }
  194. }) {
  195. wx.makePhoneCall({
  196. phoneNumber
  197. })
  198. }
  199. const login_err = {
  200. _err: {
  201. errmsg: '用户未登录',
  202. errno: 401,
  203. status: false
  204. }
  205. },
  206. _auth = ({ loginTip = true, realNameTip = false } = {}) => {
  207. if (realNameTip) {
  208. if (_auth()._err) return
  209. if (app.globalData.userInfo && app.globalData.userInfo.isRealname == "2") {
  210. wx.showModal({
  211. title: '您尚未实名认证',
  212. content: '是否立即前往用户信息进行认证',
  213. success: ({ confirm }) => confirm && navigate('/pages/user/myInfo/index')
  214. })
  215. return {
  216. _err: {
  217. errmsg: '用户未实名认证',
  218. errno: 401,//后台尚未验证实名 没有相对应的errno
  219. status: false
  220. }
  221. }
  222. }
  223. }
  224. if (app.globalData.userId) return app.globalData.userId
  225. loginTip && wx.showModal({
  226. title: '提示',
  227. content: '帐号未登录,是否跳转至登录页面',
  228. showCancel: true,
  229. success: ({
  230. confirm
  231. }) => confirm && goLogin()
  232. })
  233. wx.hideLoading()
  234. return login_err
  235. },
  236. goLogin = () => navigate('/pages/login/index'),
  237. goHome = () => navigate('/pages/home/index', 'switchTab'),
  238. goSuccess = (type, id) => navigate(`/pages/success/index?type=${type}&id=${id}`, 'reLaunch'),
  239. request = async ({
  240. url,
  241. data = {},
  242. method = "get",
  243. loading = false,
  244. loadingMsg = '',
  245. realNameTip = false,
  246. loadingHide = true
  247. }) => {
  248. wx.showNavigationBarLoading()
  249. loading && wx.showLoading({
  250. title: loadingMsg || '网络请求中...',
  251. mask: true
  252. })
  253. if (realNameTip) {
  254. let { _err } = _auth({ realNameTip })
  255. if (_err) return _err
  256. }
  257. return await new Promise((resolve, reject) => wx.request({
  258. url,
  259. data,
  260. method,
  261. success({
  262. data
  263. }) {
  264. let {
  265. errmsg,
  266. errno = 0,
  267. errcode = 0, //兼容第三方接口
  268. data: _data = data
  269. } = data
  270. if (errcode || errno)
  271. return reject({
  272. errmsg,
  273. errno: errno || errcode
  274. })
  275. return resolve(_data || { _err: null })
  276. },
  277. fail: reject,
  278. complete() {
  279. wx.hideNavigationBarLoading()
  280. loading && loadingHide && wx.hideLoading()
  281. }
  282. })).catch(({
  283. errmsg,
  284. errno = -100
  285. }) => {
  286. let status = false; //标记错误信息是否需要调用者处理
  287. switch (errno) {
  288. case -1:
  289. showTip('系统发生未知错误 请稍后重试')
  290. break
  291. case 401:
  292. goLogin()
  293. break
  294. case 402://缺少参数
  295. case 503://签名校验错误
  296. showTip('api接口请求失败')
  297. break
  298. case 501://验证码错误
  299. case 505://查询不到验证码
  300. showTip('短信验证码验证失败')
  301. break
  302. case -100:
  303. showTip('网络请求失败')
  304. break
  305. default:
  306. status = true
  307. }
  308. return {
  309. _err: {
  310. errmsg,
  311. errno,
  312. status
  313. }
  314. }
  315. })
  316. },
  317. get = async (url, data, options) => await request({ url, data, ...options }),
  318. post = async (url, data, options) => await get(url, data, { ...options, method: "post" }),
  319. get_auth = async (url, data, options = {}) => {
  320. let userId = _auth(options)
  321. if (userId._err) return userId
  322. return await get(url, Object.assign({}, data, { userId }), options)
  323. },
  324. post_auth = async (url, data, options) => await get_auth(url, data, { ...options, method: "post" }),
  325. getUserInfo = async ({ realNameTip, loading, loadingHide = true } = {}) => {
  326. if (!app.globalData.userInfo) {
  327. let { user, _err } = await get_auth(api.getUser, null, { loading, loadingHide, loadingMsg: '获取用户信息中...', })
  328. if (_err) {
  329. logout()
  330. return _err.status ? _auth() : { _err }
  331. }
  332. let { identity, userName, lUsername, lInstitutionName, pPhone, lPhone, isRealname, pDocumentNum, lInstitutionNum, pDocumentType, lInstitutionType } = app.globalData.userInfo = user,
  333. type = identity == '0'
  334. //用户中心显示 -- 主要区别在于法人身份下用户中心显示公司名称或未实名 其他情况下显示法人名称
  335. user.viewName = type ? userName : isRealname == "1" ? lInstitutionName : '未实名'
  336. // 其他页面显示
  337. user.name = type ? userName : lUsername
  338. user.phone = type ? pPhone : lPhone
  339. user.num = type ? pDocumentNum : lInstitutionNum
  340. user.phone = type ? pPhone : lPhone
  341. user.code_type = type ? pDocumentType : lInstitutionType
  342. }
  343. app.globalData.userInfo && realNameTip && _auth({ realNameTip })
  344. return app.globalData.userInfo || {}
  345. },
  346. param2Obj = url => {
  347. const [, search] = url.split('?')
  348. return search ?
  349. JSON.parse(`{"${decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`) : {}
  350. },
  351. get_global_param = () => {
  352. let t = app.globalData.url_param || {}
  353. app.globalData.url_param = {}
  354. return t;
  355. },
  356. isPhone = s => /^[1][3,4,5,6,7,8][0-9]{9}$/.test(s),
  357. isEmail = s => /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(s),
  358. form_verify = (data, verify = data.verify) => Object.keys(verify).map(k => {
  359. const v = data[k] || "", t = verify[k]
  360. if (t instanceof Function) return t(v, data)
  361. if (!v.length) return t
  362. }).filter(x => x)[0],
  363. getWeatherInfo = async () => {
  364. if (!app.globalData.weather) {
  365. let { wea, tem1, tem2, win, win_speed, wea_img, _err } = await get('https://www.tianqiapi.com/api/?version=v6&cityid=101180916&appid=37466447&appsecret=SjV4LAvH')
  366. if (_err) return _err.status && showTip('天气信息加载失败') // 免费的第三方接口 终归是靠不住的
  367. app.globalData.weather = {
  368. text: ` ${wea} ${tem2}℃~${tem1}℃ ${win}${win_speed}`,
  369. img: wea_img && `https://xuesax.com/tianqiapi/skin/pitaya/${wea_img}.png`
  370. }
  371. }
  372. return app.globalData.weather
  373. }, logout = () => {
  374. app.globalData.userId = 0
  375. app.globalData.userInfo = null
  376. // wx.clearStorage()
  377. wx.removeStorageSync("userId")
  378. };
  379. function inputChange({
  380. target: {
  381. dataset: {
  382. field
  383. }
  384. },
  385. detail: {
  386. value
  387. }
  388. }) {
  389. this.setData({
  390. [field]: value
  391. })
  392. }
  393. function pickerChange({ currentTarget: { dataset: { _index } }, detail: { value } }) {
  394. this._pickerChange(_index, value | 0)
  395. }
  396. function init(context) {
  397. const { data } = context
  398. let timer, t = {}
  399. context._setData = context.setData.bind(context)
  400. context.form_verify = value => form_verify(Object.assign(data, value))
  401. context.setData = x => {
  402. clearTimeout(timer)
  403. Object.assign(data, Object.assign(t, x))
  404. timer = setTimeout(() => t = context._setData({ ...t, _verify: !context.form_verify() }) || {}, 100)
  405. }
  406. return context
  407. }
  408. export default {
  409. regeneratorRuntime,
  410. api,
  411. getHello,
  412. formatTime,
  413. formatNumber,
  414. getCurrentDate,
  415. getApplyTime,
  416. navigate,
  417. navigateBack: (delta = 1) => wx.navigateBack({
  418. delta
  419. }),
  420. navigate_native,
  421. navigate_auth_native,
  422. goLogin,
  423. goHome,
  424. goSuccess,
  425. showTip,
  426. telephone_native,
  427. request: {
  428. get,
  429. post,
  430. get_auth,
  431. post_auth
  432. },
  433. getcitycode,
  434. pvw,
  435. pvw_native,
  436. getUserInfo,
  437. extend,
  438. inputChange,
  439. pickerChange,
  440. md5,
  441. get_global_param,
  442. verify: {
  443. isPhone,
  444. isEmail,
  445. form_verify
  446. },
  447. getWeatherInfo,
  448. logout,
  449. init,
  450. appKey: 'ZHLL_MiniPrograms'
  451. }