tools.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. import config from './config.js'
  2. function msg(title = '', param={}){
  3. if(!title){
  4. return;
  5. }
  6. const duration = param.duration || 1500;
  7. const mask = param.mask || false;
  8. const icon = param.icon || 'none';
  9. let options = {
  10. title,
  11. duration,
  12. mask,
  13. icon
  14. }
  15. if(param.type){
  16. // options.image = '/static/' + param.type + '.png';
  17. }
  18. uni.showToast(options);
  19. }
  20. function date(format, timeStamp){
  21. let date = new Date(timeStamp * 1000),
  22. Y = date.getFullYear(),
  23. m = date.getMonth() + 1,
  24. d = date.getDate(),
  25. H = date.getHours(),
  26. i = date.getMinutes(),
  27. s = date.getSeconds();
  28. m = m < 10 ? '0' + m : m;
  29. d = d < 10 ? '0' + d : d;
  30. H = H < 10 ? '0' + H : H;
  31. i = i < 10 ? '0' + i : i;
  32. s = s < 10 ? '0' + s : s;
  33. return format.replace(/[YmdHis]/g, key=>{
  34. return {Y,m,d,H,i,s}[key];
  35. });
  36. }
  37. /**
  38. * 节流原理:在一定时间内,只能触发一次
  39. *
  40. * @param {Function} func 要执行的回调函数
  41. * @param {Number} wait 延时的时间
  42. * @param {Boolean} immediate 是否立即执行
  43. * @return null
  44. * this.throttle(this.getResult, this.timeout, this.immediate);
  45. * $tools.throttle(submit)
  46. */
  47. let timer, flag;
  48. function throttle(func, wait = 2000, immediate = true) {
  49. if (immediate) {
  50. if (!flag) {
  51. flag = true;
  52. // 如果是立即执行,则在wait毫秒内开始时执行
  53. typeof func === 'function' && func();
  54. timer = setTimeout(() => {
  55. flag = false;
  56. }, wait);
  57. }
  58. } else {
  59. if (!flag) {
  60. flag = true
  61. // 如果是非立即执行,则在wait毫秒内的结束处执行
  62. timer = setTimeout(() => {
  63. flag = false
  64. typeof func === 'function' && func();
  65. }, wait);
  66. }
  67. }
  68. }
  69. /**
  70. * 防抖原理:一定时间内,只有最后一次操作,再过wait毫秒后才执行函数
  71. *
  72. * @param {Function} func 要执行的回调函数
  73. * @param {Number} wait 延时的时间
  74. * @param {Boolean} immediate 是否立即执行
  75. * @return null
  76. * this.debounce(this.getResult, this.timeout, this.immediate);
  77. */
  78. let timeout = null;
  79. function debounce(func, wait = 500, immediate = false) {
  80. // 清除定时器
  81. if (timeout !== null) clearTimeout(timeout);
  82. // 立即执行,此类情况一般用不到
  83. if (immediate) {
  84. var callNow = !timeout;
  85. timeout = setTimeout(function() {
  86. timeout = null;
  87. }, wait);
  88. if (callNow) typeof func === 'function' && func();
  89. } else {
  90. // 设置定时器,当最后一次操作后,timeout不会再被清除,所以在延时wait毫秒后执行func回调方法
  91. timeout = setTimeout(function() {
  92. typeof func === 'function' && func();
  93. }, wait);
  94. }
  95. }
  96. function inAction(fn, that, timeout = 2000){
  97. if(that['in' + fn]){
  98. return true
  99. }
  100. that['in' + fn] = true;
  101. setTimeout(()=>{
  102. that['in' + fn] = false;
  103. }, timeout)
  104. return false;
  105. }
  106. function match(str, type, showMsg=true){
  107. let exp = '';
  108. switch(type){
  109. case 'mobile':
  110. if(str === ''){
  111. showMsg && msg('请填写手机号码');
  112. return false;
  113. }
  114. exp = /(^1[3|4|5|6|7|8|9][0-9]{9}$)/; //手机号
  115. if(!exp.test(str)){
  116. showMsg && msg('手机号码格式不正确');
  117. return false;
  118. }
  119. break;
  120. case 'pwd':
  121. if(str === ''){
  122. showMsg && msg('请填写密码');
  123. return false;
  124. }
  125. //必须加break; 否则pwd校验正确后会进入 case 'code'
  126. break;
  127. case 'code':
  128. if(str === ''){
  129. showMsg && msg('请填写验证码');
  130. return false;
  131. }
  132. if(!/^[0-9]+$/.test(str)){
  133. showMsg && msg('验证码不正确');
  134. return false;
  135. }
  136. break;
  137. case 'idcard':
  138. if(str === ''){
  139. showMsg && msg('请填写身份证号码');
  140. return false;
  141. }
  142. if(!/^(\d{17}[\d|x|X]|\d{15})$/.test(str)){
  143. showMsg && msg('请输入正确身份证号');
  144. return false;
  145. }
  146. break;
  147. }
  148. return true;
  149. }
  150. // 返回上一页
  151. const prePage = (num=1) => {
  152. let pages = getCurrentPages();
  153. let prePage = pages[pages.length -1- num];
  154. // console.log('prePage--',prePage);
  155. // #ifdef H5
  156. return prePage;
  157. // #endif
  158. return prePage.$vm;
  159. }
  160. // 上传图片--注按需要对res处理 JSON.parse()
  161. function uploadImg(formData){
  162. return new Promise((resolve,reject)=>{
  163. uni.chooseImage({
  164. count:1,
  165. success(chooseImageRes){
  166. // resolve(chooseImageRes.tempFilePaths[0]);
  167. const tempFilePaths = chooseImageRes.tempFilePaths[0];
  168. // const token = sessionStorage.getItem('token');
  169. const token = uni.getStorageSync('token');
  170. uni.showLoading({
  171. title: '请稍后..',
  172. mask: true,
  173. })
  174. uni.uploadFile({
  175. url:config.uploadImgUrl,
  176. filePath: tempFilePaths,
  177. name: 'file',
  178. formData:formData,
  179. header: {
  180. 'token':token,
  181. },
  182. success:(res)=>{
  183. //需要JSON.parse
  184. let data = JSON.parse(res.data);
  185. if(!data || data.code !== 1 ){
  186. msg('上传失败');
  187. reject();
  188. return;
  189. }
  190. // console.log('tools uploadImg---',data);
  191. //即为全路径地址
  192. let fullurl = data.data.fullurl;
  193. resolve(fullurl);
  194. },
  195. fail:(err)=>{
  196. console.log('err--',err);
  197. msg('上传失败');
  198. reject();
  199. },
  200. complete:()=> {
  201. uni.hideLoading();
  202. },
  203. })
  204. },
  205. fail(err){
  206. // msg('打开相册失败');
  207. reject(err)
  208. }
  209. })
  210. })
  211. }
  212. function uploadVideo(formData={}){
  213. return new Promise((resolve,reject)=>{
  214. uni.chooseVideo({
  215. sourceType: ['camera', 'album'],
  216. success(chooseVideoRes){
  217. // resolve(chooseVideoRes.tempFilePaths[0]);
  218. const tempFilePath = chooseVideoRes.tempFilePath;
  219. // const token = sessionStorage.getItem('token');
  220. const token = uni.getStorageSync('token');
  221. uni.showLoading({
  222. title: '请稍后..',
  223. mask: true,
  224. })
  225. formData.act='video';
  226. uni.uploadFile({
  227. url:config.uploadVideoUrl,
  228. filePath: tempFilePath,
  229. name: 'file',
  230. formData:formData,
  231. header: {
  232. 'token':token,
  233. },
  234. success:(res)=>{
  235. //需要JSON.parse
  236. let data = JSON.parse(res.data);
  237. if(!data || data.code !== 1 ){
  238. msg('上传失败');
  239. reject();
  240. return;
  241. }
  242. // //即为全路径地址
  243. resolve(data.data.fullurl);
  244. // console.log('res---',res);
  245. },
  246. fail:(err)=>{
  247. console.log('err--',err);
  248. msg('上传失败');
  249. reject();
  250. },
  251. complete:()=> {
  252. uni.hideLoading();
  253. },
  254. })
  255. },
  256. fail(err){
  257. // msg('打开相册失败');
  258. reject(err)
  259. }
  260. })
  261. })
  262. }
  263. // 查看单张图片
  264. function previewImg(urls,idx=0){
  265. uni.previewImage({
  266. current: urls[idx],
  267. urls: urls,
  268. indicator: "number"
  269. })
  270. }
  271. //单个授权,针对定位await api.checkDeviceAuthorize('scope.userLocation','请开启定位,方便司机到达您的位置');
  272. let hasOpenDeviceAuthorizeModal = false;
  273. function checkDeviceAuthorize(scope,tipText) {
  274. if (hasOpenDeviceAuthorizeModal) {
  275. return
  276. }
  277. hasOpenDeviceAuthorizeModal = true
  278. return new Promise((resolve, reject) => {
  279. uni.getSetting().then((result) => {
  280. // this.authorizeCamera = result.authSetting['scope.camera']
  281. // console.log('getSetting 查看所有授权',result);
  282. let authSetting = result[1]['authSetting'];
  283. if (authSetting[scope]) {
  284. // console.log('getSetting 已授权',result);
  285. // 授权成功
  286. resolve({hasScoped:true})
  287. hasOpenDeviceAuthorizeModal = false
  288. } else {
  289. // 没有授权,弹出授权窗口
  290. // 注意: wx.authorize 只有首次调用会弹框,之后调用只返回结果,如果没有授权需要自行弹框提示处理
  291. // console.log('getSetting 查询没有授权,uni.authorize发起授权')
  292. uni.authorize({
  293. scope: scope,
  294. success: (res) => {
  295. // console.log('authorize ok', res)
  296. resolve({initAuth:true})
  297. hasOpenDeviceAuthorizeModal = false
  298. },
  299. fail: (err) => {
  300. // console.log('authorize err 弹层提示', err)
  301. openConfirm(scope,tipText,(isTrue)=>{
  302. if(isTrue){
  303. // resolve({popAuth:true})
  304. reject(new Error('popAuth:true but onShow ok')); //onShow会得新调用
  305. hasOpenDeviceAuthorizeModal = false
  306. }else{
  307. reject(new Error('authorize fail'))
  308. hasOpenDeviceAuthorizeModal = false
  309. }
  310. })
  311. }
  312. })
  313. }
  314. })
  315. })
  316. };
  317. function openConfirm(scope,tipText,callback) {
  318. return uni.showModal({
  319. content: tipText,
  320. confirmText: '确认',
  321. cancelText: '取消',
  322. success: (res) => {
  323. // 点击“确认”时打开设置页面
  324. if (res.confirm) {
  325. // console.log('用户点击确认')
  326. uni.openSetting({
  327. success: (res) => {
  328. // console.log("wx.openSetting success res..",res)
  329. if(typeof callback == 'function' && res.authSetting[scope]==true){
  330. callback(true);
  331. }
  332. },
  333. fail:()=>{
  334. callback(false)
  335. }
  336. })
  337. } else {
  338. // console.log('用户点击取消')
  339. callback(false)
  340. }
  341. },
  342. })
  343. };
  344. ///**详情页处理富文本 details仅是变化替换部分a.replace(/<text>(abc)<\/text>/,function(match,$1) $1=abc---------------------------------------------------------------------- */
  345. const replaceDetail = (details = '') => {
  346. //newContent仅是details替换后内容;
  347. let newContent = details.replace(/<img[^>]*>/gi, function (match, capture) { //去除三标签
  348. match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
  349. match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
  350. match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
  351. return match;
  352. });
  353. newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  354. newContent = newContent.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:0 auto;"');
  355. return newContent;
  356. }
  357. //处理选择时间
  358. const handleStrLength=(num)=>{
  359. return String(num).length < 2 ? '0' + num : num;
  360. }
  361. const handleDate=(date)=>{
  362. let m = handleStrLength(date.getMonth() + 1);
  363. let d = handleStrLength(date.getDate());
  364. // let h = handleStrLength(date.getHours());
  365. // let mm = handleStrLength(date.getMinutes());
  366. // let dateStr = date.getFullYear() + "-" + m + "-" + d + " " + h + ":" + mm;
  367. let dateStr = date.getFullYear() + "-" + m + "-" + d;
  368. return dateStr;
  369. }
  370. const handleDateTime=(date)=>{
  371. let m = handleStrLength(date.getMonth() + 1);
  372. let d = handleStrLength(date.getDate());
  373. let h = handleStrLength(date.getHours());
  374. let mm = handleStrLength(date.getMinutes());
  375. let dateStr = date.getFullYear() + "-" + m + "-" + d + " " + h + ":" + mm;
  376. // let dateStr = date.getFullYear() + "-" + m + "-" + d;
  377. return dateStr;
  378. }
  379. export default {
  380. msg,
  381. date,
  382. throttle,
  383. debounce,
  384. inAction,
  385. prePage,
  386. uploadImg,
  387. uploadVideo,
  388. previewImg,
  389. checkDeviceAuthorize,
  390. replaceDetail,
  391. handleDate,
  392. handleDateTime,
  393. match
  394. }