import { getSprNodeByUrl, 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() {
        cc.debug.setDisplayStats(false);
        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": [{"cardId": "","left": {"title": "123123","pic_url": "http://staging-teach.cdn.ireadabc.com/1cb7f4dfd279ec8c9faf401ef3d5395b.jpg","audio_url": "http://staging-teach.cdn.ireadabc.com/a4d27ad173a95823d4b8ec82363c5aa0.mp3","radioValue": "B"},"right": {"title": "111111","pic_url": "","audio_url": "","radioValue": "A"},"radioValue": "B"},{"cardId": "","left": {"title": "1111122222","pic_url": "http://staging-teach.cdn.ireadabc.com/8eda76334b178bbe56d1f79ff53e68d0.jpg","audio_url": "","radioValue": "A"},"right": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/34a119bfa22caf4785bacfe639d9fa05.png","audio_url": "","radioValue": "B"},"radioValue": "D"},{"cardId": "","left": {"title": "33333","pic_url": "http://staging-teach.cdn.ireadabc.com/991a9dd15e889ee4ff13538e49f6a0d7.png","audio_url": "","radioValue": "A"},"right": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/fb7ce5b740206aff8c3bb1f5cfc21ab9.png","audio_url": "","radioValue": "B"},"radioValue": "D"},{"cardId": "","left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/c029a30bf72efaa8b6a0b9de76d5bc98.png","audio_url": "","radioValue": "B"},"right": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/156b8293a073ef828f6e01fc620c3562.png","audio_url": "","radioValue": "B"},"radioValue": "D"}],"audio_url": "http://staging-teach.cdn.ireadabc.com/a4d27ad173a95823d4b8ec82363c5aa0.mp3","title": "123"},"audio_url": "http://staging-teach.cdn.ireadabc.com/a4d27ad173a95823d4b8ec82363c5aa0.mp3"}';
        // const dataJson = '{"contentObj": {"picArr": [{"cardId": "","left": {"title": "123123","pic_url": "http://staging-teach.cdn.ireadabc.com/1cb7f4dfd279ec8c9faf401ef3d5395b.jpg","audio_url": "http://staging-teach.cdn.ireadabc.com/a4d27ad173a95823d4b8ec82363c5aa0.mp3","radioValue": "B"},"right": {"title": "111111","pic_url": "","audio_url": "","radioValue": "A"},"radioValue": "B"},{"cardId": "","left": {"title": "1111122222","pic_url": "http://staging-teach.cdn.ireadabc.com/8eda76334b178bbe56d1f79ff53e68d0.jpg","audio_url": "","radioValue": "A"},"right": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/34a119bfa22caf4785bacfe639d9fa05.png","audio_url": "","radioValue": "B"},"radioValue": "D"},{"cardId": "","left": {"title": "33333","pic_url": "http://staging-teach.cdn.ireadabc.com/991a9dd15e889ee4ff13538e49f6a0d7.png","audio_url": "","radioValue": "A"},"right": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/fb7ce5b740206aff8c3bb1f5cfc21ab9.png","audio_url": "","radioValue": "B"},"radioValue": "D"},{"cardId": "","left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/c029a30bf72efaa8b6a0b9de76d5bc98.png","audio_url": "","radioValue": "B"},"right": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/156b8293a073ef828f6e01fc620c3562.png","audio_url": "","radioValue": "B"},"radioValue": "D"},{"left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/82f0ecacdc80cbb50c1a229cdee253c4.png","audio_url": ""},"right": {"title": "","pic_url": "","audio_url": ""}},{"left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/dfbba6be5ffedc34d746634bd1be1b20.png","audio_url": ""},"right": {"title": "","pic_url": "","audio_url": ""}}],"audio_url": "http://staging-teach.cdn.ireadabc.com/a4d27ad173a95823d4b8ec82363c5aa0.mp3","title": "123"},"audio_url": "http://staging-teach.cdn.ireadabc.com/a4d27ad173a95823d4b8ec82363c5aa0.mp3"}';
        // const dataJson = '{"contentObj": {"picArr": [{"cardId": "","left": {"title": "123123","pic_url": "http://staging-teach.cdn.ireadabc.com/1cb7f4dfd279ec8c9faf401ef3d5395b.jpg","audio_url": "http://staging-teach.cdn.ireadabc.com/a4d27ad173a95823d4b8ec82363c5aa0.mp3","radioValue": "B"},"right": {"title": "111111","pic_url": "","audio_url": "","radioValue": "A"},"radioValue": "B"},{"cardId": "","left": {"title": "1111122222","pic_url": "http://staging-teach.cdn.ireadabc.com/8eda76334b178bbe56d1f79ff53e68d0.jpg","audio_url": "","radioValue": "A"},"right": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/34a119bfa22caf4785bacfe639d9fa05.png","audio_url": "","radioValue": "B"},"radioValue": "D"},{"cardId": "","left": {"title": "33333","pic_url": "http://staging-teach.cdn.ireadabc.com/991a9dd15e889ee4ff13538e49f6a0d7.png","audio_url": "","radioValue": "A"},"right": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/fb7ce5b740206aff8c3bb1f5cfc21ab9.png","audio_url": "","radioValue": "B"},"radioValue": "D"},{"cardId": "","left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/c029a30bf72efaa8b6a0b9de76d5bc98.png","audio_url": "","radioValue": "B"},"right": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/156b8293a073ef828f6e01fc620c3562.png","audio_url": "","radioValue": "B"},"radioValue": "D"},{"left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/82f0ecacdc80cbb50c1a229cdee253c4.png","audio_url": ""},"right": {"title": "","pic_url": "","audio_url": ""}},{"left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/dfbba6be5ffedc34d746634bd1be1b20.png","audio_url": ""},"right": {"title": "","pic_url": "","audio_url": ""}},{"left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/dfbba6be5ffedc34d746634bd1be1b20.png","audio_url": ""},"right": {"title": "","pic_url": "","audio_url": ""}},{"left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/dfbba6be5ffedc34d746634bd1be1b20.png","audio_url": ""},"right": {"title": "","pic_url": "","audio_url": ""}},{"left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/dfbba6be5ffedc34d746634bd1be1b20.png","audio_url": ""},"right": {"title": "","pic_url": "","audio_url": ""}},{"left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/dfbba6be5ffedc34d746634bd1be1b20.png","audio_url": ""},"right": {"title": "","pic_url": "","audio_url": ""}},{"left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/dfbba6be5ffedc34d746634bd1be1b20.png","audio_url": ""},"right": {"title": "","pic_url": "","audio_url": ""}},{"left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/dfbba6be5ffedc34d746634bd1be1b20.png","audio_url": ""},"right": {"title": "","pic_url": "","audio_url": ""}}],"audio_url": "http://staging-teach.cdn.ireadabc.com/a4d27ad173a95823d4b8ec82363c5aa0.mp3","title": "123"},"audio_url": "http://staging-teach.cdn.ireadabc.com/a4d27ad173a95823d4b8ec82363c5aa0.mp3"}';
        const dataJson = '{"contentObj": {"picArr": [{"cardId": "","left": {"title": "123123","pic_url": "http://staging-teach.cdn.ireadabc.com/1cb7f4dfd279ec8c9faf401ef3d5395b.jpg","audio_url": "http://staging-teach.cdn.ireadabc.com/a4d27ad173a95823d4b8ec82363c5aa0.mp3","radioValue": "B"},"right": {"title": "111111","pic_url": "","audio_url": "","radioValue": "A"},"radioValue": "B"},{"cardId": "","left": {"title": "1111122222","pic_url": "http://staging-teach.cdn.ireadabc.com/8eda76334b178bbe56d1f79ff53e68d0.jpg","audio_url": "","radioValue": "A"},"right": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/34a119bfa22caf4785bacfe639d9fa05.png","audio_url": "","radioValue": "B"},"radioValue": "D"},{"cardId": "","left": {"title": "33333","pic_url": "http://staging-teach.cdn.ireadabc.com/991a9dd15e889ee4ff13538e49f6a0d7.png","audio_url": "","radioValue": "A"},"right": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/fb7ce5b740206aff8c3bb1f5cfc21ab9.png","audio_url": "","radioValue": "B"},"radioValue": "D"},{"cardId": "","left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/c029a30bf72efaa8b6a0b9de76d5bc98.png","audio_url": "","radioValue": "B"},"right": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/156b8293a073ef828f6e01fc620c3562.png","audio_url": "","radioValue": "B"},"radioValue": "D"},{"left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/82f0ecacdc80cbb50c1a229cdee253c4.png","audio_url": ""},"right": {"title": "","pic_url": "","audio_url": ""}},{"left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/dfbba6be5ffedc34d746634bd1be1b20.png","audio_url": ""},"right": {"title": "","pic_url": "","audio_url": ""}},{"left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/dfbba6be5ffedc34d746634bd1be1b20.png","audio_url": ""},"right": {"title": "","pic_url": "","audio_url": ""}},{"left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/dfbba6be5ffedc34d746634bd1be1b20.png","audio_url": ""},"right": {"title": "","pic_url": "","audio_url": ""}},{"left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/dfbba6be5ffedc34d746634bd1be1b20.png","audio_url": ""},"right": {"title": "","pic_url": "","audio_url": ""}},{"left": {"title": "","pic_url": "http://staging-teach.cdn.ireadabc.com/dfbba6be5ffedc34d746634bd1be1b20.png","audio_url": ""},"right": {"title": "","pic_url": "","audio_url": ""}}],"audio_url": "http://staging-teach.cdn.ireadabc.com/a4d27ad173a95823d4b8ec82363c5aa0.mp3","title": "123"},"audio_url": "http://staging-teach.cdn.ireadabc.com/a4d27ad173a95823d4b8ec82363c5aa0.mp3"}';
        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("_imageResList: ", this._imageResList);

        const cardNodeList = [];
        const picArr = this.data.contentObj.picArr;
        for (let index = 0; index < picArr.length; index++) {
            const cardNode = cc.instantiate(cc.find('Canvas/Card'));



            const imgNode = cardNode.getChildByName('img');
            const bgbackNode = cardNode.getChildByName('bgback');
            // label 加载
            const labelNode = bgbackNode.getChildByName('label');
            var label = labelNode.getComponent(cc.Label);
            label.string = this._textResList[index].text;
            // img 加载

            getSprNodeByUrl(picArr[index].left.pic_url, (spr) => {
                var maxWidth = 160;
                var maxHeight = 160;
                const sprNode = spr.node;
                const sx = maxWidth / sprNode.width;
                const sy = maxHeight / sprNode.height;
                sprNode.scale = Math.min(sx, sy);
                sprNode.parent = imgNode;
            })

            // const img = imgNode.addComponent(cc.Sprite);
            // var imgUrl = this._imageResList[index].url;
            // cc.loader.load(imgUrl, function (err, texture) {
            //     // Use texture to create sprite frame
            //     var maxWidth = 160;
            //     var maxHeight = 160;
            //     const spriteFrame = new cc.SpriteFrame(texture);
            //     img.spriteFrame = spriteFrame;
            //     var scaleX = maxWidth / imgNode.width;
            //     var scaleY = maxHeight / imgNode.height;
            //     imgNode.scale = Math.min(scaleX, scaleY);
            // });
            // audio 加载
            const playAudio = imgNode.getComponent(cc.AudioSource);



            // 背景图添加按钮
            bgbackNode.addComponent(cc.Button);
            // img添加按钮
            imgNode.addComponent(cc.Button);
            imgNode.on('click', () => {
                cc.tween(bgbackNode)
                    .call(() => {
                        bgbackNode.opacity = 1000;
                        // labelNode.opacity = 0;
                        var playAudio = bgbackNode.getComponent(cc.AudioSource);
                        var flipButton = bgbackNode.getComponent(cc.Button);
                        flipButton.enabled = true;
                        playAudio.play();
                    }).to(0.3, { scaleY: 1 })
                    .start();
            });
            const playAudioBtnNode = cardNode.getChildByName('playbtn');
            const playAudioBtnImgNode = cardNode.getChildByName('btnimg');
            playAudioBtnNode.active = false;
            playAudioBtnImgNode.active = false;
            const audioUrl = this._audioResList[index].url;

            if (audioUrl != '') {
                playAudioBtnNode.active = true;
                playAudioBtnImgNode.active = true;
                playAudioBtnNode.addComponent(cc.Button);
                playAudioBtnNode.on('click', () => {
                    playAudioBtnImgNode.opacity = 0;
                    const playAnimation = playAudioBtnNode.getComponent(cc.Animation);
                    playAnimation.play();
                    cc.assetManager.loadRemote(audioUrl, (err, audioClip) => {
                        console.log('++++++++++++', audioUrl);

                        const audioId = cc.audioEngine.play(audioClip, false, 0.8);
                        cc.audioEngine.setFinishCallback(audioId, () => {
                            console.log('audio play finish');
                            playAnimation.stop();
                            playAudioBtnImgNode.opacity = 1000;
                        });
                    });
                });
            }

            bgbackNode.on('click', () => {
                cc.tween(bgbackNode)
                    .to(0.3, { scaleY: 0 })
                    .call(() => {
                        bgbackNode.opacity = 0;
                        // labelNode.opacity = 0;
                        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();
            cardNodeList.push(cardNode);
        }

        const maxOffsetX = cardNodeList.reduce((offsetX, cardNode) => offsetX + cardNode.x, 0);
        layoutNode.x = -maxOffsetX / cardNodeList.length;
    }

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