import { buttonOnceClick } from "../Script/util";

cc.Class({
    extends: cc.Component,

    properties: {
        videoPlayer: {
            default: null,
            type: cc.VideoPlayer
        },
        ProgressBar: {
            default: null,
            type: cc.ProgressBar
        },
        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;
    },

    // use this for initialization
    onLoad: function () {

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

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

        cc.macro.ENABLE_TRANSPARENT_CANVAS = true; 
        
        this.videoPlayer.node.on('ready-to-play', () => {
            console.log('ready-to-play');
        });
        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');
        });
        this.videoPlayer.node.on('playing', () => {
            console.log('playing');
            this.durationLabel.string = this.formatTime(this.videoPlayer.getDuration());
            this.playButton.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', () => {
            console.log('completed');
            this.videoPlayer.currentTime = 0;
            // this.playButton.node.active = true;
            // this.pauseButton.node.active = false;

            // 上报答题结果
            if (window && window.courseware) {
                window.courseware.sendAnswer({isOver: true});
            }

        });
        cc.view.setResizeCallback((params) => {
            console.log('Resize', params);
            this.initdDrag()
        });
        // this.initListener();
        this.initdDrag();
        // console.log(11111)
        this.videoPlayer.getImpl = function() {
            return this._impl;
        }
        cc.debug.setDisplayStats(false);
    },
    // initListener() {
    //     buttonOnClick(cc.find(`Canvas/btnbg/btn_again`), this.replay);
	// },
    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) => {
            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) => {
            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;
            // console.log(newX, percent);
            const dur = this.videoPlayer.getDuration();
            // this.videoPlayer.currentTime = percent * dur 
            // this.updateBarByPos(this.barTag.x);
            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.node.off(cc.Node.EventType.TOUCH_START);
        this.ProgressBar.node.on(cc.Node.EventType.TOUCH_START, (e) => {
            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.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.node;
        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;
            }
        });
        // this.tw = cc.tween(this.ProgressBar.node).delay(3).to(.6, {
        //     opacity: 0
        // }).call(() => { 
        //     console.log('This is a callback'); 
        //     // this.tw.stop();
        //     // this.tw.removeSelf()
        //     // this.tw = null;
        // })
    },
    start() {

        // let video0 = document.getElementsByClassName('cocosVideo')[0];
        // console.log(video0);
        // video0.style.zIndex = 5;

        // let gCanvas = document.getElementsByClassName('gameCanvas')[0];
        // console.log(gCanvas);
        // gCanvas.style.position = 'relative';
        // gCanvas.style.zIndex = 10;
        // cc.Camera.main.backgroundColor = cc.color(0, 0, 0, 0);
        // this.videoPlayer.keepAspectRatio = false;


        if (window && window.courseware) {
            
        }
        
        let getData = this.getData.bind(this);
        let getAnswer;
		if (window && window.courseware) {
			// console.log('has window');
            getData = window.courseware.getData;
            getAnswer = window.courseware.getAnswer;
		}
		getData((data) => {
			console.log('data:', JSON.stringify(data));
            this.data = data || this.getDefaultData();
            this.videoPlayer.remoteURL = this.data.video_url;
            // this.preload()
            if (getAnswer) {
                getAnswer((ans) => {
                    if (ans) {
                        this.isOver = JSON.parse(ans).isOver;
                    }
                    if (window && window["air"]) {
                        window["air"].hideAirClassLoading();
                    }
                });
            } else {
                if (window && window["air"]) {
                    window["air"].hideAirClassLoading();
                }
            }
        });
        if(window.CustomEvent){
            window.dispatchEvent(new CustomEvent('resize'), true)
        }
    },
    triggerInteractive() {
        this.tw.stop();
        this.ProgressBar.node.opacity = 255;
        this.tw.start();
    },
    checkProgressBarStatus() {
        if (this.videoPlayer.isPlaying()) {
            if (this.tw.displayed) {
                this.tw.start();
            }
        } else {
            this.tw.stop();
            this.ProgressBar.node.opacity = 255 
        } 
    },
    updateBarByPos(newX) {
        const maxX = this.ProgressBar.node.width;
        const minX = 0;
        
        const percent = newX / maxX;
        // console.log(newX, percent);
        const dur = this.videoPlayer.getDuration();
        this.videoPlayer.currentTime = percent * dur 
    },
    updateBarByTime(ct){

        this.currentTimeLabel.string = this.formatTime(ct);
        const dur = this.videoPlayer.getDuration();
        const percent = ct / dur;
        const maxX = this.ProgressBar.node.width-20;
        const minX = 0;
        let newX = percent * maxX;
        newX = Math.min(maxX, Math.max(newX, minX));
        this.barTag.x = newX;
        this.bar.width = 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}`;
    },
    
    getData(func) {
        const middleLayer = cc.find('middleLayer');
        if (middleLayer) {
            const middleLayerComponent = middleLayer.getComponent('middleLayer');
            middleLayerComponent.getData(func);
            return;
        }

		func(this.getDefaultData());
	},
    getDefaultData() {
        // return {video_url: "http://staging-teach.cdn.ireadabc.com/5826aa205a4d33bf65552778b2aaf6f8.mp4"}
		// return {video_url: "http://staging-teach.cdn.ireadabc.com/d2b6b86798ef09034bf29417a0e747d2.mp4"}
        return {video_url: "https://iplayabc-teach-yun-test.oss-cn-beijing.aliyuncs.com/movie2.mp4"}
    },
    
    play(){
        this.videoPlayer.node.active = true;
        cc.find(`Canvas/video_cover`).active = false;
        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.videoPlayer.currentTime = 0;
        this.videoPlayer.play();
        this.triggerInteractive();
    },

    preload() {
        cc.assetManager.loadAny(this.data, {cacheAsset: true}, null, (err, data) => {
			console.log(' preload data, ', data);
			
			// typeof
			if (window && window["air"]) {
				window["air"].hideAirClassLoading();
			}
		});
    },

    isOver: null,
    onLeave(cb) {
        if (!this.isOver) {
            this.videoPlayer.pause();
            this.triggerInteractive();
            this.videoPlayer.node.active = false;

            const tips = cc.find("tips", this.node);
            cc.find(`continue`, tips).active = true;
            cc.find(`leave`, tips).active = true;
            cc.find(`btn_bl`, tips).active = false;
            cc.find(`btn_zcdt`, tips).active = false;
            tips.active = true;

            cc.find(`desc`, tips).getComponent(cc.Label).string = "确定放弃本次答题么？";

            buttonOnceClick(cc.find(`continue`, tips), () => {
                tips.active = false;
                this.videoPlayer.node.active = true;
                this.videoPlayer.play();
                this.triggerInteractive();
            });

            buttonOnceClick(cc.find(`leave`, tips), () => {
                tips.active = false;
                cb();
            });
        } else {
            cb();
        }
    },
    goBack() {
        this.onLeave(() => {
            const middleLayer = cc.find('middleLayer');
            if (middleLayer) {
                const mc = middleLayer.getComponent('middleLayer');
                // 切换上一页
                mc.goPrePage();
            } else {
                console.log("==切换上一页==");
            } 
        });
    },
    goNext() {
        this.onLeave(() => {
            const middleLayer = cc.find('middleLayer');
            if (middleLayer) {
                const mc = middleLayer.getComponent('middleLayer');
                // // 切换下一页
                mc.goNextPage();
            } else {
                console.log("==切换下一页==");
            } 
        });
    },
    goHome() {
        this.onLeave(() => {
            const middleLayer = cc.find('middleLayer');
            if (middleLayer) {
                const mc = middleLayer.getComponent('middleLayer');
                // 回首页
                mc.goTarIndexPage(0);
            } else {
                console.log("==回首页==");
            } 
        });
    },


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