util.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. import CONSTANT from "@/constant";
  2. import { mobileReg } from "@/utils/tools/validate";
  3. import { getMiniAppUrl, isWxBrowser } from "@/utils/common";
  4. // 是否为空
  5. const isEmpty = val => {
  6. if (val instanceof Array) {
  7. if (val.length === 0){
  8. return true
  9. }
  10. } else if (val instanceof Object) {
  11. if (Object.keys(val).length == 0){
  12. return true
  13. }
  14. } else {
  15. if ( val === "null" || val === null || val === "undefined" || val === undefined || val === "" || JSON.stringify(val) == "[]"){
  16. return true
  17. }
  18. return false;
  19. }
  20. return false;
  21. };
  22. /**
  23. * 深拷贝对象
  24. * @param {要拷贝对象} obj
  25. */
  26. export const copyObject = obj => {
  27. let str,
  28. newobj = Array.isArray(obj) === true ? [] : {};
  29. if (typeof obj !== "object") {
  30. return;
  31. } else if (JSON) {
  32. (str = JSON.stringify(obj)), //系列化对象
  33. (newobj = JSON.parse(str)); //还原
  34. } else {
  35. for (let i in obj) {
  36. newobj[i] = typeof obj[i] === "object" ? copyObject(obj[i]) : obj[i];
  37. }
  38. }
  39. return newobj;
  40. };
  41. const numberFormat = (number, type) => {
  42. if (number > 10000) {
  43. let num = (number / 10000 + "").split(".");
  44. return `${num[0]}.${("" + num[1]).slice(0, 1)} 万`;
  45. } else {
  46. return parseFloat(number)
  47. }
  48. };
  49. // 截取图片上传字符串
  50. const imgSubstr = val => {
  51. if (isEmpty(val)) return [];
  52. if (isArray(val)) {
  53. return val.map(e => {
  54. let index = e.indexOf("/uploads/");
  55. e = e.substring(index);
  56. return e;
  57. });
  58. } else {
  59. let index = val.indexOf("/uploads/");
  60. return val.substring(index);
  61. }
  62. };
  63. // 是否为数组
  64. const isArray = arr => {
  65. return typeof arr == "object" && arr.constructor == Array;
  66. };
  67. // 是否为字符串
  68. const isString = str => {
  69. return typeof str == "string" && str.constructor == String;
  70. };
  71. // 是否为对象
  72. const isObject = obj => {
  73. return typeof obj == "object" && obj.constructor == Object;
  74. };
  75. // 是否为数字
  76. const isNumber = num => {
  77. return typeof num == "number" && num.constructor == Number;
  78. };
  79. //是否金额
  80. const isMoney = money =>{
  81. return /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(money)
  82. }
  83. // 是否为日期类型
  84. const isDate = date => {
  85. return typeof date == "object" && date.constructor == Date;
  86. };
  87. // 是否为函数
  88. const isFunction = obj => {
  89. return typeof obj == "object" && obj.constructor == Function;
  90. };
  91. const checkMobile = num => {
  92. return mobileReg.test(num);
  93. };
  94. const checkName = str => {
  95. return /^[\u4E00-\u9FA5A-Za-z\s]+(·[\u4E00-\u9FA5A-Za-z]+)*$/.test(str);
  96. };
  97. /** *
  98. * 检查登录
  99. * @parmas query 拼接得参数对象
  100. * @parmas isFrist 为true时开头为&
  101. */
  102. export async function getCheckLogin() {
  103. let status = false;
  104. let token = uni.getStorageSync("token");
  105. if (token) {
  106. status = true;
  107. } else {
  108. // #ifdef H5
  109. if (isWxBrowser()) {
  110. let option = JSON.parse(uni.getStorageSync("currentQuery")) || {};
  111. console.log("option", option);
  112. // console.log('option', getMiniAppUrl(option, true))
  113. // return false
  114. location.href = `${CONSTANT.hostUrl}/auth/prepare?url=${encodeURIComponent(
  115. getMiniAppUrl(option, true)
  116. )}`;
  117. } else {
  118. // uni.showToast({
  119. // title: '请用微信浏览器打开!',
  120. // icon: 'none',
  121. // mask: true
  122. // })
  123. }
  124. // #endif
  125. // #ifndef H5
  126. // #endif
  127. }
  128. return status;
  129. }
  130. export const floatFormat = (f, n) => {
  131. let m = Math.pow(10, n);
  132. return parseInt(f * m, 10) / m;
  133. };
  134. /** *
  135. * 对象参数转为url参数
  136. * @parmas query 拼接得参数对象
  137. * @parmas isFrist 为true时开头为&
  138. */
  139. export const parse = (query, isFrist = false) => {
  140. let str = Object.keys(query)
  141. .filter(key => !isEmpty(query[key]))
  142. .reduce((result, key) => {
  143. const value = query[key];
  144. // in查询特殊处理
  145. if (Array.isArray(value) && !isEmpty(value)) {
  146. return `${result}&${value.reduce(
  147. (val, cVal) => `${val ? `${val}&` : val}${key}=${cVal}`,
  148. ""
  149. )}`;
  150. }
  151. // between查询做特殊处理
  152. if (typeof value === "object" && !isEmpty(value)) {
  153. const [start, end] = value;
  154. return `${result}&${key}[]=${start}&${key}[]=${end}`;
  155. }
  156. return `${result}&${key}=${value}`;
  157. }, "");
  158. return isFrist ? str : str.replace(/^&/, "?");
  159. };
  160. /** *
  161. * 全局时间转换
  162. * @parmas num 时间戳默认为11位时间戳
  163. * @parmas fmt 默认转换的时间格式
  164. * @parmas all 为true时time为13位时间戳
  165. */
  166. export const $formatDate = (num, fmt = "YYYY-MM-DD HH:mm", all) => {
  167. num = all ? num : num * 1000;
  168. let date = new Date();
  169. date.setTime(num);
  170. let o = {
  171. "M+": date.getMonth() + 1,
  172. "D+": date.getDate(),
  173. "h+": date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
  174. "H+": date.getHours(),
  175. "m+": date.getMinutes(),
  176. "s+": date.getSeconds(),
  177. "q+": Math.floor((date.getMonth() + 3) / 3),
  178. S: date.getMilliseconds()
  179. };
  180. let week = {
  181. "0": "\u65e5",
  182. "1": "\u4e00",
  183. "2": "\u4e8c",
  184. "3": "\u4e09",
  185. "4": "\u56db",
  186. "5": "\u4e94",
  187. "6": "\u516d"
  188. };
  189. if (/(Y+)/.test(fmt)) {
  190. fmt = fmt.replace(
  191. RegExp.$1,
  192. (date.getFullYear() + "").substr(4 - RegExp.$1.length)
  193. );
  194. }
  195. if (/(E+)/.test(fmt)) {
  196. fmt = fmt.replace(
  197. RegExp.$1,
  198. (RegExp.$1.length > 1
  199. ? RegExp.$1.length > 2
  200. ? "\u661f\u671f"
  201. : "\u5468"
  202. : "") + week[date.getDay() + ""]
  203. );
  204. }
  205. for (let k in o) {
  206. if (new RegExp("(" + k + ")").test(fmt)) {
  207. fmt = fmt.replace(
  208. RegExp.$1,
  209. RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
  210. );
  211. }
  212. }
  213. return fmt;
  214. };
  215. /** *
  216. * 全局公共按钮跳转
  217. * @parmas item.funtion 为可执行函数
  218. * @parmas item.url 为跳转的路径
  219. * @parmas item.query 为跳转携带的参数
  220. * @parmas item.type 为跳转调用的函数 1 navigateTo, 2 redirectTo 关闭当前页面,跳转到应用内的某个页面 3 reLaunch 关闭所有页面,打开到应用内的某个页面 4 switchTab
  221. */
  222. export const pageTo = item => {
  223. if (isNumber(item)) {
  224. uni.navigateBack({
  225. delta: item
  226. });
  227. }
  228. if (isString(item)) {
  229. uni.navigateTo({
  230. url: item
  231. });
  232. return false;
  233. }
  234. if (item.funtion) {
  235. item.funtion();
  236. }
  237. if (item.url) {
  238. let query = item.query ? parse(item.query) : "";
  239. let allUrl = `${item.url}${query}`;
  240. if (item.type == 2) {
  241. uni.redirectTo({
  242. url: allUrl
  243. });
  244. } else if (item.type == 3) {
  245. uni.reLaunch({
  246. url: allUrl
  247. });
  248. } else if (item.type == 4) {
  249. console.log("switchTab", item.query);
  250. uni.setStorageSync("switchTabQuery", item.query);
  251. uni.switchTab({
  252. url: item.url
  253. });
  254. } else {
  255. uni.navigateTo({
  256. url: allUrl
  257. });
  258. }
  259. }
  260. };
  261. /** *
  262. * 是否登录
  263. */
  264. export const isLogin = () => {
  265. let token = uni.getStorageSync("token");
  266. if (token) {
  267. return true;
  268. }
  269. return false;
  270. };
  271. export const callUp = (mobile) =>{
  272. //#ifdef MP-WEIXIN
  273. uni.makePhoneCall({
  274. phoneNumber: mobile
  275. });
  276. //#endif
  277. //#ifdef APP-PLUS
  278. plus.device.dial(mobile, true);
  279. //#endif
  280. }
  281. // 库存不足提示音 - 独立音频对象,避免与 hitVoice 冲突
  282. let noStockAudioContext = null
  283. let lastNoStockPlayTime = 0
  284. const NO_STOCK_MIN_INTERVAL = 1000 // 库存提示间隔1秒
  285. const initNoStockAudio = () => {
  286. if (noStockAudioContext) return
  287. try {
  288. noStockAudioContext = uni.createInnerAudioContext()
  289. noStockAudioContext.autoplay = false
  290. noStockAudioContext.volume = 1
  291. noStockAudioContext.src = "/static/noStock.mp3"
  292. //关键:不添加任何事件监听,避免与其他音效冲突
  293. } catch (e) {
  294. console.error('[noStockRemind] 初始化失败:', e)
  295. noStockAudioContext = null
  296. }
  297. }
  298. export const noStockRemind = () => {
  299. try {
  300. // 防抖:1秒内只播放一次
  301. const now = Date.now()
  302. if (now - lastNoStockPlayTime < NO_STOCK_MIN_INTERVAL) {
  303. return
  304. }
  305. // 初始化音频
  306. if (!noStockAudioContext) {
  307. initNoStockAudio()
  308. }
  309. if (!noStockAudioContext) {
  310. return
  311. }
  312. // 更新时间戳
  313. lastNoStockPlayTime = now
  314. // 停止之前的播放(确保不会被中断)
  315. try {
  316. noStockAudioContext.stop()
  317. } catch (e) {
  318. // 忽略停止失败
  319. }
  320. // 设置音量确保正常播放
  321. noStockAudioContext.volume = 1
  322. // 立即播放
  323. try {
  324. noStockAudioContext.play()
  325. } catch (playError) {
  326. console.error('[noStockRemind] 播放异常:', playError)
  327. noStockAudioContext = null
  328. }
  329. } catch (e) {
  330. console.error('[noStockRemind] 执行出错:', e)
  331. }
  332. }
  333. // 音效播放优化:缓存、防抖、资源控制
  334. let innerAudioContext = null
  335. let lastPlayTime = 0
  336. const MIN_PLAY_INTERVAL = 100 // 最小播放间隔,防止重复触发
  337. const initAudio = () => {
  338. if (innerAudioContext) return
  339. try {
  340. innerAudioContext = uni.createInnerAudioContext()
  341. innerAudioContext.autoplay = false
  342. innerAudioContext.src = "/static/hit.mp3"
  343. innerAudioContext.volume = 1
  344. //关键:不添加事件监听,让播放更简洁可靠
  345. // 播放时间短,不需要监听完成事件
  346. } catch (e) {
  347. console.error('[hitVoice] 初始化音频失败:', e)
  348. }
  349. }
  350. export const hitVoice = () => {
  351. try {
  352. // 防抖:检查距离上次播放是否太近
  353. const now = Date.now()
  354. if (now - lastPlayTime < MIN_PLAY_INTERVAL) {
  355. return
  356. }
  357. // 初始化
  358. if (!innerAudioContext) {
  359. initAudio()
  360. }
  361. if (!innerAudioContext) {
  362. return
  363. }
  364. // 更新时间
  365. lastPlayTime = now
  366. // 停止之前的播放,确保新的播放能完整进行
  367. try {
  368. innerAudioContext.stop()
  369. } catch (e) {
  370. // 忽略停止失败
  371. }
  372. // 设置音量
  373. innerAudioContext.volume = 1
  374. // 立即播放(不使用异步,避免被其他音效打断)
  375. try {
  376. innerAudioContext.play()
  377. } catch (e) {
  378. console.error('[hitVoice] 播放失败:', e)
  379. }
  380. } catch (e) {
  381. console.error('[hitVoice] 错误:', e)
  382. }
  383. }
  384. //去重 姜枫 2021.05.05
  385. export const unique = (arr) => {
  386. for(var i=0; i<arr.length; i++){
  387. for(var j=i+1; j<arr.length; j++){
  388. if(arr[i].classId==arr[j].classId){ //第一个等同于第二个,splice方法删除第二个
  389. arr.splice(j,1);
  390. j--;
  391. }
  392. }
  393. }
  394. return arr;
  395. };
  396. //判断是否有扫码的条件
  397. export const isScanEnv = () =>{
  398. let isScanEnv = false
  399. //#ifdef APP-PLUS
  400. if(plus.device.vendor == 'SUNMI'){
  401. isScanEnv = true
  402. }
  403. if(plus.device.vendor == 'Newland'){
  404. isScanEnv = true
  405. }
  406. //#endif
  407. return isScanEnv
  408. }
  409. export default {
  410. isEmpty,
  411. copyObject,
  412. imgSubstr,
  413. isArray,
  414. parse,
  415. checkMobile,
  416. checkName,
  417. $formatDate,
  418. floatFormat,
  419. pageTo,
  420. isLogin,
  421. getCheckLogin,
  422. numberFormat,
  423. isString,
  424. unique,
  425. isMoney,
  426. isNumber,
  427. noStockRemind,
  428. hitVoice,
  429. callUp,
  430. isScanEnv
  431. };