uniapp-app/App.vue
haomingming d44cd1516a Merge branch 'master' of https://gitea.igandanyiyuan.com/gdxz/uniapp-app
# Conflicts:
#	App.vue
#	manifest.json
2025-10-15 11:49:15 +08:00

613 lines
21 KiB
Vue
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<script >
import RootStore from "@xkit-yx/im-store-v2";
/** esm 版本 */
//@ts-ignore
// import { V2NIMConst, NIM } from './esmNim.js'
/** 常规版本*/
import NIM from "nim-web-sdk-ng/dist/v2/NIM_UNIAPP_SDK";
import { V2NIMConst } from "nim-web-sdk-ng/dist/esm/nim";
import {
customRedirectTo,
customReLaunch,
customSwitchTab,
} from "@/utils/im/customNavigate";
import { getMsgContentTipByType } from "@/utils/im/msg";
import { STORAGE_KEY } from "@/utils/im/constants";
import { isWxApp } from "@/utils/im/index";
/** 国际化*/
import { setLanguage } from "@/utils/im/i18n";
import BASE_URL from "@/utils/config.js"
import my_api from '@/api/my_api.js'
import GlobalDialog from "@/components/GlobalDialog.vue"
// #ifdef APP-PLUS
/** 推送插件 */
const nimPushPlugin = uni.requireNativePlugin("NIMUniPlugin-PluginModule");
console.log("nimPushPlugin1111");
console.log(nimPushPlugin);
/** 音视频通话插件 */
// const nimCallKit = (uni.$UIKitCallKit =
// uni.requireNativePlugin("netease-CallKit"));
// #endif
const app = getApp()
let startByNotificationId = "";
export default {
globalData: {
plAd: true
},
onLaunch() {
// #ifdef APP-PLUS
/** 关闭启动画面,锁定竖屏 */
try {
plus.navigator.closeSplashscreen();
plus.screen.lockOrientation("portrait-primary");
} catch (error) {
}
// 点击通知栏推送监听
nimPushPlugin.addOpenNotificationListener((res) => {
console.log("推送监听");
console.log("res",res);
if (typeof res === 'object') {
console.log("=====addOpenNotificationListener success:", JSON.stringify(res))
uni.redirectTo({
url: `/pages_app/patientMsg/patientMsg?from=push`,
success: () => {
app.globalData.plAd=false;
},
fail: (err) => {
console.log("跳转失败", err);
}
});
} else {
console.log("=====addOpenNotificationListener unexpected:", res)
}
});
// #endif
// uni-app客户端获取push客户端标记代码可以实现在App.vue中
uni.getPushClientId({
success: (res) => {
let push_clientid = res.cid
uni.setStorageSync("push_clientid", push_clientid)
console.log('客户端推送标识cid:',push_clientid)
const systemInfo = uni.getSystemInfoSync();
console.log("systemInfo:", systemInfo)
let userInfo= uni.getStorageSync('userInfo')
console.log("userinfo:", userInfo)
if(!userInfo){
return
}
if(userInfo.uuid){
let client_type = ""
if (systemInfo.platform === 'android') {
client_type = "A"
} else if (systemInfo.platform === 'ios') {
client_type = "I"
}
console.log("client_type:", client_type)
if(client_type){
my_api.addUniappCid({
user_uuid: userInfo.uuid,
client_type:client_type,
cid: push_clientid
})
}
}
},
fail(err) {
console.error("unipush: ", err)
}
})
uni.onPushMessage((res)=>{
console.log("收到推送消息:", res)
let app_isback = uni.getStorageSync("app_isback")
console.log("app_isback", app_isback)
uni.showModal({
title: res.data.title,
content: res.type,
showCancel: false
});
if(res.type === 'click' ){
}else{
if(app_isback){
uni.createPushMessage({
title: res.data.title,
content: res.data.content,
payload: res.data.payload,
delay: 1,
success: (res) => {
console.log("创建推送消息成功", res)
}
})
}else{
console.log('[App] emit global-dialog:show', res)
uni.$emit('global-dialog:show', {
title: res.data.title || '消息通知',
content: res.data.content || '',
confirmText: '我知道了',
position: 'top',
offsetTop: '160rpx'
})
}
}
})
/** 设置语言 此处为了方便demo切换语言将其存到本地实际需根据业务情况设置*/
setLanguage(
uni.getStorageSync("switchToEnglishFlag") == "en" ? "en" : "zh"
);
/** 已经登录了 不用走初始化逻辑*/
if (
uni?.$UIKitStore?.connectStore?.connectStatus ===
V2NIMConst.V2NIMConnectStatus.V2NIM_CONNECT_STATUS_CONNECTED
) {
return;
}
let storage_token='';
let storage_accid='';
if (process.env.UNI_PLATFORM == "h5") {
if (window.location.href.indexOf('dev') > -1) {
storage_accid=uni.getStorageSync('AUTH_YX_ACCID_App');
storage_token=uni.setStorageSync('AUTH_YX_TOKEN_App');
} else {
storage_accid=uni.getStorageSync('DEV_AUTH_YX_ACCID_App');
storage_token=uni.getStorageSync('DEV_AUTH_YX_TOKEN_App');
}
} else if(process.env.UNI_PLATFORM == "mp-weixin") {
const {
envVersion
} = uni.getAccountInfoSync().miniProgram;
if (envVersion == "release") {
storage_accid=uni.getStorageSync('AUTH_YX_ACCID_App');
storage_token=uni.setStorageSync('AUTH_YX_TOKEN_App');
} else {
storage_accid=uni.getStorageSync('DEV_AUTH_YX_ACCID_App');
storage_token=uni.getStorageSync('DEV_AUTH_YX_TOKEN_App');
}
}else{
storage_accid=uni.getStorageSync('DEV_AUTH_YX_ACCID_App');
storage_token=uni.getStorageSync('DEV_AUTH_YX_TOKEN_App');
}
const account =storage_accid;
const token = storage_token;
if(!account || !token){
uni.redirectTo({
url: '/pages_app/login/login'
});
return;
}
console.log("account",account);
console.log("token",token);
console.log("account",typeof account);
console.log("token",typeof token);
const imOptions = {
appkey: "885dea390870814acf3ba8558c717572", // 请填写你的appkey
account: String(account),//"9ufkll2xo57km6224xe", // 请填写你的account
token:String( token)//"4918605da57e573cff93209df56f351d", // 请填写你的token
};
console.log("onLaunch");
if (imOptions) {
console.log("初始化im");
this.initNim(imOptions);
} else {
/** 未登录 跳转登录页 */
// customRedirectTo({
// url: isWxApp ? "/pages/index/index" : "/pages/Login/index",
// });
}
},
onShow() {
// #ifdef APP-PLUS
console.log("onShow");
uni?.$UIKitNIM?.V2NIMSettingService?.setAppBackground(false);
uni.setStorageSync("app_isback", false)
// 点击通知栏推送监听
// nimPushPlugin.addOpenNotificationListener((res) => {
// console.log("推送监听");
// console.log("res",res);
// if (typeof res == "object" && res?.sessionId && res?.sessionType) {
// // 当前登录账号id 具体获取根据您的业务逻辑调整
// const imOptions = uni.getStorageSync(STORAGE_KEY);
// // 会话类型
// const type = res?.sessionType;
// // 拼装会话ID
// startByNotificationId = `${imOptions.account}|${type}|${res?.sessionId}`;
// }
// });
// #endif
},
onHide() {
console.log("onHide");
uni.setStorageSync("app_isback", true)
// #ifdef APP-PLUS
uni?.$UIKitNIM?.V2NIMSettingService?.setAppBackground(true);
// #endif
// 重置推送 startByNotificationId
startByNotificationId = "";
},
components:{
GlobalDialog
},
methods: {
initNim(opts) {
console.log("initNim1111111111");
/** 保存登录信息 demo 层逻辑 具体根据您的业务调整*/
uni.setStorage({
key: STORAGE_KEY,
data: opts,
});
/** 是否开启云端会话此处为了方便demo切换云端/本地会话,将其存到本地,实际需根据业务情况设置)*/
const enableV2CloudConversation =
uni.getStorageSync("enableV2CloudConversation") === "on";
/** 初始化 nim sdk */
//@ts-ignore
const nim = (uni.$UIKitNIM = NIM.getInstance(
{
appkey: opts.appkey,
needReconnect: true,
debugLevel: "debug",
apiVersion: "v2",
enableV2CloudConversation: enableV2CloudConversation,
},
{
V2NIMLoginServiceConfig: {
/**
* 微信小程序需要使用单独的lbsUrls和linkUrl
*/
lbsUrls: isWxApp
? ["https://lbs.netease.im/lbs/wxwebconf.jsp"]
: ["https://lbs.netease.im/lbs/webconf.jsp"],
linkUrl: isWxApp ? "wlnimsc0.netease.im" : "weblink.netease.im",
/**
* 使用固定设备ID
*/
isFixedDeviceId: true,
},
}
));
/** 初始化 im store */
// @ts-ignore
const store = (uni.$UIKitStore = new RootStore(
// @ts-ignore
nim,
{
// 添加好友是否需要验证
addFriendNeedVerify: true,
// 是否需要显示 p2p 消息、p2p会话列表消息已读未读默认 false
p2pMsgReceiptVisible: true,
// 是否需要显示群组消息已读未读,默认 false
teamMsgReceiptVisible: true,
// 是否显示在线离线
loginStateVisible: true,
// 群组被邀请模式,默认需要验证
teamAgreeMode:
V2NIMConst.V2NIMTeamAgreeMode.V2NIM_TEAM_AGREE_MODE_NO_AUTH,
// 发送消息前回调, 可对消息体进行修改,添加自定义参数
// @ts-ignore
sendMsgBefore: async (options) => {
const pushContent = getMsgContentTipByType({
text: options.msg.text,
messageType: options.msg.messageType,
});
const yxAitMsg = options.serverExtension
? options.serverExtension.yxAitMsg
: { forcePushIDsList: "[]", needForcePush: false };
// 如果是 at 消息,需要走离线强推
// @ts-ignore
const { forcePushIDsList, needForcePush } = yxAitMsg
? // @ts-ignore
store.msgStore._formatExtAitToPushInfo(
yxAitMsg,
options.msg.text
)
: { forcePushIDsList: "[]", needForcePush: false };
const { conversationId } = options;
const conversationType =
nim.V2NIMConversationIdUtil.parseConversationType(conversationId);
const targetId =
nim.V2NIMConversationIdUtil.parseConversationTargetId(
conversationId
);
const PACKAGE_NAME = 'cn.shangyu.gdxzExpert';
let sessionId=conversationType == 1
? uni.$UIKitStore.userStore.myUserInfo.accountId
: targetId;
// 设置离线强推,厂商相关推送在此处配置
// 具体参考文档 https://doc.yunxin.163.com/messaging2/guide/zc4MTg5MDY?platform=client#%E7%AC%AC%E4%B8%80%E6%AD%A5%E4%B8%8A%E4%BC%A0%E6%8E%A8%E9%80%81%E8%AF%81%E4%B9%A6
const pushPayload = JSON.stringify({
//pushTitle: "测试推送", // 必填,推送消息标题
notify_effect: "2", //可选项预定义通知栏消息的点击行为。1通知栏点击后打开app的Launcher Activity2通知栏点击后打开app的任一Activity开发者还需要传入intent_uri3通知栏点击后打开网页开发者还需要传入web_uri
intent_uri: `intent:#Intent;action=com.netease.nimlib.uniapp.push.NotificationClickActivity;component=${PACKAGE_NAME}/com.netease.nimlib.uniapp.push.NotificationClickActivity;launchFlags=0x04000000;i.sessionType=${conversationType};S.sessionId=${sessionId};end`,
hwField: {
click_action: {
//必填,消息点击行为
type: 1, //必填消息点击行为类型取值如下1打开应用自定义页面 2点击后打开特定URL 3点击后打开应用
// 自定义页面中intent的实现请参见指定intent参数。当type为1时字段intent和action至少二选一。scheme方式和指定activity方式都可以
intent:
`intent:#Intent;action=com.netease.nimlib.uniapp.push.NotificationClickActivity;component=${PACKAGE_NAME}/com.netease.nimlib.uniapp.push.NotificationClickActivity;launchFlags=0x04000000;i.sessionType=${conversationType};S.sessionId=${sessionId};end`
},
androidConfig: {
category: "IM", //可选项,标识消息类型,用于标识高优先级透传场景,详见官方文档 AndroidConfig.category
},
},
honorField: {
notification: {
// AndroidNotification
clickAction: {
//必填,消息点击行为
type: 1, //必填消息点击行为类型取值如下1打开应用自定义页面 2点击后打开特定URL 3点击后打开应用
//自定义页面中intent的实现请参见指定intent参数。当type为1时字段intent和action至少二选一。
intent: `intent://com.honor.push/deeplink?#Intent;scheme=pushscheme;launchFlags=0x04000000;i.sessionType=${conversationType};S.sessionId=${sessionId};end`,
},
importance: "NORMAL", //可选项Android通知消息分类决定用户设备消息通知行为取值如下LOW资讯营销类消息 NORMAL服务与通讯类消息
},
},
vivoField: {
skipType: "4", //必填,点击跳转类型 1打开APP首页 2打开链接 3自定义 4:打开app内指定页面默认为1
skipContent: `intent:#Intent;action=com.netease.nimlib.uniapp.push.NotificationClickActivity;component=${PACKAGE_NAME}/com.netease.nimlib.uniapp.push.NotificationClickActivity;launchFlags=0x04000000;i.sessionType=${conversationType};S.sessionId=${sessionId};end`,
classification: "1", //可选项,消息类型 0运营类消息1系统类消息。默认为0
category: "IM", // 可选项,二级分类
},
oppoField: {
channel_id: "", //可选项指定下发的通道ID
category: "IM", //可选项,通道类别名
notify_level: 2, //通知栏消息提醒等级1-通知栏2-通知栏+锁屏16-通知栏+锁屏+横幅+震动+铃声
click_action_type: "1", //点击通知栏后触发的动作类型。0默认0.启动应用1.跳转指定应用内页action标签名2.跳转网页4.跳转指定应用内页全路径类名5.跳转Intent scheme URL: "",
click_action_activity: "com.netease.nimlib.uniapp.push.NotificationClickActivity",
action_parameters: JSON.stringify({
sessionType: conversationType,
sessionId: sessionId,
}),
},
fcmFieldV1: {
message: {
android: {
priority: "",
data: {
sessionType: conversationType,
sessionId: sessionId,
},
notification: {
click_action: "",
},
},
},
},
// IOS apns
sessionId:sessionId,
sessionType: conversationType,
});
// @ts-ignore
const pushConfig = {
pushEnabled: true,
pushNickEnabled: true,
forcePush: needForcePush,
forcePushContent: pushContent,
forcePushAccountIds: forcePushIDsList,
pushPayload,
pushContent,
};
return { ...options, pushConfig };
},
},
"UniApp"
));
// #ifdef APP-PLUS
/** 注册推送 实际根据您在推送厂商申请的证书进行配置,具体参考文档 https://doc.yunxin.163.com/messaging2/guide/zc4MTg5MDY?platform=client#%E7%AC%AC%E4%B8%80%E6%AD%A5%E4%B8%8A%E4%BC%A0%E6%8E%A8%E9%80%81%E8%AF%81%E4%B9%A6
*/
nim.V2NIMSettingService.setOfflinePushConfig(nimPushPlugin, {
// miPush: {
// appId: "",
// appKey: "",
// certificateName: "",
// },
// hwPush: {
// appId: "",
// certificateName: "",
// },
miPush: {
appId: "2882303761517470793",
appKey: "5431747048793",
certificateName: "Expert_Mi_Push",
},
hwPush: {
appId: "10526652",
certificateName: "Expert_Hw_push_f",
},
oppoPush: {
appId: "3364888",
appKey: "75D5Vqsg63wok0S0w4SKog0w8",
certificateName: "Expert_Op_Push",
secret: "9e93Ce2AbA97E15F3852279b639b014e",
},
vivoPush: {
appId: "100034326",
appKey: "e789634c1f76c8f184b1def1101ce824",
certificateName: "Expert_vivo_Push",
secret: "416a4f5eF822ddcB73B627Cc310636D7",
},
fcmPush: {
certificateName: "FCM_PUSH_CERT",
},
mzPush: {
appId: "111",
appKey: "111",
certificateName: "MEIZU_PUSH_CERT",
},
apns: {
certificateName: "专家端Pro",
},
});
// #endif
/** nim sdk 登录 */
nim.V2NIMLoginService.login(opts.account, opts.token).then(async () => {
console.log("登录成功");
nim.V2NIMLoginService.on('onKickedOffline', (res) => {
console.log("被踢下线", res);
});
// #ifdef APP-PLUS
/** 初始化音视频通话插件*/
// nimCallKit.initConfig(
// {
// appKey: opts.appkey, // 请填写你的appkey
// account: opts.account, // 请填写你的account
// token: opts.token, // 请填写你的token
// apnsCername: "",
// pkCername: "",
// },
// (ret) => {
// if (ret.code != 200) {
// // callkit init失败
// } else {
// nimCallKit.login(
// {
// account: opts.account,
// token: opts.token,
// },
// function (ret) {
// if (ret.code != 200) {
// // 登录失败
// } else {
// // 登录成功
// }
// }
// );
// }
// }
// );
// #endif
// 判断时手动点击唤起 还是 点击推送通知栏唤起,点击通知栏唤起直接跳转到聊天页面
if (!startByNotificationId) {
// customSwitchTab({
// url: "/pages/Conversation/index",
// });
} else {
if (startByNotificationId) {
await uni.$UIKitStore.uiStore.selectConversation(
startByNotificationId
);
uni.navigateTo({
url: `/pages/Chat/index?conversationId=${startByNotificationId}`,
});
startByNotificationId = "";
}
}
}).catch((err) => {
console.log("登录失败", err);
});
},
logout() {
uni.removeStorageSync(STORAGE_KEY);
try {
// nimCallKit.logout({}, (ret) => {
// if (ret.code != 200) {
// console.log("音视频通话插件退出失败");
// } else {
// console.log("音视频通话插件退出成功");
// }
// });
} catch (error) {
console.log("音视频通话插件退出失败", error);
}
// 退出登录
uni.$UIKitNIM.V2NIMLoginService.logout().then((res) => {
console.log("退出登录", res);
uni.$UIKitStore.destroy();
uni.clearStorageSync();
// 跳转到登录页面
uni.reLaunch({
url: '/pages_app/login/login'
});
});
},
},
};
</script>
<template>
<GlobalDialog />
</template>
<style lang="scss">
/*每个页面公共css */
@import '@/uni_modules/uni-scss/index.scss';
/* #ifndef APP-NVUE */
@import '@/static/customicons.css';
// 设置整个项目的背景色
page {
background-color: #f5f5f5;
}
.uni-navbar__header-btns-right{
min-width: 120rpx;
width:auto!important;
}
/* #endif */
.uni-nav-bar-text{
font-weight: bold;
font-size: 34rpx!important;
}
.example-info {
font-size: 14px;
color: #333;
padding: 10px;
}
.twoline{
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
}
.oneline{
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.uni-navbar .uniui-left{
font-weight: bold;
font-size: 50rpx!important;
}
::-webkit-scrollbar { display: none; }
// .nav-right{
// margin-top: -20px;
// }
</style>