util.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. success(res) {
  235. },
  236. fail(err) {
  237. console.log(err);
  238. }
  239. });
  240. } else if (item.type == 3) {
  241. uni.reLaunch({
  242. url: allUrl,
  243. success(res) {
  244. },
  245. fail(err) {
  246. console.log(err);
  247. }
  248. });
  249. } else if (item.type == 4) {
  250. uni.setStorageSync("switchTabQuery", item.query);
  251. uni.switchTab({
  252. url: item.url,
  253. success(res) {
  254. },
  255. fail(err) {
  256. console.log(err);
  257. }
  258. });
  259. } else {
  260. uni.navigateTo({
  261. url: allUrl,
  262. success(res) {
  263. },
  264. fail(err) {
  265. console.log(err);
  266. }
  267. });
  268. }
  269. }
  270. };
  271. /** *
  272. * 是否登录
  273. */
  274. export const isLogin = () => {
  275. let token = uni.getStorageSync("token");
  276. if (token) {
  277. return true;
  278. }
  279. return false;
  280. };
  281. export const callUp = (mobile) =>{
  282. //#ifdef MP-WEIXIN
  283. uni.makePhoneCall({
  284. phoneNumber: mobile
  285. });
  286. //#endif
  287. //#ifdef APP-PLUS
  288. plus.device.dial(mobile, true);
  289. //#endif
  290. }
  291. //没有库存时的语音播放 shish
  292. export const noStockRemind = () =>{
  293. if(uni.getSystemInfoSync().platform != 'windows'){
  294. const innerAudioContext = uni.createInnerAudioContext()
  295. innerAudioContext.autoplay = true
  296. innerAudioContext.src = "/static/noStock.mp3"
  297. innerAudioContext.volume = 1
  298. innerAudioContext.onPlay()
  299. innerAudioContext.onError()
  300. innerAudioContext.onPause(function() {
  301. innerAudioContext.destroy()
  302. })
  303. }
  304. }
  305. //点击声效 shish
  306. export const hitRemind = () =>{
  307. if(uni.getSystemInfoSync().platform != 'windows'){
  308. const innerAudioContext = uni.createInnerAudioContext()
  309. innerAudioContext.autoplay = true
  310. innerAudioContext.src = '/static/hit.mp3'
  311. innerAudioContext.onPlay()
  312. innerAudioContext.onError()
  313. innerAudioContext.onPause(function() {
  314. innerAudioContext.destroy()
  315. })
  316. }
  317. }
  318. //去重 姜枫 2021.05.05
  319. export const unique = (arr) => {
  320. for(var i=0; i<arr.length; i++){
  321. for(var j=i+1; j<arr.length; j++){
  322. if(arr[i].classId==arr[j].classId){ //第一个等同于第二个,splice方法删除第二个
  323. arr.splice(j,1);
  324. j--;
  325. }
  326. }
  327. }
  328. return arr;
  329. };
  330. //#ifdef APP-PLUS
  331. const CLDialog=uni.requireNativePlugin("CL-Dialog")
  332. //#endif
  333. export const confirmModal = (item,okCallback=null,cancelCallback=null) => {
  334. let title = item.title || '提示'
  335. let content = item.content || '确认操作?'
  336. let okText = item.okText || '确认'
  337. let cancelText = item.cancelText || '取消'
  338. let cacelTextColor = '#999999'
  339. let okTextColor = '#38ADFF'
  340. let singer = item.singer || false
  341. //#ifdef APP-PLUS
  342. let platform=uni.getSystemInfoSync().platform
  343. if(platform=='ios'){
  344. uni.showModal({
  345. title: title,
  346. content: content,
  347. showCancel: true,
  348. cancelText: cancelText,
  349. cancelColor: cacelTextColor,
  350. confirmText: okText,
  351. confirmColor: okTextColor,
  352. success: function (res) {
  353. if (res.confirm) {
  354. if(okCallback!=null){
  355. okCallback()
  356. }
  357. } else if (res.cancel) {
  358. if(cancelCallback!=null){
  359. cancelCallback()
  360. }
  361. }
  362. }
  363. })
  364. }else if(platform=='android'){
  365. let options={
  366. title:title,//内容(可选)但是标题和内容至少选择一个
  367. con:content,
  368. okTitle:okText,//确认按钮文字(可选)
  369. cancleTitle:cancelText,//取消按钮文字(可选)
  370. okTextColor:"#38ADFF",//确认按钮颜色(可选)
  371. cancleTextColor:"#999999",//取消按钮颜色(可选)
  372. singer:singer,//是否只显示确认按钮,默认false(可选)
  373. textAlign:"center",//对齐方式 //left居左,center居中,right 居右 默认居中
  374. conColor:"",
  375. bgColor:"#FFFFFF",//自定义弹框颜色
  376. titleColor:"#3d3d3d"//自定义title颜色
  377. }
  378. CLDialog.show(options,()=>{
  379. if(okCallback!=null){
  380. okCallback()
  381. }
  382. },()=>{
  383. if(cancelCallback!=null){
  384. cancelCallback()
  385. }
  386. })
  387. }
  388. //#endif
  389. // #ifdef MP-WEIXIN
  390. uni.showModal({
  391. title: title,
  392. content: content,
  393. showCancel: true,
  394. cancelText: cancelText,
  395. cancelColor: cacelTextColor,
  396. confirmText: okText,
  397. confirmColor: okTextColor,
  398. success: function (res) {
  399. if (res.confirm) {
  400. if(okCallback!=null){
  401. okCallback()
  402. }
  403. } else if (res.cancel) {
  404. if(cancelCallback!=null){
  405. cancelCallback()
  406. }
  407. }
  408. }
  409. })
  410. //#endif
  411. }
  412. //判断是否有扫码的条件
  413. export const isScanEnv = () =>{
  414. let isScanEnv = false
  415. //#ifdef APP-PLUS
  416. if(plus.device.vendor == 'Newland'){
  417. isScanEnv = true
  418. }
  419. //#endif
  420. return isScanEnv
  421. }
  422. export default {
  423. isEmpty,
  424. copyObject,
  425. imgSubstr,
  426. isArray,
  427. parse,
  428. checkMobile,
  429. checkName,
  430. $formatDate,
  431. floatFormat,
  432. pageTo,
  433. isLogin,
  434. getCheckLogin,
  435. numberFormat,
  436. isString,
  437. unique,
  438. isMoney,
  439. isNumber,
  440. noStockRemind,
  441. callUp,
  442. hitRemind,
  443. confirmModal,
  444. isScanEnv
  445. };