import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import { MyService } from '../../my/my.service';
import { LifeCommonService } from '../../common/life-common.service';
import { Subscription } from "rxjs/index";
import { OnDestroy } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import * as uuid from 'uuid';
declare const wx : any;

@Component({
	selector: 'ydlife-activity-detail',
	templateUrl: './activity-detail.component.html',
	styleUrls: ['./activity-detail.component.scss']
})
export class ActivityDetailComponent implements OnInit, OnDestroy {
	@ViewChild('payForm') payForm : ElementRef;//控制弹框
    toastDialog: boolean;
    toastInfo: any;
	articleInfo : any;
	lifeCustomerInfo : any;
	paymentForm : any;
	customerId : number;
	agentInfo : any;
	shareAbled : boolean = false;
	subscription : Subscription;
	articleId : number;
	shareCode : string;
	articleShareCodeSaveInfo : any;
	sharePractitionerInfo : any;
	deviceType : string;
	state : string;
	offsetTop:any;
	scrollTop:any;
	tab1DistanceTop:any;
	tab2DistanceTop:any;
	tab3DistanceTop:any;
	tab4DistanceTop:any;
	tab5DistanceTop:any;
	tab6DistanceTop:any;
	
	//是否显示提交申请盒子
	isShowSubmitBox:any = false;
	//姓名
	reName : string;
	//电话
	mobileNo : number;
	
	constructor(private myService : MyService, public lifeCommonService : LifeCommonService, public router : Router, public activatedRoute : ActivatedRoute) {
		// this.subscription = lifeCommonService.shareStatus$.subscribe(status => {
		//   this.shareAbled = !(status == '0');
		// });
	}
	public tabList = [
		{ key: 'tab1', name: '项目介绍', link: '/', select: true, },
		{ key: 'tab2', name: '发展路径', link: '/', select: false, },
		{ key: 'tab3', name: '创业收获', link: '/', select: false, },
		{ key: 'tab4', name: '创业投入', link: '/', select: false, },
		{ key: 'tab5', name: '创业付出', link: '/', select: false, },
		{ key: 'tab6', name: '银盾支持', link: '/', select: false, },
	]

	ngOnInit() {
		this.articleId = this.activatedRoute.snapshot.params['id'];
		this.shareCode = this.lifeCommonService.getQueryString('shareCode');
		this.state = this.lifeCommonService.getQueryString('state');
		//检测浏览器刷新
		window.onbeforeunload = () => {
			//清除sessionStorage值
			sessionStorage.removeItem('articleTrackId')
		}
		if (this.shareCode) {
			this.practitionerFileSharingList(null, this.shareCode);
			
			if (!this.state) {
				this.articleTrackSave();
			}
		} else {
			document.getElementById("shareBox").style.bottom=70+'px';
			this.practitionerFileSharingList(this.articleId, null);
		}

		this.lifeCustomerInfo = JSON.parse(localStorage.getItem('lifeCustomerInfo')) ? JSON.parse(localStorage.getItem('lifeCustomerInfo')) : null;
		if (this.lifeCustomerInfo) {
			this.customerId = JSON.parse(localStorage.getItem('lifeCustomerInfo'))['customerId'];
			this.agentInfo = {
				headImagePath: this.lifeCustomerInfo.practitionerBasicInfo.headImagePath,
				agentName: this.lifeCustomerInfo.practitionerBasicInfo.name,
				insurerBranchName: this.lifeCustomerInfo.practitionerBasicInfo.insurerBranchName,
				qrCodePath: this.lifeCustomerInfo.practitionerBasicInfo.qrCodePath,
				mobileNo: this.lifeCustomerInfo.mobileNo
			};
		} else {
			this.customerId = null;
		}
		this.deviceType = this.lifeCommonService.checkDeviceType();
		let windowH = window.outerHeight;
		document.getElementById("content").style.height=windowH+'px';
		let bindhandleScroll = this.handleScroll.bind(this);
		document.addEventListener('scroll',bindhandleScroll, true);

	}

	ngOnDestroy() {
		if (this.shareCode && this.state == '1') {
			this.articleTrackSave();
			sessionStorage.removeItem('articleTrackId');
		}
		document.removeEventListener('scroll', this.handleScroll, true);
	}
	handleScroll() {	
		// this.scrollTop = document.documentElement.scrollTop || document.body.scrollTop || window.pageYOffset;
		this.scrollTop=document.getElementById("content").scrollTop;
		if(!this.offsetTop){
			this.offsetTop = document.getElementById("tabBox").offsetTop;
		}
		if (this.scrollTop > this.offsetTop) {
			document.getElementById("tabBox").classList.add('tabBoxXd');
			document.getElementById("tabBox").classList.remove('tabBox');
		} else {
			document.getElementById("tabBox").classList.add('tabBox');
			document.getElementById("tabBox").classList.remove('tabBoxXd');

		}
		//获取六张图片的距离顶部高度
		if(!this.tab1DistanceTop){
			this.tab1DistanceTop = document.getElementById("tab1").offsetTop;
		}
		if(!this.tab2DistanceTop){
			this.tab2DistanceTop = document.getElementById("tab2").offsetTop;
		}
		if(!this.tab3DistanceTop){
			this.tab3DistanceTop = document.getElementById("tab3").offsetTop;
		}
		if(!this.tab4DistanceTop){
			this.tab4DistanceTop = document.getElementById("tab4").offsetTop;
		}
		if(!this.tab5DistanceTop){
			this.tab5DistanceTop = document.getElementById("tab5").offsetTop;
		}
		if(!this.tab6DistanceTop){
			this.tab6DistanceTop = document.getElementById("tab6").offsetTop;
		}
		if (this.scrollTop+300 >= this.tab1DistanceTop) {
			this.tabList.map(item => item.select = false);
			this.tabList[0].select = true;
		}
		if (this.scrollTop+300 >= this.tab2DistanceTop) {
			this.tabList.map(item => item.select = false);
			this.tabList[1].select = true;
		}
		if (this.scrollTop+300 >= this.tab3DistanceTop) {
			this.tabList.map(item => item.select = false);
			this.tabList[2].select = true;
		}
		if (this.scrollTop+300 >= this.tab4DistanceTop) {
			this.tabList.map(item => item.select = false);
			this.tabList[3].select = true;
		}
		if (this.scrollTop+300 >= this.tab5DistanceTop) {
			this.tabList.map(item => item.select = false);
			this.tabList[4].select = true;
		}
		if (this.scrollTop+300 >= this.tab6DistanceTop) {
			this.tabList.map(item => item.select = false);
			this.tabList[5].select = true;
		}
	}
	c_guanw(){
		location.href='https://www.ydinsurance.cn/';
	}
	c_submit(){
		
		if(!this.reName){
			console.log(1);
			this.toastDialog = true;
			this.toastInfo = {
			  status: 1,
			  msg:'请输入姓名！',
			  timeout: 3000,
			  align: 'center'
			};
			return;
		}
		if (!this.lifeCommonService.mobileNoValid(this.mobileNo)) {
			this.toastDialog = true;
			this.toastInfo = {
				status: 1,
				msg: '输入手机号码错误',
				timeout: 3000,
				align: 'center'
			};
			return;
		}
		let param = {
			name:this.reName,
			mobileNo:this.mobileNo,
			remark:'互联网新增员信息',
			practitionerId:this.sharePractitionerInfo.practitionerId
		}
		this.myService.wxUrlRecruit(param).subscribe(res => {
			if (res['success']) {
				this.isShowSubmitBox=false;
				this.reName='';
				this.mobileNo=null;
				this.toastDialog = true;
				this.toastInfo = {
					status: 1,
					msg: '感谢您的关注，我们会尽快与您联系',
					timeout: 3000,
					align: 'center'
				};
			}else{
				this.toastDialog = true;
				this.toastInfo = {
					status: 1,
					msg: res['message'],
					timeout: 3000,
					align: 'center'
				};
				return;
			}
		})
		
	}

	c_aiofp(){
		document.removeEventListener('scroll', this.handleScroll, true);
		this.router.navigate(['/aiofp']);
	}

	// 从后台获取到获取微信code的URL
	getWxUserInfo(trackId:any) {
		this.myService.getWxUserInfo(trackId+'&type=activity').subscribe(res => {
			if (res['success']) {
				this.paymentForm = res['data'].paymentForm;
				this.getOrPost(this.paymentForm.action, this.paymentForm.param, this.paymentForm.charset, this.paymentForm.actionType);
			}
		})
	}
	selectTab(item) {
		document.getElementById(item.key).scrollIntoView({ behavior: 'smooth',block:'center' });
	}

	// 点击分享
	share() {
		this.shareAbled = true;
		this.articleShareCodeSave();
		setTimeout(() => {
			this.shareAbled = false;
		}, 6000);
	}

	// 通过文章ID或者分享码查询文章详情
	practitionerFileSharingList(id, shareCode) {
		this.myService.practitionerFileSharingList({
			shareCode: shareCode,
			id: id,
			practitionerFileShares: { pageNum: 1, pageSize: 5 },
			itemType: '2'
		}).subscribe(res => {
			this.articleInfo = res['data'].practitionerFileShares.list['0'];
			this.sharePractitionerInfo = res['data'].sharePractitionerInfo;
			if (this.sharePractitionerInfo) {
				this.agentInfo = {
					headImagePath: this.sharePractitionerInfo.headImagePath,
					agentName: this.sharePractitionerInfo.name,
					insurerBranchName: this.sharePractitionerInfo.insurerBranchName,
					qrCodePath: this.sharePractitionerInfo.qrCodePath,
					mobileNo: this.sharePractitionerInfo.mobileNo,
				};
			}


		});
	}

	// 保存文章code
	articleShareCodeSave() {
		this.articleShareCodeSaveInfo = {
			itemId: this.articleId,
			shareCode: uuid.v4(),
			practitionerId: this.lifeCustomerInfo ? this.lifeCustomerInfo.practitionerId : this.sharePractitionerInfo.practitionerId,
			customerId: this.lifeCustomerInfo ? this.lifeCustomerInfo.customerId : this.sharePractitionerInfo.customerId,
			os: this.lifeCommonService.checkOs(),
			channel: 1,
			url: window.location.href
		};
		this.lifeCommonService.wxShare(this.articleInfo.title, this.lifeCommonService.getTwenty(this.agentInfo.agentName+this.articleInfo.digest, 38), `${window.location.origin}${window.location.pathname}?shareCode=${this.articleShareCodeSaveInfo.shareCode}`, this.articleInfo.coverUrl);
		this.myService.articleShareCodeSave(this.articleShareCodeSaveInfo).subscribe(res => {
			
		});
	}

	// 保存客户痕迹:
	// 有id就是出  没id就是进
	articleTrackSave() {
		const param = {
			id: sessionStorage.getItem('articleTrackId') ? sessionStorage.getItem('articleTrackId') : null,
			shareCode: this.shareCode,
			nickname: null,
			gender: null,
			imagePath: null,
			deviceType: this.lifeCommonService.checkDeviceType()
		};
		this.myService.articleTrackSave(param).subscribe(res => {
			sessionStorage.setItem('articleTrackId', res['data']['id']);
			if (this.lifeCommonService.getQueryString('state') != '1') {
				this.getWxUserInfo(res['data']['id']);
			}
		})
	}

	// 判断是get请求还是post请求进行支付请求
	getOrPost(action, params, charset, actionType) {
		let url = '';
		let paramHTML = '';
		let hiddenContent = '';
		if (actionType.toLowerCase() === 'get') {
			url = action;
			if (params) {
				for (let i = 0; i < params.length; i++) {
					url += '&' + params[i].name + '=' + params[i].value;
				}
			}

			window.location.href = url;
		} else if (actionType.toLowerCase() === 'post') {
			if (params) {
				for (let i = 0; i < params.length; i++) {
					paramHTML += '<input type="text" value="' + params[i].value + '" name="' + params[i].name + '" hidden>'
				}
			}
			hiddenContent +=
				'<form action="' + action + '"method="post" accept-charset="' + charset + '" onsubmit="document.charset=\'' + charset + '\';">'
				+ paramHTML
				+ '<button type="submit" id="submit" hidden></button>'
				+ '</form>';
			this.payForm.nativeElement.innerHTML = hiddenContent;
			document.getElementById('submit').click();
		}
	}

	jumpTo() {
		window.location.href = 'https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzU4MDYxMDA3NA==#wechat_redirect'
	}
}