<script>
  // APP 和 小程序平台
  // #ifdef  APP-PLUS || MP-WEIXIN   
	import TIM from 'tim-wx-sdk';
	import COS from 'cos-wx-sdk-v5';
  // #endif
	
	// #ifdef H5
	import TIM from 'tim-js-sdk';
	import TIMUploadPlugin from 'tim-upload-plugin'
	// #endif
	
  // #ifdef APP-PLUS
	import Aegis from 'aegis-weex-sdk';
	// #endif
	
	// #ifdef MP-WEIXIN
	import Aegis from 'aegis-mp-sdk';
	// #endif
	
	// #ifdef H5
	import Aegis from 'aegis-web-sdk';
	// #endif
	
	import logger from './utils/logger'; // app.js
	import {
		genTestUserSig
	} from './debug/GenerateTestUserSig.js';
	import { getLang, setTabBar } from '@/utils/util'

	import animationMixin from '@/pages/mixins/animation'
	const aegis = new Aegis({
		id: 'iHWefAYqKznuxWjLnr', // 项目key
		reportApiSpeed: true, // 接口测速
	});
	uni.$aegis = aegis
	// 首先需要通过 uni.requireNativePlugin("ModuleName") 获取 module
	// #ifdef APP-PLUS
	const TUICalling = uni.requireNativePlugin('TUICallingUniPlugin-TUICallingModule');
	if(typeof(TUICalling) == 'undefined') {
		logger.error('如果需要音视频功能，请集成原生插件，使用真机运行并且自定义基座调试哦～ 插件地址：https://ext.dcloud.net.cn/plugin?id=7097 , 调试地址：https://nativesupport.dcloud.net.cn/NativePlugin/use/use');
	}
	// #endif
	export default {
		onLaunch() {
			var obj = this.$route.query;
			if (obj.adgroup_id) {
				localStorage.setItem('adgroup_id', JSON.stringify(obj.adgroup_id))
			}
			if (obj.agency_id) {
				localStorage.setItem('agency_id', JSON.stringify(obj.agency_id))
			}
			if (obj.code) {
				localStorage.setItem('agency_code', JSON.stringify(obj.code))
			}
			const SDKAppID = genTestUserSig('').sdkAppID;
			uni.$aegis.reportEvent({
					name: 'onLaunch',
					ext1: 'onLaunch-success',
					ext2: 'uniTuikitExternal',
					ext3: `${SDKAppID}`,
			})
			uni.setStorageSync(`TIM_${SDKAppID}_isTUIKit`, true);
			// 重点注意： 为了 uni-app 更好地接入使用 tim，快速定位和解决问题，请勿修改 uni.$TUIKit 命名。
			// 如果您已经接入 tim ，请将 uni.tim 修改为 uni.$TUIKit。
			uni.$TUIKit = TIM.create({
				SDKAppID: SDKAppID
			});
			// #ifndef H5
			uni.$TUIKit.registerPlugin({
				'cos-wx-sdk': COS
			});
			// #endif
			
			// #ifdef H5
			uni.$TUIKit.registerPlugin({ 'tim-upload-plugin':TIMUploadPlugin })
			// #endif
			// 将原生插件挂载在 uni 上
			// #ifdef APP-PLUS
			uni.$TUICalling = TUICalling;
			// #endif
			// 如果您已创建了 tim，请将 tim 实例挂载在 wx 上，且不可以修改 wx.$TIM（修改变量可能导致 TUICalling 组件无法正常使用）, 完成 TUICalling 初始化，
			// 如果您没有创建，可以不传
			// #ifdef MP-WEIXIN
			wx.$TIM = uni.$TUIKit;
			// #endif
			uni.$TUIKitTIM = TIM;
			uni.$TUIKitEvent = TIM.EVENT;
			uni.$TUIKitVersion = TIM.VERSION;
			uni.$TUIKitTypes = TIM.TYPES; // 监听系统级事件
			uni.$resetLoginData = this.resetLoginData();
			uni.$TUIKit.on(uni.$TUIKitEvent.SDK_READY, this.onSDKReady);
			uni.$TUIKit.on(uni.$TUIKitEvent.SDK_NOT_READY, this.onSdkNotReady);
			uni.$TUIKit.on(uni.$TUIKitEvent.KICKED_OUT, this.onKickedOut);
			uni.$TUIKit.on(uni.$TUIKitEvent.ERROR, this.onTIMError);
			uni.$TUIKit.on(uni.$TUIKitEvent.NET_STATE_CHANGE, this.onNetStateChange);
			uni.$TUIKit.on(uni.$TUIKitEvent.SDK_RELOAD, this.onSDKReload);
			this.getSystem()
			
			
			let time = new Date();
			let timeZone = time.toLocaleTimeString('en-us',{timeZoneName:'short'});  //'1:12:38 PM GMT+8'
			let timeZoneId = Intl.DateTimeFormat().resolvedOptions().timeZone; //'Asia/Shanghai'
			this.$store.state.timeZone = timeZoneId;
			this.$i18n.locale = getLang()

			setTabBar(this)
		},
		watch: {
			'$route'() {
      	this.$store.state.loginShowSign = false
			}
		},
  	mixins: [animationMixin],
		globalData: {
			// userInfo: userID userSig token phone
			userInfo: null,
			// 个人信息
			userProfile: null,
			isTUIKit: true,
			headerHeight: 0,
			statusBarHeight: 0,
			SDKAppID: genTestUserSig('').sdkAppID
		},
		mounted() {
    	this.$(window).scroll(this.scrollFun);
		},
		methods: {
			// 获取系统配置
			getSystem() {
				let _this = this
				uni.$u.http.get('/api/universal/getHot', {}).then(res => {
					// this.$db.set('system'.res.data)
					// res.announcement1 = []
					// res.announcement1.push(res.announcement)
					_this.$store.state.system = res;
					localStorage.setItem('system',JSON.stringify(res))
				})
				// 判断是否登录，没有登录需要获取游客im
				let information = this.$common.get('information') || {}
				this.getQiNiu()
				// setInterval(res=>{
				// 	this.getQiNiu()
				// },60000)
				/* 判断用户是否登录 */
				if(JSON.stringify(information) !== '{}'){
					uni.$u.http.get('api/Member/info').then(res => {
						_this.$store.state.info = res
					})
				}else {
					_this.$store.state.isLogin = 2;
				}
			},
			
			getQiNiu(status) {
				if(this.$store.state.isLogin == 2) return
				this.$store.dispatch('getQiNiu')
			},
			
			// TODO:
			resetLoginData() {
				this.globalData.expiresIn = '';
				this.globalData.sessionID = '';
				this.globalData.userInfo = {
					userID: '',
					userSig: '',
					token: '',
					phone: ''
				};
				this.globalData.userProfile = null;
				logger.log(`| app |  resetLoginData | globalData: ${this.globalData}`);
			},
			onTIMError() {},
			onSDKReady({name}) {
				  const isSDKReady = name === uni.$TUIKitEvent.SDK_READY ? true : false
					uni.$emit('isSDKReady', {
						isSDKReady: true
					});
			},
			onNetStateChange() {},
			onSDKReload() {},
			onSdkNotReady() {},
			onKickedOut() {
				uni.showToast({
					title: 'You are being kicked offline',
					icon: 'error'
				});
				this.$common.del('information');
				this.$common.del('imTouristAccount');
				this.$store.state.isLogin = 2;
				this.$store.state.info={};
				// console.log('您被踢下线');
				// uni.navigateTo({
				// 	url: './pages/TUI-Login/login'
				// });
			}
		}
	};
</script>

<style lang="scss">
	/*每个页面公共css */
	@import "uview-ui/index.scss";
	@import "@/static/css/common.scss";
	@import "@/static/css/animation.scss";
	@import "@/static/css/style.css";
	.uni-tabbar__label {
		margin-top: 0 !important;
	}
	body {
		// font-family: CWC, "Noto Sans Display", "Helvetica Neue", Helvetica, Arial, sans-serif;
	}
	.uni-app--showtabbar uni-page-wrapper::after {
		height: 0 !important;
	}
	.u-toast__content {
		position: relative;
		z-index: 9999;
	}
	.calendar .u-popup__content {
		border-top-left-radius: 20rpx;
  	border-top-right-radius: 20rpx;
	}
	uni-tabbar .uni-tabbar__icon {
		margin-bottom: 3px;
	}
</style>
