import store from "@/store/index.js"; import config from "@/common/config"; import api from "@/common/api.js"; export default { isGoLogin(isBack = true) { if (!uni.getStorageSync("user_account")) { uni.navigateTo({ url: "/pages4/login/login?isBack=" + isBack, }); return true; } else { return false; } }, isLogin() { if (uni.getStorageSync("user_account")) { return true; } else { return false; } }, isLogout() { // uni.removeStorageSync('user_account') // uni.removeStorageSync('token') }, //提示 showToast(title, icon = "none", time = 2000) { return setTimeout(() => { uni.showToast({ title: title, icon: icon, duration: time, }); }, 500); }, //图片路径填补 splitImgHost(url, scale = false, width = 250) { if (!url) { return ""; } else if ( url.indexOf("http") != -1 || url.indexOf("https") != -1 || url.indexOf("wxfile") != -1 ) {} else { url = config.BASE_IMG_URL + url; } if (scale) { url = url + "?x-oss-process=image/resize,w_" + width; } return url; }, setUuid(id) { uni.setStorageSync("uuid", id); }, getUuid() { return uni.getStorageSync("uuid"); }, exit() { uni.removeStorageSync("user_account"); uni.removeStorageSync("token"); uni.removeStorageSync("h5_code"); store.state.userInfo = null; uni.reLaunch({ url: "/pages/index/index", }); }, /* 时间戳转换成日期 * @param timestamp * @returns {*} */ timestampToTime(timestamp, isDay = true, hasChinese, line) { if (!timestamp) { return ""; } var date = new Date(timestamp * 1000); //时间戳为10位需*1000,时间戳为13位的话不需乘1000 var Y = date.getFullYear() + (hasChinese ? "" : "-"); var M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + (hasChinese ? "" : "-"); var D = date.getDate() < 10 ? "0" + date.getDate() + (hasChinese ? "" : " ") : date.getDate() + (hasChinese ? "" : " "); var h = date.getHours() < 10 ? "0" + date.getHours() + ":" : date.getHours() + ":"; var m = date.getMinutes() < 10 ? "0" + date.getMinutes() + ":" : date.getMinutes() + ":"; var s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); if (isDay) { if (hasChinese) { return Y + "年" + M + "月" + D + "日"; } else { return Y + M + D; } } if (line) { return h + m + s; } if (hasChinese) { return Y + "年" + M + "月" + D + "日" + h + m + s; } else { return Y + M + D + h + m + s; } }, // 时间戳转换日期 formDate(time, formate = "yyyy-mm-dd hh:mm:ss") { var padDate = function(va) { va = va < 10 ? "0" + va : va; return va; }; if (time) { var value = new Date(time * 1000); //时间戳为10位需*1000,时间戳为13位的话不需乘1000 // var value = new Date(parseFloat(time)) var year = value.getFullYear(); var month = padDate(value.getMonth() + 1); var day = padDate(value.getDate()); var hour = padDate(value.getHours()); var minutes = padDate(value.getMinutes()); var seconds = padDate(value.getSeconds()); let res = ""; switch (formate) { case "mm-dd": { res = month + "-" + day; break; } case "yyyy-mm-dd": { res = year + "-" + month + "-" + day; break; } case "yyyy-mm": { res = year + "-" + month; break; } case "mm月dd日": { res = month + "月" + day + "日"; break; } case "yyyy年mm月dd日": { res = year + "年" + month + "月" + day + "日"; break; } case "yyyy年mm月": { res = year + "年" + month + "月"; break; } case "hh:mm": { res = hour + ":" + minutes; break; } case "yyyy-mm-dd hh:mm": { res = year + "-" + month + "-" + day + " " + hour + ":" + minutes; break; } case "yyyy.mm.dd": res = year + "." + month + "." + day; break; case "yyyy-mm-dd hh:mm:ss": case "yyyy/mm/dd": res = year + "/" + month + "/" + day; break; default: { res = year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds; break; } } return res; } return "--"; }, //当前时间距离目标时间还有多久 GetRTime(EndTime, isDay = true) { var EndTime = EndTime; //结束时间 var NowTime = new Date(); //当前时间 //后台给我的是10位 精确到秒的 所有下面我就除以了1000,不要小数点后面的 var t = EndTime - (NowTime.getTime() / 1000).toFixed(0); if (t <= 0) { return "已结束"; } //如果后台给的是毫秒 上面不用除以1000 下面的计算时间也都要除以1000 这里我去掉1000了 var d = Math.floor(t / 60 / 60 / 24); //天 var d=Math.floor(t/1000/60/60/24) var h = Math.floor((t / 60 / 60) % 24); //时 var h=Math.floor(t/1000/60/60%24) var m = Math.floor((t / 60) % 60); //分 var m=Math.floor(t/1000/60%60) var s = Math.floor(t % 60); //秒 var s=Math.floor(t/1000%60) if (parseInt(d) < 10) { d = "0" + d; } if (parseInt(h) < 10) { h = "0" + h; } if (parseInt(m) < 10) { m = "0" + m; } if (parseInt(s) < 10) { s = "0" + s; } if (isDay) { return d; } return d + "天" + h + "小时" + m + "分" + s + "秒"; }, TimeTotimestamp(date) { var date = date.replace(/-/g, "/"); var newDate = new Date(date); return newDate.getTime() / 1000; }, timest() { var tmp = Date.parse(new Date()).toString(); tmp = tmp.substr(0, 10); return tmp; }, //压缩图片 imageInfos(url) { var self = this; return new Promise((resolve, reject) => { uni.getImageInfo({ src: url, success: async (res) => { let canvasWidth = res.width; //图片原始长宽 let canvasHeight = res.height; if (canvasWidth > 2000 || canvasHeight > 2000) { uni.compressImage({ src: url, quality: 75, width: "35%", height: "35%", success: async (rest) => { const waitUpload = await self.uploadFile(rest .tempFilePath, 0); console.log(waitUpload, "waitUpload"); resolve(waitUpload); }, }); } else if (canvasWidth > 1000 || canvasHeight > 1000) { uni.compressImage({ src: url, quality: 75, width: "50%", height: "50%", success: async (rest) => { const waitUpload = await self.uploadFile(rest .tempFilePath, 0); console.log(waitUpload, "waitUpload"); resolve(waitUpload); }, }); } else { const waitUpload = await self.uploadFile(url, 0); console.log(waitUpload, "waitUpload"); resolve(waitUpload); // console.log('无需压缩', url); // resolve(url); } }, }); }); }, //腾讯云上传图片 uploadFile(options, int) { return new Promise((resolve, reject) => { var self = this; // #ifdef MP-WEIXIN const isJPG = options.indexOf("//tmp") !== -1 || options.indexOf("//temp") !== -1; // #endif // #ifdef H5 const isJPG = true; // #endif if (!isJPG) { resolve(options); return; } var data = { imageStatus: int, }; uni.uploadFile({ url: config.BASE_URL +'/tengxun/cos/upload', name: "file", filePath: options, fileType: "image", header: { // AuthorizationToken: "WX " + uni.getStorageSync("token"), }, formData: { imageStatus: 14, }, success: (result) => { //console.log(result); result.data = result.data || '{}' let jsonData = JSON.parse(result.data) if (jsonData.code==200) { resolve(jsonData.data); } else { uni.showToast({ title: "上传接口报错", icon: "none", }); return; } }, fail: (error) => { uni.showToast({ title: "上传接口报错", icon: "none", }); return; }, }); }); }, //阿里云上传图片 uploadFile_aliyun(options, int) { return new Promise((resolve, reject) => { var self = this; // #ifdef MP-WEIXIN const isJPG = options.indexOf("//tmp") !== -1 || options.indexOf("//temp") !== -1; // #endif // #ifdef H5 const isJPG = true; // #endif if (!isJPG) { resolve(options); return; } var data = { imageStatus: int, }; api.aliyunpolicy(data).then((res) => { var ossToken = res.data.data.resultContent; uni.uploadFile({ url: ossToken.host, name: "file", filePath: options, fileType: "image", header: { AuthorizationToken: "WX " + uni.getStorageSync("token"), }, formData: { key: ossToken.dir, OSSAccessKeyId: ossToken.accessid, policy: ossToken.policy, Signature: ossToken.signature, callback: ossToken.callback, success_action_status: 200, }, success: (result) => { result.data = result.data || '{}' let jsonData = JSON.parse(result.data) if (jsonData.resultContent && Number(jsonData.resultContent.size) > 0) { resolve(ossToken.dir); } else { uni.showToast({ title: "上传接口报错", icon: "none", }); return; } }, fail: (error) => { uni.showToast({ title: "上传接口报错", icon: "none", }); return; }, }); }).catch(err => { uni.showToast({ title: "上传接口报错" + err, icon: "none", }); return; }) }); }, //腾讯云上传非图片文件H5 uploadFileH5(options, int,filetype) { return new Promise((resolve, reject) => { var self = this; // #ifdef MP-WEIXIN const isJPG = options.indexOf("//tmp") !== -1 || options.indexOf("//temp") !== -1; // #endif // #ifdef H5 const isJPG = true; // #endif if (!isJPG) { resolve(options); return; } uni.uploadFile({ url: config.BASE_URL +'/tengxun/cos/upload', name: "file", file: options, fileType: filetype, header: { // AuthorizationToken: "WX " + uni.getStorageSync("token"), }, formData: { imageStatus: 14, }, success: (result) => { console.log(result); result.data = result.data || '{}' let jsonData = JSON.parse(result.data) if (jsonData.code==200) { resolve(jsonData.data); } else { uni.showToast({ title: "上传接口报错", icon: "none", }); return; } }, fail: (error) => { console.log("adsd",error); uni.showToast({ title: "上传接口报错", icon: "none", }); return; }, }); }) }, //阿里云上传非图片文件H5 uploadFileH5_aliyun(options, int,filetype) { return new Promise((resolve, reject) => { var self = this; // #ifdef MP-WEIXIN const isJPG = options.indexOf("//tmp") !== -1 || options.indexOf("//temp") !== -1; // #endif // #ifdef H5 const isJPG = true; // #endif if (!isJPG) { resolve(options); return; } var data = { imageStatus: int, }; api.aliyunpolicy(data).then((res) => { var ossToken = res.data.data.resultContent; uni.uploadFile({ url: ossToken.host, name: "file", file: options, fileType: filetype, header: { AuthorizationToken: "WX " + uni.getStorageSync("token"), }, formData: { key: ossToken.dir, OSSAccessKeyId: ossToken.accessid, policy: ossToken.policy, Signature: ossToken.signature, callback: ossToken.callback, success_action_status: 200, }, success: (result) => { console.log(result); result.data = result.data || '{}' let jsonData = JSON.parse(result.data) if (jsonData.resultContent && Number(jsonData.resultContent.size) > 0) { resolve(ossToken.dir); } else { uni.showToast({ title: "上传接口报错", icon: "none", }); return; } }, fail: (error) => { console.log("adsd",error); uni.showToast({ title: "上传接口报错", icon: "none", }); return; }, }); }).catch(err => { uni.showToast({ title: "上传接口报错" + err, icon: "none", }); return; }) }); }, getYears(strBirthday) { if (!strBirthday) { return "-"; } var returnAge; var strBirthdayArr = strBirthday.split("-"); var birthYear = strBirthdayArr[0]; var birthMonth = strBirthdayArr[1]; var birthDay = strBirthdayArr[2]; var d = new Date(); var nowYear = d.getFullYear(); var nowMonth = d.getMonth() + 1; var 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; //返回周岁年龄 }, getDate() { let nowDate = new Date(); let date = { year: nowDate.getFullYear(), month: nowDate.getMonth() + 1, date: nowDate.getDate(), }; return date.year + "-" + date.month + "-" + date.date; }, getZeroTime() { return Number(new Date(new Date().toLocaleDateString()).getTime() / 1000); }, setClock: function(time) { var that = this, sec = parseInt(time), clockCount = {}, strTimer = ""; clockCount = setInterval(function() { if (sec == 0) { $(".js-count-down").html("活动已经结束"); clearInterval(clockCount); return false; } strTimer = that.secondToDate(sec); $(".js-count-down").html(strTimer); sec--; }, 1000); }, secondToDate(result) { var h = Math.floor(result / 3600) < 10 ? "0" + Math.floor(result / 3600) : Math.floor(result / 3600); var m = Math.floor((result / 60) % 60) < 10 ? "0" + Math.floor((result / 60) % 60) : Math.floor((result / 60) % 60); var s = Math.floor(result % 60) < 10 ? "0" + Math.floor(result % 60) : Math.floor(result % 60); if (h == 0) { result = m + ":" + s; } else { result = h + ":" + m + ":" + s; } return result; }, /** * * @param {int} result * @returns {string} * @remard 单位S转小时分钟秒 */ secondToTime(result, Diszing = true) { var h = Math.floor(result / 3600) < 10 ? "0" + Math.floor(result / 3600) : Math.floor(result / 3600); var m = Math.floor((result / 60) % 60) < 10 ? "0" + Math.floor((result / 60) % 60) : Math.floor((result / 60) % 60); var s = Math.floor(result % 60) < 10 ? "0" + Math.floor(result % 60) : Math.floor(result % 60); if (h == 0 && Diszing) { result = m + ":" + s; } else { result = h + ":" + m + ":" + s; } return result; }, /** * @param {Object} length 长度 * 获取随机字符串 */ getRandomString(length) { var str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; var result = ""; for (var i = length; i > 0; --i) result += str[Math.floor(Math.random() * str.length)]; return result; }, skipLogin(sign) { console.error("join") return api.skipLogin({ sign }).then((res) => { if (res.data.code == 200) { uni.removeStorageSync("newUser_sc"); uni.removeStorageSync("shareActivityCode"); //信息完善,直接进入页面 uni.setStorageSync("user_account", res.data.data.user_account); uni.setStorageSync("token", res.data.data.token); store.dispatch("getUserInfo").finally((e) => { return Promise.resolve(); }); } else { uni.navigateTo({ url: "/pages4/login/login", }); return Promise.reject(); } }); }, getCanvas(that, className = ".canvas") { return new Promise((resolve, reject) => { uni.getSystemInfo({ success: (res) => { const query = uni.createSelectorQuery().in(that); setTimeout(() => { query .select(className) .boundingClientRect() .exec((newRes) => { resolve({ systemInfo: res, newRes }); }); }, 1000); }, }); }); }, toLink(externalLink) { if (!externalLink) { uni.showModal({ showCancel: false, content: "链接不存在", }); return; } // #ifdef MP-WEIXIN uni.navigateTo({ url: `/pages5/webview/sdlink?url=` + externalLink, }); // #endif // #ifdef H5 window.location.href = externalLink; // #endif }, calculateScore(data) { let score = 0; //计算总分 let totalScore = 0; //总分 let doWrongQuestionIds = []; //做错题id(案例题简答不算在内) let doQuestionIds = []; //做过的题目id let lessQuestionNum = 0; //多选题少选 let rightQuestionIds = []; //做对的题目id let totalQuestionNum = 0; //排除主观题的总条数(简单题) data.forEach((item) => { totalScore += item.score * (item.type == 4 ? item.jsonStr.length : 1); if ( item.type < 4 || (item.type == 4 && !item.jsonStr.some((e) => e.type == 5)) ) { totalQuestionNum++; } if (item.type == 1 || item.type == 3) { //正确 if (item.ques == item.ans) { item.scoreResult = item.score; score += item.score; rightQuestionIds.push(item.questionId); } else { //错误 item.scoreResult = 0; if (item.ques) { doWrongQuestionIds.push(item.questionId); } } if (item.ques) { doQuestionIds.push(item.questionId); } } else if (item.type == 2) { let isRight = item.ans && item.ans.every((quesItem, quesIndex) => { if (item.ques) { return item.ques[quesIndex] == item.ans[quesIndex]; } else { return false; } }); if (isRight) { score += item.score; item.scoreResult = item.score; rightQuestionIds.push(item.questionId); } else { let hasPart = false; let checkboxScore = 1; //获取单题总分数 item.ques && item.ques.forEach((ques, quesIndex) => { //选错一个全扣 if (item.ques) { if (item.ans.indexOf(item.ques[quesIndex]) == -1) { checkboxScore = 0; } } else { checkboxScore = 0; } }); //没选错 if (checkboxScore) { checkboxScore = 0; item.ans.forEach((ans, quesIndex) => { //漏选扣一部分,对n题给n X partScore 分 if (item.ques) { if (item.ques.indexOf(item.ans[quesIndex]) != -1) { checkboxScore += item.partScore; hasPart = true; } } else { checkboxScore = 0; } }); } if (!hasPart) { //0分 item.scoreResult = 0; if (item.ques) { doWrongQuestionIds.push(item.questionId); } } else { //部分分 lessQuestionNum++; item.scoreResult = checkboxScore; score += checkboxScore; } } if (item.ques && item.ques.length) { doQuestionIds.push(item.questionId); } } else if (item.type == 4) { let len = item.ans.length; let questionScore = 0; if (item.ques && item.ques.length) { item.ques.forEach((ele, idx) => { if ( ele == item.ans[idx] || (item.jsonStr[idx].type == 2 && ele.toString() == item.ans[idx].toString()) ) { len--; questionScore += item.score; } }); score += questionScore; item.scoreResult = questionScore; len == 0 && rightQuestionIds.push(item.questionId); doQuestionIds.push(item.questionId); } } else if (item.type == 5) { if (item.ques && (item.ques.imageList.length || item.ques.text)) { doQuestionIds.push(item.questionId); } } }); return { reportStatus: score >= (data[0].passScore || totalScore * 0.6) ? 1 : 0, lessQuestionNum, performance: score, totalScore, doQuestionNum: doQuestionIds.length, doQuestionIds: doQuestionIds.join(","), rightQuestionIds: rightQuestionIds.join(","), rightQuestionNum: rightQuestionIds.length, rightRate: (rightQuestionIds.length / totalQuestionNum).toFixed(2), historyExamJson: JSON.stringify(data), questionIds: doWrongQuestionIds, totalQuestionNum, }; }, checkDomain(str) { let domain = /^([\w-]+\.)+((com)|(net)|(org)|(gov\.cn)|(info)|(cc)|(com\.cn)|(net\.cn)|(org\.cn)|(name)|(biz)|(tv)|(cn)|(mobi)|(name)|(sh)|(ac)| (io)|(tw)|(com\.tw)|(hk)|(com\.hk)|(ws)|(travel)|(us)|(tm)|(la)|(me\.uk)|(org\.uk)|(ltd\.uk)|(plc\.uk)|(in)|(eu)|(it)|(jp))$/; return domain.test(str); }, isWeixin() { var ua = window.navigator.userAgent.toLowerCase(); if ( ua.match(/MicroMessenger/i) == "micromessenger" || ua.match(/_SQ_/i) == "_sq_" ) { return true; } else { return false; } }, isIPad() { const userAgent = navigator.userAgent || navigator.vendor || window.opera; return /iPad/.test(userAgent); }, isTablet() { const userAgent = navigator.userAgent || navigator.vendor || window.opera; const screenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;// 判断是否是平板电脑 const isTablet = /Tablet/i.test(userAgent) || (screenWidth >= 768 && screenWidth < 1024); return isTablet; }, imageToBase64(url, quality = 0.8) { return new Promise((resolve, reject) => { url = this.splitImgHost(url); // #ifdef MP-WEIXIN let that = this; uni.downloadFile({ url, success: (res) => { if (res.statusCode === 200) { that.fileToBase64(res.tempFilePath).then((res) => { resolve(res); }); } }, }); // #endif // #ifdef H5 let image = new Image(); image.onload = function() { let canvas = document.createElement("canvas"); canvas.width = image.width; canvas.height = image.height; let context = canvas.getContext("2d"); context.drawImage(image, 0, 0, image.width, image.height); let base64 = canvas.toDataURL("image/jpeg", quality); //将图片格式转为base64 resolve(base64); }; image.setAttribute("crossOrigin", "Anonymous"); image.src = url + "?time=" + Date.now(); image.onerror = () => { reject(new Error("urlToBase64 error")); }; // #endif }); }, fileToBase64(url) { return new Promise((resolve, reject) => { // #ifdef MP-WEIXIN let fileSystem = uni.getFileSystemManager(); fileSystem.readFile({ filePath: url, encoding: "base64", position: 0, success: (res) => { resolve("data:image/jpg;base64," + res.data); }, fail(err) { console.error(err, "err"); }, }); // #endif // #ifdef H5 let reader = new FileReader(); reader.readAsDataURL(url); reader.onload = (e) => { resolve(e.target.result); }; // #endif }); }, isBase64(str) { var reg = /^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s]*?)\s*$/i; return reg.test(str); }, isObject(object) { return object !== null && typeof object === "object"; }, isEmptyObject(object) { return this.isObject(object) && Object.keys(object).length < 1; }, checkLock(action = "jxjy") { return new Promise((resolve, reject) => { api .lockLockStatus({ action, uuid: this.getUuid(), }) .then((res) => { if (res.data.code == 200) { //有其他端在操作,不能学习 uni.showModal({ title: "提示", content: "有其他端在操作,是否将该用户踢下线?", success: (res) => { if (res.confirm) { api.offline().then((r) => { if (r.data.code === 200) { resolve(); } }); } }, }); } else if (res.data.code == 500) { //可以学习 resolve(); } }); }); }, myBrowser() { var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串 console.log(userAgent) var isOpera = userAgent.indexOf("Opera") > -1 || userAgent.indexOf("OPR") > -1; //判断是否Opera浏览器 var isQQ = userAgent.indexOf("QQBrowser") > -1; //判断是否QQBrowser浏览器 var isUC = userAgent.indexOf("UCBrowser") > -1; //判断是否UC浏览器 var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE7~IE10浏览器 var isIE11 = userAgent.indexOf("compatible") === -1 && userAgent.indexOf("Trident") > -1; //判断是否IE11浏览器 var isEdge = userAgent.indexOf("Edge") > -1; //判断是否IE的Edge浏览器 var isFF = userAgent.indexOf("Firefox") > -1; //判断是否Firefox浏览器 var isSafari = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") === -1; //判断是否Safari浏览器 var isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("; Win") > -1 && userAgent.indexOf("Safari") > -1; //判断Chrome浏览器 var is360 = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("; WOW") > -1 && userAgent.indexOf("Safari") > -1; //判断360浏览器 if (isIE) { var reIE = /MSIE (\d+)\.\d+;/; // match() 返回一个数组。数组第一项是匹配到的所有文本;数组第二项是正则中小括号匹配到的文本 var matchReg = userAgent.match(reIE) var fIEVersion = matchReg[1]; if (fIEVersion == 7) { return "IE7及其以下"; } else if (fIEVersion == 8) { return "IE8"; } else if (fIEVersion == 9) { return "IE9"; } else if (fIEVersion == 10) { return "IE10"; } else { return "0"; } //IE版本过低 return "IE"; } if (isUC) { return "UC"; } if (isQQ) { return "QQBrowser"; } if (isIE11) { return "IE11"; } if (isOpera) { return "Opera"; } if (isEdge) { return "Edge"; } if (isFF) { return "Firefox"; } if (isSafari) { return "Safari"; } if (isChrome) { return "Chrome"; } if (is360) { return "360"; } }, };