You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
customAgent/src/utils/utils.js

1010 lines
38 KiB

import { useAppStore } from '@/store/app.js'
import wx from "weixin-js-sdk";
import CryptoJS from 'crypto-js'
import { showToast, showLoadingToast, closeToast } from 'vant'
import { fetchPost } from "@/utils/https"
// 惰性获取 Pinia store(替代原 Vuex 的 import store from "@/store")
const appStore = () => useAppStore()
export default {
//侦听事件
on: function (ele, ev, handler) {
if (ele.addEventListener) {
ele.addEventListener(ev, handler, false)
} else {
ele.attachEvent('on' + ev, function () {
fn.call(handler);
})
}
},
//取消事件
off: function (ele, ev, handler) {
if (ele.removeEventListener) {
ele.removeEventListener(ev, handler, false)
} else {
ele.detachEvent('on' + ev, function () {
fn.call(handler);
})
}
},
//添加class
addClass: function (ele, cls) {
var oClass = ele.className.split(' ');
if (!ele.className) {
ele.className = cls;
return;
}
for (var i = 0; i < oClass.length; i++) {
if (oClass[i] === cls) {
return;
}
}
ele.className += " " + cls;
},
//移除class
removeClass: function (obj, sClass) {
var aClass = obj.className.split(' ');
if (!obj.className) return;
for (var i = 0; i < aClass.length; i++) {
if (aClass[i] === sClass) {
aClass.splice(i, 1);
obj.className = aClass.join(' ');
break;
}
}
},
//类名包含
hasClass: function (elem, className) {
if (elem.classList) {
return elem.classList.contains(className);
} else {
return new RegExp('(^| )' + className + '( |$)', 'gi').test(elem.className);
}
},
//处理a标签href为空情况下刷新页面问题
aHrefJump(className) {
if (className) {
let tagA = Array.from(className);
tagA.forEach(e => {
if (!e.getAttribute('href')) {
e.setAttribute('href', 'javascript:;');
}
});
}
},
getPerformanceTiming() {
var performance = window.performance;
if (!performance) {
// 当前浏览器不支持
console.log('你的浏览器不支持 performance 接口');
return;
}
// var t = performance.timing;
// var times = {};
// //【重要】页面加载完成的时间
// //【原因】这几乎代表了用户等待页面可用的时间
// times.loadPage = t.loadEventEnd - t.navigationStart;
// //【重要】解析 DOM 树结构的时间
// //【原因】反省下你的 DOM 树嵌套是不是太多了!
// times.domReady = t.domComplete - t.responseEnd;
// //【重要】重定向的时间
// //【原因】拒绝重定向!比如,http://example.com/ 就不该写成 http://example.com
// times.redirect = t.redirectEnd - t.redirectStart;
// //【重要】DNS 查询时间
// //【原因】DNS 预加载做了么?页面内是不是使用了太多不同的域名导致域名查询的时间太长?
// // 可使用 HTML5 Prefetch 预查询 DNS ,见:[HTML5 prefetch](http://segmentfault.com/a/1190000000633364)
// times.lookupDomain = t.domainLookupEnd - t.domainLookupStart;
// //【重要】读取页面第一个字节的时间
// //【原因】这可以理解为用户拿到你的资源占用的时间,加异地机房了么,加CDN 处理了么?加带宽了么?加 CPU 运算速度了么?
// // TTFB 即 Time To First Byte 的意思
// // 维基百科:https://en.wikipedia.org/wiki/Time_To_First_Byte
// times.ttfb = t.responseStart - t.navigationStart;
// //【重要】内容加载完成的时间
// //【原因】页面内容经过 gzip 压缩了么,静态资源 css/js 等压缩了么?
// times.request = t.responseEnd - t.requestStart;
// //【重要】执行 onload 回调函数的时间
// //【原因】是否太多不必要的操作都放到 onload 回调函数里执行了,考虑过延迟加载、按需加载的策略么?
// times.loadEvent = t.loadEventEnd - t.loadEventStart;
// // DNS 缓存时间
// times.appcache = t.domainLookupStart - t.fetchStart;
// // 卸载页面的时间
// times.unloadEvent = t.unloadEventEnd - t.unloadEventStart;
// // TCP 建立连接完成握手的时间
// times.connect = t.connectEnd - t.connectStart;
var times = {};
var timing = performance.timing;
var start = timing.navigationStart;
times.dnsTime = timing.domainLookupEnd - timing.domainLookupStart;
times.tcpTime = timing.connectEnd - timing.connectStart;
times.firstPaintTime = timing.responseStart - start;
times.domRenderTime = Math.abs(timing.domContentLoadedEventEnd - start);
times.loadTime = Math.abs(timing.loadEventEnd - start);
console.log('DNS解析时间:', times.dnsTime)
console.log('TCP建立时间:', times.tcpTime)
console.log('首屏时间:', times.firstPaintTime / 1000 + 's')
console.log('dom渲染完成时间:', times.domRenderTime / 1000 + 's')
console.log('页面onload时间:', times.loadTime / 1000 + 's')
return times;
},
formatTimer() {
let date = new Date();
let y = date.getFullYear();
let MM = date.getMonth() + 1;
MM = MM < 10 ? "0" + MM : MM;
let d = date.getDate();
d = d < 10 ? "0" + d : d;
let h = date.getHours();
h = h < 10 ? "0" + h : h;
let m = date.getMinutes();
m = m < 10 ? "0" + m : m;
let s = date.getSeconds();
s = s < 10 ? "0" + s : s;
let S = date.getMilliseconds();
S = S < 10 ? "0" + S : S;
console.log("页面加载时间:", y + "-" + MM + "-" + d + " " + h + ":" + m + ":" + s);
return y + "-" + MM + "-" + d + " " + h + ":" + m + ":" + s;
},
//获取样式
getStyle: function (dom, attr) {
return dom.currentStyle ? dom.currentStyle[attr] : getComputedStyle(dom, false)[attr];
},
//获取url参数
getUrlKey: function (name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || "";
},
//可见窗口大小
view: function () {
return {
w: document.documentElement.clientWidth,
h: document.documentElement.clientHeight
};
},
// 时间格式化
time_formatter(time) {
let year = time.getFullYear()
let month = time.getMonth() + 1
let date = time.getDate()
let hour = time.getHours()
let minute = time.getMinutes()
let second = time.getSeconds()
month = month < 10 ? `0${month}` : month
date = date < 10 ? `0${date}` : date
hour = hour < 10 ? `0${hour}` : hour
minute = minute < 10 ? `0${minute}` : minute
second = second < 10 ? `0${second}` : second
return `${year}-${month}-${date} ${hour}:${minute}:${second}`
},
//计算base64图片的大小
countBase64Size: function (base64) {
let str = base64.split(",")[1];
let equalIndex = str.indexOf('=');
if (str.indexOf('=') > 0) {
str = str.substring(0, equalIndex);
}
let strLength = str.length;
let fileLength = parseInt(strLength - (strLength / 8) * 2);
return fileLength;
},
//判断是不是微信浏览器
isWeiXin() {
var ua = window.navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) == "micromessenger") {
return true;
} else {
return false;
}
},
//判断是不是小程序
isMiniProgram() {
var ua = window.navigator.userAgent.toLowerCase();
if (ua.match(/miniProgram/i) == "miniprogram") {
return true;
} else {
return false;
}
},
// VIN码验证
validate_vin(vin) {
if (vin.length > 0 && vin.length != 17) {
return false;
}
let vinVal = vin.toUpperCase();
let charToNum = { A: 1, B: 2, C: 3, D: 4, E: 5, F: 6, G: 7, H: 8, J: 1, K: 2, L: 3, M: 4, N: 5, P: 7, R: 9, S: 2, T: 3, U: 4, V: 5, W: 6, X: 7, Y: 8, Z: 9 };
let obj = 0;
let arr = new Array();
for (let i = 0; i < vinVal.length; i++) {
let temp = vinVal.charAt(i);
if (charToNum[temp]) {
arr[i] = charToNum[temp];
} else {
arr[i] = Number(temp);
}
if (i == 8) {
arr[i] = vinVal.charAt(i);
}
}
let a1 = 8;
for (let i = 0; i < 7; i++) {
obj += Number(arr[i]) * a1;
a1--;
}
obj += Number(arr[7]) * 10;
let a2 = 9;
for (let i = 9; i < 17; i++) {
obj += Number(arr[i]) * a2;
a2--;
}
let result = Number(obj) % 11;
if (parseInt(result) === 10) {
result = "X";
}
if (result == arr[8]) {
//成功
return true;
} else {
//失败
return false;
}
},
// 去除base64前缀
delete_prefix_Base64(base64) {
return base64.replace('data:image/jgp', 'data:image/jpeg').replace(
/data:image\/jpeg;base64,/gi,
""
)
},
// 获取url的参数
getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)")
var r = window.location.search.substr(1).match(reg)
if (r != null) return unescape(r[2])
return null
},
/**
* [获取URL中的参数名及参数值的集合]
* 示例URL:http://htmlJsTest/getrequest.html?uid=admin&rid=1&fid=2&name=小明
* @param {[string]} urlStr [当该参数不为空的时候,则解析该url中的参数集合]
* @return {[string]} [参数集合]
*/
getUrlParams(urlStr) {
urlStr = urlStr || window.location.href; //获取url中"?"符后的字串
if (typeof urlStr == "undefined") {
var url = decodeURIComponent(location.search); //获取url中"?"符后的字符串
} else {
var url = "?" + urlStr.split("?")[1];
}
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
var strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
if (decodeURIComponent(strs[i].split("=")[1]) == '' || decodeURIComponent(strs[i].split("=")[1]) == null || decodeURIComponent(strs[i].split("=")[1]) == 'null' || decodeURIComponent(strs[i].split("=")[1]) == undefined || !decodeURIComponent(strs[i].split("=")[1])) {
theRequest[strs[i].split("=")[0]] = '';
}
}
}
return theRequest;
},
/**
* 增加Cookie
* @param name
* @param value
* @param hours
* @return
*/
writeCookie(name, value, hours) {
var expire = "";
if (hours != null) {
expire = new Date((new Date()).getTime() + hours * 3600000);
expire = "; expires=" + expire.toGMTString();
}
document.cookie = name + "=" + encodeURI(value) + expire;
},
/**
* 读取Cookie
* @param name
* @return
*/
readCookie(name) {
var cookieValue = "";
var search = name + "=";
if (document.cookie.length > 0) {
var offset = document.cookie.indexOf(search);
if (offset != -1) {
offset += search.length;
var end = document.cookie.indexOf(";", offset);
if (end == -1) {
end = document.cookie.length;
}
cookieValue = decodeURI(document.cookie.substring(offset, end));
}
}
return cookieValue;
},
setTitle(title) {
// document.title = title;
var mobile = navigator.userAgent.toLowerCase();
if (/iphone|ipad|ipod/.test(mobile)) {
var iframe = document.createElement('iframe')
iframe.style.display = 'none'
// iframe.setAttribute('src', '')
var iframeCallback = function () {
setTimeout(function () {
iframe.removeEventListener('load', iframeCallback);
document.body.removeChild(iframe);
}, 0)
}
iframe.addEventListener('load', iframeCallback);
document.body.appendChild(iframe)
}
},
isPc() {
var ua = navigator.userAgent.toLowerCase();
var mobile = /mobile/gi.test(ua);
if (!mobile) {
console.log('当前为PC')
return true;
} else {
console.log('当前不是PC')
return false;
}
},
//判断是安卓或ios
isAndroid() {
var userNav = navigator.userAgent;
var isAndroid = userNav.toLowerCase().indexOf('android') > -1 || userNav.toLowerCase().indexOf('adr') > -1; //android终端
var isiOS = !!userNav.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
var isAndroidIOS = '';
if (isAndroid) {
isAndroidIOS = 'isAndroid';
} else if (isiOS) {
isAndroidIOS = 'isiOS';
}
return isAndroidIOS;
},
//判断系统类型:安卓、iOS、鸿蒙
getSystemType() {
var userAgent = navigator.userAgent.toLowerCase();
var systemType = 'unknown';
// 判断鸿蒙系统(HarmonyOS)
// 鸿蒙系统的userAgent中可能包含 'harmonyos' 或 'ohos'
if (userAgent.indexOf('harmonyos') > -1 || userAgent.indexOf('HarmonyOS') || userAgent.indexOf('ohos') > -1) {
systemType = 'harmonyos';
}
// 判断iOS系统
else if (userAgent.indexOf('iphone') > -1 || userAgent.indexOf('ipad') > -1 || userAgent.indexOf('ipod') > -1 || !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
systemType = 'ios';
}
// 判断安卓系统
else if (userAgent.indexOf('android') > -1 || userAgent.indexOf('adr') > -1) {
systemType = 'android';
}
return systemType;
},
onBridgeReady() {
try {
if (this.isWeiXin()) {
WeixinJSBridge.call('hideOptionMenu');
}
} catch (error) {
console.log(error.message)
}
},
/**
* 是否禁用右上角
*/
disabledOptionMenu() {
var that = this;
if (typeof WeixinJSBridge == "undefined") {
if (document.addEventListener) {
document.addEventListener('WeixinJSBridgeReady', that.onBridgeReady(), false);
} else if (document.attachEvent) {
document.attachEvent('WeixinJSBridgeReady', that.onBridgeReady());
document.attachEvent('onWeixinJSBridgeReady', that.onBridgeReady());
}
} else {
that.onBridgeReady();
}
},
/**
* 隐藏微信网页底部的导航栏
*/
disabledToolbar(disable = true) {
if (typeof WeixinJSBridge == "undefined") {
document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
// 通过下面这个API隐藏底部导航栏
WeixinJSBridge.call(disable ? 'hideToolbar' : 'showToolbar');
});
}
},
closeWindow() {
var userAgent = navigator.userAgent;
if (appStore().notitle === '1') {
return
}
try {
if (this.isMiniProgram()) {
wx.miniProgram.navigateBack({ delta: 1 });
} else if (this.isWeiXin()) {
// 微信中关闭
setTimeout(function () {
// alert("关闭页面"); //必须有弹窗,否则可能无法关闭
//这个可以关闭安卓系统的手机
document.addEventListener('WeixinJSBridgeReady', function () {
WeixinJSBridge.call('closeWindow');
}, false);
//这个可以关闭ios系统的手机
WeixinJSBridge.call('closeWindow');
}, 300)
} else {
// 浦发银行返回按钮跳转到基座
if (appStore().source === '95410000') {
window.location.href = `https://${location.origin.includes("-dev") || location.origin.includes("-sit") || location.origin.includes("-uat") || location.origin.includes("-pt") ? 'life-open-sit' : 'life-open'}.trace.com.cn/web-guard-h5/`;
return
}
if (window.wxx && typeof (window.wxx.back) == 'function') {
window.wxx.back();
} else if (userAgent.indexOf("Firefox") != -1 || userAgent.indexOf("Chrome") != -1) {
window.open('', '_self', '');
open(location, '_self').close();
window.location.href = "about:blank";
window.close();
} else if (userAgent.indexOf('Android') > -1 || userAgent.indexOf('Linux') > -1) {
window.opener = null;
window.open('about:blank', '_self', '').close();
} else {
window.opener = null;
window.open("", "_self");
window.close();
}
}
} catch (error) {
// console.log("关闭页面closeWindow", error.message)
}
},
//判断网络状态
onLine(callback) {
var curWwwPath = window.document.location.href;
var pathName = window.document.location.pathname;
var pos = curWwwPath.indexOf(pathName);
var host = window.location.host;
var protocol = window.location.protocol;
var localhostPaht = curWwwPath.substring(0, pos);
var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
var isWs = protocol == 'https:' ? 'wss' : 'ws';
var img = new Image();
if (localhostPaht.indexOf("localhost") >= 0) {
img.src = `https://ssp-dev.trace.com.cn${projectName}/favicon.ico?v=${Date.now()}`;
} else {
img.src = `${localhostPaht}${projectName}/favicon.ico?v=${Date.now()}`;
}
// console.log("判断有没有网络==", img.src);
img.onload = function () {
if (callback) callback(true)
};
img.onerror = function () {
if (callback) callback(false)
};
},
appendUrl(params, flag) {
var urlPar = '';
Object.getOwnPropertyNames(params).forEach((item, index) => {
if (index === 0 && !flag) {
urlPar += `?${item}=${params[item]}`;
} else {
urlPar += `&${item}=${params[item]}`
}
});
// console.log(urlPar)
return urlPar;
},
openWxPage(url, params) {
let flag = url.indexOf("?") != -1 ? true : false
let urlPar = '';
if (url) {
if (params) {
Object.getOwnPropertyNames(params).forEach((item, index) => {
if (index === 0 && !flag) {
urlPar += `?${item}=${params[item]}`;
} else {
urlPar += `&${item}=${params[item]}`
}
});
}
console.log(url + urlPar)
setTimeout(() => {
closeToast();
window.location.href = url + urlPar ;
}, 200);
} else {
console.log('跳转链接不存在!')
}
},
// 给付系统跳转链接, 从后台获取,外联库也会走这里
openSpecPage(params) {
if(params.generateType == 0){
//官微跳转
window.location.href = params.url;
}else if(params.generateType == 3){
// 查门店不调用前置接口
const userInfo = appStore().userInfo
let cmdUrl =`${params.url}&idnum=1&openId=${userInfo.sourceUserId}&entryOpenid=${userInfo.entryOpenid}`
fetchPost("semantic/getYdbqTicket", { url: cmdUrl , generateType:params.generateType ,userId:appStore().userId,isCmd:"1"}).then(ticketRes => {
console.log(ticketRes)
if (ticketRes.code === 0) {
//data空表示开关关闭
if (ticketRes.data === "" || ticketRes.data === null || ticketRes.data === undefined) {
window.location.href = params.url;
} else {
const ticketUrl = params.url + `&accessTicket=${ticketRes.data}`
console.log("ticketUrl===",ticketUrl)
window.location.href = ticketUrl;
}
} else {
showToast("网络异常,请重试")
}
})
}else if(params.generateType == 4){
// 1v1专属服务
const userInfo = appStore().userInfo
fetchPost("thirdPartyAuth/getExclusiveServicesToken").then(res=>{
if(res.code===0){
if(res.data){
let vUrl=`${params.url}&sour=yykf&omoSource=${userInfo.source}&omoSourceName=${encodeURIComponent(userInfo.sourceName)}&token=${res.data}`
window.location.href =vUrl
}
}else{
showToast("网络异常,请重试")
}
})
}else if(params.generateType == 5){
// 一站式复效
let yParams=params.url.split('&')
fetchPost("semantic/getYzsUrl",{userId:appStore().userId,bqType:yParams[0],urlType:yParams[1]}).then(res=>{
if(res.code===0){
if(res.data){
window.location.href =res.data
}
}else{
showToast("网络异常,请重试")
}
})
}else if(params.generateType == 6){
//官微小程序
const url = params.url
wx.miniProgram.navigateTo({
url
});
}else{
fetchPost("semantic/generateUrl", params)
.then(res => {
if (res.code && res.code != 0) {
showToast(res.msg);
return;
}
//置换密匙
const newUrl = res.data;
fetchPost("semantic/getYdbqTicket", { url: newUrl , generateType:params.generateType ,userId:appStore().userId}).then(ticketRes => {
if (ticketRes.code === 0) {
//data空表示开关关闭
if (ticketRes.data === "" || ticketRes.data === null || ticketRes.data === undefined) {
window.location.href = params.url;
} else {
const ticketUrl = params.url + `&accessTicket=${ticketRes.data}`
console.log(ticketUrl)
window.location.href = ticketUrl;
}
} else {
showToast("网络异常,请重试")
}
})
})
.catch(err => {
console.error(err)
});
}
},
//在app内打开h5(带参数)
AppOpenH5(url, params) {
let flag = url.indexOf("?") != -1 ? true : false
let urlPar = '';
if (url) {
if (params) {
Object.getOwnPropertyNames(params).forEach((item, index) => {
if (index === 0 && !flag) {
urlPar += `?${item}=${params[item]}`;
} else {
urlPar += `&${item}=${params[item]}`
}
});
}
// console.log(url + urlPar)
showLoadingToast('跳转中...');
setTimeout(() => {
closeToast();
this.AppRedirect(url + urlPar);
}, 200);
} else {
console.log('跳转链接不存在!')
}
},
//app 壳的方法 跳转购买产品 跳转享服务 官网
AppToOutModules(params) {
params = params || '';
//寿险:
//跳转购产品:
// {
// "from": "yykfTosxapp", // yykfTosxapp — 从洋洋客服进入到寿险APP流程
// "toPage": "BuyProduct", // BuyProduct — 跳转到购产品页面
// "extParams": {
// }, // 扩展参数
// }
//跳转享服务:
// {
// "from": "yykfTosxapp", // yykfTosxapp — 从洋洋客服进入到寿险APP流程
// "toPage": "ServicesPage", // ServicesPage — 跳转到享服务页面
// "extParams": { }, // 扩展参数
// }
//官网:
// {
// "appId":"com.trace.app.rnbxx"
// "appType":"reactnative"
// "url":"/pages/screen/main/Initialize.js"
// "params":
// {
// "source":"sapp"
// }
// }
try {
if (!window.wxx && appStore().source != '95290000') {//如果不是app渠道
showToast('当前为跳转APP功能按钮,请在APP中点击。');
// window.location.href = params.url;
} else {
window.wxx.toOutModules(params);
}
// console.log('调用app方法toOutModules==', params)
} catch (error) {
// console.log(error.message)
}
},
//app 壳的方法 打开外部链接 url:跳转的url地址
AppToHttpHtml(url) {
url = url || '';
try {
if (!window.wxx && appStore().source != '95290000') {
window.location.href = url;
} else {
window.wxx.toHttpHtml(url);
}
// console.log('调用app方法toHttpHtml==', url)
} catch (error) {
// console.log(error.message)
}
},
//app 壳的方法 内部打开链接方法 (url:跳转的url地址 titleName:title名字)
AppRedirect(url, titleName) {
url = url || '';
titleName = titleName || '洋洋客服';
try {
if (!window.wxx && appStore().source != '95290000') {
window.location.href = url;
} else {
window.wxx.redirect(url, titleName);
}
} catch (error) {
// console.log(error.message)
}
},
//app 壳的方法 copy (msg:复制内容)
AppCopy(msg) {
msg = msg || '';
try {
if (!window.wxx && appStore().source != '95290000') {
showToast('请在App里使用');
} else {
window.wxx.copyBoard(msg);
// if (this.isAndroid() == 'isiOS') {
// window.wxx.copyBoard(msg);
// } else if (this.isAndroid() == 'isAndroid') {
// window.wxx.copy(msg);
// }
}
} catch (error) {
// console.log(error.message)
}
},
//退出页面
AppBack() {
try {
if (!window.wxx && appStore().source != '95290000') {
this.closeWindow();
} else {
window.wxx.back();
}
} catch (error) {
// console.log(error.message)
}
},
AppReloadHtml() {
try {
if (!window.wxx && appStore().source != '95290000') {
window.location.reload();
} else {
window.wxx.reloadHtml();
}
} catch (error) {
// console.log(error.message)
}
},
// 替换url中的参数
changeURLArg(url, arg, arg_val) {
var pattern = arg + '=([^&]*)';
var replaceText = arg + '=' + arg_val;
if (url.match(pattern)) {
var tmp = '/(' + arg + '=)([^&]*)/gi';
tmp = url.replace(eval(tmp), replaceText);
return tmp;
} else {
if (url.match('[\?]')) {
return url + '&' + replaceText;
} else {
return url + '?' + replaceText;
}
}
},
async useSdk(item) {
// 洋洋客服人工满意度评价推送优化(坐席接通后,顾客不说话不触发满意度)
if(!appStore().isHumanChat){
return
}
//开关关闭不调用
if(!appStore().mydFlag){
return
}
//满意度黑名单用户
if (appStore().reviewRestricted) {
console.log('满意度黑名单用户');
return
}
console.log('结束会话的item====',item);
//新老满意度判断
if (appStore().integratedUser) {
// 触发自定义人工满意度评价弹窗
console.log('触发自定义人工满意度评价弹窗');
const hxSessionId = item.hxSessionId
appStore().setHxSessionId(hxSessionId);
appStore().setShowHumanAppraise(true);
} else {
if (!appStore().sdkLoaded) {
console.log('sdk未加载');
return
}
const fn = window.Evaluate?.default;
const businessNo = item.hxSessionId || item.sessionId || appStore().sessionId
if (typeof fn !== 'undefined' && fn?.Entrance) {
let obj = {
isDialog: "1",
businessNo: businessNo,
sceneNo: '80e6959f3dd111ef93216805caef3a29',
systemNo: 'FWZC',
userType: 'C',
// oprNo: localStorage.userId,
oprNo: appStore().userId,
oprIdType: 'z',
terminal: 'MOBILE',
target: 'myd',
ENV: location.host.includes('-sit') ? 'SIT' : 'PRO',
nextUrl: '',
nextUrlParams: {}
}
console.log('useSdk',obj);
try {
const result = await fn.Entrance(obj);
console.log('useSdk--result',result);
if (result.type == '00') {
showToast('您已完成本次满意度调查,谢谢您的参与!')
}
} catch (error) {
console.error('Error calling SDK method', error);
}
} else {
console.error('SDK function or method not available');
}
}
},
async useTechSdk() {
if (!appStore().sdkLoaded) {
setTimeout(() => {
showToast('满意度调查加载失败,请重试');
}, 500);
return
}
const fn = window.Evaluate?.default;
const businessNo = appStore().sessionId
const userInfo = appStore().userInfo
const oprIdType = 'z';
const oprNo = userInfo.sourceUserId
if (typeof fn !== 'undefined' && fn?.Entrance) {
let obj = {
isDialog: "1",
businessNo: businessNo,
sceneNo: 'e386b9895eca11ef9912946daedd8bf0',
systemNo: 'FWZC',
userType: 'C',
oprNo,
oprIdType,
terminal: 'MOBILE',
target: 'myd',
ENV: location.host.includes('-sit') ? 'SIT' : 'PRO',
nextUrl: '',
nextUrlParams: {}
}
console.log(obj);
try {
const result = await fn.Entrance(obj);
if (result.type == '00') {
showToast('您已完成本次满意度调查,谢谢您的参与!')
}
} catch (error) {
console.error('Error calling SDK method', error);
}
} else {
console.error('SDK function or method not available');
}
},
// 打开小程序
launchVideoServiceMiniProgram(params, callback) {
try {
if (appStore().source === '95290000') {
// 超级APP环境,使用SuperAPPUtils打开小程序
if (window.SuperAPPUtils && typeof window.SuperAPPUtils.launchWXMiniProgram === 'function') {
window.SuperAPPUtils.launchWXMiniProgram(params, callback);
} else {
console.log('SuperAPPUtils not available');
if (callback) callback({ status: 9999, statusMsg: "SuperAPPUtils not available" });
}
} else {
console.log('Video service mini program only available in SuperAPP');
if (callback) callback({ status: 9999, statusMsg: "Not in SuperAPP" });
}
} catch (error) {
console.log('launchVideoServiceMiniProgram error:', error.message);
if (callback) callback({ status: 9999, statusMsg: error.message });
}
},
// 归一化与降级解析特殊标签消息
normalizeMessage: function (item) {
if (!item || typeof item !== 'object') return item;
let msgText = item.msgText || '';
// 保单时效性类型的答案,直接返回
if(!!item.cmd && (item.cmd == 'yhzzsx' ||
item.cmd == 'fhzzsx' ||
item.cmd == 'scjzzsx' ||
item.cmd == 'wnzhzzsx' ||
item.cmd == 'tbzzsx' ||
item.cmd == 'dkzzsx' ||
item.cmd == 'lpzzsx' ||
item.cmd == 'grtbbd' ||
item.cmd == 'tttbbd' ||
item.cmd == 'YYWDBD' ||
item.cmd == 'YYWDDA' ||
item.cmd == 'GMMDBDCX' ||
item.cmd == '$gmmdbdcx-da' ||
item.cmd == 'RGAN' ||
item.cmd == 'XQJFZZSXBD' ||
item.cmd == '$xqjfzzsx-da' ||
item.cmd == '$zzsx-da')){
return item;
}
// 1. 模块推送 [scene]
if (msgText.toLowerCase().includes('[scene]')) {
let match = msgText.match(/\[scene\]([\s\S]*?)\[\/scene\]/i);
if (match && match[1]) {
try {
let parsed = JSON.parse(match[1]);
item.sceneData = item.sceneData ? Object.assign({}, parsed, item.sceneData) : parsed;
} catch (e) {
console.warn("Parse [scene] failed:", e);
}
}
item.reqAndResType = '21';
if (!item.msgType) item.msgType = '01';
}
// 2. 卡片/表单推送 [cardpush] 或 [card_push]
if (msgText.toLowerCase().includes('[cardpush]') || msgText.toLowerCase().includes('[card_push]')) {
let match = msgText.match(/\[(?:cardpush|card_push)\]([\s\S]*?)\[\/(?:cardpush|card_push)\]/i);
if (match && match[1]) {
try {
let parsed = JSON.parse(match[1]);
item.cardPushDto = item.cardPushDto ? Object.assign({}, parsed, item.cardPushDto) : parsed;
} catch (e) {
console.warn("Parse [cardpush] failed:", e);
}
}
item.reqAndResType = '22';
if (!item.msgType) item.msgType = '01';
}
// 3. 转产险 [transfer] 或 [sxzcx]
if (msgText.toLowerCase().includes('[transfer]') || msgText.toLowerCase().includes('[sxzcx]')) {
let match = msgText.match(/\[(?:transfer|sxzcx)\]([\s\S]*?)\[\/(?:transfer|sxzcx)\]/i);
if (match && match[1]) {
try {
let parsed = JSON.parse(match[1]);
item.transferDto = item.transferDto ? Object.assign({}, parsed, item.transferDto) : parsed;
} catch (e) {
console.warn("Parse [transfer] failed:", e);
}
}
item.reqAndResType = '23';
if (!item.msgType) item.msgType = '01';
}
// 4. 引用消息 [quoted] 或 [quote]
if (typeof item.quoteData === 'string') {
try {
item.quoteData = JSON.parse(item.quoteData);
} catch (e) {
console.warn("Parse string quoteData failed:", e);
}
} else if (!item.quoteData && (msgText.toLowerCase().includes('[quoted]') || msgText.toLowerCase().includes('[quote]'))) {
let match = msgText.match(/\[(?:quoted|quote)\]([\s\S]*?)\[\/(?:quoted|quote)\]/i);
if (match && match[1]) {
try {
item.quoteData = JSON.parse(match[1]);
} catch (e) {
item.quoteData = { quoteMsg: match[1], quoteType: '1' };
}
}
}
return item;
}
}