tools.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. // 返回上一页
  107. const prePage = (num=1) => {
  108. let pages = getCurrentPages();
  109. let prePage = pages[pages.length -1- num];
  110. // console.log('prePage--',prePage);
  111. // #ifdef H5
  112. return prePage;
  113. // #endif
  114. return prePage.$vm;
  115. }
  116. // 上传图片--注按需要对res处理 JSON.parse()
  117. function uploadImg(formData){
  118. return new Promise((resolve,reject)=>{
  119. uni.chooseImage({
  120. count:1,
  121. success(chooseImageRes){
  122. // resolve(chooseImageRes.tempFilePaths[0]);
  123. const tempFilePaths = chooseImageRes.tempFilePaths[0];
  124. // const token = sessionStorage.getItem('token');
  125. const token = uni.getStorageSync('token');
  126. uni.showLoading({
  127. title: '请稍后..',
  128. mask: true,
  129. })
  130. uni.uploadFile({
  131. url:config.uploadImgUrl,
  132. filePath: tempFilePaths,
  133. name: 'file',
  134. formData:formData,
  135. header: {
  136. 'token':token,
  137. },
  138. success:(res)=>{
  139. //需要JSON.parse
  140. let data = JSON.parse(res.data);
  141. if(!data || data.code !== 1 ){
  142. msg('上传失败');
  143. reject();
  144. return;
  145. }
  146. // console.log('tools uploadImg---',data);
  147. //即为全路径地址
  148. let fullurl = data.data.fullurl;
  149. resolve(fullurl);
  150. },
  151. fail:(err)=>{
  152. console.log('err--',err);
  153. msg('上传失败');
  154. reject();
  155. },
  156. complete:()=> {
  157. uni.hideLoading();
  158. },
  159. })
  160. },
  161. fail(err){
  162. // msg('打开相册失败');
  163. reject(err)
  164. }
  165. })
  166. })
  167. }
  168. function uploadVideo(formData={}){
  169. return new Promise((resolve,reject)=>{
  170. uni.chooseVideo({
  171. sourceType: ['camera', 'album'],
  172. success(chooseVideoRes){
  173. // resolve(chooseVideoRes.tempFilePaths[0]);
  174. const tempFilePath = chooseVideoRes.tempFilePath;
  175. // const token = sessionStorage.getItem('token');
  176. const token = uni.getStorageSync('token');
  177. uni.showLoading({
  178. title: '请稍后..',
  179. mask: true,
  180. })
  181. formData.act='video';
  182. uni.uploadFile({
  183. url:config.uploadVideoUrl,
  184. filePath: tempFilePath,
  185. name: 'file',
  186. formData:formData,
  187. header: {
  188. 'token':token,
  189. },
  190. success:(res)=>{
  191. //需要JSON.parse
  192. let data = JSON.parse(res.data);
  193. if(!data || data.code !== 1 ){
  194. msg('上传失败');
  195. reject();
  196. return;
  197. }
  198. // //即为全路径地址
  199. resolve(data.data.fullurl);
  200. // console.log('res---',res);
  201. },
  202. fail:(err)=>{
  203. console.log('err--',err);
  204. msg('上传失败');
  205. reject();
  206. },
  207. complete:()=> {
  208. uni.hideLoading();
  209. },
  210. })
  211. },
  212. fail(err){
  213. // msg('打开相册失败');
  214. reject(err)
  215. }
  216. })
  217. })
  218. }
  219. // 查看单张图片
  220. function previewImg(urls,idx=0){
  221. uni.previewImage({
  222. current: urls[idx],
  223. urls: urls,
  224. indicator: "number"
  225. })
  226. }
  227. //单个授权,针对定位await api.checkDeviceAuthorize('scope.userLocation','请开启定位,方便司机到达您的位置');
  228. let hasOpenDeviceAuthorizeModal = false;
  229. function checkDeviceAuthorize(scope,tipText) {
  230. if (hasOpenDeviceAuthorizeModal) {
  231. return
  232. }
  233. hasOpenDeviceAuthorizeModal = true
  234. return new Promise((resolve, reject) => {
  235. uni.getSetting().then((result) => {
  236. // this.authorizeCamera = result.authSetting['scope.camera']
  237. // console.log('getSetting 查看所有授权',result);
  238. let authSetting = result[1]['authSetting'];
  239. if (authSetting[scope]) {
  240. // console.log('getSetting 已授权',result);
  241. // 授权成功
  242. resolve({hasScoped:true})
  243. hasOpenDeviceAuthorizeModal = false
  244. } else {
  245. // 没有授权,弹出授权窗口
  246. // 注意: wx.authorize 只有首次调用会弹框,之后调用只返回结果,如果没有授权需要自行弹框提示处理
  247. // console.log('getSetting 查询没有授权,uni.authorize发起授权')
  248. uni.authorize({
  249. scope: scope,
  250. success: (res) => {
  251. // console.log('authorize ok', res)
  252. resolve({initAuth:true})
  253. hasOpenDeviceAuthorizeModal = false
  254. },
  255. fail: (err) => {
  256. // console.log('authorize err 弹层提示', err)
  257. openConfirm(scope,tipText,(isTrue)=>{
  258. if(isTrue){
  259. // resolve({popAuth:true})
  260. reject(new Error('popAuth:true but onShow ok')); //onShow会得新调用
  261. hasOpenDeviceAuthorizeModal = false
  262. }else{
  263. reject(new Error('authorize fail'))
  264. hasOpenDeviceAuthorizeModal = false
  265. }
  266. })
  267. }
  268. })
  269. }
  270. })
  271. })
  272. };
  273. function openConfirm(scope,tipText,callback) {
  274. return uni.showModal({
  275. content: tipText,
  276. confirmText: '确认',
  277. cancelText: '取消',
  278. success: (res) => {
  279. // 点击“确认”时打开设置页面
  280. if (res.confirm) {
  281. // console.log('用户点击确认')
  282. uni.openSetting({
  283. success: (res) => {
  284. // console.log("wx.openSetting success res..",res)
  285. if(typeof callback == 'function' && res.authSetting[scope]==true){
  286. callback(true);
  287. }
  288. },
  289. fail:()=>{
  290. callback(false)
  291. }
  292. })
  293. } else {
  294. // console.log('用户点击取消')
  295. callback(false)
  296. }
  297. },
  298. })
  299. };
  300. ///**详情页处理富文本 details仅是变化替换部分a.replace(/<text>(abc)<\/text>/,function(match,$1) $1=abc---------------------------------------------------------------------- */
  301. const replaceDetail = (details = '') => {
  302. //newContent仅是details替换后内容;
  303. let newContent = details.replace(/<img[^>]*>/gi, function (match, capture) { //去除三标签
  304. match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
  305. match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
  306. match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
  307. return match;
  308. });
  309. newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  310. newContent = newContent.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:0 auto;"');
  311. return newContent;
  312. }
  313. //处理选择时间
  314. const handleStrLength=(num)=>{
  315. return String(num).length < 2 ? '0' + num : num;
  316. }
  317. const handleDate=(date)=>{
  318. let m = handleStrLength(date.getMonth() + 1);
  319. let d = handleStrLength(date.getDate());
  320. // let h = handleStrLength(date.getHours());
  321. // let mm = handleStrLength(date.getMinutes());
  322. // let dateStr = date.getFullYear() + "-" + m + "-" + d + " " + h + ":" + mm;
  323. let dateStr = date.getFullYear() + "-" + m + "-" + d;
  324. return dateStr;
  325. }
  326. const handleDateTime=(date)=>{
  327. let m = handleStrLength(date.getMonth() + 1);
  328. let d = handleStrLength(date.getDate());
  329. // let h = handleStrLength(date.getHours());
  330. // let mm = handleStrLength(date.getMinutes());
  331. let dateStr = date.getFullYear() + "-" + m + "-" + d + " " + h + ":" + mm;
  332. // let dateStr = date.getFullYear() + "-" + m + "-" + d;
  333. return dateStr;
  334. }
  335. export default {
  336. msg,
  337. date,
  338. throttle,
  339. debounce,
  340. inAction,
  341. prePage,
  342. uploadImg,
  343. uploadVideo,
  344. previewImg,
  345. checkDeviceAuthorize,
  346. replaceDetail,
  347. handleDate,
  348. handleDateTime
  349. }