<script lang="ts">
import { V2NIMMessage, V2NIMMessagePushConfig, V2NIMConversation } from "nim-web-sdk-ng/dist/v2/NIM_UNIAPP_SDK/V2NIMMessageService";
import { unix } from "dayjs";
import { V2NIMConst, NIM } from "./utils/nim";
import.meta.env.VITE_APP_THEMECOLOR = "#000";
// console.log("系统信息：", uni.getSystemInfoSync());
let isWxApp = uni.getSystemInfoSync().uniPlatform == "mp-weixin";

export default {
	globalData: {
		version: "1.0.0",
		serverVersion: "1.0.1",
		uid: 0,
		isUseNewJob: true,
		messageTab: 0,
		messageId: "",
		title: "",
		
		// themeColor: "#3578f6",
		// themeBackgroundColor: "#3578f621",
		
		// themeColor: "#00B666",
		// themeBackgroundColor: "#00B66621",
		
		themeColor: "#fea702",
		themeBackgroundColor: "#fea70221",

		// themeColor: "#2FC67D",
		// themeBackgroundColor: "#2FC67D21",
		
		logo: "",
		// #ifdef MP-WEIXIN
		"g-open-env": "MP-MINI",
		appId: uni.getAccountInfoSync().miniProgram.appId,
		// #endif
		// #ifdef MP-TOUTIAO
		"g-open-env": "MP-TOUTIAO",
		appId: tt.getEnvInfoSync().microapp.appId,
		// #endif
		// #ifdef MP-KUAISHOU
		"g-open-env": "MP-KUAISHOU",
		appId: uni.getAccountInfoSync().miniProgram.appId,
		// #endif
	},
	data() {
		return {
			themeColor: "#3578f6",
			themeBackgroundColor: "#3578f621",
			currentInfo: {},
		};
	},
	onShow: function (options) {
		let that = this;
		uni.setStorageSync('is_use_im',1);
		let requestComeFrom = this.G.globalConstantData.requestComeFrom;
		uni.setStorageSync("requestComeFrom", requestComeFrom && (requestComeFrom == "assistant_miniapp" || requestComeFrom == "supply_chain_miniapp") ? "isToB" : "isToC");

		uni.onNetworkStatusChange((res) => {
			// console.log("res", res);
			// console.log("网络状态改变");
		});
		if (that.globalData.appId == "wxb0c590fd696b79be") {
			that.globalData.title = "稻田工作";
			that.themeColor = "#ff4400";
			that.themeBackgroundColor = "#ff440011";
			that.globalData.themeColor = "#ff4400";
			that.globalData.themeBackgroundColor = "#ff440011";
			that.globalData.logo = uni.getStorageSync("miniApp-info").logo || "https://bocai-cms.oss-cn-beijing.aliyuncs.com/web-resource/bocaigongyinglian/logo.png";
		} else if (that.globalData.appId == "wx15bc9c758f4eb129") {
			that.globalData.title = "业小满招聘";
			that.globalData.logo = uni.getStorageSync("miniApp-info").logo || "https://bocai-cms.oss-cn-beijing.aliyuncs.com/web-resource/pugongying/yexiaoman.png";
		} else if (that.globalData.appId == "wxfab5320942daaafa") {
			that.globalData.thmemeColor = "#2FC67D";
			that.globalData.themeBackgroundColor = "#2FC67D21";
			that.globalData.title = "人海发单宝";
			that.globalData.logo = uni.getStorageSync("miniApp-info").logo || "https://bocai-cms.oss-cn-beijing.aliyuncs.com/5220b1cd-c5a7-4a2c-895c-b75310ff7410_wx_logo.png";
		} else if (that.globalData.appId == "wx92d63109b01e74d2") {
			that.globalData.title = "人海招工宝";
			that.globalData.logo = uni.getStorageSync("miniApp-info").logo || "https://bocai-cms.oss-cn-beijing.aliyuncs.com/5220b1cd-c5a7-4a2c-895c-b75310ff7410_wx_logo.png";
		} else if (that.globalData.appId == "wxcd0e4a001e1d87bd") {
			that.globalData.title = "会聘工作";
			that.globalData.logo = uni.getStorageSync("miniApp-info").logo || "https://bocai-cms.oss-cn-beijing.aliyuncs.com/web-resource/pugongying/kuaipin.jpg";
		} else if (that.globalData.appId == "wx581db3f39c49ed2b") {
			that.globalData.title = "英华招工";
			that.globalData.logo = uni.getStorageSync("miniApp-info").logo || "https://bocai-cms.oss-cn-beijing.aliyuncs.com/web-resource/pugongying/yinghua.png";
		} else if (that.globalData.appId == "wxd522e45fa0d4be09") {
			that.globalData.title = "鑫都直聘";
			that.globalData.logo = uni.getStorageSync("miniApp-info").logo || "https://bocai-cms.oss-cn-beijing.aliyuncs.com/web-resource/pugongying/xindu.png";
		} else if (that.globalData.appId == "wx5e1d6e017a193336") {
			that.globalData.title = "春雷人力";
			that.globalData.logo = uni.getStorageSync("miniApp-info").logo || "https://bocai-cms.oss-cn-beijing.aliyuncs.com/web-resource/pugongying/chunleilogo.png";
		} else if (that.globalData.appId == "wx57e965905e6b4530") {
			that.globalData.title = "人海劳务";
			that.globalData.logo = uni.getStorageSync("miniApp-info").logo || "https://bocai-cms.oss-cn-beijing.aliyuncs.com/web-resource/pugongying/renhailaowu.png";
		} else if (that.globalData.appId == "wx5fa8701bfff4357d") {
			that.globalData.title = "靖杨劳务";
			that.globalData.logo = uni.getStorageSync("miniApp-info").logo || "https://bocai-cms.oss-cn-beijing.aliyuncs.com/web-resource/pugongying/renhailaowu.png";
		} else if (that.globalData.appId == "wx70153a578d847bc1") {
			that.globalData.title = "打工猫";
			that.globalData.logo = uni.getStorageSync("miniApp-info").logo || "https://bocai-cms.oss-cn-beijing.aliyuncs.com/web-resource/pugongying/zhi_logo.png";
		} else if (that.globalData.appId == "wx89702db2259e0247") {
			that.globalData.title = "鑫职一聘";
			that.globalData.logo = uni.getStorageSync("miniApp-info").logo || "https://bocai-cms.oss-cn-beijing.aliyuncs.com/web-resource/pugongying/xinyi_logo.png";
		} else if (that.globalData.appId == "wx21f6c6445a194d4d") {
			that.globalData.title = "铂诚人力";
			that.globalData.logo = uni.getStorageSync("miniApp-info").logo || "https://bocai-cms.oss-cn-beijing.aliyuncs.com/web-resource/pugongying/bocheng_logo.png";
		} else if (that.globalData.appId == "wxf14dd76421b8ce8f") {
			that.globalData.title = "工企创联";
			that.globalData.logo = uni.getStorageSync("miniApp-info").logo || "https://bocai-cms.oss-cn-beijing.aliyuncs.com/80d0daf4-82f8-4ddf-88dc-169dde051df8_gongqichuanglian.png";
		} else if (that.globalData.appId == "wxbc6d9dbb9dff5b37") {
			that.globalData.title = "伯才稻田";
			that.themeColor = "#ff4400";
			that.themeBackgroundColor = "#ff440011";
			that.globalData.themeColor = "#ff4400";
			that.globalData.themeBackgroundColor = "#ff440011";
			that.globalData.logo = uni.getStorageSync("miniApp-info").logo || "https://bocai-cms.oss-cn-beijing.aliyuncs.com/web-resource/1shoudan/daotianLogo.png";
		}

		// #ifdef MP-WEIXIN

		const updateManager = uni.getUpdateManager();
		updateManager.onCheckForUpdate(function (res) {
			// console.log("检测是否有新版本：", res.hasUpdate);
		});
		updateManager.onUpdateReady(function (res) {
			uni.showModal({
				title: "更新提示",
				content: "新版本已经准备好，需重启应用",
				showCancel: false,
				success(res) {
					if (res.confirm) {
						// console.log("新版本已经准备好，需重启应用");
						updateManager.applyUpdate();
					}
				},
			});
		});
		updateManager.onUpdateFailed(function (res) {
			uni.showModal({
				title: "更新提示",
				content: "新版本下载异常，需重启应用",
				showCancel: false,
				success(res) {
					if (res.confirm) {
						// console.log("新版本下载异常，需重启应用");
						updateManager.applyUpdate();
					}
				},
			});
		});
		this.G.getAgencyInfo();
		this.G.getServiceQRCode();

		// #endif

		// #ifdef APP-PLUS
		// that.globalData.nim && that.globalData.nim.V2NIMSettingService.setAppBackground(false);
		// #endif

		if (uni.getStorageSync("apply-token")) {
			that.G.checkToken();
		}
	},
	onHide: function () {
		// #ifdef APP-PLUS
		// this.globalData.nim && this.globalData.nim.V2NIMSettingService.setAppBackground(true);
		// #endif
	},
	onLaunch(options) {
		let that = this;

		console.log("0127 APP", options);

		if (options.scene) {
			// console.log("XXXXXXXXXXXX");
			//扫小程序码携带参数
			var sceneStr = decodeURIComponent(options.query.scene);
			var sceneJson = this.G.sceneToJson(sceneStr);

			console.log("sceneJson===", sceneJson);

			if (sceneJson.tk) {
				uni.setStorageSync("apply-token", sceneJson.tk);
			}
		}

		// that.G.getAgencyInfo();
		uni.$on("isGlogin", function (data) {
			// console.log("app.vue 接收", data);
			if (uni.getStorageSync("apply-token")) {
				that.initWyyx();
			}
		});

		// const applyToken = uni.getStorageSync("apply-token");
		//   const applyUid = uni.getStorageSync("apply-uid");

		// 无token直接返回
		if (uni.getStorageSync("apply-token")) {
			try {
				// 有uid直接初始化；无uid则先校验token
				if (uni.getStorageSync("apply-uid")) {
					that.initWyyx();
				} else {
					that.G.checkToken().then(() => {
						console.log("已执行");
						that.initWyyx();
					});
				}
			} catch (err) {
				console.error("初始化wyyx失败：", err);
				// 可补充token失效后的处理，比如清除无效token、跳转登录页等
				// uni.removeStorageSync("apply-token");
				// uni.navigateTo({ url: '/pages/login/login' });
			}
		}

		if (uni.getStorageSync("apply-token") && uni.getStorageSync("apply-uid")) {
			// console.log("app.vue 是否调用");
			that.initWyyx();
		}else{
			if(uni.getStorageSync("apply-token")){
				that.G.checkToken().then(()=>{
					console.log("已执行")
					that.initWyyx();
				})
			}
		}
		uni.removeStorageSync("selectedCity");
		uni.showShareMenu({
			shareTypes: "normal",
		});
		// this.getLocation().then(() => {
		// 	// console.log("that.currentInfo", that.currentInfo);
		// 	if (that.currentInfo.longitude) {
		// 		that.G.Get(that.api.getCityNameByLatLng, { lng: that.currentInfo.longitude, lat: that.currentInfo.latitude }, (res) => {
		// 			// console.log("res", res);
		// 			if (res) {
		// 				let currentCity = res.replace("市", "");
		// 				uni.setStorageSync("selectedCity", currentCity);
		// 				uni.$emit("setCity");
		// 			}
		// 		});
		// 	} else {
		// 		uni.$emit("setCity");
		// 	}
		// });
		// // 隐藏默认底部
		// uni.hideTabBar();
	},
	methods: {
		getLocation() {
			let that = this;
			return new Promise((resolve, reject) => {
				uni.authorize({
					// 检测是否授权位置信息
					scope: "scope.userLocation",
					success() {
						uni.getLocation({
							type: "wgs84",
							success(res) {
								that.currentInfo = {
									latitude: res.latitude,
									longitude: res.longitude,
									timestamp: new Date().getTime(),
								};
								resolve();
							},
							fail(err) {
								console.log(err);
							},
							complete() {
								resolve();
							},
						});
					},
					fail(err) {
						console.log(err);
						uni.showToast({
							title: "请在设置中开启定位权限以获取当前城市定位",
							icon: "none",
						});
						resolve();
						// that.showRefuseLocationPermission();
					},
				});
			});
		},
		initWyyx() {
			let that = this;
		
			that.F.wyyxPost(
				that.api.wyyx_getConfig,
				{
					userId: uni.getStorageSync("apply-uid"),
				},
				(res) => {
					// console.log("wyyx_getConfig", res);
		
					// 检查返回数据有效性
					if (!res || !res.appKey || !res.accid || !res.token) {
						console.error("获取IM配置失败，参数不完整");
						return;
					}
		
					let resData = {
						appkey: res.appKey,
						accid: res.accid,
						token: res.token,
					};
		
					// 保存IM配置信息
					uni.setStorageSync("im-appkey", resData.appkey);
					uni.setStorageSync("im-accid", resData.accid);
					uni.setStorageSync("im-token", resData.token);
		
					const imOptions = {
						appkey: resData.appkey,
						account: resData.accid,
						token: resData.token,
					};
		
					this.initNim(imOptions);
				},
			);
		},
		async initNim(opts) {
			let that = this;
			const account = opts.account;
			const token = opts.token;
			const appkey = opts.appkey;
			const params1 = {
				appkey: appkey,
				debugLevel: "warning",
				apiVersion: "v2",
				readReceiptEnabled: true,
				enableV2CloudConversation: true,
			};
			console.log("ems   NIM", NIM);
			const nim = NIM.getInstance(params1, {
				V2NIMLoginServiceConfig: {
					lbsUrls: isWxApp ? ["https://lbs.netease.im/lbs/wxwebconf.jsp"] : ["https://lbs.netease.im/lbs/webconf.jsp"],
					linkUrl: isWxApp ? "wlnimsc0.netease.im" : "weblink.netease.im",
					isFixedDeviceId: true,
					autoLogin: true,
				},
			});
			this.offWatchIM(nim);
			this.watchIMLoginStatus(nim);
			this.watchIMFriendChange(nim);
			this.watchIMMessageChange(nim);
		
			try {
				await nim.V2NIMLoginService.login(account, token, {
					forceMode: false,
					timeout: 60000,
					retryCount: 3,
					authType: 0,
				});
				that.globalData.nim = nim;
				that.G.nim = nim;
			} catch (err) {
				console.error("error", err);
			}
		},
		/**
		 * IM信息更新监听回调
		 */
		watchIMMessageChange(nim) {
			let that = this;
			// 消息接收回调
			nim.V2NIMMessageService.on("onReceiveMessages", function (messages) {
				console.log("收到 V2NIMMessageService 模块的 onReceiveMessages 事件", messages);
				let message = messages[0];
				uni.$emit("updateMessageList", { ...message, messageFrom: "yunxin" });
			});
			// 发送消息接收监听
			nim.V2NIMMessageService.on("onSendMessage", function (messages) {
				console.log("收到 V2NIMMessageService 模块的 onSendMessage 事件", messages);
			});
			// 监听单聊已读回执
			nim.V2NIMMessageService.on("onReceiveP2PMessageReadReceipts", function (readReceipts) {
				console.log("收到 V2NIMMessageService 模块的 onReceiveP2PMessageReadReceipts 事件", readReceipts);
				uni.$emit("updateMessageReadInfo", readReceipts[0]);
			});
			// 撤回成功回调
			nim.V2NIMMessageService.on("onMessageRevokeNotifications", function (messages) {
				console.log("收到 V2NIMMessageService 模块的 onMessageRevokeNotifications 事件", messages);
			});
			// 修改消息字段的回调
			nim.V2NIMMessageService.on("onReceiveMessagesModified", function (messages) {
				console.log("收到 V2NIMMessageService 模块的 onReceiveMessagesModified 事件", messages);
				uni.$emit("updateMessage", messages);
			});
			// 会话列表变化改变
			nim.V2NIMConversationService.on("onConversationChanged", function (conversationList: V2NIMConversation[]) {
				console.log("初始化监听会话:", conversationList);
				uni.$emit("updateConversationList");
				let unreadConversations = conversationList.filter((item) => {
					return Number(item.unreadCount) > 0;
				});
				console.log("未读会话数量:", unreadConversations);
				if (unreadConversations.length > 0) {
					that.playAudio();
				}
			});
			// 未读消息总数变化
			nim.V2NIMConversationService.on("onTotalUnreadCountChanged", function (messages) {
				console.log("收到 V2NIMMessageService 模块的 onTotalUnreadCountChanged 事件", messages);
				uni.$emit("newMessage", { count: messages, type: "message" });
				uni.setStorageSync("chat_info", { count: messages, type: "message" });
			});
			// 删除回话的监听
			nim.V2NIMConversationService.on("onConversationDeleted", function (conversationIds) {
				uni.$emit("deleteConversationList", conversationIds);
				console.log("conversationIds", conversationIds);
			});
		},
		offWatchIM(nim) {
			// 信息监听
			nim.V2NIMMessageService.off("onReceiveMessages");
			nim.V2NIMMessageService.off("onMessageRevokeNotifications");
			nim.V2NIMMessageService.off("onReceiveMessagesModified");
			nim.V2NIMConversationService.off("onConversationChanged");
			nim.V2NIMConversationService.off("onConversationDeleted");
			nim.V2NIMConversationService.off("onReceiveP2PMessageReadReceipts");
			// 好友信息监听
			nim.V2NIMFriendService.off("onFriendAdded");
			nim.V2NIMFriendService.off("onFriendDeleted");
			nim.V2NIMFriendService.off("onFriendAddApplication");
			nim.V2NIMFriendService.off("onFriendAddRejected");
			nim.V2NIMFriendService.off("onFriendInfoChanged");
		},
		/**
		 * IM好友信息更新监听回调
		 */
		watchIMFriendChange(nim) {
			// 添加好友成功回调，返回添加成功的好友信息列表
			nim.V2NIMFriendService.on("onFriendAdded", function (friend) {
				console.log("watchIMFriend", friend);
			});
			// 删除好友回调，返回删除的好友信息
			nim.V2NIMFriendService.on("onFriendDeleted", function (accountId, deletionType) {
				console.log("watchIMFriend", accountId);
				console.log("watchIMFriend", deletionType);
			});
			// 申请添加好友回调，返回申请添加为好友的信息
			nim.V2NIMFriendService.on("onFriendAddApplication", function (application) {
				console.log("watchIMFriend", application);
			});
			// 被对方拒绝好友添加申请的回调，被拒绝的好友申请信息
			nim.V2NIMFriendService.on("onFriendAddRejected", function (rejection) {
				console.log("watchIMFriend", rejection);
			});
			// 好友信息更新回调，返回变更的好友信息
			nim.V2NIMFriendService.on("onFriendInfoChanged", function (friend) {
				console.log("watchIMFriend", friend);
			});
		},
		/**
		 * IM登录状态监听回调
		 */
		watchIMLoginStatus(nim) {
			/**
			 * 登录瞬时状态监听
			 */
			//  登录状态变化回调
			nim.V2NIMLoginService.on("onLoginStatus", function (arg1) {
				console.log("收到 V2NIMLoginService 模块的 onLoginStatus 事件", arg1);
			});
			//  登录失败回调
			nim.V2NIMLoginService.on("onLoginFailed", function (arg1) {
				console.log("收到 V2NIMLoginService 模块的 onLoginFailed 事件", arg1);
			});
			//  登录终端被其他端踢下线回调
			nim.V2NIMLoginService.on("onKickedOffline", function (arg1) {
				console.log("收到 V2NIMLoginService 模块的 onKickedOffline 事件", arg1);
			});
			//  登录终端登录信息变更回调
			nim.V2NIMLoginService.on("onLoginClientChanged", function (arg1) {
				console.log("收到 V2NIMLoginService 模块的 onLoginClientChanged 事件", arg1);
			});
			/**
			 * 登录持续性状态监听
			 */
			//  登录连接状态变化回调
			nim.V2NIMLoginService.on("onConnectStatus", function (arg1) {
				console.log("收到 V2NIMLoginService 模块的 onConnectStatus 事件", arg1);
			});
			//  登录连接断开回调
			nim.V2NIMLoginService.on("onDisconnected", function (arg1) {
				console.log("收到 V2NIMLoginService 模块的 onDisconnected 事件", arg1);
			});
			//  登录连接失败回调
			nim.V2NIMLoginService.on("onConnectFailed", function (arg1) {
				console.log("收到 V2NIMLoginService 模块的 onConnectFailed 事件", arg1);
			});
			//  数据同步状态变化回调
			nim.V2NIMLoginService.on("onDataSync", function (arg1) {
				console.log("收到 V2NIMLoginService 模块的 onDataSync 事件", arg1);
			});
		},
		playAudio() {
			let that = this;
			const innerAudioContext = uni.createInnerAudioContext();
			innerAudioContext.autoplay = true;
			innerAudioContext.src = "https://bocai-cms.oss-cn-beijing.aliyuncs.com/web-resource/ibocai/tip.mp3";
			innerAudioContext.onPlay(() => {
				// console.log("开始播放");
			});
			uni.vibrateShort();

			innerAudioContext.onError((res) => {
				// console.log(res.errMsg);
				// console.log(res.errCode);
			});
		},
	},
};
</script>
<style lang="scss">
@import "./uni_modules/vk-uview-ui/index.scss";
@import "./static/css/base.scss";
@import "./static/css/iconfont.css";

uni-page-body {
	height: 100%;
	background-color: #ededed;
}

uni-page-body > uni-view {
	height: 100%;
}

.g-components-panel-hr {
	padding-bottom: 16px;

	.doc-left {
		width: 43px;
		height: 2px;
		border: 1px solid;
		border-image: linear-gradient(270deg, rgba(255, 255, 255, 0.2), #cccccc) 1 1;
		transform: rotate(180deg);
	}

	.doc-right {
		width: 43px;
		height: 2px;
		border: 1px solid;
		border-image: linear-gradient(270deg, rgba(255, 255, 255, 0.2), #cccccc) 1 1;
	}
}
</style>
