<script>//com.vi1688cityexpress.user
// const toast = uni.requireNativePlugin('Ba-Toast');//android
// const callerID = uni.requireNativePlugin('Ba-CallerID');//android
// const KJPip = uni.requireNativePlugin('KJ-Pip');//ios

import baseUrlconst from "@/config/urlConfig.js"

 import api from "@/pages/api/api.js"
  export default {
	  data() {
	    	return {
	  		isAndroid:false,
	  		androidflType:0,
	  		isInback:false,
			isfirst:true,
			audioObj:null,
	  	}
	  },
	  globalData:{
	  	_i18n:{},
	  	$t:{},
		sj:{},
		iosfl:{},
		token:'',
		imViewOpen:false,
		EXViewOpen:false,
		goEasy:null,
		goEasycnt:false,
		initgoEasy:{},
		getUrl:{}
	  },
    onLaunch: function() {
      console.log('App Launch:',uni.getStorageSync("token"))
	  this.globalData._i18n=this.$i18n;
	  this.globalData.$t=str=>this.$t(str);
	  this.globalData.sj=str=>this.getTimestr();
	  this.globalData.getUrl=index=>this.getBaseUrl(index);
	  this.globalData.iosfl=index=>this.showpiaof(index);
	  this.globalData.token = uni.getStorageSync("token");
	  this.globalData.imViewOpen=false;
	  this.globalData.EXViewOpen=false;
	  this.globalData.goEasy = this.goEasy;
	  this.globalData.initgoEasy=str=>this.connectGoEasy();
	  let systemInfo = uni.getSystemInfoSync();
	  this.isAndroid = systemInfo.platform.toLowerCase() === 'android';
	  
	  var language = uni.getStorageSync('language');
	  console.log(language)
	  if(''==language||null==language||undefined==language){
		  uni.setStorageSync('language',"zh-Hant");
		  uni.setLocale('zh-Hant');
		  if(!this.isAndroid){
			  this.$i18n.locale = 'zh-Hant';
		  }
		  this.uploadLanguagesSet('zh-Hant');
	  }
	  else{
		  uni.setLocale(language);
		  if(!this.isAndroid){
			this.$i18n.locale = language;
		  }
		  //this.uploadLanguagesSet(language);
	  }
	  this.connectGoEasy();
	  
	  uni.setStorageSync('userAddrLocation',"");
	  uni.onPushMessage((res) => {
	  	console.log("收到推送消息：",res) //监听推送消息
		var payload=res.data.payload;
		if(payload.indexOf("rcuser")!=-1){
			this.updataxiaoxi(payload);
		}
		if(res.type=='click'){
			var content=res.data.title;
			plus.runtime.setBadgeNumber(0);
			// if(content.indexOf("Call")!=-1){
			// 	if(this.globalData.imViewOpen){
			// 		return;
			// 	}
			// 	uni.setStorageSync('impayload',res.data.payload);
			// 	this.imcallrecive(res.data.payload);
			// 	return
			// }
			// if(content.indexOf("message")!=-1){
			// 	if(this.globalData.EXViewOpen){
			// 		return;
			// 	}
			// 	uni.setStorageSync('impayload',res.data.payload);
			// 	this.immessagerecive(res.data.payload);
			// 	return
			// }
			
			setTimeout(function() {
			  // 这里写要延时执行的代码
			  uni.switchTab({
			  	url:'/pages/OrderList/OrderList'
			  })
			}, 1500);
			return;
		}
		if(res.type=='receive'){
			plus.runtime.setBadgeNumber(0);
			var content=res.data.title;
			// if(content.indexOf("Call")!=-1){
			// 	if(this.globalData.imViewOpen){
			// 		return;
			// 	}
			// 	uni.setStorageSync('impayload',res.data.payload);
			// 	this.imcallrecive(res.data.payload);
			// 	return
			// }
			// if(content.indexOf("message")!=-1){
			// 	if(this.globalData.EXViewOpen){
			// 		return;
			// 	}
			// 	uni.setStorageSync('impayload',res.data.payload);
			// 	this.immessagerecive(res.data.payload);
			// 	return
			// }
			content=res.data.content;
			if(content.indexOf("骑手定位")!=-1){
				plus.runtime.setBadgeNumber(0);
				return;
			}
			uni.createPushMessage({
				content:res.data.content,
				success: (res) => {
					console.log(res);
				},
				fail(er) {
				}
			});
		}
	  });
	  //-----------------------------------
	  var that = this;
	  //android---------------------------------------------
	  that.audioObj=uni.createInnerAudioContext();
	  that.audioObj.src='static/y800.mp3';
	  var globalEvent = uni.requireNativePlugin('globalEvent');
	  globalEvent.addEventListener('baCallerIdEvent', function(e) {
	  	console.log('baCallerIdEvent：' + JSON.stringify(e));
	  		console.log(e);
	  		if(e.tag=='call'&&e.action=='onClick'){
	  			if(that.isInback){
	  				plus.runtime.launchApplication({pname:'com.vi1688cityexpress.user'});
	  			}
	  			
	  			if(that.androidflType==1){
	  				uni.navigateTo({
	  					url:'/pages/imcall/audioCall?iscaller=0'
	  				})
	  			}
	  			else if(that.androidflType==2){
	  				uni.navigateTo({
	  					url:'/pages/imcall/GoeasyExchange?iscaller=0'
	  				})
	  			}
	  			that.audioObj.pause();
	  			that.hideFW();
	  		}
	  		if(e.tag=='uncall'&&e.action=='onClick'){
				that.audioObj.pause();
	  			that.hideFW();
	  		}
	  });
	  //ios-------------------------------------------------------------
	  globalEvent.addEventListener('onPip', function(res) {
	      console.log("onPip:" + JSON.stringify(res));
	      if (res.method == "willStartPip") {
	          console.log("即将开启画中画");
	      } else if (res.method == "didStartPip") {
	          console.log("已经开启画中画");
	      } else if (res.method == "failedStartPip") {
	          console.log("开启画中画失败");
	      } else if (res.method == "willStopPip") {
	          console.log("即将关闭画中画");
	  			  //that.imdef();
	      } else if (res.method == "didStopPip") {
	          console.log("已经关闭画中画");
	  			 
	      } else if (res.method == "restorePip") {
	          console.log("恢复");
	      }
	  });
	  globalEvent.addEventListener('onWebview', function(res) {
	      console.log("onWebview:" + JSON.stringify(res));
	      if (res.method == "finish") {
	          console.log("页面加载完成");
	      } else if (res.method == "fail") {
	          console.log("加载失败");
	      }
	  });
	  if(!this.isAndroid){
	  		  this.onH5SendDataCallBack();
	  }
    },
    onShow: function() {
      console.log('App Show')
	  if(!this.isAndroid){
	  		  //this.closePip();
	  }
	  this.isInback=false;
	  this.initflaotView();
    },
    onHide: function() {
      console.log('App Hide')
	  this.isInback=true;
    },
	
	methods:{
		getTimestr(){
			var time=new Date();
			var n,y,r,h,m,s;
			n=time.getFullYear();
			y=time.getMonth()+1;
			r=time.getDate();
			h=time.getHours();
			m=time.getMinutes();
			s=time.getSeconds();
			var timsStr = n+'-'+y+'-'+r+' '+h+':'+m+':'+s;
			return timsStr;
		},
		
		getBaseUrl(index){
			if(index==1){
				return this.$baseUrl.getimageBaseUrl();
			}
			if(index==2){
				return this.$baseUrl.getUploadUrl();
			}
			if(index==3){
				return this.$baseUrl.getApibaseUrl();
			}
			if(index==4){
				return this.$baseUrl.getwebBaseUrl();
			}
			
		},
		async uploadLanguagesSet(lang){
			var userId = uni.getStorageSync('userId');
			if(lang=='yuenan'){
				lang='vi';
			}
			if(lang=='zh-Hans'){
				lang='zh-CN';
			}
			if(lang=='zh-Hant'){
				lang='zh-TW';
			}
			console.log("changeLanguages");
			api('changeLanguages',{
				lang:lang
			},res=>{
				console.log('changeLanguages',res)
			},failc=>{
				//console.log('getadvertis----',failc)
			})
		},
		updataxiaoxi(str){
			var xiaoxiList = uni.getStorageSync('dachexiaoxi');
			if(''==xiaoxiList||null==xiaoxiList||undefined==xiaoxiList){
				xiaoxiList=[];
			}
			xiaoxiList.push(str);
			uni.setStorageSync('dachexiaoxi',xiaoxiList);
		},
		
		//imcall&&immessage------------------------------------------------
		initflaotView(){
			if(this.isAndroid){
				if(this.isfirst){
					//this.isPermissionFW();
					this.isfirst=false
				}
			}
			else{//ios
				//this.initPip("landscape");
			}
		},
		imcallrecive(str){
			
			if(str.indexOf("\\\"")!=-1){
				str=str.replace(/\\\"/g, '\"');
				str = str.replace(/\"{/g, '{');
				str = str.replace(/}\"/g, '}');
			}
			var obj = JSON.parse(str)
			console.log('imcallrecive',obj)
			if(this.isAndroid){
				if(this.androidflType!=0){
					return;
				}
				var uobj={
					name:obj.nickName,
					content:this.$t('audioCall.cteyhcall'),
					call:this.$t('audioCall.jietingyy'),
					uncall:this.$t('audioCall.jujuejieting')
				}
				this.androidflType=1;
				this.showFW(uobj,false);
				this.audioObj.play();
			}
			else{//ios
				this.imCall();
			}
		},
		immessagerecive(str){
			if(str.indexOf("\\\"")!=-1){
				str=str.replace(/\\\"/g, '\"');
				str = str.replace(/\"{/g, '{');
				str = str.replace(/}\"/g, '}');
			}
			var obj = JSON.parse(str);
			if(this.isAndroid){
				if(this.androidflType!=0){
					return;
				}
				var uobj={
					name:obj.nickName,
					content:this.$t('exchange.cteyhmsg'),
					call:this.$t('exchange.chakanxinxi'),
					uncall:this.$t('exchange.quxiao')
				}
				this.androidflType=2;
				this.showFW(uobj,false);
				this.audioObj.play();
			}
			else{//ios
				this.imMessage();
			}
		},
		//android-------------------------------------------------
		// showFW(obj,isInit) { //显示
		// 	var that = this;
		// 	callerID.show({
		// 			gravity: 1, //显示位置：0中间 1上 2下
		// 			name:obj.name,//用户昵称 ,
		// 			content:obj.content,//说明是骑手来电、来信息
		// 			call: obj.call,//接听IM，查看IM信息
		// 			uncall: obj.uncall,//拒绝接听IM，拒绝查看IM信息
		// 			empty: "",
		// 			avatar: "/static/logo.png",
		// 			totalHint: "",
		// 			tel: "",
		// 			list:[]
		// 		},
		// 		(res) => {
		// 			console.log(res);
		// 			if(isInit){
		// 				that.hideFW()
		// 			}
		// 			// uni.showToast({
		// 			// 	title: res.msg,
		// 			// 	icon: "none",
		// 			// 	duration: 3000
		// 			// })
		// 		});
		// },
		// hideFW() { //隐藏
		// 	this.androidflType=0;
		// 	callerID.hide(
		// 		(res) => {
		// 			console.log(res);
		// 			// uni.showToast({
		// 			// 	title: res.msg,
		// 			// 	icon: "none",
		// 			// 	duration: 3000
		// 			// })
		// 		});
		// },
		// permissionFW() { //申请悬浮窗权限
		// 	callerID.permission(
		// 		(res) => {
		// 			console.log('permissionFW',res);
		// 	});
		// },
		// goPermissionFW() { //跳转到悬浮窗权限页面
		// 	callerID.goPermission(
		// 		(res) => {
		// 			console.log('goPermissionFW',res);
		// 	});
		// },
		// isPermissionFW() { //是否申请悬浮窗权限
		// 	var that = this;
		// 	callerID.isPermission(
		// 		(res) => {
		// 			console.log('是否申请悬浮窗权限',res);
		// 			if (res.data) {
		// 				if(res.data.isPermission){
		// 					var uobj={
		// 						name:'CTE',
		// 						content:'',
		// 						call:'',
		// 						uncall:''
		// 					}
		// 					that.showFW(uobj,true);
		// 				}
		// 				else{
		// 					that.goPermissionFW();
		// 				}
		// 			}
		// 	});
		// },
		//ios--------------------------------------
		// showpiaof(index){
			
		// 	var that = this;
		// 	if(index==1){
		// 		setTimeout(function() {
		// 		  // 这里写要延时执行的代码
		// 		  that.initPip("landscape");
		// 		}, 800);
		// 	}
		// 	if(index==2){
		// 		that.closePip();
		// 	}
		// 	if(index==3){
		// 		var language = uni.getStorageSync('language');
		// 		if(language=='yuenan'){
		// 			var dic = {
		// 			    "js": "changeImgvi()"
		// 			}
		// 			KJPip.webView_evaluateJavaScript(dic, (res) => {
		// 			    console.log("webView_evaluateJavaScript:" + JSON.stringify(res));
		// 			})
		// 		}
		// 		else{
		// 			var dic = {
		// 			    "js": "changeImg()"
		// 			}
		// 			KJPip.webView_evaluateJavaScript(dic, (res) => {
		// 			    console.log("webView_evaluateJavaScript:" + JSON.stringify(res));
		// 			})
		// 		}
		// 	}
		// 	if(index==4){
		// 		var language = uni.getStorageSync('language');
		// 		if(language=='yuenan'){
		// 			var dic = {
		// 			    "js": "changeImgMSvi()"
		// 			}
		// 			KJPip.webView_evaluateJavaScript(dic, (res) => {
		// 			    console.log("webView_evaluateJavaScript:" + JSON.stringify(res));
		// 			})
		// 		}
		// 		else{
		// 			var dic = {
		// 			    "js": "changeImgMS()"
		// 			}
		// 			KJPip.webView_evaluateJavaScript(dic, (res) => {
		// 			    console.log("webView_evaluateJavaScript:" + JSON.stringify(res));
		// 			})
		// 		}
		// 	}
		// 	return '';
		// },
		// initPip(shape) {
		//     var dic = {
		//         "shape": shape, //弹窗形状 square(正方形) landscape(横向) portrait(竖向)
		//     }
		//     KJPip.initPip(dic)
			
		// 	console.log('initPip')
		// 	var that = this;
		// 	that.iosInit=true;
		// 	setTimeout(function() {
		// 	  // 这里写要延时执行的代码
		// 	  that.openPip1();
		// 	}, 2000);
		// },
		// openPip1() {//打开，加载本地页面?language='+language
		// 	var language = uni.getStorageSync('language');
		//     this.openPip(plus.io.convertLocalFileSystemURL("hybrid/html/xuanfu/index.html"));
		// },
		// openPip(url) {
		// 	var that = this;
		//     KJPip.isPictureInPictureActive((res) => {
		//         console.log("isPictureInPictureActive:" + JSON.stringify(res));
		//     })
		//     KJPip.isPictureInPictureSuspended((res) => {
		//         console.log("isPictureInPictureSuspended:" + JSON.stringify(res));
		//     })
		//     KJPip.isPictureInPicturePossible((res) => {
		//         console.log("isPictureInPicturePossible:" + JSON.stringify(res));
		// 		// if(!res.result){
		// 		// 	setTimeout(function() {
		// 		// 	  // 这里写要延时执行的代码
		// 		// 	  //that.initPip("landscape");
		// 		// 	}, 800);
		// 		// }
		//     })
		//     KJPip.isPictureInPictureSupported((res) => {
		//         console.log("isPictureInPictureSupported:" + JSON.stringify(res));
		//     })
		//     var dic = {
		//         "url": url
		//     }
		//     KJPip.openPip(dic, (res) => {
		//         console.log("openPip:" + JSON.stringify(res));
		//     })
		// },
		// closePip() {//关闭弹窗
		//     KJPip.closePip()
		// },
		
		imCall(){//收到IM语音通话请求
			
			uni.navigateTo({
				url:'/pages/imcall/audioCall?iscaller=0'
			})
			
		},
		
		imMessage(){//收到im文字聊天请求
			
			uni.navigateTo({
				url:'/pages/imcall/GoeasyExchange?iscaller=0'
			})
			
		},
		
		imdef(){//收到im文字聊天请求
			var dic = {
			    "js": "changeImgdef()"
			}
			// KJPip.webView_evaluateJavaScript(dic, (res) => {
			//     console.log("webView_evaluateJavaScript:" + JSON.stringify(res));
			// })
		},
		
		onH5SendDataCallBack() { //注意ios16之后，弹出里的内容不能点击
			var that = this;
		  //   KJPip.onH5SendDataCallBack((res) => {
				// console.log("onH5SendDataCallBack:",res);
		  //   })
		},
		//GoEasy--------------------------------------------
		connectGoEasy() {
			var that = this;
			if(that.globalData.goEasycnt==true){
				that.goeasydisconnect();
				return;
			}
			var userInfo=uni.getStorageSync('userInfo');
			if(''==userInfo||null==userInfo||undefined==userInfo){
				return;
			}
			console.log(userInfo);
			this.goEasy.connect({
				id:'userid_'+userInfo.userId,
				data: {
				  name:userInfo.nickName,
				  avatar:userInfo.avatar
				},
				onSuccess: () => {
				  console.log('GoEasy connect successfully.')
				  that.goEasyPush();
				  that.globalData.goEasycnt=true;
				},
				onFailed: (error) => {
				  console.log('Failed to connect GoEasy, code:' + error.code + ',error:' + error.content);
				},
				onProgress: (attempts) => {
				  console.log('GoEasy is connecting', attempts);
				}
		  });
		},
		goEasyPush(){
			var userInfo=uni.getStorageSync('userInfo');
			if(''==userInfo||null==userInfo||undefined==userInfo){
				return;
			}
			//console.log(userInfo);
			var that = this;
			var pubsub = this.goEasy.pubsub;
			pubsub.subscribe({
				channel:'userid_'+userInfo.userId,
				onMessage: function (message) {
					console.log("goEasyPush:",message);
					var obj = JSON.parse(message.content);
					if(obj.ptype==1){
						if(that.globalData.imViewOpen){
							return;
						}
						uni.setStorageSync('impayload',message.content);
						that.imcallrecive(message.content);
					}
					if(obj.ptype==2){
						if(that.globalData.EXViewOpen){
							return;
						}
						uni.setStorageSync('impayload',message.content);
						that.immessagerecive(message.content);
					}
				},
				onSuccess: function () {
					console.log("Subscribe successfully.")
				},
				onFailed: function () {
					console.log("Subscribe onFailed.")
				}
			
			});
		},
		//断开连接
		goeasydisconnect(){
			var that = this;
			this.goEasy.disconnect({
			    onSuccess: function(){
			        console.log("GoEasy disconnect successfully.")
					that.globalData.goEasycnt=false;
					that.connectGoEasy();
			    },
			    onFailed: function(error){
			        console.log("Failed to disconnect GoEasy, code:"+error.code+ ",error:"+error.content);
			    }
			});
		},
	},
  }
</script>

<style lang="scss">
@font-face {
	font-family: zrht;
	src: url('/uni_modules/font/zrht.otf');
}
  .container {
    padding: 15px;
  }
/*
  button {
    margin-bottom: 15px;
  }
  */
 .ztextfontB1{
	 font-size: 36rpx;
	 font-weight: bold;
 }
 .ztextfontB2{
 	 font-size: 34rpx;
 	 font-weight: bold;
 }
 .ztextfontB3{
 	 font-size: 32rpx;
 	 font-weight: bold;
 }
 .ztextfontB4{
 	 font-size: 30rpx;
 	 font-weight: bold;
 }
 .ztextfontB5{
 	 font-size: 28rpx;
 	 font-weight: bold;
 }
 .ztextfontS1{
 	 font-size: 26rpx;
 	 font-weight: bold;
 }
 .ztextfontS2{
 	 font-size: 24rpx;
 	 font-weight: bold;
 }
 .ztextfontS3{
 	 font-size: 22rpx;
 	 font-weight: bold;
 }
 
 .textfontB1{
 	 font-size: 36rpx;
 }
 .textfontB2{
 	 font-size: 34rpx;
 }
 .textfontB3{
 	 font-size: 32rpx;
 }
 .textfontB4{
 	 font-size: 30rpx;
 }
 .textfontB5{
 	 font-size: 28rpx;
 }
 .textfontS1{
 	 font-size: 26rpx;
 }
 .textfontS2{
 	 font-size: 24rpx;
 }
 .textfontS3{
 	 font-size: 22rpx;
 }
 
 .content{
 	display: flex;
 	flex-direction: column;
 	width: 94%;
 	margin-left: 3%;
 	background-color: white;
 	border-radius: 16rpx;
 	box-shadow: 0rpx 0rpx 10rpx 0rpx lightgray;
 }
 .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;
 }
 .text1row{
 	overflow: hidden;
 	text-overflow: ellipsis;
 	/* #ifndef APP-PLUS-NVUE */
 	display: -webkit-box;
 	-webkit-line-clamp: 1;
 	-webkit-box-orient: vertical;
 	/* #endif */
 }
 .text2row{
 	overflow: hidden;
 	text-overflow: ellipsis;
 	/* #ifndef APP-PLUS-NVUE */
 	display: -webkit-box;
 	-webkit-line-clamp: 2;
 	-webkit-box-orient: vertical;
 	/* #endif */
 }
 
</style>
