import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { MyService } from '../../my.service';
import { ActivatedRoute, Router } from "@angular/router";
import { LifeCommonService } from "../../../common/life-common.service";
import { EmployBasicQuery } from '../../../domain/employBasicQuery';
declare const wx : any;
declare class MediaRecorder {
	constructor(stream : MediaStream);
	start() : void;
	stop() : void;
	// 其他方法和属性...  
}
@Component({
	selector: 'ydlife-record-video',
	templateUrl: './record-video.component.html',
	styleUrls: ['./record-video.component.scss']
})
export class RecordVideoComponent implements OnInit {
	hiringBasicInfoId : any;
	toastDialog : boolean;
	toastInfo : any;
	isNeedAlert : boolean;
	dialogInfo : any;
	approveStatus : any;
	editEmployBasicInfo:EmployBasicQuery = new EmployBasicQuery();

	mediaRecorder : any;
	mediaStream : any;
	recorderFile : any;
	chunks : any = [];
	stopRecordCallback : any;
	videoType : any = 1;
	recrodTime = 0;
	intervalTime = null;
	initType=1;

	constructor(private activatedRoute : ActivatedRoute,
		private router : Router, public lifeCommonService : LifeCommonService,
		public myService : MyService, private changeDetectorRef : ChangeDetectorRef) { }
		
	ngOnInit() {
		const title = this.activatedRoute.snapshot.data[0]['title'];
		this.lifeCommonService.setTitle(title);
		this.hiringBasicInfoId = this.activatedRoute.snapshot.queryParams.hiringBasicInfoId ? this.activatedRoute.snapshot.queryParams.hiringBasicInfoId : null;
		this.queryWholeInfo(this.hiringBasicInfoId);
		
	}
	c_video(){
		this.initType=1;
		const video = document.getElementsByTagName('video')[0];
		video.src=this.editEmployBasicInfo.videoOssPath;
		video.play();
	}
	openCamera(start) {
		var constraints = {
			audio: true,
			video: {
				// width: { min: 1024, ideal: 1280, max: 1920 },
				// height: { min: 776, ideal: 720, max: 1080 },
				deviceId: "default",
				facingMode: "user" //调用前置摄像头
			}
		};
		this.getUserMedia(constraints, (err, stream) => {
			if (err) {
				// this.$emit('error', err)
				throw err;
			} else {
				// 通过 MediaRecorder 记录获取到的媒体流
				const video = document.getElementsByTagName('video')[0];
				this.mediaRecorder = new MediaRecorder(stream);
				this.mediaStream = stream;
				this.chunks = [],
				video.srcObject = stream;
				video.play();

				this.mediaRecorder.ondataavailable = (e) => {
					this.mediaRecorder.blobs.push(e.data);
					this.chunks.push(e.data);
				};
				this.mediaRecorder.blobs = [];
				this.mediaRecorder.onstop = (e) => {
					this.recorderFile = new Blob(this.chunks, {
						'type': this.mediaRecorder.mimeType
					});
					this.chunks = [];
					if (null != this.stopRecordCallback) {
						this.stopRecordCallback();
					}
				};
				if (start) {
					this.mediaRecorder.start();
				}
			}
		});
	}

	/**
		* 获取用户媒体设备(处理兼容的问题)
		* @param videoEnable {boolean} - 是否启用摄像头
		* @param audioEnable {boolean} - 是否启用麦克风
		* @param callback {Function} - 处理回调
		*/
	getUserMedia(constraints, callback) {
		if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
			navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
				callback(false, stream);
			})['catch'](function (err) {
				callback(err);
			});
		} else if (navigator['getUserMedia']) {
			navigator.getUserMedia(constraints, function (stream) {
				callback(false, stream);
			}, function (err) {
				callback(err);
			});
		} else {
			callback(new Error('Not support userMedia'));
		}
	}

	/**
	 * 关闭媒体流
	 * @param stream {MediaStream} - 需要关闭的流
	 */
	closeStream(stream) {
		if (!stream) return;
		if (typeof stream.stop === 'function') {
			stream.stop();
		} else {
			let trackList = [stream.getAudioTracks(), stream.getVideoTracks()];

			for (let i = 0; i < trackList.length; i++) {
				let tracks = trackList[i];
				if (tracks && tracks.length > 0) {
					for (let j = 0; j < tracks.length; j++) {
						let track = tracks[j];
						if (typeof track.stop === 'function') {
							track.stop();
						}
					}
				}
			}
		}
	}
	//开始录制
	start() {
		this.mediaRecorder.start();
		this.videoType = 2;
		this.startRecordReadTime();
	}
	//停止录制
	stop() {
		this.videoType = 3;
		this.initType=2;
		var element = document.getElementById("loadingBox");
		element.classList.remove('loadingBoxHide');  
		element.classList.add('loadingBox');  

		this.stopRecord(() => {
			this.send();
		});
		this.clearIntervaltime();
	}
	//重新录制
	reStart() {
		this.initType=1;
		this.videoType = 2;
		this.clearIntervaltime();
		this.startRecordReadTime();
		this.openCamera('start');
	}
	// 清除定时器
	clearIntervaltime() {
		this.recrodTime = 0;
		if (this.intervalTime) {
			clearInterval(this.intervalTime);
		}
	}
	// 录制时间
	startRecordReadTime() {
		var that = this;
		that.intervalTime = setInterval(() => {
			if (that.recrodTime == 20) {
				that.initType=2;
				that.stop();
			} else {
				that.recrodTime += 1;
			}
		}, 1000)
	}
	// 停止录制
	stopRecord(callback) {
		// 终止录制器 关闭媒体流
		this.mediaRecorder.stop();
		this.stopRecordCallback = callback;
	}
	closeBtn() {
		this.closeStream(this.mediaStream);
	}
	send() {
		let that = this;
		
		let fileName = 'figure.mp4'  // 可自定义文件名称
		var file = new File([this.recorderFile], fileName, {
			type: 'video/mp4'
		});

		const video = document.getElementsByTagName('video')[0];
		var formData = new FormData();
		formData.append("file", file);
		this.myService.uploadFile(formData,(e)=>{
			var element = document.getElementById("loadingBox");
			element.classList.remove('loadingBox');  
			element.classList.add('loadingBoxHide');  
			if(e.status==200){
				let response = JSON.parse(e.responseText);
				if(response.success){
					
					that.editEmployBasicInfo.videoOssPath=response.data.filePath;
					video.src = that.editEmployBasicInfo.videoOssPath;
					video.play();
				}else{
				window.alert('上传文件失败')
				}
			}else{
				window.alert('上传文件失败')
			}
		});
	}
	// blob 转化url
	blobToUrl(blob) {
		let url = window.URL.createObjectURL(blob)
		return url
	}


	next() {
		if (!this.editEmployBasicInfo.videoOssPath) {
			this.openPopInfo('请录制并上传视频！')
			return;
		}
		this.myService.saveBasicInfo(this.editEmployBasicInfo).subscribe((res) => {
			if (res['success']) {
				this.router.navigate(["/signature"], {
				  queryParams: { hiringBasicInfoId: this.hiringBasicInfoId },
				});
			} else {
				this.toastDialog = true;
				this.toastInfo = {
					status: 1,
					msg: res['message'],
					timeout: 3000,
					align: 'center'
				};
			}
		})

	}

	// 打开弹窗
	openPopInfo(message) {
		this.isNeedAlert = true;
		this.dialogInfo = {
			title: null,
			content: { value: message, align: 'center' },
			footer: [{ value: '我知道了', routerLink: '', className: 'weui-dialog__btn_primary' }],
		};
	}

	// 关闭弹窗
	getPopInfo() {
		this.isNeedAlert = false;
	}

	queryWholeInfo(hiringBasicInfoId) {
		this.myService.queryWholeInfo({ hiringBasicInfoId: hiringBasicInfoId }).subscribe((res) => {
			if (res['success']) {
				this.approveStatus = res['data']['hiringBasicInfo']['approveStatus'];
				this.editEmployBasicInfo = res['data']['hiringBasicInfo'];
				if(this.editEmployBasicInfo.videoOssPath){
					this.initType=2;
					this.videoType = 3;
					const video = document.getElementsByTagName('video')[0];
					video.src = this.editEmployBasicInfo.videoOssPath;
					
				}else{
					//开启摄像头
					this.initType=1;
					this.openCamera(null);
				}
			} else {
				this.editEmployBasicInfo = null;
			}
		})
	}

	viewNext() {
		this.router.navigate(['/signature'], { queryParams: { hiringBasicInfoId: this.hiringBasicInfoId } });
	}

	goBack() {
		history.go(-1)
	}
}