import { buttonOnceClick, buttonOnClick, getSpriteFrimeByUrl, asyncGetSpriteFrimeByUrl, playAudioByUrl,
    asyncLoadDragonBoneAnime, asyncDelay,  setNetImg} from "../Script/util";
import { defaultData } from "../Script/defaultData";

cc.Class({
    extends: cc.Component,

    properties: {
        videoPlayer: {
            default: null,
            type: cc.VideoPlayer
        },
        ProgressBar: {
            default: null,
            type: cc.Node
        },
        playButton: {
            default: null,
            type: cc.Button
        },
        pauseButton: {
            default: null,
            type: cc.Button
        },
        restartButton: {
            default: null,
            type: cc.Button
        },
        backButton: {
            default: null,
            type: cc.Button
        },
        forwardButton: {
            default: null,
            type: cc.Button
        },
        durationLabel: {
            default: null,
            type: cc.Label
        },
        currentTimeLabel: {
            default: null,
            type: cc.Label
        },
        barTag: {
            default: null,
            type: cc.Node
        },
        bar: {
            default: null,
            type: cc.Node
        }
        // defaults, set visually when attaching this script to the Canvas
        // text: 'Hello, World!'
    },

    _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;

        cc.director['_scene'].width = frameSize.width;
        cc.director['_scene'].height = frameSize.height;
    },

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

		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)
		}
	},

    // use this for initialization
    _isPlayComplated: null,
    onLoad () {
        cc.debug.setDisplayStats(false);

        this.initSize();
        cc.find('Canvas/bg').scale = this._mapScaleMax;
        cc.find('Canvas/video_node/bg').scale = this._mapScaleMax;

        this._isReadyToPlay = false;
        window['vv'] = this;

        this.videoPlayer.getImpl = function() {
            return this._impl;
        }

        cc.macro.ENABLE_TRANSPARENT_CANVAS = true; 
        
        this.videoPlayer.node.on('ready-to-play', () => {
            console.log('ready-to-play');
            if (window && window["air"]) {
                window["air"].hideAirClassLoading();
            }
            this.playButton.active = true;
        });
        this.videoPlayer.node.on('meta-loaded', () => {
            console.log('meta-loaded');
            this._isReadyToPlay = true;
            this.durationLabel.string = this.formatTime(this.videoPlayer.getDuration());
            // this.videoPlayer.resume();
            this.videoPlayer.stop();
        });
        this.videoPlayer.node.on('clicked', () => {
            console.log('clicked');
            if (this.isVideoFull) {
                this.videoPlayer.stayOnBottom = true;
                cc.find(`Canvas/Controls`).active = true;
                if (this.time1) {
                    clearTimeout(this.time1);
                }
                this.time1 = setTimeout(() => {
                    this.videoPlayer.stayOnBottom = false;
                    cc.find(`Canvas/Controls`).active = false;
                }, 6000);
            }
        });
        this.videoPlayer.node.on('touchstart', () => {
            console.log('touchstarted');
            if (this.isVideoFull) {
                this.videoPlayer.stayOnBottom = true;
                cc.find(`Canvas/Controls`).active = true;
                if (this.time1) {
                    clearTimeout(this.time1);
                }
                this.time1 = setTimeout(() => {
                    this.videoPlayer.stayOnBottom = false;
                    cc.find(`Canvas/Controls`).active = false;
                }, 6000);
            }
        });
        this.videoPlayer.node.on('playing', () => {
            console.log('playing');
            this.durationLabel.string = this.formatTime(this.videoPlayer.getDuration());
            this.playButton.node.active = false;
            this.restartButton.node.active = false;
            this.pauseButton.node.active = true;
        });
        this.videoPlayer.node.on('paused', () => {
            console.log('paused');
            // this.playButton.node.active = true;
            // this.pauseButton.node.active = false;
        });
        this.videoPlayer.node.on('stopped', () => {
            console.log('stopped');
            // this.playButton.node.active = true;
            // this.pauseButton.node.active = false;
        });
        this.videoPlayer.node.on('completed', async () => {
            console.log('completed');
            // this.videoPlayer.currentTime = 0;
            this._isPlayComplated = true;
            this.playButton.node.active = false;
            this.pauseButton.node.active = false;
            this.restartButton.node.active = true;
        });
        cc.view.setResizeCallback((params) => {
            console.log('Resize', params);
            this.initdDrag()
        });
        
        this.initdDrag();
    },


    initListener() {
    },
    initdDrag() {
        const maxX = this.ProgressBar.width;
        const minX = 0;
        
        
        this.barTag.off(cc.Node.EventType.TOUCH_START);
        this.barTag.on(cc.Node.EventType.TOUCH_START, (e) => {
            console.log("TOUCH_START");
            this.userDragStart = true;
            this.triggerInteractive()
        });
        this.barTag.off(cc.Node.EventType.TOUCH_MOVE);
        this.barTag.on(cc.Node.EventType.TOUCH_MOVE,(e) => {
            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 );
            this.triggerInteractive()
        });
        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.triggerInteractive()
        });
        this.barTag.on(cc.Node.EventType.MOUSE_UP, (e) => {
            console.log("MOUSE_UP");
            this.userDragStart = false;
            this.updateBarByPos(this.barTag.x);
            this.triggerInteractive()
        });
        
        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.triggerInteractive() 
        });
        // this.ProgressBar.off(cc.Node.EventType.TOUCH_START);
        // this.ProgressBar.on(cc.Node.EventType.TOUCH_START, (e) => {
        //     console.log("==ProgressBar TOUCH_START==");
        //     const pos = e.getLocation();
        //     const pPos = this.ProgressBar.convertToNodeSpaceAR(pos);
        //     const newX = Math.min(maxX, Math.max(pPos.x, minX));
        //     this.updateBarByPos(newX);
        //     // console.log("ProgressBar TOUCH_START", newX); 
        // });
        // this.videoPlayer.node.off(cc.Node.EventType.TOUCH_START);
        // this.videoPlayer.node.on(cc.Node.EventType.TOUCH_START, (e) => {
        //     console.log("screen TOUCH_START");
        //     this.triggerInteractive()
        // });
        const pgBar = this.ProgressBar;
        this.tw = new (function(){
            this._tw = cc.tween(pgBar).delay(3).to(.6, {
                opacity: 255
            }).call(() => { 
                console.log('This is a callback'); 
                this.running = false;
                // this.displayed = false;
                // this.tw.stop();
                // this.tw.removeSelf()
                // this.tw = null;
            }), 
            this.running = false;
            this.displayed = true;
            this.start = () => {
                this.running = true;
                this.displayed = false;
                pgBar.opacity = 255;
                this._tw.start();
            }
            this.stop = () => {
                this.running = false;
                this.displayed = true;
                this._tw.stop();
                pgBar.opacity = 255;
            }
        });
    },
    async initView() {

        cc.find(`Canvas/bg_title/title`).getComponent(cc.Label).string = this.data.title;

        // 提示音频和动画
        if (this.data.tipSwitch == 1) {
            const animBg = cc.find("Canvas/animBg");
            const animNode = cc.find("Canvas/animNode");
            animBg.active = true;
            animNode.active = true;
            await asyncLoadDragonBoneAnime(animNode, {
                skeJsonData: this.data.imgAni.ske,
                texJsonData: this.data.imgAni.tex,
                texPngData: this.data.imgAni.png
            });

            const animaNode = animNode['animaNode'];
            animaNode.x = 500;
            const db = animaNode.getComponent(dragonBones.ArmatureDisplay);
            const anis = db.getAnimationNames(db.armatureName);

            db.playAnimation(anis[0], 0);
            cc.tween(animaNode).by(1, { x: -500 }).call(() => {
                playAudioByUrl(this.data.audio, ()=>{
                    cc.tween(animaNode).delay(1).by(1, { x: 500 }).call(()=>{
                        animBg.active = false;
                        animNode.active = false;
                    }).start();
                });
            }).start();
        }

        this.initListener();
    },

    start() {
        let getData = this.getData.bind(this);
		if (window && window.courseware) {
			// console.log('has window');
            getData = window.courseware.getData;
        }
		getData(async (data) => {
			console.log('data:', JSON.stringify(data));
            this.data = data || this.getDefaultData();
            // this.getVideoUrl(videoUrl => {
            //     this.data.video_url = videoUrl;
                this.videoPlayer.remoteURL = this.data.video_url;
            // });
            await this.initView();
        });

        if(window.CustomEvent){
            window.dispatchEvent(new CustomEvent('resize'), true)
        }
    },
    triggerInteractive() {
        this.tw.stop();
        this.ProgressBar.opacity = 255;
        this.tw.start();
    },
    checkProgressBarStatus() {
        if (this.videoPlayer.isPlaying()) {
            if (this.tw.displayed) {
                this.tw.start();
            }
        } else {
            this.tw.stop();
            this.ProgressBar.opacity = 255 
        } 
    },
    updateBarByPos(newX) {
        const maxX = this.ProgressBar.width;
        const minX = 0;
        
        const percent = newX / maxX;
        // console.log(newX, percent);
        const dur = this.videoPlayer.getDuration();
        this.videoPlayer.currentTime = percent * dur 
    },
    updateBarByTime(ct){
        if (this._isPlayComplated) {
            return;
        }
        this.currentTimeLabel.string = this.formatTime(ct);
        const dur = this.videoPlayer.getDuration();
        const percent = ct / dur;
        const maxX = this.ProgressBar.width;
        const minX = 0;
        let newX = percent * maxX;
        newX = Math.min(maxX, Math.max(newX, minX));
        this.barTag.x = newX>=(maxX-90)?(maxX-90):(newX-15);
        this.bar.width = newX;
        this.bar.x = 0 - (maxX / 2);
    },
    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}`;
    },
    
    getData(func) {
        const middleLayer = cc.find('middleLayer');
        if (middleLayer) {
            const middleLayerComponent = middleLayer.getComponent('middleLayer');
            middleLayerComponent.getData(func);
            return;
        }

		func(this.getDefaultData());
	},
    getDefaultData() {
        return defaultData;
    },
    
    play(){
        const {width, height} = cc.find(`Canvas/bg`);
        cc.find(`Canvas/Controls/ProgressBar/text_tips_left`).active = false;
        cc.find(`Canvas/bg`).active = false;
        cc.find(`Canvas/bgwhite`).active = false;
        cc.find(`Canvas/bg_empty`).active = false;

        cc.find('Canvas/video_node/bg').width = width;
        cc.find('Canvas/video_node/bg').height = height;
        this.videoPlayer.node.x = 0;
        this.videoPlayer.node.y = 0;
        // this.videoPlayer.node.active = true;
        this.videoPlayer.play();
        this.triggerInteractive()
    },
    pause(){
        this.videoPlayer.pause();
        this.triggerInteractive()
    },
    forward(){
        this.videoPlayer.currentTime =this.videoPlayer.getImpl().currentTime() + 5;
        this.triggerInteractive()
    },
    backward(){
        this.videoPlayer.currentTime = this.videoPlayer.getImpl().currentTime() - 5;
        this.triggerInteractive()

    },
    replay(){
        this._isPlayComplated = false;
        this.videoPlayer.currentTime = 0;
        this.videoPlayer.play();
        this.triggerInteractive();
    },

    playLocalAudio(audioName) {
        cc.audioEngine.stopAll();
        const audio = cc.find(`Canvas/res/audio/${audioName}`).getComponent(cc.AudioSource);
        cc.audioEngine.playEffect(audio.clip, false);
    },

    time1: null,
    isVideoFull: false,
    fullScreen() {
        if (this.isVideoFull) {
            return;
        }
        console.log("====进入全屏===");
        this.isVideoFull = true;
        this.videoPlayer.stayOnBottom = true;
        cc.find(`Canvas/Controls/fullscreen`).active = !this.isVideoFull;
        cc.find(`Canvas/Controls/exitfull`).active = this.isVideoFull;

        cc.find(`Canvas/video_node`).width = this.node.width;
        cc.find(`Canvas/video_node`).height = this.node.height;
        cc.find(`Canvas/bg_empty`).width = this.node.width;
        cc.find(`Canvas/bg_empty`).height = this.node.height;

        this.videoPlayer.node.height = this.node.height;
        this.videoPlayer.node.width = this.node.width;
        setTimeout(() => {
            // IOS下视频的全屏适配比例有问题，所以做一个计算
            this.videoPlayer.node.width = Math.min(this.node.width, this.node.height*16/9);
        }, 100);

        this.time1 = setTimeout(() => {
            this.videoPlayer.stayOnBottom = false;
            cc.find(`Canvas/Controls`).active = false;
        }, 3000);
    },

    exitFullScreen() {
        if (!this.isVideoFull) {
            return;
        }
        console.log("====退出全屏===");
        this.isVideoFull = false;
        cc.find(`Canvas/Controls/fullscreen`).active = !this.isVideoFull;
        cc.find(`Canvas/Controls/exitfull`).active = this.isVideoFull;

        cc.find(`Canvas/video_node`).width = 1377;
        cc.find(`Canvas/video_node`).height = 775;
        cc.find(`Canvas/bg_empty`).width = 1377;
        cc.find(`Canvas/bg_empty`).height = 775;

        this.videoPlayer.node.width = 1377;
        this.videoPlayer.node.height = 775;

        if(this.time1) { 
            clearTimeout(this.time1); 
        }
    },

    onDestroy() {
		if(this.time1) { clearTimeout(this.time1); }
	},


    // called every frame
    update: function (dt) {
        // if (this._isReadyToPlay) {
            // const ct = this.videoPlayer.currentTime
             
        // }
        // if (this.wardState && this.videoPlayer.isPlaying()) {
        //     this.wardState = false;
        //     this.pause();
        // }
        if (this.videoPlayer) {
            // console.log(this.userDragStart);
            if (!this.userDragStart) {
                const ct = this.videoPlayer.getImpl().currentTime();
                this.updateBarByTime(ct);
            }
            this.checkProgressBarStatus();
            if (this.videoPlayer.isPlaying()) {
                if (this.playButton.node.active) {
                    this.playButton.node.active = false;
                    this.restartButton.node.active = false;
                }
                if (!this.pauseButton.node.active) {
                    this.pauseButton.node.active = true;
                } 
                
            } else {
                if (!this.playButton.node.active) {
                    this.playButton.node.active = true;
                }
                if (this.pauseButton.node.active) {
                    this.pauseButton.node.active = false;
                } 
                if (this.restartButton.node.active) {
                    this.playButton.node.active = false;
                }
            }
        }
        
    },
});
