util.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. console.log(item,'itemitem')
  224. if (isNumber(item)) {
  225. uni.navigateBack({
  226. delta: item
  227. });
  228. }
  229. if (isString(item)) {
  230. uni.navigateTo({
  231. url: item
  232. });
  233. return false;
  234. }
  235. if (item.funtion) {
  236. item.funtion();
  237. }
  238. if (item.url) {
  239. let query = item.query ? parse(item.query) : "";
  240. let allUrl = `${item.url}${query}`;
  241. if (item.type == 2) {
  242. uni.redirectTo({
  243. url: allUrl
  244. });
  245. } else if (item.type == 3) {
  246. uni.reLaunch({
  247. url: allUrl
  248. });
  249. } else if (item.type == 4) {
  250. console.log("switchTab", item.query);
  251. uni.setStorageSync("switchTabQuery", item.query);
  252. uni.switchTab({
  253. url: item.url
  254. });
  255. } else {
  256. uni.navigateTo({
  257. url: allUrl
  258. });
  259. }
  260. }
  261. };
  262. /** *
  263. * 是否登录
  264. */
  265. export const isLogin = () => {
  266. let token = uni.getStorageSync("token");
  267. if (token) {
  268. return true;
  269. }
  270. return false;
  271. };
  272. export const callUp = (mobile) =>{
  273. //#ifdef MP-WEIXIN
  274. uni.makePhoneCall({
  275. phoneNumber: mobile
  276. });
  277. //#endif
  278. //#ifdef APP-PLUS
  279. plus.device.dial(mobile, true);
  280. //#endif
  281. }
  282. //没有库存时的语音播放 shish
  283. export const noStockRemind = () =>{
  284. //没有库存声音提醒
  285. const innerAudioContext = uni.createInnerAudioContext();
  286. innerAudioContext.autoplay = true;
  287. innerAudioContext.src = `${CONSTANT.imgUrl}/voice/noStock.mp3`;
  288. innerAudioContext.onPlay(() => {
  289. //console.log('开始播放');
  290. });
  291. innerAudioContext.onError((res) => {
  292. //console.log(res.errMsg);
  293. //console.log(res.errCode);
  294. });
  295. innerAudioContext.onPause(function() {
  296. //console.log('end');
  297. innerAudioContext.destroy();
  298. })
  299. }
  300. //点击声效 shish
  301. export const hitRemind = () =>{
  302. //没有库存声音提醒
  303. const innerAudioContext = uni.createInnerAudioContext();
  304. innerAudioContext.autoplay = true;
  305. innerAudioContext.src = `${CONSTANT.imgUrl}/hit.mp3`;
  306. innerAudioContext.volume = 0.5
  307. innerAudioContext.onPlay(() => {
  308. //console.log('开始播放');
  309. });
  310. innerAudioContext.onError((res) => {
  311. //console.log(res.errMsg);
  312. //console.log(res.errCode);
  313. });
  314. innerAudioContext.onPause(function() {
  315. //console.log('end');
  316. innerAudioContext.destroy();
  317. })
  318. }
  319. //去重 姜枫 2021.05.05
  320. export const unique = (arr) => {
  321. for(var i=0; i<arr.length; i++){
  322. for(var j=i+1; j<arr.length; j++){
  323. if(arr[i].classId==arr[j].classId){ //第一个等同于第二个,splice方法删除第二个
  324. arr.splice(j,1);
  325. j--;
  326. }
  327. }
  328. }
  329. return arr;
  330. };
  331. //判断是否有扫码的条件
  332. export const isScanEnv = () =>{
  333. let isScanEnv = false
  334. //#ifdef APP-PLUS
  335. if(plus.device.vendor == 'SUNMI'){
  336. isScanEnv = true
  337. }
  338. if(plus.device.vendor == 'Newland'){
  339. isScanEnv = true
  340. }
  341. //#endif
  342. return isScanEnv
  343. }
  344. //加
  345. export const add = (arg1, arg2) => {
  346. var r1, r2, m, n;
  347. try {
  348. r1 = arg1.toString().split(".")[1].length
  349. } catch (e) {
  350. r1 = 0
  351. }
  352. try {
  353. r2 = arg2.toString().split(".")[1].length
  354. } catch (e) {
  355. r2 = 0
  356. }
  357. m = Math.pow(10, Math.max(r1, r2))
  358. n = (r1 >= r2) ? r1 : r2;
  359. return ((arg1 * m + arg2 * m) / m).toFixed(n);
  360. }
  361. //减
  362. export const sub = (arg1, arg2) => {
  363. var re1, re2, m, n;
  364. try {
  365. re1 = arg1.toString().split(".")[1].length;
  366. } catch (e) {
  367. re1 = 0;
  368. }
  369. try {
  370. re2 = arg2.toString().split(".")[1].length;
  371. } catch (e) {
  372. re2 = 0;
  373. }
  374. m = Math.pow(10, Math.max(re1, re2));
  375. n = (re1 >= re2) ? re1 : re2;
  376. return ((arg1 * m - arg2 * m) / m).toFixed(n);
  377. }
  378. //乘
  379. export const mul = (arg1, arg2) => {
  380. var m = 0;
  381. var s1 = arg1.toString();
  382. var s2 = arg2.toString();
  383. try {
  384. m += s1.split(".")[1].length;
  385. } catch (e) {}
  386. try {
  387. m += s2.split(".")[1].length;
  388. } catch (e) {}
  389. return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
  390. }
  391. // 除数,被除数, 保留的小数点后的位数
  392. export const div = (arg1,arg2,digit) =>{
  393. var t1=0,t2=0,r1,r2;
  394. try{t1=arg1.toString().split(".")[1].length}catch(e){}
  395. try{t2=arg2.toString().split(".")[1].length}catch(e){}
  396. r1=Number(arg1.toString().replace(".",""))
  397. r2=Number(arg2.toString().replace(".",""))
  398. //获取小数点后的计算值
  399. var result= ((r1/r2)*Math.pow(10,t2-t1)).toString()
  400. var result2=result.split(".")[1];
  401. result2=result2.substring(0,digit>result2.length?result2.length:digit);
  402. return Number(result.split(".")[0]+"."+result2);
  403. }
  404. export default {
  405. isEmpty,
  406. copyObject,
  407. imgSubstr,
  408. isArray,
  409. parse,
  410. checkMobile,
  411. checkName,
  412. $formatDate,
  413. floatFormat,
  414. pageTo,
  415. isLogin,
  416. getCheckLogin,
  417. numberFormat,
  418. isString,
  419. unique,
  420. isMoney,
  421. isNumber,
  422. noStockRemind,
  423. callUp,
  424. hitRemind,
  425. isScanEnv,
  426. add,
  427. sub,
  428. mul,
  429. div
  430. };