import { exchangeNodePos, onHomeworkFinish } from "../script/util";
import { defaultData } from "../script/defaultData";
function RemoteResourceCounter(count, cb) {
	this.remoteResourceCount = count
	this.currentLoadedResourceCount = 0;
	this.finishCallback = cb;
}
RemoteResourceCounter.prototype.load = function(num) {
	this.currentLoadedResourceCount += num;
	console.log('RemoteResourceCounter', this.remoteResourceCount , this.currentLoadedResourceCount);
	if (this.remoteResourceCount <= this.currentLoadedResourceCount) {
		this.finishCallback && this.finishCallback();
	}
}
const TOGGLE_BUTTON_STATUS = {
	PAUSE: 0,
	PLAY: 1
}
cc.Class({

	extends: cc.Component,

	properties: {
		videoplayer: {
            // ATTRIBUTES:
            default: null,        // The default value will be used only when the component attaching
                                  // to a node for the first time
            type: cc.VideoPlayer, // optional, default is typeof default
        },
		cat: {
            // ATTRIBUTES:
            default: null,        // The default value will be used only when the component attaching
                                  // to a node for the first time
            type: cc.Node, // optional, default is typeof default
        },
		toggleButton: {
            // ATTRIBUTES:
            default: null,        // The default value will be used only when the component attaching
                                  // to a node for the first time
            type: cc.Node, // optional, default is typeof default
        },
		toggleButtonSprite: {
            // ATTRIBUTES:
            default: null,        // The default value will be used only when the component attaching
                                  // to a node for the first time
            type: cc.Node, // optional, default is typeof default
        },
		loadingSprite: {
            // ATTRIBUTES:
            default: null,        // The default value will be used only when the component attaching
                                  // to a node for the first time
            type: cc.Node, // optional, default is typeof default
        },
		beginAudioClip: cc.AudioClip,
		finishAudioClip: cc.AudioClip,
		hintAudioClip: cc.AudioClip,

		playStatus: {
			default: null, 
			type: cc.SpriteFrame, 
		},
		pauseStatus: {
			default: null, 
			type: cc.SpriteFrame, 
		},
		m1: {
			default: null, 
            type: cc.Sprite,
        },
		m2: {
			default: null, 
            type: cc.Sprite,
        },
		durationLabel: {
            default: null,
            type: cc.Label
        },
        currentTimeLabel: {
            default: null,
            type: cc.Label
        },
        barTag: {
            default: null,
            type: cc.Node
        },
		ProgressBar: {
            default: null,
            type: cc.ProgressBar
        },
		qupeiyinBtn: {
            default: null,
            type: cc.Sprite
        },
		hintBtn: {
			default: null,
            type: cc.Button
		}

	},

	// 生命周期 onLoad
	onLoad() {
		this.initSceneData();
		this.initSize();
		this._armatureDisPlay = this.cat.getComponent(dragonBones.ArmatureDisplay);
        //获取 Armatrue
        this._armature = this._armatureDisPlay.armature();
		
		
		this._isReadyToPlay = false;
		
		this.toggleButtonSpriteNode = this.toggleButtonSprite.getComponent(cc.Sprite);
		this.setButtonPlayStatus(TOGGLE_BUTTON_STATUS.PAUSE);
		
	},
	onDestroy() {
		this.isPlayMusicAnimation = false;
		cc.audioEngine.stop(this.beginAudioID );
		cc.audioEngine.stop(this.finishAudioID );
		cc.audioEngine.stop(this.hintAudioID );
		this.isDestroy = true;
		if (this.hideControlId) {
			clearTimeout(this.hideControlId);
		}
		
		if (this.videoPlayer) {
			this.videoplayer.pause();
		}
	},
	ctor() { 
		this.beginPlayed = false;
		this.finishPlayed = false;
		this.gameStatus = new RemoteResourceCounter(0, this.hideRabbit.bind(this))
		
	},


	// onPaused(player) {
	// 	console.log('onPaused');
	// 	this.videoStatus.isVideoPlaying = false;
	// },
	// onStoped(player) {
	// 	console.log('onStoped');
	// 	this.videoStatus.isVideoPlaying = false;
	// },
	onCompleted(player) {
		console.log('onCompleted');
		// this.videoStatus.isVideoPlaying = false;
		
		if (this.hideControlId) {
			clearTimeout(this.hideControlId);
		}
		this.showWolf();
		this.showControler();

		if (!this.finishPlayed) {

			this._armatureDisPlay.playAnimation('begin', 0);
			this.finishAudioID = cc.audioEngine.playMusic(this.finishAudioClip, false, 1);
			if (this.finishAudioID) {
				cc.audioEngine.setFinishCallback(this.finishAudioID, () => {
					this._armatureDisPlay.playAnimation('normal', 0);
					if (window && window.courseware && window.courseware.nextPage) {
						console.log('call window.courseware.nextPage');
						// window.courseware.nextPage();
					}
					onHomeworkFinish();
				});
			} else {
				onHomeworkFinish();
			}
			this.finishPlayed = true;

			
		} else {
			this._armatureDisPlay.playAnimation('normal', 0);
			if (window && window.courseware && window.courseware.nextPage) {
					console.log('call window.courseware.nextPage');
					// window.courseware.nextPage();
				}
		}
		// this.videoplayer.currentTime = 0 ;
		// this.ProgressBar.progress = 0;
		// this.barTag.x = 0 ;
		// this.updateBarByTime(0);
		this.setButtonPlayStatus(false);
		this.videoplayer.stop();
	},

	prepareAudioClip(url, key) {
		if (url) {
			cc.assetManager.loadRemote(url, (err, audioClip) => {
				if (audioClip) {
					this[key] = audioClip;
				}
				this.gameStatus.load(1);
			});
		} else {
			this.gameStatus.load(1);
		}

		
	},
	hideRabbit() {
		// console.log('hideRabbit');
		// if (window && window["air"]) {
		// 	window.air.onCourseInScreen = (next) => {
		// 		this.playGame();
		// 		next();
		// 	}
		// 	window["air"].hideAirClassLoading();
		// } else {
		// 	this.playGame();
		// }
		
	},
	playGame() {
		console.log('playGame');
		this._armatureDisPlay.playAnimation('normal', 0);
		this.setButtonPlayStatus(true);
		this._isReadyToPlay = true;
		return;

		if (!this.beginPlayed) {
			this._armatureDisPlay.playAnimation('begin', 0);
			this.beginAudioID = cc.audioEngine.playMusic(this.beginAudioClip, false, 1);
			cc.audioEngine.setFinishCallback(this.beginAudioID, () => {
				this._armatureDisPlay.playAnimation('normal', 0);
				this.setButtonPlayStatus(true);
				this._isReadyToPlay = true;
			});
			this.beginPlayed = true;
		}
	},

	playMusicAnimation(){
		this.isPlayMusicAnimation = true;
		const op1 = this.m1.node.position
		const op2 = this.m2.node.position
		const fn = (sprNode, op) => {
			if (!this.isPlayMusicAnimation) {
				return
			}
			const pos1 = this.getRandomPosInRect(op, 20);
			pos1.angle = this.randRange(-15, 15)
			const pos2 = this.getRandomPosInRect(op, 20);
			pos2.angle = this.randRange(-15, 15)
			const dur1 = this.randRange(0.5, 1.2)
			const dur2 = this.randRange(0.5, 1.2)
			cc.tween(sprNode)
			.to(dur1, pos1, { easing: 'cubicOut' })
			.to(dur2, pos2, { easing: 'cubicIn' })
			.call(() => {
				// console.log('anim play ends');
				fn(sprNode, op);
			})
			.start();
		}
		fn(this.m1.node, op1);
		fn(this.m2.node, op2);
	},
	stopMusicAnimation(){
		this.isPlayMusicAnimation  = false;
	},
	randRange(a, b) {
		const t = [a, b].sort()
		let r = Math.random() * (t[1] - t[0]) 
		if (a >= 1) {
			r =  Math.random() * (t[1] - t[0] + 1) 
		}
		return  r + t[0];
	},
	getRandomPosInRect(target, r) {
		const x = this.randRange(target.x - r, target.x + r);
		const y = this.randRange(target.y - r, target.y + r);
		return {x, y}
	},






	_imageResList: null,
	_audioResList: null,
	_animaResList: null,
	initSceneData() {
		this._imageResList = [];
		this._audioResList = [];
		this._animaResList = [];
	},

	_designSize: null,  // 设计分辨率
	_frameSize: null,  // 屏幕分辨率
	_mapScaleMin: null,  // 场景中常用缩放（取大值）
	_mapScaleMax: null,  // 场景中常用缩放（取小值）
	_cocosScale: null,  // cocos 自缩放 （较少用到）
	initSize() {
		// 注意cc.winSize只有在适配后(修改fitHeight/fitWidth后)才能获取到正确的值,因此使用cc.getFrameSize()来获取初始的屏幕大小
		let screen_size = cc.view.getFrameSize().width / cc.view.getFrameSize().height
		let design_size = cc.Canvas.instance.designResolution.width / cc.Canvas.instance.designResolution.height
		let f = screen_size >= design_size
		cc.Canvas.instance.fitHeight = f
		cc.Canvas.instance.fitWidth = !f

		const frameSize = cc.view.getFrameSize();
		this._frameSize = frameSize;

		this._designSize = cc.view.getDesignResolutionSize();

		let sx = cc.winSize.width / frameSize.width;
		let sy = cc.winSize.height / frameSize.height;
		this._cocosScale = Math.min(sx, sy);

		sx = frameSize.width / this._designSize.width;
		sy = frameSize.height / this._designSize.height;
		this._mapScaleMin = Math.min(sx, sy) * this._cocosScale;
		this._mapScaleMax = Math.max(sx, sy) * this._cocosScale;
	},


	// 生命周期 start
	start() {
		this.initView();
		this.initListener();

		let getData = this.getData.bind(this);
		if (window && window.courseware) {
			getData = window.courseware.getData;
		}

		getData((data) => {
			console.log('data:', data);
			this.data = data || this.getDefaultData();
			this.data = JSON.parse(JSON.stringify(this.data))
			this.preloadItem()
		});
		this.qupeiyinBtn.node.on(cc.Node.EventType.TOUCH_START, function() {
			console.log(123123);
			if (window.courseware && window.courseware.nextPage) {
				window.courseware.nextPage();
			}
			
		}, this);
		this.toggleButton.on(cc.Node.EventType.TOUCH_START, function() {

			this.hideWolf();
			this.delayHideControl();

			cc.audioEngine.stop(this.hintAudioID);
			console.log(cc.audioEngine.isMusicPlaying());
			if (cc.audioEngine.isMusicPlaying()) {
				return;
			} 
			cc.audioEngine.stop(this.finishAudioID);
			
			
			
			if (this.toggleButton.status == TOGGLE_BUTTON_STATUS.PAUSE) {
				this.setButtonPlayStatus(true);
			} else {
				this.setButtonPlayStatus(false);
			}
			this._armatureDisPlay.playAnimation('normal', 0);
			
			
		}, this);
		this.hintBtn.node.on('click', function() {
			console.log('play hint', (!cc.audioEngine.isMusicPlaying() && !this.videoplayer.isPlaying()));
			if (!cc.audioEngine.isMusicPlaying() && !this.videoplayer.isPlaying()){
				this.hintAudioID = cc.audioEngine.playMusic(this.hintAudioClip, false, 1);
				this._armatureDisPlay.playAnimation('begin', 0);
				cc.audioEngine.setFinishCallback(this.hintAudioID, () => {
					this._armatureDisPlay.playAnimation('normal', 0);
				})
			}
			
		}, this);

		// 设置缓冲加载动画 转动
		cc.tween(this.loadingSprite)
			.by(0.1, { angle: -10 })
            .repeatForever()
            .start();
			
		// 覆盖Air中的dialogStatus方法 用于监测视频加载状态
		if(window['air']) {
			window["air"].dialogStatus = (statusCode) => {
				console.log("缓冲", statusCode)
				if(statusCode == 701) {
					// 缓冲中
					this.loadingSprite.active = true;
				} else if(statusCode == 702) {
					// 缓冲结束
					this.loadingSprite.active = false;
				} 
			}
		}

		cc.view.setResizeCallback((params) => {
            console.log('Resize', params);
            this.initdDrag()
        });
        this.initdDrag();
		window.p = this;
	},
	initdDrag() {


        const maxX = this.ProgressBar.node.width;
        const minX = 0;
        
        this.barTag.off(cc.Node.EventType.TOUCH_START);
        this.barTag.on(cc.Node.EventType.TOUCH_START, (e) => {
			// return;
			if (!this.videoplayer.isPlaying()) {
				return
			}
			if (cc.audioEngine.isMusicPlaying()) {
				return;
			}
			if (!this._isReadyToPlay) {
				return;
			}
            console.log("TOUCH_START");
            // this.userDragStart = true;
        });
        this.barTag.off(cc.Node.EventType.TOUCH_MOVE);
        this.barTag.on(cc.Node.EventType.TOUCH_MOVE,(e) => {

					this.delayHideControl();

			
			// if (!this.videoplayer.isPlaying() ) {
			// 	return;
			// }
			// console.log("TOUCH_MOVE");
            var delta = e.getDelta();
            let newX = this.barTag.x+delta.x;
            
            newX = Math.min(maxX, Math.max(newX, minX));
            this.barTag.x = newX;
            const percent = newX / maxX;
            
            const dur = this.videoplayer.getDuration();

            this.currentTimeLabel.string = this.formatTime(percent * dur );
			// console.log(percent * dur);
			this.videoplayer.currentTime = percent * dur;
        });
        this.barTag.off(cc.Node.EventType.TOUCH_ENDED);
        this.barTag.on(cc.Node.EventType.TOUCH_ENDED, (e) => {
           console.log("TOUCH_ENDED");
        //    this.userDragStart = false;
           this.updateBarByPos(this.barTag.x);
        });
        this.barTag.on(cc.Node.EventType.MOUSE_UP, (e) => {
            console.log("MOUSE_UP");
            // this.userDragStart = false;
            this.updateBarByPos(this.barTag.x);
        });
        
        // this.barTag.off(cc.Node.EventType.TOUCH_CANCEL);
        // this.barTag.on(cc.Node.EventType.TOUCH_CANCEL, (e) => {
        //    console.log("TOUCH_CANCEL");
        //    this.userDragStart = false;
        //    this.updateBarByPos(this.barTag.x);
        // });
        // this.ProgressBar.node.off(cc.Node.EventType.TOUCH_START);
        // this.ProgressBar.node.on(cc.Node.EventType.TOUCH_START, (e) => {
		// 	if (this.videoplayer.isPlaying()) {
		// 		const pos = e.getLocation();
		// 		const pPos = this.ProgressBar.node.convertToNodeSpaceAR(pos);
		// 		const newX = Math.min(maxX, Math.max(pPos.x, minX));
		// 		this.updateBarByPos(newX);
		// 	}
        //     // console.log("ProgressBar TOUCH_START", newX); 
        // });

        // this.node.off(cc.Node.EventType.TOUCH_START);
        // this.node.on(cc.Node.EventType.TOUCH_START, (e) => {
        //    console.log("screen TOUCH_START");
        // });
        // const pgBar = this.ProgressBar.node;
        
    },
	getData(func) {
		if (window && window.courseware) {
			window.courseware.getData(func, 'scene');
			return;
		}

		const middleLayer = cc.find('middleLayer');
		if (middleLayer) {
			const middleLayerComponent = middleLayer.getComponent('middleLayer');
			middleLayerComponent.getData(func);
			return;
		}

		func(this.getDefaultData());
	},

	getDefaultData() {
		return defaultData;
	},

	preloadItem() {
		console.log('preloadItem');
		// this.add reloadImage();
		// this.addPreloadAudio();
		// this.addPreloadAnima();
		// this.preload();
		// this.prepareAudioClip(this.data.begin_audio_url, 'beginAudioClip');
		this.prepareAudioClip(this.data.finish_audio_url, 'finishAudioClip');
		this.prepareAudioClip(this.data.hint_audio_url, 'hintAudioClip');

		// const d = this.data.video_url.lastIndexOf('.');
		// const u = this.data.video_url.substring(0, d) + '_l'  + this.data.video_url.substring(d)
		// console.log('video', u);

		this.addPreloadAudio(() => {
			this.preload();
		});
		
		cc.debug.setDisplayStats(false);
	},

	onReadyToPlay(player) {
		console.log('onReadyToPlay');
		this.gameStatus.load(1);

		this.videoplayer.stayOnBottom = true;

		setTimeout(() => {
			this.videoCanPlay = true;
			if (window && window["air"] && this.pageLoaded) {
				window["air"].hideAirClassLoading();
			}
		}, 100);

	},
	onMetaLoaded(player) {
		console.log('onMetaLoaded');
		this.durationLabel.string = this.formatTime(this.videoplayer.getDuration());
	},
	onClicked(player) {
		console.log('onClicked');
	},
	onPlaying(player) {
		console.log('onPlaying');
		// this.videoStatus.isVideoPlaying = true;
	},

	videoCanPlay: false,
	pageLoaded: false,

	preload() {
		const preloadArr = this._imageResList.concat(this._audioResList).concat(this._animaResList);
		console.log('preloadArr:  ', JSON.stringify( preloadArr) );
		cc.assetManager.loadAny(preloadArr, null, null, (err, data) => {

			this.videoplayer.remoteURL = this.data.video_url;


			this.addServerListener();
			this.pageLoaded = true;
			if (window && window["air"] && this.videoCanPlay) {
				window["air"].hideAirClassLoading();
			}
		});
	},
	
	addServerListener() {

		console.log('addServerListener');
		if (window && window["air"]) {
			window.air.onCourseInScreen = (next) => {
				this.playGame();
				next();
			}
		} else {
			this.playGame();
		}
	},


	addPreloadAudio(callback) {

		this._audioResList.push({url: this.data.finish_audio_url || ''});
		this._audioResList.push({url: this.data.hint_audio_url || ''});

		const url1 = this.data.video_url;
		if (!url1) {
			callback();
			return;
		}

		this.getVideoUrl((url) => {

			console.log('url: ', url);
			this.data.video_url = url;
			this._audioResList.push({ url: url || '' });

			callback();
		}) 
	},
	getVideoUrl(callback) {
		const url1 = this.data.video_url;

		// 强制使用原视频
		// console.log("强制使用原视频")
		// callback(url1);
		// return
		// ==== End ===

		const url2 = url1.replace(/.mp4$/g, "_h.mp4");
		this.httpHeadCall(url2, (success) => {
			if (success) {
				console.log('return url2: ', url2);
				callback(url2);
			} else {
				console.log('return url1: ', url1);
				callback(url1);
			}
		})
	},

	httpHeadCall(requsetUrl, callback) {

		let xhr = new XMLHttpRequest();
		console.log("Status: Send Post Request to " + requsetUrl);
		try {
			xhr.onreadystatechange = () => {
				try {

					console.log('xhr.readyState: ', xhr.readyState);

					if (xhr.readyState == 4) {
						if ((xhr.status >= 200 && xhr.status < 400)) {
							callback(true);
						} else {
							callback(false);
						}
					}

				} catch (e) {
					console.log(e)
				}
			};

			xhr.open("HEAD", requsetUrl, true);
			xhr.send();

			xhr.timeout = 15000;
			xhr.onerror = (e) => {
				console.log("汪汪汪 posterror", e);
				callback(false);
			};

			xhr.ontimeout = (e) => {
				console.log("汪汪汪 ontimeout", e);
				callback(false);
			};

		} catch (e) {
			console.log("Send Get Request error: ", e)
		}
	},




	initView() {

		this.initBg();
		this.videoplayer.node.on('ready-to-play', this.onReadyToPlay, this);
		this.videoplayer.node.on('meta-loaded', this.onMetaLoaded, this);
		this.videoplayer.node.on('clicked', this.onClicked, this);
		this.videoplayer.node.on('playing', this.onPlaying, this);
		// this.videoplayer.node.on('paused', this.onPaused, this);
		// this.videoplayer.node.on('stopped', this.onStoped, this);
		this.videoplayer.node.on('completed', this.onCompleted, this);

		// this.initPic();
		// this.initBtn();
		// this.initIcon();

		this.controlNode = cc.find("Canvas/Controls");
		this.wolfNode = cc.find("Canvas/catBox");
		
		this.controlNode.active = false;
		this.wolfNode.active = false;
	},

	initBg() {
		const bgNode = cc.find('Canvas/bg');
		bgNode.scale = this._mapScaleMax;

		// this.initMask(bgNode);
	},

	initMask(bg) {
		const house = cc.find("Canvas/house")
		const bgMask = cc.find("Canvas/bg_mask");
		bgMask.x = house.x;
		bgMask.y = house.y;

		const pos = exchangeNodePos(bgMask, bg);
		bg.parent = bgMask;
		bg.x = pos.x;
		bg.y = pos.y;
	},

	setButtonPlayStatus(s) {

		console.log('setButtonPlayStatus', s);
		if (s) {
			if (this.toggleButton.status == TOGGLE_BUTTON_STATUS.PLAY) {
				return;
			}
			this.toggleButtonSpriteNode.spriteFrame= this.pauseStatus;
			this.toggleButton.status = TOGGLE_BUTTON_STATUS.PLAY;
			this.videoplayer.play();
			this.playMusicAnimation();
		} else {
			if (this.toggleButton.status == TOGGLE_BUTTON_STATUS.PAUSE) {
				return;
			}
			this.toggleButtonSpriteNode.spriteFrame= this.playStatus ;
			this.toggleButton.status = TOGGLE_BUTTON_STATUS.PAUSE;
			this.videoplayer.pause();
			this.stopMusicAnimation();
		}
	},
	getButtonPlayStatus() {
		return !!this.toggleButton.status;
	},

    updateBarByPos(newX) {
        const maxX = this.ProgressBar.node.width;
        const minX = 0;
        
        const percent = newX / maxX;
		if (percent > 1) {
			percent = 1
		}
        this.ProgressBar.progress = percent;
        const dur = this.videoplayer.getDuration();
		console.log('updateBarByPos',percent * dur);
        this.videoplayer.currentTime = percent * dur 
    },
    updateBarByTime(ct){

			this.currentTimeLabel.string = this.formatTime(ct);
			const dur = this.videoplayer.getDuration();
			let percent = ct / dur;
		if (percent > 1) {
			percent = 1
		}
		this.ProgressBar.progress = percent;
        const maxX = this.ProgressBar.node.width;
        const minX = 0;
        let newX = percent * maxX;
        newX = Math.min(maxX, Math.max(newX, minX));
		// console.log('updateBarByTime', newX);
        this.barTag.x = newX;
    },
    formatTime(time) {
			if (time === undefined) {
				return '';
			}
			let hh = Math.floor(time / 60 / 60);
			if (hh > 0) {
				hh = `${hh.toString().padStart(2, '0')}:`;
			} else {
					hh = '';
			}
				
			const mm = Math.floor(time / 60).toString().padStart(2, '0');
			const ss = Math.round(time % 60).toString().padStart(2, '0');
	
			return `${hh}${mm}:${ss}`;
    },

	update (dt) {
		if (this.toggleButtonSpriteNode) {
            // console.log(this.userDragStart);
			const ct = this.videoplayer.currentTime;
            if (ct) {
                this.updateBarByTime(ct);
            }

            if (this.videoplayer.isPlaying()) {
				if (this.toggleButton.status === TOGGLE_BUTTON_STATUS.PLAY) {
					return;
				}
                this.setButtonPlayStatus(false);
                
            } else {
				if (this.toggleButton.status === TOGGLE_BUTTON_STATUS.PAUSE) {
					return;
				}
                this.setButtonPlayStatus(true);
            }
        }
	},



	hideControler() {
		this.controlNode.active = false;
		this.hideBackBtn();
		// cc.tween(this.controlNode)
		// .to(0.1, {opacity: 0})
		// .call(() => {
		// 	this.controlNode.active = false;
		// })
		// .start()
	},

	showControler() {
		this.controlNode.active = true;

		this.showBackBtn();
		// this.controlNode.active = true;
		// this.controlNode.opacity = 0;

		// cc.tween(this.controlNode)
		// .to(0.1, {opacity: 255})
		// .call(() => {

		// })
		// .start()
	},

	hideWolf() {
		this.wolfNode.active = false;
		this.replayBtn.active = false;

		// cc.tween(this.wolfNode)
		// 	.to(0.1, {opacity: 0})
		// 	.call(() => {
		// 		this.wolfNode.active = false;
		// 	})
		// 	.start()
	},

	showBackBtn() {
		const middleLayer = cc.find('middleLayer');
		if (middleLayer) {
			const middleLayerComponent = middleLayer.getComponent('middleLayer');
			middleLayerComponent.showButtons();
			return;
		}
	},

	hideBackBtn() {

		const middleLayer = cc.find('middleLayer');
		if (middleLayer) {
			const middleLayerComponent = middleLayer.getComponent('middleLayer');
			middleLayerComponent.hideButtons();
			return;
		}
	},

	showWolf() {
		this.wolfNode.active = true;
		this.replayBtn.active = true;

		// this.wolfNode.active = true;
		// this.wolfNode.opacity = 0;

		// cc.tween(this.wolfNode)
		// .to(0.1, {opacity: 255})
		// .call(() => {

		// })
		// .start()
	},

	initListener() {
		// const canvas = cc.find("Canvas");
		this.videoplayer.node.on('touchstart', () => {
			this.showControler();
			this.delayHideControl();
		})

		this.initReplayBtn();
		this.initArrowBtn();
	
	},

	initArrowBtn() {
		const arrow_left = cc.find("Canvas/Controls/arrow_left");
		const arrow_right = cc.find("Canvas/Controls/arrow_right");

		const jumpTime = 3;
		arrow_left.on('touchstart', () => {
			this.videoplayer.currentTime -= jumpTime;
		})

		arrow_right.on('touchstart', () => {
			this.videoplayer.currentTime += jumpTime;
		})
	},


	initReplayBtn() {
		this.replayBtn = cc.find("Canvas/btn_replay");
		this.replayBtn.on('touchstart', () => {
			
			this.hideWolf();
			this.delayHideControl();

			cc.audioEngine.stop(this.hintAudioID);
			console.log(cc.audioEngine.isMusicPlaying());
			if (cc.audioEngine.isMusicPlaying()) {
				return;
			} 
			cc.audioEngine.stop(this.finishAudioID);
			
			
			
			if (this.toggleButton.status == TOGGLE_BUTTON_STATUS.PAUSE) {
				this.setButtonPlayStatus(true);
			} else {
				this.setButtonPlayStatus(false);
			}
			this._armatureDisPlay.playAnimation('normal', 0);

		})
	},

	delayHideControl() {
		if (this.wolfNode.active) {
			return;
		}
		if (this.hideControlId) {
			clearTimeout(this.hideControlId);
		}

		this.hideControlId = setTimeout(() => {
			if (this.isDestroy) {
				return;
			}
			this.hideControler();
		}, 5000);
	},



















	// ------------------------------------------

});
