common.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. import {checkLogin,logoutjpushId,getLastAndReadStatus,updateHistoryApp} from '@/api/user'
  2. import { getSopCourseStudyList } from "@/api/courseAnswer.js"
  3. import { bdCallBackReq } from '@/api/index.js'
  4. import { bindCompanyFsUser } from '@/api/companyUser.js'
  5. const TOKEN_KEY = 'AppToken'; // token 信息
  6. const CONFIG_KEY = 'QXT_MAGMT_CONFIG_KEY'; // 系统配置
  7. const USER_KEY = 'QXT_MAGMT_USER_KEY'; // 账号信息
  8. const SITE_BASE_URL_KEY = 'SITE_BASE_URL_KEY'; // 链接信息
  9. const SIP_ACCOUNT_KEY = 'SIP_ACCOUNT_KEY'; // 链接信息
  10. let idCode=null;
  11. // #ifdef APP-PLUS
  12. idCode = uni.requireNativePlugin('Ba-IdCode');
  13. // #endif
  14. // tabBar
  15. const tabBarPages = [
  16. '/pages/index/index',
  17. '/pages/course/index',
  18. '/pages/course/video/living-app',
  19. '/pages/TUIKit/TUIPages/TUIConversation/index',
  20. '/pages/user/index'
  21. ]
  22. function userDefaults(key) {
  23. let ret = '';
  24. ret = uni.getStorageSync(key);
  25. if (!ret) {
  26. ret = '{}';
  27. }
  28. let obj = JSON.parse(ret);
  29. return obj;
  30. }
  31. /**
  32. * 获取当前登录用户的令牌信息
  33. * @return {Object} 登录令牌信息
  34. */
  35. function getUserToken() {
  36. let usertoken = userDefaults(TOKEN_KEY);
  37. return usertoken;
  38. };
  39. /**
  40. * 添加当前登录用户的令牌信息
  41. * @param {Object} tokenInfo 令牌信息
  42. */
  43. function setUserToken(tokenInfo) {
  44. let tokens = getUserToken()
  45. let newToken = Object.assign(tokens, tokenInfo); // 只有在登陆是才能获取签名、实名状态,刷新token时只会返回token,不能直接得到状态,这里只调整覆盖原来的token
  46. uni.setStorageSync(TOKEN_KEY, JSON.stringify(newToken));
  47. };
  48. export function parseText(txt,len) {
  49. if(txt.length>len){
  50. var text=txt.substr(0,len)+"..."
  51. return text;
  52. }
  53. return txt;
  54. }
  55. export function parseIDCardInfo(idCard) {
  56. // 正则表达式匹配身份证号格式
  57. var reg = /^\d{17}[\dXx]$/;
  58. if (reg.test(idCard)) {
  59. // 提取出生日期
  60. var birthday = idCard.substring(6, 14);
  61. var year = birthday.substring(0, 4);
  62. var month = birthday.substring(4, 6);
  63. var day = birthday.substring(6, 8);
  64. // 计算年龄
  65. var currentYear = new Date().getFullYear();
  66. var age = currentYear - parseInt(year);
  67. // 提取性别
  68. var genderCode = parseInt(idCard.charAt(16));
  69. var gender = genderCode % 2 === 0 ? "女" : "男";
  70. return {
  71. birthday: year + "-" + month + "-" + day,
  72. age: age,
  73. gender: gender
  74. };
  75. }
  76. return null; // 身份证号格式不正确
  77. }
  78. export function isEmpty(obj) {
  79. if (obj == undefined || obj == null || obj=="") {
  80. return true;
  81. } else {
  82. return false;
  83. }
  84. }
  85. /**
  86. * 是否登录
  87. * @return {Boolean} true 登录 false 未登录
  88. */
  89. export function isLogin() {
  90. let obj=uni.getStorageSync(TOKEN_KEY);
  91. return !!obj;
  92. }
  93. export function logout() {
  94. // #ifdef APP-PLUS
  95. logoutjpushId().then(res=>{
  96. if(res.code == 200){
  97. uni.setStorageSync(TOKEN_KEY,null);
  98. uni.removeStorageSync("onLaunch")
  99. uni.removeStorageSync("imUnread")
  100. uni.$emit("refreshUserInfo")
  101. uni.navigateTo({
  102. url: '/pages/auth/loginIndex'
  103. })
  104. //关闭推送事件监听
  105. uni.offPushMessage();
  106. // #ifdef APP-PLUS
  107. plus.runtime.setBadgeNumber(-1)
  108. // #endif
  109. } else {
  110. uni.showToast({
  111. title: res.msg,
  112. icon: 'none'
  113. })
  114. }
  115. })
  116. // #endif
  117. // #ifndef APP-PLUS
  118. uni.setStorageSync(TOKEN_KEY,null);
  119. uni.removeStorageSync("onLaunch")
  120. uni.removeStorageSync("imUnread")
  121. uni.$emit("refreshUserInfo")
  122. uni.navigateTo({
  123. url: '/pages/auth/loginIndex'
  124. })
  125. // #endif
  126. }
  127. export function loginOut(){
  128. uni.setStorageSync(TOKEN_KEY,null);
  129. uni.removeStorageSync("onLaunch")
  130. uni.removeStorageSync("imUnread")
  131. uni.$emit("refreshUserInfo")
  132. uni.navigateTo({
  133. url: '/pages/auth/loginIndex'
  134. });
  135. }
  136. var toast=function(msg) {
  137. // #ifdef APP-PLUS
  138. uni.showToast({title: msg,icon: 'none',duration:2000,position:'bottom'});
  139. // #endif
  140. // #ifdef H5
  141. uni.showToast({ title: msg,icon: 'none',duration:2000});
  142. // #endif
  143. }
  144. export function getDictLabelName(dicts,dictValue) {
  145. if(dictValue==null){
  146. return "";
  147. }
  148. var name="";
  149. dicts.forEach(function(item, index, array) {
  150. if(dictValue.toString()==item.dictValue.toString())
  151. {
  152. name=item.dictLabel
  153. }
  154. });
  155. return name;
  156. }
  157. export function getStoreDictByName(key,dictValue) {
  158. if(dictValue==null || dictValue==-1){
  159. return "请选择";
  160. }
  161. var dicts = uni.getStorageSync(key);
  162. var dict=JSON.parse(dicts);
  163. var name="";
  164. dict.forEach(function(item, index, array) {
  165. if(dictValue.toString()==item.dictValue.toString()){
  166. name=item.dictLabel
  167. }
  168. });
  169. return name;
  170. }
  171. var getStoreIndexByName= function(key,dictValue) {
  172. if(dictValue==null || dictValue==-1){
  173. return [0];
  174. }
  175. var dicts = uni.getStorageSync(key);
  176. var dict=JSON.parse(dicts);
  177. var defIndexs=[0];
  178. dict.forEach(function(item, index, array) {
  179. if(dictValue.toString()==item.dictValue.toString()){
  180. defIndexs=[index];
  181. }
  182. });
  183. return defIndexs;
  184. }
  185. var getStorageByKey=function(key){
  186. let storageObj=uni.getStorageSync(key);
  187. var dataArr=[];
  188. if(!!storageObj){
  189. dataArr=JSON.parse(storageObj);
  190. }
  191. return dataArr;
  192. }
  193. var getStorageNamesByKey=function(key){
  194. let storageObj=uni.getStorageSync(key);
  195. if(!!storageObj){
  196. var tempArr=JSON.parse(storageObj);
  197. var valueArr=[];
  198. tempArr.forEach(function(item, index, array) {
  199. valueArr.push(item.dictLabel);
  200. });
  201. return valueArr;
  202. }
  203. }
  204. var getDict= function(key) {
  205. var dicts = uni.getStorageSync('dicts');
  206. dicts=JSON.parse(dicts);
  207. var dict=dicts[key]
  208. return dict;
  209. }
  210. var photosToArr= function(photoUrl) {
  211. var photos=[];
  212. if(photoUrl!=null&&photoUrl!=''){
  213. photos=photoUrl.split(',');
  214. }
  215. return photos
  216. }
  217. var dateFormat=function dateFormat(fmt, date) {
  218. let ret;
  219. const opt = {
  220. "Y+": date.getFullYear().toString(), // 年
  221. "m+": (date.getMonth() + 1).toString(), // 月
  222. "d+": date.getDate().toString(), // 日
  223. "H+": date.getHours().toString(), // 时
  224. "M+": date.getMinutes().toString(), // 分
  225. "S+": date.getSeconds().toString() // 秒
  226. // 有其他格式化字符需求可以继续添加,必须转化成字符串
  227. };
  228. for (let k in opt) {
  229. ret = new RegExp("(" + k + ")").exec(fmt);
  230. if (ret) {
  231. fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
  232. };
  233. };
  234. return fmt;
  235. }
  236. var getProvider = service => {
  237. return new Promise((resolve, reject) => {
  238. // 获取当前环境的服务商
  239. uni.getProvider({
  240. service: service || 'oauth',
  241. success: function (res) {
  242. // 此处可以排除h5
  243. if (res.provider) {
  244. resolve(res.provider[0])
  245. }
  246. },
  247. fail() {
  248. reject('获取环境服务商失败')
  249. },
  250. })
  251. }).catch(error => {
  252. console.log('167', error)
  253. })
  254. }
  255. export function parsePhone(mobile) {
  256. var str = mobile.substr(0,3)+"****"+mobile.substr(7);
  257. return str;
  258. }
  259. export function getAge(strBirthday){
  260. var returnAge,
  261. strBirthdayArr=strBirthday.split("-"),
  262. birthYear = strBirthdayArr[0],
  263. birthMonth = strBirthdayArr[1],
  264. birthDay = strBirthdayArr[2],
  265. d = new Date(),
  266. nowYear = d.getFullYear(),
  267. nowMonth = d.getMonth() + 1,
  268. nowDay = d.getDate();
  269. if(nowYear == birthYear){
  270. returnAge = 0;//同年 则为0周岁
  271. }
  272. else{
  273. var ageDiff = nowYear - birthYear ; //年之差
  274. if(ageDiff > 0){
  275. if(nowMonth == birthMonth) {
  276. var dayDiff = nowDay - birthDay;//日之差
  277. if(dayDiff < 0) {
  278. returnAge = ageDiff - 1;
  279. }else {
  280. returnAge = ageDiff;
  281. }
  282. }else {
  283. var monthDiff = nowMonth - birthMonth;//月之差
  284. if(monthDiff < 0) {
  285. returnAge = ageDiff - 1;
  286. }
  287. else {
  288. returnAge = ageDiff ;
  289. }
  290. }
  291. }else {
  292. returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
  293. }
  294. }
  295. return returnAge;//返回周岁年龄
  296. }
  297. const urlToObj = function(url) {
  298. let obj = {}
  299. let str = url.slice(url.indexOf('?') + 1)
  300. let arr = str.split('&')
  301. for (let j = arr.length, i = 0; i < j; i++) {
  302. let arr_temp = arr[i].split('=')
  303. obj[arr_temp[0]] = arr_temp[1]
  304. }
  305. return obj
  306. }
  307. /**
  308. * 判断是否为空对象
  309. * @param {Object} 时间字符串
  310. */
  311. var isNullObj=function(obj) {
  312. let isNull=(JSON.stringify(obj) == "{}");
  313. return isNull;
  314. }
  315. var arrContainsVal=function(arr,val){
  316. var isContains=false;
  317. for (var i = 0; i < arr.length; i++) {
  318. if (arr[i] == val) {
  319. isContains= true;
  320. break;
  321. }
  322. }
  323. return isContains;
  324. }
  325. var arrIndexOf = function(arr,val) {
  326. var isContains = this.arrContainsVal(arr,val);
  327. if (isContains) {
  328. return arr.indexOf(val);
  329. } else{
  330. return -1;
  331. }
  332. }
  333. export function navBack() {
  334. uni.navigateBack({
  335. animationType: 'pop-out',
  336. animationDuration: 200
  337. });
  338. }
  339. export function navTo(url) {
  340. uni.navigateTo({
  341. url: url
  342. });
  343. }
  344. var loginNavTo=function(url){
  345. if(isLogin()){
  346. uni.navigateTo({
  347. url: url
  348. });
  349. }else{
  350. this.$showLoginPage();
  351. }
  352. }
  353. var loginCallBack=function(callBack){
  354. if(isLogin()){
  355. callBack();
  356. }else{
  357. this.$showLoginPage();
  358. }
  359. }
  360. /**
  361. * 获取用户信息
  362. *
  363. */
  364. export function getUserInfo(){
  365. let userInfo=uni.getStorageSync('userInfo');
  366. userInfo=userInfo ? JSON.parse(userInfo) : {};
  367. return userInfo;
  368. };
  369. export function parseIdCard(idCard) {
  370. var str = idCard.substr(0,4)+"****"+idCard.substr(8);
  371. return str;
  372. }
  373. /**
  374. * 获取腕表用户信息
  375. *
  376. */
  377. export function getUser(callback) {
  378. getWatchUserInfo({isFamily:false}).then(res => {
  379. if (res.code == 200) {
  380. uni.setStorageSync("userWatchInfo", JSON.stringify(res.user))
  381. callback(res.user)
  382. } else {
  383. callback({})
  384. }
  385. })
  386. }
  387. /**
  388. * type == 1表示 00:00 改成0, 01:00 改成1, 23:00 改成23格式
  389. * type != 1表示 0 改成00:00, 1 改成01:00, 23 改成23:00格式
  390. */
  391. export function formatHour(time,type) {
  392. if(type == 1) {
  393. const parts = time.split(":");
  394. const hour = parseInt(parts[0]);
  395. return hour;
  396. } else {
  397. let str = time.toString();
  398. if (str.length === 1) {
  399. str = '0' + str;
  400. }
  401. return str + ':00';
  402. }
  403. }
  404. var bdCallBack=function(data,bdCmdType) {
  405. bdCallBackReq(data).then(res => {
  406. if(res.code==200){
  407. uni.setStorageSync("bdCmdType",bdCmdType);
  408. if(bdCmdType==2){
  409. uni.setStorageSync("bdCmdType",3);
  410. }
  411. }else{
  412. uni.showToast({
  413. icon:'none',
  414. title: res.msg
  415. });
  416. }
  417. });
  418. }
  419. var bdAdvFeedback=function(aType,aValue,bdCmdType,userId) { //获取设备的各种标识码
  420. let devinfo=uni.getDeviceInfo();
  421. console.log("qxj bdAdvFeedback devInfo:"+JSON.stringify(devinfo));
  422. let that=this;
  423. // #ifdef APP-PLUS
  424. idCode.getIdCodes(res => {
  425. console.log("qxj getIdCodes:"+JSON.stringify(res));
  426. if (res.data) {
  427. let params={"oaid":res.data.OAID,"model":devinfo.model,"osType":2,"aType":aType,"aValue":aValue.toString()};
  428. if(!!userId){
  429. params["userId"]=userId;
  430. }
  431. bdCallBack(params,bdCmdType);
  432. }
  433. });
  434. // #endif
  435. }
  436. export function registerIdCode(aType,bdCmdType,aValue,userId) {
  437. //bdCmdType -1未操作 0:激活 1:已注册 2:已下单 3:已回传
  438. //注册,先注册再获取,注意APP合规性,若最终用户未同意隐私政策则不要调用
  439. // #ifdef APP-PLUS
  440. let that=this;
  441. idCode.register(res => {
  442. console.log(res);
  443. bdAdvFeedback(aType,aValue,bdCmdType,userId);
  444. });
  445. // #endif
  446. }
  447. export function dateFormatStr(fmt, date){
  448. let dateStr=dateFormat(fmt,date);
  449. return dateStr;
  450. }
  451. // 设置tabbar消息红点
  452. export async function updateMsgDot(){
  453. const resOther = await getLastAndReadStatus()
  454. let num1 = resOther.data && resOther.data.unReadNum ? resOther.data.unReadNum : 0
  455. const resCourse = await getSopCourseStudyList({pageNum: 1,pageSize: 10})
  456. let num2 = resCourse.isNotRead || 0
  457. const imUnred = uni.getStorageSync("imUnread") || 0;
  458. let BadgeNumber = (num1 + num2+imUnred) > 0 ? num1 + num2+imUnred : -1;
  459. //BadgeNumber=num2;
  460. const status = BadgeNumber > 0 ? 1 : 0;
  461. console.log("--qxj num1:"+num1+" num2:"+num2);
  462. // 获取当前页面实例(通常在页面生命周期或方法中调用)
  463. const currentPages = getCurrentPages();
  464. const currentPage = currentPages[currentPages.length - 1];
  465. const currentRoute = currentPage.route;
  466. const formattedRoute = `/${currentRoute}`;
  467. const isTabBarPage = tabBarPages.includes(formattedRoute);
  468. if(isTabBarPage) {
  469. if(status == 1) {
  470. uni.showTabBarRedDot({
  471. index: 3,
  472. });
  473. } else {
  474. uni.hideTabBarRedDot({
  475. index: 3,
  476. });
  477. }
  478. }
  479. // #ifdef APP-PLUS
  480. plus.runtime.setBadgeNumber(BadgeNumber)
  481. // #endif
  482. }
  483. // 绑定销售
  484. export function handleBindCompanyFsUser(comUserId) {
  485. bindCompanyFsUser(comUserId).then(res=>{
  486. if(res.code == 200) {
  487. uni.navigateTo({
  488. url: '/pages/user/bindCompanyUser'
  489. })
  490. } else {
  491. uni.showToast({
  492. title: res.msg,
  493. icon: 'none'
  494. })
  495. }
  496. // #ifdef APP-PLUS
  497. plus.runtime.arguments = ''
  498. // #endif
  499. }).catch(()=>{
  500. // #ifdef APP-PLUS
  501. plus.runtime.arguments = ''
  502. // #endif
  503. })
  504. }
  505. // 设置来源
  506. export function setSource() {
  507. // #ifdef APP-PLUS
  508. const historyApp = plus.runtime.channel || 'app'
  509. updateHistoryApp({historyApp:historyApp})
  510. // #endif
  511. }