util.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. import CONSTANT from "@/constant";
  2. import { mobileReg } from "@/utils/tools/validate";
  3. import { getMiniAppUrl, isWxBrowser } from "@/utils/common";
  4. import permision from "@/utils/wa-permission_1.1/permission.js";
  5. // 是否为空
  6. const isEmpty = val => {
  7. if (val instanceof Array) {
  8. if (val.length === 0){
  9. return true
  10. }
  11. } else if (val instanceof Object) {
  12. if (Object.keys(val).length == 0){
  13. return true
  14. }
  15. } else {
  16. if ( val === "null" || val === null || val === "undefined" || val === undefined || val === "" || JSON.stringify(val) == "[]"){
  17. return true
  18. }
  19. return false;
  20. }
  21. return false;
  22. };
  23. /**
  24. * 深拷贝对象
  25. * @param {要拷贝对象} obj
  26. */
  27. export const copyObject = obj => {
  28. let str,
  29. newobj = Array.isArray(obj) === true ? [] : {};
  30. if (typeof obj !== "object") {
  31. return;
  32. } else if (JSON) {
  33. (str = JSON.stringify(obj)), //系列化对象
  34. (newobj = JSON.parse(str)); //还原
  35. } else {
  36. for (let i in obj) {
  37. newobj[i] = typeof obj[i] === "object" ? copyObject(obj[i]) : obj[i];
  38. }
  39. }
  40. return newobj;
  41. };
  42. const numberFormat = (number, type) => {
  43. if (number > 10000) {
  44. let num = (number / 10000 + "").split(".");
  45. return `${num[0]}.${("" + num[1]).slice(0, 1)} 万`;
  46. } else {
  47. return parseFloat(Number(number));
  48. }
  49. };
  50. // 截取图片上传字符串
  51. const imgSubstr = val => {
  52. if (isEmpty(val)) return [];
  53. if (isArray(val)) {
  54. return val.map(e => {
  55. if(e.indexOf("?") > -1){
  56. e = e.slice(0,e.indexOf("?"))
  57. }
  58. let index = e.indexOf("uploads/");
  59. e = e.substring(index);
  60. return e;
  61. });
  62. } else {
  63. if(e.indexOf("?") > -1){
  64. e = e.slice(0,e.indexOf("?"))
  65. }
  66. let index = val.indexOf("uploads/");
  67. return val.substring(index);
  68. }
  69. };
  70. // 是否为数组
  71. const isArray = arr => {
  72. return typeof arr == "object" && arr.constructor == Array;
  73. };
  74. // 是否为字符串
  75. const isString = str => {
  76. return typeof str == "string" && str.constructor == String;
  77. };
  78. // 是否为对象
  79. const isObject = obj => {
  80. return typeof obj == "object" && obj.constructor == Object;
  81. };
  82. // 是否为数字
  83. const isNumber = num => {
  84. return typeof num == "number" && num.constructor == Number;
  85. };
  86. // 是否为日期类型
  87. const isDate = date => {
  88. return typeof date == "object" && date.constructor == Date;
  89. };
  90. // 是否为函数
  91. const isFunction = obj => {
  92. return typeof obj == "object" && obj.constructor == Function;
  93. };
  94. const checkMobile = num => {
  95. return mobileReg.test(num);
  96. };
  97. const checkName = str => {
  98. return /^[\u4E00-\u9FA5A-Za-z\s]+(·[\u4E00-\u9FA5A-Za-z]+)*$/.test(str);
  99. };
  100. //是否金额
  101. const isMoney = money =>{
  102. return /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(money)
  103. }
  104. /** *
  105. * 检查登录
  106. * @parmas query 拼接得参数对象
  107. * @parmas isFrist 为true时开头为&
  108. */
  109. export async function getCheckLogin() {
  110. let status = false;
  111. let token = uni.getStorageSync("token");
  112. if (token) {
  113. status = true;
  114. } else {
  115. // #ifdef H5
  116. if (isWxBrowser()) {
  117. let option = JSON.parse(uni.getStorageSync("currentQuery")) || {};
  118. console.log("option", option);
  119. // console.log('option', getMiniAppUrl(option, true))
  120. // return false
  121. location.href = `${CONSTANT.hostUrl}/auth/prepare?url=${encodeURIComponent(
  122. getMiniAppUrl(option, true)
  123. )}`;
  124. } else {
  125. // uni.showToast({
  126. // title: '请用微信浏览器打开!',
  127. // icon: 'none',
  128. // mask: true
  129. // })
  130. }
  131. // #endif
  132. // #ifndef H5
  133. // #endif
  134. }
  135. return status;
  136. }
  137. export const floatFormat = (f, n) => {
  138. let m = Math.pow(10, n);
  139. return parseInt(f * m, 10) / m;
  140. };
  141. /** *
  142. * 对象参数转为url参数
  143. * @parmas query 拼接得参数对象
  144. * @parmas isFrist 为true时开头为&
  145. */
  146. export const parse = (query, isFrist = false) => {
  147. let str = Object.keys(query)
  148. .filter(key => !isEmpty(query[key]))
  149. .reduce((result, key) => {
  150. const value = query[key];
  151. // in查询特殊处理
  152. if (Array.isArray(value) && !isEmpty(value)) {
  153. return `${result}&${value.reduce(
  154. (val, cVal) => `${val ? `${val}&` : val}${key}=${cVal}`,
  155. ""
  156. )}`;
  157. }
  158. // between查询做特殊处理
  159. if (typeof value === "object" && !isEmpty(value)) {
  160. const [start, end] = value;
  161. return `${result}&${key}[]=${start}&${key}[]=${end}`;
  162. }
  163. return `${result}&${key}=${value}`;
  164. }, "");
  165. return isFrist ? str : str.replace(/^&/, "?");
  166. };
  167. /** *
  168. * 全局时间转换
  169. * @parmas num 时间戳默认为11位时间戳
  170. * @parmas fmt 默认转换的时间格式
  171. * @parmas all 为true时time为13位时间戳
  172. */
  173. export const $formatDate = (num, fmt = "YYYY-MM-DD HH:mm", all) => {
  174. num = all ? num : num * 1000;
  175. let date = new Date();
  176. date.setTime(num);
  177. let o = {
  178. "M+": date.getMonth() + 1,
  179. "D+": date.getDate(),
  180. "h+": date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
  181. "H+": date.getHours(),
  182. "m+": date.getMinutes(),
  183. "s+": date.getSeconds(),
  184. "q+": Math.floor((date.getMonth() + 3) / 3),
  185. S: date.getMilliseconds()
  186. };
  187. let week = {
  188. "0": "\u65e5",
  189. "1": "\u4e00",
  190. "2": "\u4e8c",
  191. "3": "\u4e09",
  192. "4": "\u56db",
  193. "5": "\u4e94",
  194. "6": "\u516d"
  195. };
  196. if (/(Y+)/.test(fmt)) {
  197. fmt = fmt.replace(
  198. RegExp.$1,
  199. (date.getFullYear() + "").substr(4 - RegExp.$1.length)
  200. );
  201. }
  202. if (/(E+)/.test(fmt)) {
  203. fmt = fmt.replace(
  204. RegExp.$1,
  205. (RegExp.$1.length > 1
  206. ? RegExp.$1.length > 2
  207. ? "\u661f\u671f"
  208. : "\u5468"
  209. : "") + week[date.getDay() + ""]
  210. );
  211. }
  212. for (let k in o) {
  213. if (new RegExp("(" + k + ")").test(fmt)) {
  214. fmt = fmt.replace(
  215. RegExp.$1,
  216. RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
  217. );
  218. }
  219. }
  220. return fmt;
  221. };
  222. /** *
  223. * 全局公共按钮跳转
  224. * @parmas item.funtion 为可执行函数
  225. * @parmas item.url 为跳转的路径
  226. * @parmas item.query 为跳转携带的参数
  227. * @parmas item.type 为跳转调用的函数 1为navigateTo, 2为redirectTo 关闭当前页,跳转到指定页, 3为reLaunch, 4为switchTab
  228. */
  229. export const pageTo = item => {
  230. if (isNumber(item)) {
  231. uni.navigateBack({
  232. delta: item
  233. });
  234. }
  235. if (isString(item)) {
  236. uni.navigateTo({
  237. url: item
  238. });
  239. return false;
  240. }
  241. if (item.funtion) {
  242. item.funtion();
  243. }
  244. if (item.url) {
  245. let query = item.query ? parse(item.query) : "";
  246. let allUrl = `${item.url}${query}`;
  247. if (item.type == 2) {
  248. uni.redirectTo({ url: allUrl })
  249. } else if (item.type == 3) {
  250. uni.reLaunch({ url: allUrl })
  251. } else if (item.type == 4) {
  252. uni.setStorageSync("switchTabQuery", item.query);
  253. uni.switchTab({ url: item.url })
  254. } else {
  255. uni.navigateTo({ url: allUrl })
  256. }
  257. }
  258. };
  259. /** *
  260. * 是否登录
  261. */
  262. export const isLogin = () => {
  263. let token = uni.getStorageSync("token");
  264. if (token) {
  265. return true;
  266. }
  267. return false;
  268. };
  269. /**
  270. * 去重
  271. * 姜枫 2021.05.05
  272. * **/
  273. export const unique = (arr) => {
  274. for(var i=0; i<arr.length; i++){
  275. for(var j=i+1; j<arr.length; j++){
  276. if(arr[i].classId==arr[j].classId){ //第一个等同于第二个,splice方法删除第二个
  277. arr.splice(j,1);
  278. j--;
  279. }
  280. }
  281. }
  282. return arr;
  283. };
  284. //点击声效 shish
  285. export const hitRemind = () =>{
  286. if(uni.getSystemInfoSync().platform != 'windows'){
  287. const innerAudioContext = uni.createInnerAudioContext()
  288. innerAudioContext.autoplay = true
  289. innerAudioContext.src = '/static/hit.mp3'
  290. innerAudioContext.onPlay()
  291. innerAudioContext.onError()
  292. innerAudioContext.onPause(function() {
  293. innerAudioContext.destroy()
  294. })
  295. }
  296. }
  297. //#ifdef APP-PLUS
  298. const CLDialog=uni.requireNativePlugin("CL-Dialog")
  299. //#endif
  300. export const confirmModal = (item,okCallback=null,cancelCallback=null) => {
  301. let title = item.title || '提示'
  302. let content = item.content || '确认操作?'
  303. let okText = item.okText || '确认'
  304. let cancelText = item.cancelText || '取消'
  305. let cacelTextColor = '#999999'
  306. let okTextColor = '#38ADFF'
  307. let singer = item.singer || false
  308. //#ifdef APP-PLUS
  309. let platform=uni.getSystemInfoSync().platform
  310. if(platform=='ios'){
  311. uni.showModal({
  312. title: title,
  313. content: content,
  314. showCancel: true,
  315. cancelText: cancelText,
  316. cancelColor: cacelTextColor,
  317. confirmText: okText,
  318. confirmColor: okTextColor,
  319. success: function (res) {
  320. if (res.confirm) {
  321. if(okCallback!=null){
  322. okCallback()
  323. }
  324. } else if (res.cancel) {
  325. if(cancelCallback!=null){
  326. cancelCallback()
  327. }
  328. }
  329. }
  330. })
  331. }else if(platform=='android'){
  332. let options={
  333. title:title,//内容(可选)但是标题和内容至少选择一个
  334. con:content,
  335. okTitle:okText,//确认按钮文字(可选)
  336. cancleTitle:cancelText,//取消按钮文字(可选)
  337. okTextColor:"#38ADFF",//确认按钮颜色(可选)
  338. cancleTextColor:"#999999",//取消按钮颜色(可选)
  339. singer:singer,//是否只显示确认按钮,默认false(可选)
  340. textAlign:"center",//对齐方式 //left居左,center居中,right 居右 默认居中
  341. conColor:"",
  342. bgColor:"#FFFFFF",//自定义弹框颜色
  343. titleColor:"#3d3d3d"//自定义title颜色
  344. }
  345. CLDialog.show(options,()=>{
  346. if(okCallback!=null){
  347. okCallback()
  348. }
  349. },()=>{
  350. if(cancelCallback!=null){
  351. cancelCallback()
  352. }
  353. })
  354. }
  355. //#endif
  356. // #ifdef MP-WEIXIN
  357. uni.showModal({
  358. title: title,
  359. content: content,
  360. showCancel: true,
  361. cancelText: cancelText,
  362. cancelColor: cacelTextColor,
  363. confirmText: okText,
  364. confirmColor: okTextColor,
  365. success: function (res) {
  366. if (res.confirm) {
  367. if(okCallback!=null){
  368. okCallback()
  369. }
  370. } else if (res.cancel) {
  371. if(cancelCallback!=null){
  372. cancelCallback()
  373. }
  374. }
  375. }
  376. })
  377. //#endif
  378. }
  379. //判断是否有扫码的条件
  380. export const isScanEnv = () =>{
  381. let isScanEnv = false
  382. //#ifdef APP-PLUS
  383. if(plus.device.vendor == 'Newland'){
  384. isScanEnv = true
  385. }
  386. //#endif
  387. return isScanEnv
  388. }
  389. //没有库存时的语音播放 shish
  390. export const noStockRemind = () =>{
  391. const innerAudioContext = uni.createInnerAudioContext()
  392. innerAudioContext.autoplay = false
  393. innerAudioContext.src = "/static/noStock.mp3"
  394. innerAudioContext.volume = 1
  395. innerAudioContext.onPlay()
  396. innerAudioContext.onError()
  397. innerAudioContext.onPause(function() {
  398. innerAudioContext.destroy()
  399. })
  400. innerAudioContext.play()
  401. }
  402. export async function callUp(mobile){
  403. //#ifdef MP-WEIXIN
  404. uni.makePhoneCall({phoneNumber: mobile})
  405. //#endif
  406. //#ifdef APP-PLUS
  407. let env = uni.getSystemInfoSync().platform
  408. if(env == 'android'){
  409. //Android是动态权限,请求权限状态时会触发弹框询问是否赋权(如果已经同意或永久禁止则不会询问),所以必须使用异步方式来处理
  410. var result = await permision.requestAndroidPermission('android.permission.CALL_PHONE')
  411. if(Number(result) == -1){
  412. confirmModal({content:'请在权限管理中开启【拨打电话】','okText':'去开启'},() => {
  413. permision.gotoAppPermissionSetting()
  414. })
  415. return
  416. }
  417. }
  418. uni.makePhoneCall({phoneNumber: mobile})
  419. //#endif
  420. }
  421. export default {
  422. isEmpty,
  423. copyObject,
  424. imgSubstr,
  425. isArray,
  426. parse,
  427. checkMobile,
  428. checkName,
  429. $formatDate,
  430. floatFormat,
  431. pageTo,
  432. isLogin,
  433. getCheckLogin,
  434. numberFormat,
  435. isString,
  436. unique,
  437. isMoney,
  438. confirmModal,
  439. isScanEnv,
  440. hitRemind,
  441. noStockRemind,
  442. callUp
  443. };