util.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. location.href = `${CONSTANT.hostUrl}/auth/prepare?url=${encodeURIComponent(
  112. getMiniAppUrl(option, true)
  113. )}`;
  114. }
  115. // #endif
  116. // #ifndef H5
  117. // #endif
  118. }
  119. return status;
  120. }
  121. export const floatFormat = (f, n) => {
  122. let m = Math.pow(10, n);
  123. return parseInt(f * m, 10) / m;
  124. };
  125. /** *
  126. * 对象参数转为url参数
  127. * @parmas query 拼接得参数对象
  128. * @parmas isFrist 为true时开头为&
  129. */
  130. export const parse = (query, isFrist = false) => {
  131. let str = Object.keys(query)
  132. .filter(key => !isEmpty(query[key]))
  133. .reduce((result, key) => {
  134. const value = query[key];
  135. // in查询特殊处理
  136. if (Array.isArray(value) && !isEmpty(value)) {
  137. return `${result}&${value.reduce(
  138. (val, cVal) => `${val ? `${val}&` : val}${key}=${cVal}`,
  139. ""
  140. )}`;
  141. }
  142. // between查询做特殊处理
  143. if (typeof value === "object" && !isEmpty(value)) {
  144. const [start, end] = value;
  145. return `${result}&${key}[]=${start}&${key}[]=${end}`;
  146. }
  147. return `${result}&${key}=${value}`;
  148. }, "");
  149. return isFrist ? str : str.replace(/^&/, "?");
  150. };
  151. /** *
  152. * 全局时间转换
  153. * @parmas num 时间戳默认为11位时间戳
  154. * @parmas fmt 默认转换的时间格式
  155. * @parmas all 为true时time为13位时间戳
  156. */
  157. export const $formatDate = (num, fmt = "YYYY-MM-DD HH:mm", all) => {
  158. num = all ? num : num * 1000;
  159. let date = new Date();
  160. date.setTime(num);
  161. let o = {
  162. "M+": date.getMonth() + 1,
  163. "D+": date.getDate(),
  164. "h+": date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
  165. "H+": date.getHours(),
  166. "m+": date.getMinutes(),
  167. "s+": date.getSeconds(),
  168. "q+": Math.floor((date.getMonth() + 3) / 3),
  169. S: date.getMilliseconds()
  170. };
  171. let week = {
  172. "0": "\u65e5",
  173. "1": "\u4e00",
  174. "2": "\u4e8c",
  175. "3": "\u4e09",
  176. "4": "\u56db",
  177. "5": "\u4e94",
  178. "6": "\u516d"
  179. };
  180. if (/(Y+)/.test(fmt)) {
  181. fmt = fmt.replace(
  182. RegExp.$1,
  183. (date.getFullYear() + "").substr(4 - RegExp.$1.length)
  184. );
  185. }
  186. if (/(E+)/.test(fmt)) {
  187. fmt = fmt.replace(
  188. RegExp.$1,
  189. (RegExp.$1.length > 1
  190. ? RegExp.$1.length > 2
  191. ? "\u661f\u671f"
  192. : "\u5468"
  193. : "") + week[date.getDay() + ""]
  194. );
  195. }
  196. for (let k in o) {
  197. if (new RegExp("(" + k + ")").test(fmt)) {
  198. fmt = fmt.replace(
  199. RegExp.$1,
  200. RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
  201. );
  202. }
  203. }
  204. return fmt;
  205. };
  206. /** *
  207. * 全局公共按钮跳转
  208. * @parmas item.funtion 为可执行函数
  209. * @parmas item.url 为跳转的路径
  210. * @parmas item.query 为跳转携带的参数
  211. * @parmas item.type 为跳转调用的函数 1为navigateTo, 2为redirectTo 关闭当前页面,跳转到应用内的某个页面 3为reLaunch 关闭所有页面,打开到应用内的某个页面 4为switchTab
  212. */
  213. export const pageTo = item => {
  214. if (isNumber(item)) {
  215. uni.navigateBack({
  216. delta: item
  217. });
  218. }
  219. if (isString(item)) {
  220. uni.navigateTo({
  221. url: item
  222. });
  223. return false;
  224. }
  225. if (item.funtion) {
  226. item.funtion();
  227. }
  228. if (item.url) {
  229. let query = item.query ? parse(item.query) : "";
  230. let allUrl = `${item.url}${query}`;
  231. if (item.type == 2) {
  232. uni.redirectTo({
  233. url: allUrl
  234. });
  235. } else if (item.type == 3) {
  236. uni.reLaunch({
  237. url: allUrl
  238. });
  239. } else if (item.type == 4) {
  240. uni.setStorageSync("switchTabQuery", item.query);
  241. uni.switchTab({
  242. url: item.url
  243. });
  244. } else {
  245. uni.navigateTo({
  246. url: allUrl
  247. });
  248. }
  249. }
  250. };
  251. /** *
  252. * 是否登录
  253. */
  254. export const isLogin = () => {
  255. let token = uni.getStorageSync("token");
  256. if (token) {
  257. return true;
  258. }
  259. return false;
  260. };
  261. export const callUp = (mobile) =>{
  262. //#ifdef MP-WEIXIN
  263. uni.makePhoneCall({
  264. phoneNumber: mobile
  265. });
  266. //#endif
  267. //#ifdef APP-PLUS
  268. plus.device.dial(mobile, true);
  269. //#endif
  270. }
  271. //没有库存时的语音播放 shish
  272. export const noStockRemind = () =>{
  273. const innerAudioContext = uni.createInnerAudioContext()
  274. innerAudioContext.autoplay = false
  275. innerAudioContext.src = "/static/noStock.mp3"
  276. innerAudioContext.volume = 1
  277. innerAudioContext.onPlay()
  278. innerAudioContext.onError()
  279. innerAudioContext.onPause(function() {
  280. innerAudioContext.destroy()
  281. })
  282. innerAudioContext.play()
  283. }
  284. //点击声效 shish
  285. export const hitRemind = () =>{
  286. const innerAudioContext = uni.createInnerAudioContext()
  287. innerAudioContext.autoplay = false
  288. innerAudioContext.src = "/static/hit.mp3"
  289. innerAudioContext.onPlay()
  290. innerAudioContext.onError()
  291. innerAudioContext.onPause(function() {
  292. innerAudioContext.destroy()
  293. })
  294. innerAudioContext.play()
  295. }
  296. //去重 姜枫 2021.05.05
  297. export const unique = (arr) => {
  298. for(var i=0; i<arr.length; i++){
  299. for(var j=i+1; j<arr.length; j++){
  300. if(arr[i].classId==arr[j].classId){ //第一个等同于第二个,splice方法删除第二个
  301. arr.splice(j,1);
  302. j--;
  303. }
  304. }
  305. }
  306. return arr;
  307. };
  308. //#ifdef APP-PLUS
  309. const CLDialog=uni.requireNativePlugin("CL-Dialog")
  310. //#endif
  311. export const confirmModal = (item,okCallback=null,cancelCallback=null) => {
  312. let title = item.title || '提示'
  313. let content = item.content || '确认操作?'
  314. let okText = item.okText || '确认'
  315. let cancelText = item.cancelText || '取消'
  316. let cacelTextColor = '#999999'
  317. let okTextColor = '#38ADFF'
  318. let singer = item.singer || false
  319. //#ifdef APP-PLUS
  320. let platform=uni.getSystemInfoSync().platform
  321. if(platform=='ios'){
  322. uni.showModal({
  323. title: title,
  324. content: content,
  325. showCancel: true,
  326. cancelText: cancelText,
  327. cancelColor: cacelTextColor,
  328. confirmText: okText,
  329. confirmColor: okTextColor,
  330. success: function (res) {
  331. if (res.confirm) {
  332. if(okCallback!=null){
  333. okCallback()
  334. }
  335. } else if (res.cancel) {
  336. if(cancelCallback!=null){
  337. cancelCallback()
  338. }
  339. }
  340. }
  341. })
  342. }else if(platform=='android'){
  343. let options={
  344. title:title,//内容(可选)但是标题和内容至少选择一个
  345. con:content,
  346. okTitle:okText,//确认按钮文字(可选)
  347. cancleTitle:cancelText,//取消按钮文字(可选)
  348. okTextColor:"#38ADFF",//确认按钮颜色(可选)
  349. cancleTextColor:"#999999",//取消按钮颜色(可选)
  350. singer:singer,//是否只显示确认按钮,默认false(可选)
  351. textAlign:"center",//对齐方式 //left居左,center居中,right 居右 默认居中
  352. conColor:"",
  353. bgColor:"#FFFFFF",//自定义弹框颜色
  354. titleColor:"#3d3d3d"//自定义title颜色
  355. }
  356. CLDialog.show(options,()=>{
  357. if(okCallback!=null){
  358. okCallback()
  359. }
  360. },()=>{
  361. if(cancelCallback!=null){
  362. cancelCallback()
  363. }
  364. })
  365. }
  366. //#endif
  367. // #ifdef MP-WEIXIN
  368. uni.showModal({
  369. title: title,
  370. content: content,
  371. showCancel: true,
  372. cancelText: cancelText,
  373. cancelColor: cacelTextColor,
  374. confirmText: okText,
  375. confirmColor: okTextColor,
  376. success: function (res) {
  377. if (res.confirm) {
  378. if(okCallback!=null){
  379. okCallback()
  380. }
  381. } else if (res.cancel) {
  382. if(cancelCallback!=null){
  383. cancelCallback()
  384. }
  385. }
  386. }
  387. })
  388. //#endif
  389. }
  390. //判断是否有扫码的条件
  391. export const isScanEnv = () =>{
  392. let isScanEnv = false
  393. //#ifdef APP-PLUS
  394. if(plus.device.vendor == 'Newland'){
  395. isScanEnv = true
  396. }
  397. //#endif
  398. return isScanEnv
  399. }
  400. export default {
  401. isEmpty,
  402. copyObject,
  403. imgSubstr,
  404. isArray,
  405. parse,
  406. checkMobile,
  407. checkName,
  408. $formatDate,
  409. floatFormat,
  410. pageTo,
  411. isLogin,
  412. getCheckLogin,
  413. numberFormat,
  414. isString,
  415. unique,
  416. isMoney,
  417. isNumber,
  418. noStockRemind,
  419. callUp,
  420. hitRemind,
  421. confirmModal,
  422. isScanEnv
  423. };