util.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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(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. const innerAudioContext = uni.createInnerAudioContext()
  285. innerAudioContext.autoplay = false
  286. innerAudioContext.src = "/static/noStock.mp3"
  287. innerAudioContext.onPlay()
  288. innerAudioContext.onError()
  289. innerAudioContext.onPause(function() {
  290. innerAudioContext.destroy()
  291. })
  292. innerAudioContext.play()
  293. }
  294. //点击声效 shish
  295. export const hitRemind = () =>{
  296. const innerAudioContext = uni.createInnerAudioContext()
  297. innerAudioContext.autoplay = false
  298. innerAudioContext.src = "/static/hit.mp3"
  299. innerAudioContext.onPlay()
  300. innerAudioContext.onError()
  301. innerAudioContext.onPause(function() {
  302. innerAudioContext.destroy()
  303. })
  304. innerAudioContext.play()
  305. }
  306. //去重 姜枫 2021.05.05
  307. export const unique = (arr) => {
  308. for(var i=0; i<arr.length; i++){
  309. for(var j=i+1; j<arr.length; j++){
  310. if(arr[i].classId==arr[j].classId){ //第一个等同于第二个,splice方法删除第二个
  311. arr.splice(j,1);
  312. j--;
  313. }
  314. }
  315. }
  316. return arr;
  317. };
  318. //#ifdef APP-PLUS
  319. const CLDialog=uni.requireNativePlugin("CL-Dialog")
  320. //#endif
  321. export const confirmModal = (item,okCallback=null,cancelCallback=null) => {
  322. let title = item.title || '提示'
  323. let content = item.content || '确认操作?'
  324. let okText = item.okText || '确认'
  325. let cancelText = item.cancelText || '取消'
  326. let cacelTextColor = '#999999'
  327. let okTextColor = '#38ADFF'
  328. let singer = item.singer || false
  329. //#ifdef APP-PLUS
  330. let platform=uni.getSystemInfoSync().platform
  331. if(platform=='ios'){
  332. uni.showModal({
  333. title: title,
  334. content: content,
  335. showCancel: true,
  336. cancelText: cancelText,
  337. cancelColor: cacelTextColor,
  338. confirmText: okText,
  339. confirmColor: okTextColor,
  340. success: function (res) {
  341. if (res.confirm) {
  342. if(okCallback!=null){
  343. okCallback()
  344. }
  345. } else if (res.cancel) {
  346. if(cancelCallback!=null){
  347. cancelCallback()
  348. }
  349. }
  350. }
  351. })
  352. }else if(platform=='android'){
  353. let options={
  354. title:title,//内容(可选)但是标题和内容至少选择一个
  355. con:content,
  356. okTitle:okText,//确认按钮文字(可选)
  357. cancleTitle:cancelText,//取消按钮文字(可选)
  358. okTextColor:"#38ADFF",//确认按钮颜色(可选)
  359. cancleTextColor:"#999999",//取消按钮颜色(可选)
  360. singer:singer,//是否只显示确认按钮,默认false(可选)
  361. textAlign:"center",//对齐方式 //left居左,center居中,right 居右 默认居中
  362. conColor:"",
  363. bgColor:"#FFFFFF",//自定义弹框颜色
  364. titleColor:"#3d3d3d"//自定义title颜色
  365. }
  366. CLDialog.show(options,()=>{
  367. if(okCallback!=null){
  368. okCallback()
  369. }
  370. },()=>{
  371. if(cancelCallback!=null){
  372. cancelCallback()
  373. }
  374. })
  375. }
  376. //#endif
  377. // #ifdef MP-WEIXIN
  378. uni.showModal({
  379. title: title,
  380. content: content,
  381. showCancel: true,
  382. cancelText: cancelText,
  383. cancelColor: cacelTextColor,
  384. confirmText: okText,
  385. confirmColor: okTextColor,
  386. success: function (res) {
  387. if (res.confirm) {
  388. if(okCallback!=null){
  389. okCallback()
  390. }
  391. } else if (res.cancel) {
  392. if(cancelCallback!=null){
  393. cancelCallback()
  394. }
  395. }
  396. }
  397. })
  398. //#endif
  399. }
  400. //判断是否有扫码的条件
  401. export const isScanEnv = () =>{
  402. let isScanEnv = false
  403. //#ifdef APP-PLUS
  404. if(plus.device.vendor == 'SUNMI'){
  405. isScanEnv = true
  406. }
  407. if(plus.device.vendor == 'Newland'){
  408. isScanEnv = true
  409. }
  410. //#endif
  411. return isScanEnv
  412. }
  413. export default {
  414. isEmpty,
  415. copyObject,
  416. imgSubstr,
  417. isArray,
  418. parse,
  419. checkMobile,
  420. checkName,
  421. $formatDate,
  422. floatFormat,
  423. pageTo,
  424. isLogin,
  425. getCheckLogin,
  426. numberFormat,
  427. isString,
  428. unique,
  429. isMoney,
  430. isNumber,
  431. noStockRemind,
  432. callUp,
  433. hitRemind,
  434. confirmModal,
  435. isScanEnv
  436. };