import { playAudioByUrl } from "./util";

cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},
    onLoad() {
        this.initSceneData();
        this.initSize();
    },

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

    _designSize: null,
    _frameSize: null,
    _mapScaleMin: null,
    _mapScaleMax: null,
    _cocosScale: null,
    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.log('cc.Canvas: ', cc.Canvas);
    },

    start() {
        let getData = this.getData.bind(this);
        if (window && window.courseware) {
            // console.log('has window');
            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()
        })
    },


    _imageResList: null,
    _audioResList: null,
    _animaResList: null,
    _textResList: null,
    _titleUrl: null,
    _titleStr: null,
    preloadItem() {
        this.addPreloadImage();
        this.addPreloadAudio();
        // this.addPreloadAnima();
        this.preload();
    },

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

    getDefaultData() {

        const dataJson = ' {"contentObj":{"picArr":[{"left":{"title":"","pic_url":"","audio_url":""},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"","pic_url":"","audio_url":""},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"","pic_url":"","audio_url":""},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"","pic_url":"","audio_url":""},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"","pic_url":"","audio_url":""},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"","pic_url":"","audio_url":""},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"","pic_url":"","audio_url":""},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"","pic_url":"","audio_url":""},"right":{"title":"","pic_url":"","audio_url":""}}],"audio_url":"","title":""},"audio_url":""}';
        // const dataJson = '{"contentObj":{"picArr":[{"left":{"title":"11111","pic_url":"http://staging-teach.cdn.ireadabc.com/156b8293a073ef828f6e01fc620c3562.png","audio_url":"http://staging-teach.cdn.ireadabc.com/83513f8d6083ebe072e3f9e47a21558a.mp3"},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"222222","pic_url":"http://staging-teach.cdn.ireadabc.com/e029bf3210a23a169f1cc14a851cc9e4.jpg","audio_url":"http://staging-teach.cdn.ireadabc.com/5285e1e88a26a08783757e9c43a8653f.mp3"},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"3333","pic_url":"http://staging-teach.cdn.ireadabc.com/89f8093ced2b9ddeccec352e9b7f2775.jpg","audio_url":"http://staging-teach.cdn.ireadabc.com/440cf9d57752b30691d90ed565e8c924.mp3"},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"444444","pic_url":"http://staging-teach.cdn.ireadabc.com/5a2c61d8faf5935e70fd9b15953b12f6.png","audio_url":"http://staging-teach.cdn.ireadabc.com/a5fa20e0c6024421b0d9a7007c303503.mp3"},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"5555","pic_url":"http://staging-teach.cdn.ireadabc.com/ce2e48ecefbf8b7011385a95133fe987.jpg","audio_url":"http://staging-teach.cdn.ireadabc.com/a41f0f2bf190396e2641ec8dada8edfe.mp3"},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"66","pic_url":"http://staging-teach.cdn.ireadabc.com/13845267419e50bd7f0c0f74ba424be2.jpg","audio_url":"http://staging-teach.cdn.ireadabc.com/32258b839eca32b6ccf94f3dd6c86e0c.mp3"},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"77777","pic_url":"http://staging-teach.cdn.ireadabc.com/7ec7599c86f974c9f88409893010811d.png","audio_url":"http://staging-teach.cdn.ireadabc.com/49ac987d13695eb411da4bef0adb318f.mp3"},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"8888888","pic_url":"http://staging-teach.cdn.ireadabc.com/24ee95ea61a2a653ce25c65557b18356.jpg","audio_url":"http://staging-teach.cdn.ireadabc.com/85cff126986f5cc11b05e95181da5869.mp3"},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"99999999999999999","pic_url":"http://staging-teach.cdn.ireadabc.com/3aa5a936d8e0e6f1dd2f6eb6d3d26645.jpg","audio_url":"http://staging-teach.cdn.ireadabc.com/a4d27ad173a95823d4b8ec82363c5aa0.mp3"},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"10101010101010","pic_url":"http://staging-teach.cdn.ireadabc.com/5ec43bf9507ff08d556487dee9234653.png","audio_url":"http://staging-teach.cdn.ireadabc.com/66878465ec50d162bd60fcdaa641933b.mp3"},"right":{"title":"","pic_url":"","audio_url":""}}]}}'
        const data1 = JSON.parse(dataJson);
        return data1;
    },

    preload() {

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

            // typeof
            this.loadEnd();
            if (window && window["air"]) {
                window["air"].hideAirClassLoading();
            }
            this.myStart();
        });
    },

    addPreloadImage() {
        // if (this.data.contentObj.picArr) {
        //     this.data.contentObj.picArr.forEach(group => {
        //         if (group.left.pic_url && group.left.title) {
        //             this._imageResList.push({ url: group.left.pic_url });
        //             this._textResList.push({ text: group.left.title });
        //         }
        //         // if (group.right) {
        //         //     this._imageResList.push({ url: group.right.pic_url });
        //         // }
        //     })
        // }
        this.data.contentObj.picArr.forEach(group => {
            this._imageResList.push({ url: group.left.pic_url });
            this._textResList.push({ text: group.left.title });
        })
    },

    addPreloadAudio() {
        // if (this.data.contentObj.picArr) {
        //     this.data.contentObj.picArr.forEach((item) => {
        //         if (item.left.audio_url) {
        //             this._audioResList.push({ url: item.left.audio_url });
        //         }
        //     });
        // }
        this.data.contentObj.picArr.forEach((item) => {
            this._audioResList.push({ url: item.left.audio_url });
        });

    },

    addPreloadAnima() {
        if (!this.data.contentObj.picArr) {
            return;
        }
        this.data.contentObj.picArr.forEach((group) => {

            if (group.hotZoneItemArr) {
                group.hotZoneItemArr.forEach((item) => {
                    if (item.gIdx == '0' & item.skeJsonData) {
                        this._animaResList.push({ url: item.skeJsonData.url });
                        this._animaResList.push({ url: item.texJsonData.url });
                        this._animaResList.push({ url: item.texPngData.url });
                    }
                })
            }

            if (group.skeJsonData) {
                this._animaResList.push({ url: group.skeJsonData.url });
                this._animaResList.push({ url: group.texJsonData.url });
                this._animaResList.push({ url: group.texPngData.url });
            }
        })
    },

    loadEnd() {
        // this.initData();
        // this.initAudio();
        // this.initView();
        // this.initListener();
    },
    myStart() {
        const layoutNode = cc.find('Canvas/AutoContainer/layout');
        var layout = layoutNode.getComponent(cc.Layout);

        const signNode = cc.find('Canvas/background/sign');
        const bg1Node = signNode.getChildByName('bg1');
        bg1Node.addComponent(cc.Button);
        var labelTitle = signNode.getChildByName('label').getComponent(cc.Label);
        const data = this.data;
        labelTitle.string = data.contentObj.title;

        var audioUrl = data.contentObj.audio_url;
        const playAudio = bg1Node.getComponent(cc.AudioSource);
        cc.assetManager.loadRemote(audioUrl, (err, audioClip) => {
            playAudio.clip = audioClip;
        });
        bg1Node.on('click', () => {
            console.log('fdsafdsa');
            playAudio.play();
        });

        console.log('++++++++++++++++++', this._imageResList.length);
        for (let index = 0; index < this._imageResList.length; index++) {
            const cardNode = cc.instantiate(cc.find('Canvas/Card'));
            const imgNode = cardNode.getChildByName('img');
            const bgbackNode = cardNode.getChildByName('bgback');
            const labelNode = bgbackNode.getChildByName('label');
            var label = labelNode.getComponent(cc.Label);
            label.string = this._textResList[index].text;
            const img = imgNode.getComponent(cc.Sprite);
            var imgUrl = this._imageResList[index].url;
            cc.loader.load(imgUrl, function (err, texture) {
                // Use texture to create sprite frame
                const spriteFrame = new cc.SpriteFrame(texture);
                img.spriteFrame = spriteFrame;
            });
            var audioUrl = this._audioResList[index].url;
            const playAudio = imgNode.getComponent(cc.AudioSource);
            cc.assetManager.loadRemote(audioUrl, (err, audioClip) => {
                playAudio.clip = audioClip;
            });

            bgbackNode.addComponent(cc.Button);
            imgNode.addComponent(cc.Button);
            imgNode.on('click', () => {
                console.log('imgclick');
                playAudio.play();
            });
            bgbackNode.on('click', () => {
                cc.tween(bgbackNode)
                    .to(0.3, { scaleY: 0 })
                    .call(() => {
                        bgbackNode.opacity = 0;
                        // labelNode.opacity = 0;
                        imgNode.zIndex = 1000;
                        var playAudio = bgbackNode.getComponent(cc.AudioSource);
                        var flipButton = bgbackNode.getComponent(cc.Button);
                        flipButton.enabled = false;
                        playAudio.play();
                    })
                    .to(0.3, { scaleY: 0.8 })
                    .start();
            }, this);
            layoutNode.addChild(cardNode);
            if (this._imageResList.length > 8) {
                cardNode.scaleY = 0.8;
                cardNode.scaleX = 0.8;
                layout.spacingX = 120;
                // layout.paddingLeft = 60;
            } else {
                cardNode.scaleY = 0.9;
                cardNode.scaleX = 0.9;
                layout.spacingX = 180;
                // layout.paddingLeft = 100;
            }
            layout.updateLayout();
        }
    }

    // update (dt) {},
});
