<!-- com.encryptedIM.im   com.aiim.app.demo   6OQrPSweuBcdbhg -->
<script setup lang="ts">//setup lang="ts"

import {onHide, onLaunch, onShow} from "@dcloudio/uni-app";
import {getCurrentInstance,watch} from "vue";
import {storeToRefs} from "pinia";
import {useSysStore} from "@/store/sysStore";
import Auth from "@/api/Auth";
import {clearVoipTk} from "@/api/Login";
import VimPlugin from "@/plugins/VimPlugin";
import WebrtcCtr from "@/imcall/WebrtcCtr";
import {useWsStore} from "@/store/WsStore";
import ChatType from "@/utils/ChatType";
import type VideoSendInfo from "@/plugins/video/mode/VideoSendInfo";
import SendVideoCode from "@/plugins/video/SendVideoCode";
const bugly = uni.requireNativePlugin("LX-Bugly");
import dbactApi from '@/api/DBactApi';
import {useUserStore} from "@/store/userStore";
import UserApi from '@/api/UserApi';
import { usePeerStore } from '@/store/peerStore';
import {
	UTSVoipMgr,
	UTSLocalNotification
} from "@/uni_modules/wrs-uts-voip";
import {
	UTSWebRTC
} from "@/uni_modules/wrs-uts-webrtc";


let sendInfo=null;
let isRc=false;
let isclearVoipTk=false;
var mtpushModule = uni.requireNativePlugin("EL-MTPush");
const wsStore = useWsStore();
const peerStore = usePeerStore();
const {isClose} = storeToRefs(peerStore);

watch(isClose, (newVal) => {
  console.log('isCloseisClose APP',newVal)
  if (newVal) {
	  if(uni.getSystemInfoSync().platform == "ios"&&isRc==false){
		UTSVoipMgr.endCall({
			uuid: uni.getStorageSync("voip_UUID")
		}, (resp: any)=>{
			if(resp.false){
			}
			else{
				usePeerStore().updateCloseStatus(false);
			}
		})
	  }
  }
})

onLaunch(() => {
	plus.screen.lockOrientation('portrait-primary');
	if(uni.getSystemInfoSync().platform == 'android'){
		bugly.init("ed19003953","true");
	}
	UTSWebRTC.peerConnectionFactoryInit();
	setInterval(() => {
		uni.getNetworkType({
		  success: function (res) {
		    const networkType = res.networkType;
		    if (networkType === 'none') {
		      //console.log('networkType N')
			  isclearVoipTk=false;
			  if(Auth.getToken()!=''){
				  Auth.logout();//无法连接网络，跳转登录页面
			  }
		    } else {
		      // 有网络
			  if(Auth.getToken()==''&&Auth.getvoipTk()!=''&&!isclearVoipTk){
			     var data={
			     	"voipTk":Auth.getvoipTk()
			     }
			     clearVoipTk(JSON.stringify(data)).then((res)=>{
					 if(res.code==200){
						 isclearVoipTk=true;
					 }
			     	console.log('clearVoipTk1',res);
			     })
			     .catch((err) => {
			        console.log('clearVoipTk2',err);
			      });
			  }
		      //console.log('networkType Y')
		    }
		  }
		});
	}, 5000);
  uni.getSystemInfo({
    success: function (e) {
      //@ts-ignore
      const {proxy} = getCurrentInstance();
      // #ifndef MP
      proxy.statusBar = e.statusBarHeight;
      if (e.platform == 'android') {
        //@ts-ignore
        proxy.customBar = e.statusBarHeight + 50;
      } else {
        //@ts-ignore
        proxy.customBar = e.statusBarHeight + 45;
      }
      ;
      // #endif

      // #ifdef MP-WEIXIN
      proxy.statusBar = e.statusBarHeight;
      //@ts-ignore
      let custom = wx.getMenuButtonBoundingClientRect();
      proxy.Custom = custom;
      //@ts-ignore
      proxy.customBar = custom.bottom + custom.top - e.statusBarHeight;
      // #endif

      // #ifdef MP-ALIPAY
      proxy.statusBar = e.statusBarHeight;
      //@ts-ignore
      proxy.customBar = e.statusBarHeight + e.titleBarHeight;
      // #endif
      // #ifdef APP-PLUS
      //自动更新 安卓
      if (e.platform === 'android') {
        // app_upgrade(async () => {
        //   //查询是否更新
        //   const {statusCode, data} = await uni.request({
        //     url: update.checkUrl,
        //     method: 'GET'
        //   })
        //   const version = packageJson.version
        //   if (statusCode === 200) {
        //     return {
        //       changelog: data.changelog,
        //       status: data.android > version ? 1 : 0, // 0 无新版本 | 1 有新版本
        //       path: data.url // 新apk地址
        //     }
        //   }
        // })
      }
      // #endif
    }
  })
  
  //极光推送
 console.log('App Launch')
 var platformType='a';
 if(uni.getSystemInfoSync().platform == "ios"){
 	platformType='i';
 	mtpushModule.requestNotificationAuthorization((result)=>{
 		let status = result.status
 		if (status < 2) {
 			uni.showToast({
 				icon: 'none',
 				title: '您还没有打开通知权限',
 				duration: 3000
 			})
 		}
 	})
 }
 
 mtpushModule.initPushService();
 mtpushModule.setLoggerEnable(true);
 console.log(mtpushModule);
 mtpushModule.addConnectEventListener(result=>{
	 console.log(result);
 	let connectEnable = result.connectEnable
 	uni.$emit('connectStatusChange',connectEnable)
	mtpushModule.getRegistrationID(resultID=>{
		let registerID = resultID.registerID
		console.log(registerID)
		Auth.setregisterID(registerID);
		if(Auth.getToken()&&Auth.getToken()!=''){
			const currentUser = useUserStore().getUser();
			currentUser.registrationId=registerID;
			var data={
				"userId": currentUser?.id,
				"registrationId":registerID,
				"platformType":platformType//a---(android),i---(ios)
			}
			UserApi.setUser(JSON.stringify(data)).then((res)=>{
				console.log('setuser',res);
			});
		}
	})
 });
 
 mtpushModule.addNotificationListener(result=>{
	 console.log(result);
 	// let notificationEventType = result.notificationEventType
 	// let messageID = result.messageID
 	// let title = result.title
 	// let content = result.content
 	// let extras = result.extras
 	
 	// uni.showToast({
 	// 	icon: 'none',
 	// 	title: JSON.stringify(result),
 	// 	duration: 3000
 	// })
 });
 
 mtpushModule.addCustomMessageListener(result=>{
	 console.log(result);
 	// let type = result.type
 	// let messageType = result.messageType
 	// let content = result.content
 	// uni.showToast({
 	// 	icon: 'none',
 	// 	title: JSON.stringify(result),
 	// 	duration: 3000
 	// })
 })
 
 if(uni.getSystemInfoSync().platform == "ios"){
 	mtpushModule.addLocalNotificationListener(result=>{
		console.log(result);
 		// let messageID = result.messageID
 		// let title = result.title
 		// let content = result.content
 		// let extras = result.extras
 		// uni.showToast({
 		// 	icon: 'none',
 		// 	title: JSON.stringify(result),
 		// 	duration: 3000
 		// })
 	})
 }
 


 
 
 if(platformType!='i'){
	 return;
 }
 
 // 请求通知权限
 UTSLocalNotification.requestAuthorization({
 	types: ["badge", "sound", "alert"]
 }, (resp) => {
 	let flag = resp.flag
 	if (!flag) { // 请求权限失败
 		console.log("requestAuthorization:" + JSON.stringify(resp))
 	}
 })
 console.log('App Launch')
 UTSVoipMgr.onCallback((resp:any) => {
 	let opt = resp.opt
	console.log("onCallback:",resp)
 	switch (opt) {
 		//  获取到本机token，需要上传给后端，后端发送voip时需要token参数，token可以理解为手机的ID
 		case "didUpdatePushCredentials":
 			let token = resp.token
 			console.log("token:" + token)
			Auth.setvoipTk(token)
			if(Auth.getToken()&&Auth.getToken()!=''){
				const currentUser = useUserStore().getUser();
				var data={
					"userId": currentUser?.id,
					"voipTk":Auth.getvoipTk(),
				}
				console.log(data)
				UserApi.setUser(JSON.stringify(data)).then((res)=>{
					console.log('setuser',res);
				});
			}
 			break;
 			// 用户接听了电话
 		case "performAnswerCall":
		    console.log("performAnswerCall:",resp)
			if(sendInfo&&sendInfo!=''){
				WebrtcCtr.messageListener(sendInfo.message);//新的通话方式
				//VimPlugin.messageListener(sendInfo);
				isRc=true;
			}
 			break;
 			// 电话挂断
 		case "performEndCall":
 			console.log("performEndCall:",isRc)
			if(isRc){
				return;
			}
			if(sendInfo&&sendInfo!=''){
				const userId = useUserStore().getUser()?.id
				if (userId) {
					const closeMessage: VideoSendInfo<VideoClose> = {
					  code: SendVideoCode.CLOSE,
					  message: {
					    chatId:sendInfo.message.fromId,
					    fromId: sendInfo.message.chatId,
					    timestamp: new Date().getTime(),
					    type: ChatType.FRIEND
					  }
					}
					wsStore.send(JSON.stringify(closeMessage))
				}
			}
 			break;
 			// 拉起接听电话界面结果
 		case "startCall":
			Auth.setvoipUUID(resp.uuid);
			isRc=false;
 			console.log("startCall:", resp)
			UTSVoipMgr.deleteWaitingResponseUuid(resp.uuid);
 			break;
 		default:
 			console.log('default',resp,)
			sendInfo=resp.payload.imMsg;
 			break;
 	}
 })
 
  
});
onShow(() => {
	if(uni.getSystemInfoSync().platform == 'android'){
		//bugly.report("上报内容11112")
	}
  plus.runtime.setBadgeNumber(0);
  if (Auth.getToken()) {
    if (wsStore.wsRequest.socket?.readyState === 1) {
      wsStore.checkStatus()
    } else {
      wsStore.close(true)
      wsStore.init()
    }
  }
  if(dbactApi.DBisOpen()){
	  //console.log('dbactApi.DBisOpen')
	   if (Auth.getToken()){
		   dbactApi.createMSGtable();
		   dbactApi.createchattable();
		   dbactApi.createLocalMSGtable();
	   }
  }else{
  	  dbactApi.openDb().then((res)=>{
  	  	 
		  if (Auth.getToken()){
		  	dbactApi.createMSGtable();
			dbactApi.createchattable();
			dbactApi.createLocalMSGtable();
		  }
  	  });
  }
  useSysStore().setShow(true)
});
onHide(() => {
	console.log('onHide')
  useSysStore().setShow(false)
  dbactApi.closeDB();
});

</script>
<style>
@import "colorui/main.css";
@import "colorui/icon.css";
@import "static/css/font.css";

page {
  height: 100%;
}
.tab-bar-mar {
  margin-bottom: 140upx
}

.contentInRowL{
 	display: flex;
 	flex-direction: row;
 	justify-content: flex-start;
 }
 
 .contentInRowC{
 	display: flex;
 	flex-direction: row;
 	justify-content: center;
 	align-items: center;
 }
 .contentInRowR{
 	display: flex;
 	flex-direction: row;
 	justify-content: flex-end;
 }
 .contentInRowS{
 	display: flex;
 	flex-direction: row;
 	align-items: center;
 	justify-content: space-between;
 }
 
 .contentColumn{
 	display: flex;
 	flex-direction: column;
 }
 
 .contentColumnC{
 	display: flex;
 	flex-direction: column;
 	align-items: center;
 	justify-content: center;
 }
</style>
