代码偏译

master
wujingling0908 2 weeks ago
parent a46b274612
commit 754591bc4c
  1. 9
      src/store/index.js
  2. 22
      src/utils/config.js
  3. 4
      src/utils/http.js
  4. 324
      src/utils/https.js
  5. 100
      src/views/chat.vue
  6. 9
      vite.config.js

@ -121,7 +121,7 @@ export const useAppStore = defineStore('app', () => {
const msgReply = ref(true)
const hotUserData = ref(null)
function set_isBqCalcClaim(isBqCalcClaim) {
function setIsBqCalcClaim(isBqCalcClaim) {
isBqCalcClaim.value = isBqCalcClaim
}
function set_token(token) {
@ -189,7 +189,7 @@ export const useAppStore = defineStore('app', () => {
console.log(e)
}
}
function set_source(notitle) {
function set_notitle(notitle) {
notitle.value = notitle
try {
localStorage.notitle = notitle
@ -570,15 +570,16 @@ export const useAppStore = defineStore('app', () => {
mydFlag,
msgReply,
hotUserData,
set_isBqCalcClaim,
setIsBqCalcClaim,
set_token,
set_sessionId,
setSessionId,
set_configId,
set_appentry,
set_bpErrorInfo,
del_token,
set_userid,
set_source,
set_notitle,
set_planCode,
set_entrance,
set_elder,

@ -1,9 +1,9 @@
let curWwwPath = window.document.location.href;
let pathName = window.document.location.pathname;
let curWwwPath = window.location.href;
let pathName = ''; // window.location.pathname
let pos = curWwwPath.indexOf(pathName);
let host = window.location.host;
let protocol = window.location.protocol;
let localhostPaht = curWwwPath.substring(0, pos);
let localhostPath = curWwwPath // downSource.substring(0, pos);
let projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
let isWs = protocol == 'https:' ? 'wss' : 'ws';
@ -12,28 +12,28 @@ let WSURL = '';
let envType = '';
//开发环境
if(localhostPaht.indexOf("localhost") >=0 || localhostPaht.indexOf("172.16") >=0){
if(localhostPath.indexOf("localhost") >=0 || localhostPath.indexOf("172.16") >=0){
baseUrl = '/api';
WSURL = `${isWs}://${host}/api/liics_api/webSocket/`; //ws://ssp-dev.trace.com.cn/liics_api/webSocket/
envType = 'dev';
//测试环境
}else if(
localhostPaht.includes("-dev") ||
localhostPaht.includes("-sit") ||
localhostPaht.includes("-uat") ||
localhostPaht.includes("-pt")
localhostPath.includes("-dev") ||
localhostPath.includes("-sit") ||
localhostPath.includes("-uat") ||
localhostPath.includes("-pt")
){
baseUrl = localhostPaht;
baseUrl = localhostPath;
WSURL = `${isWs}://${host}/liics_api/webSocket/`; //ws://ssp-dev.trace.com.cn/liics_api/webSocket/
envType = 'sit';
//生产环境
}else{
baseUrl = localhostPaht;
baseUrl = localhostPath;
WSURL = `${isWs}://${host}/liics_api/webSocket/`; //ws://ssp-dev.trace.com.cn/liics_api/webSocket/
envType = 'production';
}
console.log('baseUrl', baseUrl, localhostPath, window.location.href, window.location.pathname);
// switch (process.env.NODE_ENV) {
// case 'development':

@ -12,7 +12,7 @@ import { showToast, showConfirmDialog } from 'vant'
// Toast.setDefaultOptions({ forbidClick: true });
const base = {
baseUrl: '',
baseUrl: 'https://ssp-sit.cpic.com.cn',
timeout: 300000,
}
@ -375,7 +375,7 @@ export function Get(url, params) {
export function Post(url, params) {
return new Promise((resolve, reject) => {
url = base.baseUrl + url;
console.log('url', url,base);
const request = params?.idempotentKey
? postWithIdempotentRequest(url, params)
: axios.post(url, params);

@ -7,13 +7,13 @@ import router from '@/router'
import config from './config'
import utils from './utils'
import { useAppStore } from '@/store/app.js'
import { showToast, showConfirmDialog, allowMultipleToast, setToastDefaultOptions } from 'vant';
import { showToast, showConfirmDialog, allowMultipleToast, setToastDefaultOptions } from 'vant'
// 惰性获取 Pinia store(替代原 Vuex 的 import store from "@/store/index")
const appStore = () => useAppStore()
allowMultipleToast();
setToastDefaultOptions({ forbidClick: true });
allowMultipleToast()
setToastDefaultOptions({ forbidClick: true })
const base = {
baseUrl: config.baseUrl,
@ -22,19 +22,19 @@ const base = {
//关闭页面
const closeWindow = () => {
var userAgent = navigator.userAgent;
if (userAgent.indexOf("Firefox") != -1 || userAgent.indexOf("Chrome") != -1) {
window.location.href = "about:blank";
window.close();
var userAgent = navigator.userAgent
if (userAgent.indexOf('Firefox') != -1 || userAgent.indexOf('Chrome') != -1) {
window.location.href = 'about:blank'
window.close()
} else {
window.opener = null;
window.open("", "_self");
window.close();
window.opener = null
window.open('', '_self')
window.close()
}
// 微信中关闭
if (WeixinJSBridge) {
WeixinJSBridge.call('closeWindow');
WeixinJSBridge.call('closeWindow')
}
}
@ -42,12 +42,12 @@ const closeWindow = () => {
* 提示函数
* 禁止点击蒙层、显示3秒后关闭
*/
const toast = msg => {
const toast = (msg) => {
showToast({
message: msg,
duration: 4000,
forbidClick: true
});
forbidClick: true,
})
}
/**
@ -58,9 +58,9 @@ const toLogin = () => {
router.replace({
path: '/liics/login',
query: {
redirect: router.currentRoute.fullPath
}
});
redirect: router.currentRoute.fullPath,
},
})
}
/**
@ -74,74 +74,74 @@ const errorHandle = (status, msg) => {
case 401:
// toLogin();
// 清除token
toast('【401】当前会话超时,请刷新页面');
appStore().del_token();
sessionStorage.removeItem('token');
break;
toast('【401】当前会话超时,请刷新页面')
appStore().del_token()
sessionStorage.removeItem('token')
break
// 403 token过期
// 清除token并跳转登录页
case 403:
toast('【403】当前会话超时,请刷新页面');
toast('【403】当前会话超时,请刷新页面')
// 清除token
appStore().del_token();
sessionStorage.removeItem('token');
appStore().del_token()
sessionStorage.removeItem('token')
setTimeout(() => {
// toLogin();
}, 1000);
break;
}, 1000)
break
// 404请求不存在
case 404:
toast('哎呦~404了~休息一下');
break;
toast('哎呦~404了~休息一下')
break
case 408:
toast('【408】请求超时');
break;
toast('【408】请求超时')
break
case 500:
toast('【500】当前网络不给力,请检查你的网络设置');
break;
toast('【500】当前网络不给力,请检查你的网络设置')
break
case 503:
toast('【503】当前服务器不可用,请稍后重试');
break;
toast('【503】当前服务器不可用,请稍后重试')
break
// 其他错误,直接抛出错误提示
default:
toast(`连接错误${msg}`);
toast(`连接错误${msg}`)
}
}
// 请求超时时间
axios.defaults.timeout = base.timeout;
axios.defaults.timeout = base.timeout
//设置默认请求头
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.post['Content-Type'] = 'application/json'
// 请求拦截器
axios.interceptors.request.use(
config => {
(config) => {
// 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了
// 即使本地存在token,也有可能token是过期的,所以在响应拦截器中要对返回状态进行判断
const token = appStore().token;
const token = appStore().token
// console.log("https===token:", token)
token && (config.headers.token = token);
return config;
token && (config.headers.token = token)
return config
},
error => {
return Promise.reject(error);
})
(error) => {
return Promise.reject(error)
},
)
// 响应拦截器
axios.interceptors.response.use(
// 请求成功
(res) => {
if (res.data.code === 10001) {
appStore().del_token();
sessionStorage.removeItem("token"); // 删除已经失效或过期的token(不删除也可以,因为登录后覆盖)
appStore().del_token()
sessionStorage.removeItem('token') // 删除已经失效或过期的token(不删除也可以,因为登录后覆盖)
// 如果没有展示返回头部的话去掉弹窗按钮
if (appStore().notitle === '1') {
toast('当前会话已结束,请刷新页面或关闭页面重新进入');
return Promise.resolve(res);
toast('当前会话已结束,请刷新页面或关闭页面重新进入')
return Promise.resolve(res)
}
showConfirmDialog({
@ -150,47 +150,50 @@ axios.interceptors.response.use(
confirmButtonText: '取消',
cancelButtonText: '确认',
confirmButtonColor: '#000000',
cancelButtonColor: '#000000'
}).then(() => {
cancelButtonColor: '#000000',
})
.then(() => {
// on cancel (现在是右边的取消按钮)
// utils.closeWindow();
// router.replace({
// path: '/404' // 到登录页重新获取token
// })
}).catch(() => {
})
.catch(() => {
// on confirm (现在是左边的确认按钮)
//确认重新刷新页面获取token
// window.location.reload();
utils.AppReloadHtml();
});
utils.AppReloadHtml()
})
return Promise.resolve(res);
return Promise.resolve(res)
}
res.status === 200 ? Promise.resolve(res) : Promise.reject(res);
res.status === 200 ? Promise.resolve(res) : Promise.reject(res)
return res
},
// 服务器状态码不是200的情况
// 请求失败
async error => {
const {
response
} = error;
async (error) => {
const { response } = error
if (response) {
//过滤排队接口弹窗问题
if (response.config.url.indexOf('HumanChat/queueNumbers') != -1 || response.config.url.indexOf('HumanChat/msgCallBack') != -1) {
return Promise.reject(response);
if (
response.config.url.indexOf('HumanChat/queueNumbers') != -1 ||
response.config.url.indexOf('HumanChat/msgCallBack') != -1
) {
return Promise.reject(response)
}
if (response.data.code === 10001) {
appStore().del_token();
sessionStorage.removeItem("token"); // 删除已经失效或过期的token(不删除也可以,因为登录后覆盖)
appStore().del_token()
sessionStorage.removeItem('token') // 删除已经失效或过期的token(不删除也可以,因为登录后覆盖)
// 如果没有展示返回头部的话去掉弹窗按钮
if (appStore().notitle === '1') {
toast('当前会话已结束,请刷新页面或关闭页面重新进入');
return Promise.reject(response);
toast('当前会话已结束,请刷新页面或关闭页面重新进入')
return Promise.reject(response)
}
showConfirmDialog({
@ -199,41 +202,45 @@ axios.interceptors.response.use(
confirmButtonText: '取消',
cancelButtonText: '确认',
confirmButtonColor: '#000000',
cancelButtonColor: '#000000'
}).then(() => {
cancelButtonColor: '#000000',
})
.then(() => {
// on cancel (现在是右边的取消按钮)
// utils.closeWindow();
// router.replace({
// path: '/404' // 到登录页重新获取token
// })
}).catch(() => {
})
.catch(() => {
// on confirm (现在是左边的确认按钮)
//确认重新刷新页面获取token
// window.location.reload();
utils.AppReloadHtml();
});
utils.AppReloadHtml()
})
return Promise.reject(response);
return Promise.reject(response)
}
// 请求已发出,但是不在2xx的范围
errorHandle(response.status, response.statusText);
return Promise.reject(response);
errorHandle(response.status, response.statusText)
return Promise.reject(response)
} else {
// 处理断网的情况
// eg:请求超时或断网时,更新state的network状态
// network状态在app.vue中控制着一个全局的断网提示组件的显示隐藏
// 关于断网组件中的刷新重新获取数据,会在断网组件中说明
// store.commit('changeNetwork', false);
if (error?.message?.includes('timeout')) { // 判断请求异常信息中是否含有超时timeout字符串
toast('请求超时,稍后重试!');
return Promise.reject(error);
if (error?.message?.includes('timeout')) {
// 判断请求异常信息中是否含有超时timeout字符串
toast('请求超时,稍后重试!')
return Promise.reject(error)
}
toast('当前网络不给力,请检查你的网络设置');
return Promise.reject(error);
toast('当前网络不给力,请检查你的网络设置')
return Promise.reject(error)
}
});
},
)
/**
* get方法,对应get请求
@ -242,16 +249,17 @@ axios.interceptors.response.use(
*/
export function Get(url, params) {
return new Promise((resolve, reject) => {
url = base.baseUrl + url;
url = base.baseUrl + url
axios.get(url, QS.stringify(params))
.then(res => {
resolve(res.data);
axios
.get(url, QS.stringify(params))
.then((res) => {
resolve(res.data)
})
.catch(err => {
.catch((err) => {
reject(err.status)
})
});
})
}
/**
@ -261,19 +269,19 @@ export function Get(url, params) {
*/
export function Post(url, params) {
return new Promise((resolve, reject) => {
url = base.baseUrl + url;
axios.post(url, params)
.then(res => {
resolve(res.data);
url = base.baseUrl + url
console.log('url', url, base);
axios
.post(url, params)
.then((res) => {
resolve(res.data)
})
.catch(err => {
.catch((err) => {
reject(err.status)
})
});
})
}
/**
* post方法,对应post请求
* @param {String} url [请求的url地址]
@ -281,24 +289,24 @@ export function Post(url, params) {
*/
export function fetchPost(url, params) {
return new Promise((resolve, reject) => {
url = base.baseUrl + url;
url = base.baseUrl + url
axios.post(url, params, {
axios
.post(url, params, {
headers: {
'Content-Type': 'application/json',
token: appStore().token
token: appStore().token,
},
})
.then(res => {
resolve(res.data);
.then((res) => {
resolve(res.data)
})
.catch(err => {
.catch((err) => {
reject(err.status)
})
});
})
}
/**
* post方法,对应post请求 上传图片专用
* @param {String} url [请求的url地址]
@ -306,24 +314,25 @@ export function fetchPost(url, params) {
*/
export function upLoadImgHttp(url, params) {
return new Promise((resolve, reject) => {
url = base.baseUrl + url;
url = base.baseUrl + url
const instance = axios.create({
withCredentials: true,
})
instance.post(url, params, {
instance
.post(url, params, {
headers: {
'Content-Type': 'multipart/form-data',
token: appStore().token
}
token: appStore().token,
},
})
.then(res => {
resolve(res.data);
.then((res) => {
resolve(res.data)
})
.catch(err => {
.catch((err) => {
reject(err.status)
})
});
})
}
/**
@ -334,42 +343,41 @@ export function upLoadImgHttp(url, params) {
*/
export function fetchImageData(url, params, options = {}) {
return new Promise((resolve, reject) => {
url = base.baseUrl + url;
url = base.baseUrl + url
const {
timeout = 10000
} = options;
const { timeout = 10000 } = options
const instance = axios.create({
timeout,
withCredentials: true,
});
})
instance.post(url, params, {
instance
.post(url, params, {
headers: {
'Content-Type': 'application/json',
token: appStore().token
}
token: appStore().token,
},
})
.then(res => {
.then((res) => {
// 检查响应格式
if (res.data.code !== 0) {
reject(new Error(res.data.msg || 'Request failed'));
return;
reject(new Error(res.data.msg || 'Request failed'))
return
}
const imageData = res.data.data;
const imageData = res.data.data
if (!imageData || !imageData.content) {
reject(new Error('Invalid response: missing image content'));
return;
reject(new Error('Invalid response: missing image content'))
return
}
// 验证文件扩展名是否为图片格式
const validImageExts = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp'];
const fileExt = imageData.fileNameExt?.toLowerCase();
const validImageExts = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp']
const fileExt = imageData.fileNameExt?.toLowerCase()
if (!validImageExts.includes(fileExt)) {
reject(new Error(`Unsupported image format: ${fileExt}`));
return;
reject(new Error(`Unsupported image format: ${fileExt}`))
return
}
resolve({
@ -378,13 +386,13 @@ export function fetchImageData(url, params, options = {}) {
fileNameExt: imageData.fileNameExt,
content: imageData.content,
// 构建完整的data URL
dataUrl: `data:image/${fileExt};base64,${imageData.content}`
});
dataUrl: `data:image/${fileExt};base64,${imageData.content}`,
})
})
.catch((err) => {
reject(err)
})
})
.catch(err => {
reject(err);
});
});
}
/**
@ -392,10 +400,10 @@ export function fetchImageData(url, params, options = {}) {
* @deprecated 使用 fetchImageData 替代
*/
export function fetchImageStream(url, params, options = {}) {
return fetchImageData(url, params, options).then(imageData => {
return fetchImageData(url, params, options).then((imageData) => {
// 将base64转换为blob以保持兼容性
return base64ToBlob(imageData.content, `image/${imageData.fileNameExt}`);
});
return base64ToBlob(imageData.content, `image/${imageData.fileNameExt}`)
})
}
/**
@ -407,17 +415,17 @@ export function fetchImageStream(url, params, options = {}) {
export function base64ToBlob(base64Data, contentType = 'image/png') {
try {
// 解码base64数据
const byteCharacters = atob(base64Data);
const byteNumbers = new Array(byteCharacters.length);
const byteCharacters = atob(base64Data)
const byteNumbers = new Array(byteCharacters.length)
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
byteNumbers[i] = byteCharacters.charCodeAt(i)
}
const byteArray = new Uint8Array(byteNumbers);
return new Blob([byteArray], { type: contentType });
const byteArray = new Uint8Array(byteNumbers)
return new Blob([byteArray], { type: contentType })
} catch (error) {
throw new Error(`Failed to convert base64 to blob: ${error.message}`);
throw new Error(`Failed to convert base64 to blob: ${error.message}`)
}
}
@ -429,37 +437,33 @@ export function base64ToBlob(base64Data, contentType = 'image/png') {
*/
export function downloadFile(url, params, options = {}) {
return new Promise((resolve, reject) => {
url = base.baseUrl + url;
url = base.baseUrl + url
const {
timeout = 30000,
responseType = 'blob',
method = 'POST'
} = options;
const { timeout = 30000, responseType = 'blob', method = 'POST' } = options
const config = {
url,
method,
headers: {
'Content-Type': 'application/json',
token: appStore().token
token: appStore().token,
},
responseType,
timeout
};
timeout,
}
if (method.toUpperCase() === 'POST') {
config.data = params;
config.data = params
} else {
config.params = params;
config.params = params
}
axios(config)
.then(res => {
resolve(res.data);
.then((res) => {
resolve(res.data)
})
.catch((err) => {
reject(err)
})
})
.catch(err => {
reject(err);
});
});
}

@ -1,11 +1,11 @@
<template>
<div>
<chat-main
<!-- <chat-main
v-if="isToken"
:tokenExist="isToken"
:isWX="isWX"
:lostChatInfoNum="lostChatInfoNum"
/>
/> -->
<chat-new />
<!-- <human-appraise-popup /> -->
</div>
@ -25,7 +25,8 @@ import Utils from '@/utils/utils'
// 状态管理
const store = useAppStore()
const router = useRouter()
console.log(store, 'store');
const { set_source , set_userInfo, set_notitle , set_configId,set_entrance,set_appentry,set_htmlExtParams,set_complaint, set_navigationCorpus, setSessionId }= store
// 响应式数据
const isToken = ref(false)
const isWX = ref(false)
@ -38,8 +39,91 @@ const source = computed(() => store.source)
// 生命周期
onMounted(async () => {
var liccsAds = localStorage.getItem("liccsAds"); // 记录用户弹窗提示
localStorage.clear();
localStorage.liccsAds = liccsAds || "";
//清除session 清除上次的记录
sessionStorage.clear();
urlParams.value = Utils.getUrlParams();
console.log("txfModules参数", urlParams.value.txfModules);
console.log('this.urlParams--', urlParams.value)
let userInfo = {
phone: urlParams.value.phone || "",
name: urlParams.value.name || "",
sex: urlParams.value.sex || "",
openid: urlParams.value.openid || "",
idtype: urlParams.value.idtype || "",
pid: urlParams.value.pid || "",
auStatus: urlParams.value.auStatus || "", //实名认证状态 枚举:1、0、其他(1为已认证状态,其他为非认证认证状态)
bdStatus: urlParams.value.bStatus || urlParams.value.bdStatus || "", //老客户绑定状态 1为已绑定状态,其他为非绑定状态
bthdate: urlParams.value.bthdate || "", //出生日期
workNum: urlParams.value.workNum || "", //营销员工号
unit: urlParams.value.unit || "", //单位
orgname: urlParams.value.orgname || "", //机构名称
txfModules: urlParams.value.txfModules || "", //太享福渠道活动与功能显示
sceneId: urlParams.value.sceneId || "", //场景标识(微信跟随)
entrance: urlParams.value.entrance || "", // 入口标识
planCode: urlParams.value.planCode || urlParams.value.modelCode || "", //星云渠道产品代码
// 断点服务
bpErrorCode: urlParams.value.bErrorCode || urlParams.value.brErrorCode || "",
bpErrorContent: urlParams.value.bErrorContent || urlParams.value.errorMsg || "",
bpErrorModule: urlParams.value.bErrorModule || "", // 电子回访断点服务
bpErrorPicture: urlParams.value.bErrorPicture || "", // 微信给付断点服务
entryIdnum: '', // 查门店证件号加密传参
entryOpenid: '', // 查门店openid加密传参
userType: urlParams.value.usertype || "", // 95980000渠道(b2bi),说明一下是游客
};
isWX.value = Utils.isWeiXin();
// set_userInfo(userInfo);//用户信息
// set_source(urlParams.value.ht || ""); //来源
// set_notitle(urlParams.value.notitle || ""); //是否展示头部
// set_configId(urlParams.value.configId || ""); //环信参数
// set_entrance(urlParams.value.entrance || ""); //入口标识
// set_appentry(urlParams.value.appentry || ""); // 是否为老版本app
// set_htmlExtParams(urlParams.value.htmlExtParams || ""); //扩展参数
// set_complaint(urlParams.value.complaint || ""); //扩展参数
// set_navigationCorpus(urlParams.value.navigationCorpus || ""); //扩展参数
// 渠道校验
let checkToast = null;
try {
checkToast = showLoadingToast({
message: "加载中...",
duration: 0,
loadingType: "spinner",
forbidClick: true,
});
const checkRes = await Post("config/downSource", {
source: urlParams.value.ht || "95810000"
});
checkToast.clear();
if (checkRes.code === 0 && checkRes.data !== null) {
Dialog.alert({
title: "提示",
message: checkRes.data.toast,
confirmButtonText: "确定"
}).then(res => {
Utils.closeWindow();
});
return;
}
} catch (error) {
console.log("渠道校验异常:", error);
// if (checkToast) {
// checkToast.clear();
// }
}
urlParams.value = Utils.getUrlParams()
// await initToken()
await initToken()
})
// 方法
@ -101,12 +185,16 @@ const getToken = async () => {
params.userId = decodeURIComponent(urlParams.value.appTicket).replace(/ /g, '+')
}
showLoadingToast({ message: '加载中...', duration: 0, loadingType: 'spinner', forbidClick: true })
console.log('Post', Post);
try {
const res = await Post('user/info', params)
closeToast()
console.log('res', res);
// await Post('user/info', params)
// closeToast()
return res
} catch (error) {
closeToast()
console.log('error', error);
// closeToast()
throw error
}
}

@ -14,14 +14,13 @@ export default defineConfig(({ command }) => {
base: "./",
server: {
proxy: {
'/yyfw': {
'/api': {
// target: 'https://aioblu-sit.cpic.com.cn',
// target: 'https://aioblu-dev.cpic.com.cn',
target: 'http://yyfw-lf19ssp-dev.life.cpic.com',
// target: 'http://www.sinosoftzx.cn:40005',
// target: 'https://aioblu-dev.cpic.com.cn/yyfw',
target: 'https://ssp-sit.cpic.com.cn',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/yyfw/, '/yyfw'),
rewrite: (path) => path.replace(/^\/api/, '/api'),
},
},
},

Loading…
Cancel
Save