import { Component, ElementRef, OnDestroy, OnInit } from '@angular/core';
import { AuthService } from "./auth/auth.service";
import { LifeCommonService } from "./common/life-common.service";
import { Subscription } from "rxjs/index";
import { Router, NavigationStart, ActivatedRoute, NavigationEnd, ActivationEnd } from '@angular/router';
import { MyService } from './my/my.service';


declare var wx : any;
@Component({
	selector: 'app-root',
	templateUrl: './app.component.html',
	styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {
	shareGuidePageEnable : boolean;
	subscription : Subscription;
	currentVersion : any;
	isNeedAlert : boolean;
	dialogInfo : any;
	// 是否显示首页浮标
	isShowIndexBtn : boolean;
	loginId : any;
	// 提问icon显示隐藏
	askIconFlag : boolean = true;
	iconShowFlag : boolean = true;
	
	isShowhead : boolean = true;
	
	// 0是未看 1是已看
	viewStatus : number;
	lifeCustomerInfo : any;
	constructor(private router : Router,
		private authService : AuthService,
		private lifeCommonService : LifeCommonService,
		private activatedRoute : ActivatedRoute,
		private myService : MyService,
		private el : ElementRef) {
		this.subscription = lifeCommonService.shareStatus$.subscribe(status => {
			this.shareGuidePageEnable = status == '1';
		})



	}

	public menuLists = [
		{ key: 1, name: '首页', icon: 'index', link: '/' },
		{ key: 2, name: '产品库', icon: 'product', link: '/product' },
		{ key: 3, name: '日程', icon: 'schedule', link: '/todo' },
		{ key: 4, name: '我的', icon: 'mine', link: '/mine' },
	]
	public selectedMenuKey : number = 1;
	// 点击底部菜单
	menuSelect(item) {
		this.selectedMenuKey = item.key;
		this.router.navigate([item.link]);
	}

	closeDialog(e) {
		if (e.target.className.indexOf('tipsInfoContainer') > -1) {
			this.viewStatus = 1;
			sessionStorage.setItem('hadView', 'true')
		}
	}
	viewDetail() {
		this.viewStatus = 1;
		sessionStorage.setItem('hadView', 'true');
		this.router.navigate(['/renewal_reminder'])
	}

	ngOnInit() {
		sessionStorage.setItem('iconShowFlag', 'true');
		this.lifeCustomerInfo = JSON.parse(localStorage.getItem('lifeCustomerInfo')) ? JSON.parse(localStorage.getItem('lifeCustomerInfo')) : null;
		this.loginId = this.lifeCustomerInfo ? this.lifeCustomerInfo.mobileNo : null;
		this.authService.obtainToken(this.loginId).subscribe(res => {
			if (res['success']) {
				localStorage.setItem('lifeToken', res['data']['token']);
				this.ydWxConfig();
			}
		});

		this.getVersion();
		this.router.events.forEach((event) => {
			if (event instanceof NavigationStart) {
				// 控制首页浮标显示与否和底部菜单
				this.isShowIndexBtn = event.url.indexOf('/login') < 0;
				this.iconShowFlag = !!localStorage.getItem('lifeCustomerInfo');
				if ((event.url.indexOf('/activityDetail') >= 0 && event.url.indexOf('shareCode') >= 0)
					|| event.url.indexOf('/aiofp') >= 0
				) {
					this.iconShowFlag = false;
				}
				if (event.url.indexOf('/material/') >= 0
					|| event.url.indexOf('/inviter') >= 0
					|| event.url.indexOf('/register') >= 0
					|| event.url.indexOf('/invitees') >= 0
					|| event.url.indexOf('/video/') >= 0
					|| (event.url.indexOf('/activityDetail') >= 0 && event.url.indexOf('shareCode') >= 0)
					|| event.url.indexOf('/aiofp') >= 0
				) {
					this.isShowIndexBtn = false;
				}
				if (event.url.indexOf('/activityDetail') >= 0) {
					this.isShowhead = false;
				}
				
				
				// 更新底部图标状态
				if (event.url.indexOf('/product') === 0) {
					this.selectedMenuKey = 2
				} else if (event.url.indexOf('/todo') === 0) {
					this.selectedMenuKey = 3
				} else if (event.url == '/' || event.url == '/my') {
					this.selectedMenuKey = 1
					// 查询是否有续期提醒订单
					if (sessionStorage.getItem('hadView')) {
						this.viewStatus = 1;
					} else {
						if (this.lifeCustomerInfo) {
							this.queryNoticeList();
						}
					}
				} else if (event.url.indexOf('/mine') === 0) {
					this.selectedMenuKey = 4
				} else {
					this.selectedMenuKey = 0;
				}
			}

			if (event instanceof ActivationEnd) {
				this.lifeCommonService.setTitle(`${event.snapshot.data[0] && event.snapshot.data[0].title ? event.snapshot.data[0].title : '银盾保险经纪'}`)
			}
		});
	}

	ngOnDestroy() {
		this.subscription.unsubscribe();
	}

	// 微信JS-SDK注册
	ydWxConfig() {
		const url = encodeURIComponent(location.href.split('#')[0]);
		this.authService.ydWxConfig(url).subscribe(res => {
			const data = res['data'];
			wx.config({
				debug: false,
				appId: data.appId,
				timestamp: data.timestamp,
				nonceStr: data.nonceStr,
				signature: data.signature,
				jsApiList: data.jsApiList,
				beta: true
			});
		});
	}

	// 获取是否有续期提醒订单
	queryNoticeList() {
		this.myService.queryNoticeList({ practitionerId: this.lifeCustomerInfo.practitionerId, status: 0 }).subscribe(res => {
			if (res['success']) {
				if (res['data']['list'] && res['data']['list'].length > 0) {
					this.viewStatus = 0;
				} else {
					sessionStorage.setItem('hadView', 'true')
				}
			}
		})
	}

	// 关闭弹窗
	getPopInfo() {
		this.isNeedAlert = false;
		let { search, href } = window.location;
		href = href.replace(/&?t_reload=(\d+)/g, '');
		window.location.href = href + (search ? '&' : '?') + 't_reload=' + new Date().getTime();
		localStorage.setItem('Version', this.currentVersion)
	}

	getVersion() {
		this.authService.currentVersionQuery().subscribe((res) => {
			if (res['data']['currentVersion']) {
				this.currentVersion = res['data']['currentVersion'];
			}
			//只在微信端判断缓存
			if (this.lifeCommonService.checkDeviceType() === '3') {
				//如果本地没有版本号设置缓存
				if (!localStorage.getItem('Version')) {
					localStorage.setItem('Version', this.currentVersion);
				} else {
					const Version = localStorage.getItem('Version');
					//如果缓存有版本号对比本地和接口版本
					if (Version != this.currentVersion) {
						localStorage.clear();
						this.isNeedAlert = true;
						this.dialogInfo = {
							title: null,
							content: { value: '检测到新版本', align: 'center' },
							footer: [{ value: '更新', routerLink: '', className: 'weui-dialog__btn_primary' }],
						};
					}
				}
			}

		})
	}

	close() {
		this.askIconFlag = this.iconShowFlag = false
		sessionStorage.setItem('iconShowFlag', this.iconShowFlag + '')
	}
}