/**
 * 主场景 1.0
 */

cc.Class({
    extends: cc.Component,

    properties: {
        options: {
            default: null,
            type: cc.Node,
        },

        // 标题
        title: {
            default: null,
            type: cc.Label,
        },

        question: {
            default: null,
            type: cc.Label,
        },

        openMusic: {
            default: null,
            type: cc.AudioClip,
        },

        op_1: {
            default: null,
            type: cc.Prefab,
        },

        op_2: {
            default: null,
            type: cc.Prefab,
        },

        cloud: {
            default: null,
            type: cc.Node,
        },

        che: {
            default: null,
            type: cc.Node,
        },

        _isPlayTitle: false,
        _isPlayQuestion: false,
    },

    onEnable() {
        cc.game.on("STOPALL", this.stopAllAudio, this);
    },
    onDisable() {
        cc.game.off("STOPALL", this.stopAllAudio, this);
    },
    // 生命周期 onLoad
    onLoad() {
        this.initSceneData();
        this.initSize();
    },

    _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() {
        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();
        });
    },

    getData(cb) {
        cb(this.getDefaultData());
    },

    getDefaultData() {
        const dataJson =
            '{"title":"test","answer":3,"question":"hello world hello world hello world hello world","options":[{"pic_url":"http://staging-teach.cdn.ireadabc.com/3064a1f8bec54390c031b2c2d8b84e7f.jpeg","audio_url":"http://staging-teach.cdn.ireadabc.com/e8627e7f3ec1a04fdb3660eae81f7636.mp3","text":"选项2"},{"pic_url":"http://staging-teach.cdn.ireadabc.com/3064a1f8bec54390c031b2c2d8b84e7f.jpeg","audio_url":"http://staging-teach.cdn.ireadabc.com/e8627e7f3ec1a04fdb3660eae81f7636.mp3","text":"选项2, how are you doing aaaa"},{"pic_url":"http://staging-teach.cdn.ireadabc.com/3064a1f8bec54390c031b2c2d8b84e7f.jpeg","audio_url":"","text":"选项2, how are you doing aaaa"}],"audio_title":"http://staging-teach.cdn.ireadabc.com/f7fb9f71ab7d460ac2f78c85efba7610.mp3","audio_question":"http://staging-teach.cdn.ireadabc.com/7934cdcec68eabe639020bad5420d7f8.mp3"}';
        const data = JSON.parse(dataJson);
        return data;
    },

    preloadItem() {
        this.addPreloadImage();
        this.addPreloadAudio();
        this.addPreloadAnima();
        this.preload();
    },

    addPreloadImage() {
        for (var i = 0; i < this.data.options; i++) {
            this._imageResList.push({ url: this.data.options[i]["pic_url"] });
        }
    },

    addPreloadAudio() {
        for (var i = 0; i < this.data.total; i++) {
            this._audioResList.push({ url: this.data.options[i]["audio_url"] });
        }
        this._audioResList.push({ url: this.data.audio_title });
        this._audioResList.push({ url: this.data.audio_question });
    },

    addPreloadAnima() {},

    preload() {
        const preloadArr = this._imageResList.concat(this._audioResList).concat(this._animaResList);
        cc.assetManager.loadAny(preloadArr, null, null, (err, data) => {
            this.loadEnd();
            if (window && window["air"]) {
                window["air"].hideAirClassLoading();
            }

            cc.debug.setDisplayStats(false);
        });
    },

    loadEnd() {
        this.initData();
        this.initView();
    },

    _cantouch: null,
    initData() {
        // 所有全局变量 默认都是null
        this._cantouch = true;
    },

    initView() {
        this.initBg();

        // 初始化title
        this.title.string = this.data.title;
        this.question.string = this.data.question;

        let count = this.data.options.length;

        // let scale = 1;
        // let countScale = this.data.options.length - 4;
        // if (countScale > 0) {
        //     scale = 1 - countScale * 0.16;
        // }
        // this.options.scale = scale;

        for (let i = 0; i < this.data.options.length; i++) {
            let op = null;
            if (count >= 4) {
                op = cc.instantiate(this.op_1);
            } else {
                op = cc.instantiate(this.op_2);
            }

            if (i == this.data.answer) {
                op.getComponent("option")._isAnswer = true;
            }
            op.getComponent("option").setPic(this.data.options[i].pic_url);
            op.getComponent("option").setTitle(this.data.options[i].text);
            op.getComponent("option").setAudio(this.data.options[i].audio_url);
            op.getComponent("option")._count = this.data.options.length;
            this.options.addChild(op);
        }

        cc.audioEngine.playEffect(this.openMusic, false);
    },

    playTitle() {
        if (this.data.audio_title && !this._isPlayTitle) {
            cc.game.emit("STOPALL");
            this._isPlayTitle = true;
            this.playAudioByUrl(this.data.audio_title, () => {
                this._isPlayTitle = false;
            });
        }
    },

    playQuestion() {
        if (this.data.audio_question && !this._isPlayQuestion) {
            cc.game.emit("STOPALL");
            this._isPlayQuestion = true;
            this.playAudioByUrl(this.data.audio_question, () => {
                this._isPlayQuestion = false;
            });
        }
    },

    initBg() {
        const bgNode = cc.find("Canvas/bg");
        bgNode.scale = this._mapScaleMax;
        this.che.scale = this._mapScaleMax;
        this.cloud.scale = this._mapScaleMax;
    },

    // ------------------------------------------------
    getSprNode(resName) {
        const sf = cc.find("Canvas/res/img/" + resName).getComponent(cc.Sprite).spriteFrame;
        const node = new cc.Node();
        node.addComponent(cc.Sprite).spriteFrame = sf;
        return node;
    },

    getSpriteFrimeByUrl(url, cb) {
        cc.loader.load({ url }, (err, img) => {
            const spriteFrame = new cc.SpriteFrame(img);
            if (cb) {
                cb(spriteFrame);
            }
        });
    },

    getSprNodeByUrl(url, cb) {
        const node = new cc.Node();
        const spr = node.addComponent(cc.Sprite);
        this.getSpriteFrimeByUrl(url, (sf) => {
            spr.spriteFrame = sf;
            if (cb) {
                cb(node);
            }
        });
    },

    playAudioByUrl(audio_url, cb = null) {
        if (audio_url) {
            cc.assetManager.loadRemote(audio_url, (err, audioClip) => {
                const audioId = cc.audioEngine.play(audioClip, false);
                if (cb) {
                    cc.audioEngine.setFinishCallback(audioId, () => {
                        cb();
                    });
                }
            });
        }
    },

    stopAllAudio() {
        cc.audioEngine.stopAllEffects();
        this._isPlayQuestion = false;
        this._isPlayTitle = false;
    },

    // ------------------------------------------
});
