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

cc.Class({
    extends: cc.Component,

    properties: {
        startNode: {
            default: null,
            type: cc.Node
        },
        page_view: {
            default: null,
            type: cc.Node
        },
        tip_label: {
            default: null,
            type: cc.Node
        },
        tip_left: {
            default: null,
            type: cc.Node
        },
        tip_right: {
            default: null,
            type: cc.Node
        },
        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 () {

        cc.debug.setDisplayStats(false);

        this.initSize();
        const bgNode = cc.find('Canvas/bg');
        bgNode.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');
            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');
        });
        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', async () => {
            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, video_url: this.data.video_url, score: this.data.questionScore});
                await this.showFinal();

                const middleLayer = cc.find('middleLayer');
                if (middleLayer) {
                    const mc = middleLayer.getComponent('middleLayer');
                    // // 切换下一页
                    mc.goNextPage();
                } else {
                    console.log("==切换下一页==");
                } 
            }

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

    async initBg() {
        const bgNode = cc.find('Canvas/bg');
        const sfpr = await asyncGetSpriteFrimeByUrl(this.data.image);
        bgNode.getComponent(cc.Sprite).spriteFrame = sfpr;
        bgNode.scale = this._mapScaleMax;
    },

    async initTips() {
        if (this.data.tipSwitch == 0) {
            cc.find("btn_start", this.node).active = false;
            return;
        }
        this.startNode.active = true;

        const data = await setNetImg(cc.find("s_group/startbg", this.startNode), this.data.tipBg, { w: 0, h: 0 }, false);
       
        this.page_view.width = data.w - 340;
        this.page_view.height = data.h - 150;
        this.page_view.x = -(data.w / 2) - 85;
        
        this.data.tipPage.forEach((dt, idx) => {
            let desc = cc.instantiate(this.tip_label);
            desc.getComponent(cc.Label).string = dt.title;
            desc.width = this.page_view.width;
            desc.height = this.page_view.height - 40;
            this.page_view.getComponent(cc.PageView).addPage(desc);
            desc.active = true;
            desc["data"] = dt;
        })
        this.updataTipArrow();


        const btnStart = cc.find("btn_start", this.node);
        await asyncLoadDragonBoneAnime(btnStart, {
            skeJsonData: this.data.imgAni.ske,
            texJsonData: this.data.imgAni.tex,
            texPngData: this.data.imgAni.png
        });

        const animaNode = btnStart['animaNode'];
        animaNode.y = -80;
        const db = animaNode.getComponent(dragonBones.ArmatureDisplay);
        let anis = db.getAnimationNames("armatureName");
        db.playAnimation(anis[0], 0);
    },

    updataTipArrow() {
        let index = this.page_view.getComponent(cc.PageView).getCurrentPageIndex();
        let pages = this.page_view.getComponent(cc.PageView).getPages();
        // this.tip_left.active = pages.length > 0 && index > 0;
        this.tip_right.active = pages.length > 0 && index < pages.length - 1;
        cc.find("s_group/startbg/btn_close", this.startNode).active = index === pages.length - 1;
        let page = pages[index];
        if (page) {
            cc.audioEngine.stopAll();
            playAudioByUrl(page["data"].audio);
        }
    },
    initListener() {
        const btnStart = cc.find("btn_start", this.node);
        const start_ske = btnStart['animaNode'];
        btnStart.on('click', () => {
            if (btnStart['cantClick']) {
              return;
            }
            btnStart['cantClick'] = true;

            this.startNode.active = true;
            cc.tween(start_ske).to(0.2, { scale: 1 }).start();
            this.updataTipArrow();
        });

        buttonOnClick(cc.find("s_group/startbg/btn_close", this.startNode), () => {
            cc.audioEngine.stopAll();
            const btnStart = cc.find("btn_start", this.node);
            let start_ske = btnStart['animaNode'];
            cc.tween(start_ske).to(0.2, { scale: 0.3 }).call(() => {
                btnStart['cantClick'] = false;
            }).start();
            this.page_view.getComponent(cc.PageView).setCurrentPageIndex(0);
            this.startNode.active = false;
        });

        const tipRight = cc.find("s_group/startbg/tip_right", this.startNode);
        buttonOnClick(tipRight, () => {
            tipRight.active = false;
            let index = this.page_view.getComponent(cc.PageView).getCurrentPageIndex();
            this.page_view.getComponent(cc.PageView).scrollToPage(index + 1, 0.3);
            this.updataTipArrow();
        });
    },
    async showFinal() {
        let final = cc.find("final", this.node);
        let f_group = cc.find("f_group", final);
        f_group.scale = 1;
        f_group.setPosition(0, -265);
        f_group.active = true;

        await asyncLoadDragonBoneAnime(f_group, {
            skeJsonData: this.data.endImgAni.ske,
            texJsonData: this.data.endImgAni.tex,
            texPngData: this.data.endImgAni.png
        });
        const animaNode = f_group['animaNode'];
        const db = animaNode.getComponent(dragonBones.ArmatureDisplay);
        let anis = db.getAnimationNames("armatureName");
        db.playAnimation(anis[0], 0);

        this.playLocalAudio("success");

        final.active = true;
        let desc = cc.find("desc", f_group);
        let final_title = cc.find("final_title", f_group);

        let head = cc.find("top/player/mask", this.node);
        let worldPoint = head.convertToWorldSpaceAR(cc.v2(0, 0));
        let pos = final.convertToNodeSpaceAR(worldPoint);
        desc.getComponent(cc.Label).string = this.data.endImgTitle || "";
        await asyncDelay(2);
        desc.active = true;
        final_title.active = true;

        await asyncDelay(1);
        let sc = cc.scaleTo(0.2, 0.2);
        var actionTo = cc.jumpTo(1, cc.v2(pos.x, pos.y), 300, 1);
        let call = cc.callFunc(() => {
            final.active = false;
        })
        f_group.runAction(cc.sequence(sc, actionTo, call));
    },
    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;
        // })
    },
    async initView() {
        await this.initBg();
        await this.initTips();
        this.initListener();
    },

    start() {
        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(async (data) => {
			console.log('data:', JSON.stringify(data));
            this.data = data || this.getDefaultData();
            this.videoPlayer.remoteURL = this.data.video_url;
            // this.preload()
            if (getAnswer) {
                getAnswer(null, async (ans) => {
                    if (ans) {
                        this.isOver = JSON.parse(ans).isOver;
                    }
                    await this.initView();
                    if (window && window["air"]) {
                        window["air"].hideAirClassLoading();
                    }
                });
            } else {
                await this.initView();
                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 defaultData;
    },
    
    play(){
        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.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;
                } 
            }
        }
        
    },
});
