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,
    preloadItem() {
        this.addPreloadImage();
        this.addPreloadAudio();
        // this.addPreloadAnima();
        this.preload();
    },

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

    getDefaultData() {

        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":"","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":""}}]}}'
        // const dataJson = '{"contentObj":{"picArr":[{"left":{"title":"ant","pic_url":"http://staging-teach.cdn.ireadabc.com/ae171e6f3d70323f407aa254d2c3bd4e.jpg","audio_url":"http://staging-teach.cdn.ireadabc.com/b4e6f8abf69975813c2a44d1b5d3d9e0.mp3"},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"ant2","pic_url":"http://staging-teach.cdn.ireadabc.com/6ea7e019a03c7cfaf516cdee66671047.jpg","audio_url":""},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"ant3","pic_url":"http://staging-teach.cdn.ireadabc.com/ba2422c95c71d9991039d4b980af2166.jpg","audio_url":""},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"ant4","pic_url":"http://staging-teach.cdn.ireadabc.com/c5fabd5e07386171fbddcde40be08dbb.jpg","audio_url":""},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"ant5","pic_url":"http://staging-teach.cdn.ireadabc.com/9c26888dfe02eb79877c4fcc64867ecc.jpg","audio_url":""},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"ant6","pic_url":"http://staging-teach.cdn.ireadabc.com/34a119bfa22caf4785bacfe639d9fa05.png","audio_url":""},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"第七个","pic_url":"http://staging-teach.cdn.ireadabc.com/8eda76334b178bbe56d1f79ff53e68d0.jpg","audio_url":""},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"第八个","pic_url":"http://staging-teach.cdn.ireadabc.com/3be3efc51e3e5178e3afc882c9a528d1.jpg","audio_url":""},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"9","pic_url":"http://staging-teach.cdn.ireadabc.com/fb7ce5b740206aff8c3bb1f5cfc21ab9.png","audio_url":""},"right":{"title":"","pic_url":"","audio_url":""}},{"left":{"title":"10","pic_url":"http://staging-teach.cdn.ireadabc.com/97a054918747798f6e6e1f19f99b08d2.jpg","audio_url":""},"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 });
                // }
            })
        }
    },

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

    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/layout');
        var layout = layoutNode.getComponent(cc.Layout);
        console.log('fdsafdsa', this._imageResList);
        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.6;
                cardNode.scaleX = 0.6;
                layout.spacingX = 80;
                layout.paddingLeft = 60;
            } else {
                cardNode.scaleY = 0.7;
                cardNode.scaleX = 0.7;
                layout.spacingX = 120;
                layout.paddingLeft = 100;
            }
            layout.updateLayout();
        }
    }

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