import { checkLogin, logoutjpushId, getLastAndReadStatus, updateHistoryApp } from '@/api/user' import { getSopCourseStudyList } from "@/api/courseAnswer.js" import { bdCallBackReq } from '@/api/index.js' import { bindCompanyFsUser } from '@/api/companyUser.js' const TOKEN_KEY = 'AppToken'; // token 信息 const CONFIG_KEY = 'QXT_MAGMT_CONFIG_KEY'; // 系统配置 const USER_KEY = 'QXT_MAGMT_USER_KEY'; // 账号信息 const SITE_BASE_URL_KEY = 'SITE_BASE_URL_KEY'; // 链接信息 const SIP_ACCOUNT_KEY = 'SIP_ACCOUNT_KEY'; // 链接信息 let idCode = null; let sdkwx = null; // #ifdef APP-PLUS idCode = uni.requireNativePlugin('Ba-IdCode'); sdkwx = uni.requireNativePlugin('Wework-SdkWX'); // 企业微信登陆、分享插件 // #endif // tabBar const tabBarPages = [ '/pages/index/index', '/pages/course/index', '/pages/course/video/living-app', '/pages/TUIKit/TUIPages/TUIConversation/index', '/pages/user/index' ] // 直播模块h //直播静默登录 export function checkLiveToken(){ var token = uni.getStorageSync('liveToken'); if (token == null || token == undefined || token == "") { return false; } return true; } function userDefaults(key) { let ret = ''; ret = uni.getStorageSync(key); if (!ret) { ret = '{}'; } let obj = JSON.parse(ret); return obj; } /** * 获取当前登录用户的令牌信息 * @return {Object} 登录令牌信息 */ function getUserToken() { let usertoken = userDefaults(TOKEN_KEY); return usertoken; }; /** * 添加当前登录用户的令牌信息 * @param {Object} tokenInfo 令牌信息 */ function setUserToken(tokenInfo) { let tokens = getUserToken() let newToken = Object.assign(tokens, tokenInfo); // 只有在登陆是才能获取签名、实名状态,刷新token时只会返回token,不能直接得到状态,这里只调整覆盖原来的token uni.setStorageSync(TOKEN_KEY, JSON.stringify(newToken)); }; export function parseText(txt, len) { if (txt.length > len) { var text = txt.substr(0, len) + "..." return text; } return txt; } export function parseIDCardInfo(idCard) { // 正则表达式匹配身份证号格式 var reg = /^\d{17}[\dXx]$/; if (reg.test(idCard)) { // 提取出生日期 var birthday = idCard.substring(6, 14); var year = birthday.substring(0, 4); var month = birthday.substring(4, 6); var day = birthday.substring(6, 8); // 计算年龄 var currentYear = new Date().getFullYear(); var age = currentYear - parseInt(year); // 提取性别 var genderCode = parseInt(idCard.charAt(16)); var gender = genderCode % 2 === 0 ? "女" : "男"; return { birthday: year + "-" + month + "-" + day, age: age, gender: gender }; } return null; // 身份证号格式不正确 } export function isEmpty(obj) { if (obj == undefined || obj == null || obj == "") { return true; } else { return false; } } /** * 是否登录 * @return {Boolean} true 登录 false 未登录 */ export function isLogin() { let obj = uni.getStorageSync(TOKEN_KEY); return !!obj; } export function logout() { const logoutAction = () => { uni.setStorageSync(TOKEN_KEY, null); uni.removeStorageSync("userInfo"); uni.removeStorageSync("onLaunch"); uni.removeStorageSync("companyUser"); uni.removeStorageSync("CompanyUserToken"); uni.$emit("refreshUserInfo") uni.navigateTo({ url: '/pages/auth/loginIndex' }); //关闭推送事件监听 uni.offPushMessage(); plus.runtime.setBadgeNumber(0); }; // #ifdef APP-PLUS logoutjpushId().then(res => { if (res.code == 200) { logoutAction(); } else { uni.clearStorage() uni.navigateTo({ url: '/pages/auth/loginIndex' }) // uni.showToast({ // title: res.msg, // icon: 'none' // }); } }, rej => { logoutAction(); } ); // #endif // #ifndef APP-PLUS uni.setStorageSync(TOKEN_KEY, null); uni.removeStorageSync("companyUser"); uni.removeStorageSync("CompanyUserToken"); uni.removeStorageSync("onLaunch") uni.$emit("refreshUserInfo") uni.navigateTo({ url: '/pages/auth/loginIndex' }) // #endif } var toast = function(msg) { // #ifdef APP-PLUS uni.showToast({ title: msg, icon: 'none', duration: 2000, position: 'bottom' }); // #endif // #ifdef H5 uni.showToast({ title: msg, icon: 'none', duration: 2000 }); // #endif } export function checkCompanyUserLoginState() { var token = uni.getStorageSync('CompanyUserToken'); if (token) { return true } else { return false } } export function getDictLabelName(key, dictValue) { if (dictValue == null) { return ""; } var dicts = uni.getStorageSync('dicts'); if (!dicts) { return '' } if (dicts && Object.prototype.toString.call(dicts) == '[object String]') { dicts = JSON.parse(dicts); } var dict = dicts[key] var name = ""; dict.forEach(function(item, index, array) { if (dictValue.toString() == item.dictValue.toString()) { name = item.dictLabel } }); return name; } export function getStoreDictByName(key, dictValue) { if (dictValue == null || dictValue == -1) { return "请选择"; } var dicts = uni.getStorageSync(key); var dict = JSON.parse(dicts); var name = ""; dict.forEach(function(item, index, array) { if (dictValue.toString() == item.dictValue.toString()) { name = item.dictLabel } }); return name; } var getStoreIndexByName = function(key, dictValue) { if (dictValue == null || dictValue == -1) { return [0]; } var dicts = uni.getStorageSync(key); var dict = JSON.parse(dicts); var defIndexs = [0]; dict.forEach(function(item, index, array) { if (dictValue.toString() == item.dictValue.toString()) { defIndexs = [index]; } }); return defIndexs; } var getStorageByKey = function(key) { let storageObj = uni.getStorageSync(key); var dataArr = []; if (!!storageObj) { dataArr = JSON.parse(storageObj); } return dataArr; } var getStorageNamesByKey = function(key) { let storageObj = uni.getStorageSync(key); if (!!storageObj) { var tempArr = JSON.parse(storageObj); var valueArr = []; tempArr.forEach(function(item, index, array) { valueArr.push(item.dictLabel); }); return valueArr; } } export function getDict(key) { var dicts = uni.getStorageSync('dicts'); if (dicts && Object.prototype.toString.call(dicts) == '[object String]') { dicts = JSON.parse(dicts); } var dict = dicts[key] return dict; } var photosToArr = function(photoUrl) { var photos = []; if (photoUrl != null && photoUrl != '') { photos = photoUrl.split(','); } return photos } var dateFormat = function dateFormat(fmt, date) { let ret; const opt = { "Y+": date.getFullYear().toString(), // 年 "m+": (date.getMonth() + 1).toString(), // 月 "d+": date.getDate().toString(), // 日 "H+": date.getHours().toString(), // 时 "M+": date.getMinutes().toString(), // 分 "S+": date.getSeconds().toString() // 秒 // 有其他格式化字符需求可以继续添加,必须转化成字符串 }; for (let k in opt) { ret = new RegExp("(" + k + ")").exec(fmt); if (ret) { fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0"))) }; }; return fmt; } var getProvider = service => { return new Promise((resolve, reject) => { // 获取当前环境的服务商 uni.getProvider({ service: service || 'oauth', success: function(res) { // 此处可以排除h5 if (res.provider) { resolve(res.provider[0]) } }, fail() { reject('获取环境服务商失败') }, }) }).catch(error => { console.log('167', error) }) } export function parsePhone(mobile) { var str = mobile.substr(0, 3) + "****" + mobile.substr(7); return str; } export function getAge(strBirthday) { var returnAge, strBirthdayArr = strBirthday.split("-"), birthYear = strBirthdayArr[0], birthMonth = strBirthdayArr[1], birthDay = strBirthdayArr[2], d = new Date(), nowYear = d.getFullYear(), nowMonth = d.getMonth() + 1, nowDay = d.getDate(); if (nowYear == birthYear) { returnAge = 0; //同年 则为0周岁 } else { var ageDiff = nowYear - birthYear; //年之差 if (ageDiff > 0) { if (nowMonth == birthMonth) { var dayDiff = nowDay - birthDay; //日之差 if (dayDiff < 0) { returnAge = ageDiff - 1; } else { returnAge = ageDiff; } } else { var monthDiff = nowMonth - birthMonth; //月之差 if (monthDiff < 0) { returnAge = ageDiff - 1; } else { returnAge = ageDiff; } } } else { returnAge = -1; //返回-1 表示出生日期输入错误 晚于今天 } } return returnAge; //返回周岁年龄 } const urlToObj = function(url) { let obj = {} let str = url.slice(url.indexOf('?') + 1) let arr = str.split('&') for (let j = arr.length, i = 0; i < j; i++) { let arr_temp = arr[i].split('=') obj[arr_temp[0]] = arr_temp[1] } return obj } /** * 判断是否为空对象 * @param {Object} 时间字符串 */ var isNullObj = function(obj) { let isNull = (JSON.stringify(obj) == "{}"); return isNull; } var arrContainsVal = function(arr, val) { var isContains = false; for (var i = 0; i < arr.length; i++) { if (arr[i] == val) { isContains = true; break; } } return isContains; } var arrIndexOf = function(arr, val) { var isContains = this.arrContainsVal(arr, val); if (isContains) { return arr.indexOf(val); } else { return -1; } } export function navBack() { uni.navigateBack({ animationType: 'pop-out', animationDuration: 200 }); } export function navTo(url) { uni.navigateTo({ url: url }); } export function loginNavTo(url) { if (isLogin()) { uni.navigateTo({ url: url }); } else { this.$showLoginPage(); } } export function loginCallBack() { if (isLogin()) { callBack(); } else { this.$showLoginPage(); } } /** * 获取用户信息 * */ export function getUserInfo() { let userInfo = uni.getStorageSync('userInfo'); if (userInfo && JSON.stringify(userInfo) != '{}') { userInfo = JSON.parse(userInfo); } else { userInfo = {} } return userInfo; }; export function parseIdCard(idCard) { var str = idCard.substr(0, 4) + "****" + idCard.substr(8); return str; } /** * 获取腕表用户信息 * */ export function getUser(callback) { getWatchUserInfo({ isFamily: false }).then(res => { if (res.code == 200) { uni.setStorageSync("userWatchInfo", JSON.stringify(res.user)) callback(res.user) } else { callback({}) } }) } /** * type == 1表示 00:00 改成0, 01:00 改成1, 23:00 改成23格式 * type != 1表示 0 改成00:00, 1 改成01:00, 23 改成23:00格式 */ export function formatHour(time, type) { if (type == 1) { const parts = time.split(":"); const hour = parseInt(parts[0]); return hour; } else { let str = time.toString(); if (str.length === 1) { str = '0' + str; } return str + ':00'; } } var bdCallBack = function(data, bdCmdType) { bdCallBackReq(data).then(res => { if (res.code == 200) { uni.setStorageSync("bdCmdType", bdCmdType); if (bdCmdType == 2) { uni.setStorageSync("bdCmdType", 3); } } else { uni.showToast({ icon: 'none', title: res.msg }); } }); } var bdAdvFeedback = function(aType, aValue, bdCmdType, userId) { //获取设备的各种标识码 let devinfo = uni.getDeviceInfo(); console.log("qxj bdAdvFeedback devInfo:" + JSON.stringify(devinfo)); let that = this; // #ifdef APP-PLUS idCode.getIdCodes(res => { console.log("qxj getIdCodes:" + JSON.stringify(res)); if (res.data) { let params = { "oaid": res.data.OAID, "model": devinfo.model, "osType": 2, "aType": aType, "aValue": aValue.toString() }; if (!!userId) { params["userId"] = userId; } bdCallBack(params, bdCmdType); } }); // #endif } export function registerIdCode(aType, bdCmdType, aValue, userId) { //bdCmdType -1未操作 0:激活 1:已注册 2:已下单 3:已回传 //注册,先注册再获取,注意APP合规性,若最终用户未同意隐私政策则不要调用 // #ifdef APP-PLUS let that = this; idCode.register(res => { console.log(res); bdAdvFeedback(aType, aValue, bdCmdType, userId); }); // #endif } export function dateFormatStr(fmt, date) { let dateStr = dateFormat(fmt, date); return dateStr; } // 设置tabbar消息红点 export async function updateMsgDot() { const resOther = await getLastAndReadStatus() let num1 = resOther.data && resOther.data.unReadNum ? resOther.data.unReadNum : 0 const resCourse = await getSopCourseStudyList({ pageNum: 1, pageSize: 10 }) let num2 = resCourse.isNotRead || 0 const imUnred = uni.getStorageSync("imUnread") || 0; let BadgeNumber = (num1 + num2 + imUnred) > 0 ? num1 + num2 + imUnred : -1; //BadgeNumber=num2; const status = BadgeNumber > 0 ? 1 : 0; // console.log("--qxj num1:"+num1+" num2:"+num2); // 获取当前页面实例(通常在页面生命周期或方法中调用) const currentPages = getCurrentPages(); const currentPage = currentPages[currentPages.length - 1]; const currentRoute = currentPage.route; const formattedRoute = `/${currentRoute}`; const isTabBarPage = tabBarPages.includes(formattedRoute); return; if (isTabBarPage) { if (status == 1) { uni.showTabBarRedDot({ index: 0, }); } else { uni.hideTabBarRedDot({ index: 0, }); } } // #ifdef APP-PLUS plus.runtime.setBadgeNumber(BadgeNumber) // #endif } // 绑定销售 export function handleBindCompanyFsUser(comUserId) { bindCompanyFsUser(comUserId).then(res => { if (res.code == 200) { uni.navigateTo({ url: '/pages/user/bindCompanyUser' }) } else { uni.showToast({ title: res.msg, icon: 'none' }) } // #ifdef APP-PLUS plus.runtime.arguments = '' // #endif }).catch(() => { // #ifdef APP-PLUS plus.runtime.arguments = '' // #endif }) } // 设置来源 export function setSource() { // #ifdef APP-PLUS let historyApp = plus.runtime.channel || 'app' if (plus.os.name == 'iOS') { historyApp = "iOS"; } console.log("qxj setSource"); updateHistoryApp({ historyApp: historyApp }) // #endif } // 设置来源 export function companyUserIsLogin() { let companyUser = uni.getStorageSync('companyUser'); if (!!companyUser && companyUser != '') { return true; } return false; } // 关闭订单 export function finishTransaction(transaction, iapChannel) { console.log("关闭订单") return new Promise((resolve, reject) => { iapChannel.finishTransaction(transaction, (res) => { console.log("关闭订单成功", res) resolve(res); }, (err) => { reject(err); }); }); } // 初始化注册到企业微信 export function registerQW(callback, shareItem) { let schema = getApp().globalData.shareSchema; //应用跳转标识,显示在具体应用下的 Schema字段 let appid = getApp().globalData.shareCorpId; //企业唯一标识。创建企业后显示在,我的企业 CorpID字段 let agentid = getApp().globalData.shareAgentid; //应用唯一标识。显示在具体应用下的 AgentId字段 console.log(schema, appid, agentid) if (!schema || !appid || !agentid) { uni.showToast({ title: "企业微信配置不正确", icon: "none" }) return } sdkwx.registerApp(schema, appid, agentid); isAppInstalledShare(callback, shareItem) } function uploadFilePromise(url) { return new Promise((resolve, reject) => { let a = uni.uploadFile({ url: uni.getStorageSync('requestPath') + '/app/common/uploadOSS', // 仅为示例,非真实的接口地址 filePath: url, name: 'file', formData: { user: 'test' }, success: (res) => { resolve(JSON.parse(res.data).url) }, fail: (e) => { uni.showToast({ title: "分享失败", icon: "none" }) } }); }) } //检测是否安装企业微信并分享 function isAppInstalledShare(callback, shareItem) { sdkwx.isAppInstalled(async function(ret) { if (ret) { // 处理图片 let newImg = '' const isHttp = typeof shareItem.imageUrl === 'string' && shareItem.imageUrl.startsWith("http"); if (isHttp) { newImg = shareItem.imageUrl } else { newImg = await uploadFilePromise(shareItem.imageUrl) } newImg = newImg + "?imageMogr2/thumbnail/300x" // console.log('企业微信已安装'); if (shareItem.isMini) { let appid_gh = getApp().globalData.shareAppid_gh; //必须是应用关联的小程序,注意要有@app后缀 const path = shareItem.path.replace(/\?/g, '.html?') // 分享到小程序 uni.downloadFile({ url: newImg, success: (images) => { let imagePath = plus.io.convertLocalFileSystemURL(images.tempFilePath) sdkwx.shareMiniProgram({ username: appid_gh, //必须是应用关联的小程序,注意要有@app后缀 title: shareItem.title, hdImageData: imagePath, path: path }, (resp) => { // console.log("分享到小程序",JSON.stringify(resp)); if (resp && resp.errCode == 5) { uni.showToast({ title: JSON.stringify(resp), icon: "none", duration: 2000 }) } else { if (typeof callback === 'function') { callback(ret); } } }); }, fail: (e) => { uni.showToast({ title: "分享失败", icon: "none" }) } }); } else { // 分享链接 let thumbUrl = newImg; let webpageUrl = shareItem.url; let title = shareItem.title; let description = shareItem.summary; try { sdkwx.shareLink(thumbUrl, webpageUrl, title, description); if (typeof callback === 'function') { callback(ret); } } catch (e) { console.log(e) } } } else { uni.showToast({ title: "未安装企业微信", icon: "error" }) } }); } export function checkWechatInstalled() { let isInstalled = false; if (plus.runtime.isApplicationExist({ pname: 'com.tencent.mm', action: 'weixin://' })) { isInstalled = true; } return isInstalled; } export function isAndroid() { const systemInfo = uni.getSystemInfoSync(); let isAndroid = systemInfo.platform === 'android'; return isAndroid; } export function isIos() { const systemInfo = uni.getSystemInfoSync(); let isIos = systemInfo.platform === 'ios'; return isIos; } export function isAgreePrivacy(){ // #ifdef APP-PLUS if(isAndroid()){ return plus.runtime.isAgreePrivacy(); } else{ return true; } // #endif return true; }