<script setup lang="ts">
	// #ifdef APP-PLUS
	import { setSdkLanguageFromSystem } from '@/uni_modules/tuikit-atomic-x/utils/setSdkLanguageFromSystem'
	import * as call from "@/uni_modules/RongCloud-CallWrapper/lib/index"
	// #endif
	import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'
	import { reLaunch } from './utils/router'
	import { useAuthUser } from './composables/useAuthUser'
	import { useUserStore } from './stores/user'
	import { TUIChatKit } from './TUIKit'
	import { getIpBlack } from './api'
	import {reasonDeal,errorDeal,imCode} from '@/utils/code.js'
	import { navigateTo } from '@/utils/router'

	TUIChatKit.init()

	const { token, tencentUserSig } = useAuthUser()
	const { loginTencentIM } = useUserStore()
	/** 静默登录逻辑 */
	const silentLogin = async (e : any) => {
		if (token.value) {
			loginTencentIM()
			// reLaunch('/TUIKit/components/TUIConversation/index')
			return
		}

		console.log(tencentUserSig, '=====222==')
		if (e?.query?.invitationCode) {
			reLaunch('/pages/login/phone-register/phone-register', {
				invitationCode: e.query.invitationCode
			})
		} else {
			// 没有token去登录页
			reLaunch('/pages/login/login')
		}
	}

	onLaunch((e : any) => {
		// return
		console.log('App Launch111')
		silentLogin(e)

		// #ifdef APP-PLUS
		setSdkLanguageFromSystem()
		onAllListeners()
		// #endif
	})

	onShow(() => {
		console.log('App Show222')
	})

	onHide(async () => {
		if (token.value) {
			const show = await getIpBlack(false)
			console.log(show.data.data, '======')
		}
		// #ifdef APP-PLUS
		removeAllListeners()
		// #endif
		console.log('App Hide333')
	})
	
	function onAllListeners () {
		call.onCallReceived( (res)=> {
			console.log(res)
			console.log("Engine:OnCallReceived=>"+"监听通话呼入, 目标id=>", res.data.targetId);
			if (res.data.targetId) {
				// let url = res.data.mediaType == 0 ? "" : "/pages/room/room"
				uni.setStorageSync('room-parameters', {
					callType: 'in',
					mediaType: res.data.mediaType === 0 ? 'audio' : 'video'
				});
				uni.showToast({
					title:"有通话呼入该跳转了"+res.data.targetId,
					duration:3000
				})
				navigateTo("/pages/room/incom", {
					type: res.data.extra,
					callType: 'in',
					mediaType: res.data.mediaType == 0 ? "audio" : "video",
					userID: res.data.mine.userId // 对方的用户id
				})
			}
		});
		call.onCallDisconnected((res)=>{
			console.log(res)
			console.log("Engine:OnCallDisconnected=>"+"通话挂断/拒绝, 挂断原因=>", res.data.reason);
			// 重新渲染视频视图
			// uni.$emit('OnCallDisconnected');
			uni.showToast({
				title:reasonDeal(res.data.reason),
				error:"error",
				icon:'none',
				duration:2000
			})
			goback()
		});
		call.onCallConnected((res)=>{
			console.log(res)
			console.log("Engine:OnCallConnected=>"+"已建立通话通话接通时，通过回调 onCallConnected 通知当前 call 的详细信息", res);
		});
		call.onRemoteUserInvited((res)=>{
			console.log("Engine:OnRemoteUserInvited=>"+"通话中的某一个参与者，邀请好友加入通话 ,远端Id为=>", res.data.userId);
			uni.$emit('OnCallConnected');
		})
		call.onRemoteUserJoined((res)=>{
			console.log("Engine:OnRemoteUserJoined=>"+"主叫端拨出电话，被叫端收到请求后，加入通话，对端Id为=>", res.data.userId);
			uni.$emit('OnCallConnected');
		})
		call.onRemoteUserLeft((res)=>{
			console.log("Engine:OnRemoteUserLeft=>"+"远端用户挂断(群聊触发)，远端Id为=>", res.data.reason);
			uni.$emit('OnCallConnected');
			uni.showToast({
				title:reasonDeal(res.data.reason),
				error:"error",
				icon:'none',
				duration:2000
			})
		})
		call.onCallOutgoing((res)=>{
			console.log('电话已拨出 主叫端拨出电话后，通过回调 onCallOutgoing 通知当前 call 的详细信息')
		})
		call.onRemoteUserRinging((res)=>{
			console.log('被叫端正在振铃，主叫端拨出电话，被叫端收到请求，发出振铃响应时，回调 onRemoteUserRingin,对端Id为=>', res.data.userId)
		})
		call.onError((res)=>{
			console.log('通话过程中，发生异常')
			uni.showToast({
				title:errorDeal(res.data.reason),
				error:"error",
				icon:'none',
				duration:2000
			});
			goback()
		})
		call.onRemoteUserMediaTypeChanged((res)=>{
			console.log('当通话中的某一个参与者切换通话类型，例如由 audio 切换至 video，回调 onMediaTypeChanged,切换媒体类型的Id为=>',res.data.user.userId);
		})
	}
	
	function goback () {
		const pages = getCurrentPages()
		console.log('pages: ',pages);
		if (pages.length > 1) {
			console.log("走返回");
			uni.showToast({
				title:"走返回",
				duration:3000
			})
			uni.navigateBack({
				delta: 1
			})
			const currentPage = pages[pages.length - 1]
			const prevPage = pages[pages.length - 2]
			
			// 判断上一页是否是 tabBar 页面
			// const isPrevPageTabBar = isTabBarPage(currentPage.route)
			// if(!isPrevPageTabBar){
				
			// }
		}
	}
	
	// 判断页面是否是 tabBar 页面
	function isTabBarPage(route) {
		// 这里根据你的 pages.json 配置来判断
		const tabBarPages = [
			'TUIKit/components/TUIConversation/index',
			'TUIKit/components/TUIContact/index',
			'pages/discover/discover',
			'pages/my-index/my-index'
		]
		
		// 判断路由是否在 tabBar 页面列表中
		return tabBarPages.includes(route)
	}
	
	function removeAllListeners(){
		call.unInit();
		//移除监听-接收到通话呼入
		call.removeCallReceivedListener();
		// 移除监听-开始呼叫通话的回调
		call.removeCallOutgoingListener();
		// 移除监听-通话已接通
		call.removeCallReceivedListener();
		// 移除监听-通话已结束
		call.removeCallDisconnectedListener();
		// 移除监听-对端用户正在振铃
		call.removeRemoteUserRingingListener();
		// 移除监听-对端用户加入了通话
		call.removeRemoteUserJoinedListener();
		// 移除监听-有用户被邀请加入通话
		call.removeRemoteUserInvited();
		// 移除监听-对端用户挂断
		call.removeRemoteUserLeftListener();
		// 移除监听-对端用户切换了媒体类型
		call.removeRemoteUserMediaTypeChangedListener();
		// 移除监听-通话出现错误的回调
		call.removeErrorListener();
		
	}
	
</script>

<style lang="scss">
	/*每个页面公共css */
	@import './styles/global.scss';

	/* common css for page */
	// uni-page-body,
	// html,
	// body,
	// page {
	//   width: 100% !important;
	//   height: 100% !important;
	//   overflow: hidden;
	// }
</style>