util.js 11 KB

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