import { RandomInt, playDragonBoneAnimation } from "../script/util";

cc.Class({
    extends: cc.Component,

    properties: {

    },

    ctor() {
        this._resultList = [];
        this._maxPlayerNumber = 5;
    },

    setFinishAudioList(finishAudioList) {
        this._finishAudioList = finishAudioList;
    },

    start() {
        this.updateLabel('等待其他小伙伴中');
    },

    addPlayerResult(headUrl, isSelf, name, duration, uuid) {
        if (this._resultList.find(player => player.uuid == uuid)) {
            return;
        }
        this._resultList.push({ headUrl, isSelf, name, duration, uuid });
        if (isSelf) {
            this.showJiangTai();
        }
        this.updatePlayer();

        if (isSelf) {
            const idx = this._resultList.findIndex(result => result.isSelf == true);
            if (idx != -1) {
                const cat = cc.find("resultNode/catFrame/CoolCat");
                playDragonBoneAnimation(cat, "begin", -1);
                this.playAudioByUrl(this._finishAudioList[idx], ()=>{
                    playDragonBoneAnimation(cat, "normal", -1);
                });
            }
        }
    },

    showLight() {
        const fire = cc.find('jiangtaiNode/fire', this.node);
        cc.tween(fire)
            .set({ opacity: 200 })
            .to(1, { opacity: 255, scale: 1.0 }, { easing: 'quadOut' })
            .to(1, { opacity: 200, scale: 0.8 }, { easing: 'quadIn' })
            .union()
            .repeatForever()
            .start();

        const light = cc.find('jiangtaiNode/light', this.node);
        cc.tween(light)
            .by(4, { angle: 360 })
            .repeatForever()
            .start();
    },

    showJiangTai() {
        const label = cc.find('label', this.node);
        label.active = false;

        const jiangtaiNode = cc.find('jiangtaiNode', this.node);
        jiangtaiNode.active = true;
        jiangtaiNode.zIndex = 1;

        const catFrame = cc.find('catFrame', this.node);
        catFrame.zIndex = 1;

        this.showLight();

        this.showStar();

        this.updatePlayer();
    },

    showStar() {
        for (let i = 0; i < 100; i++) {
            const star = cc.instantiate(cc.find('star', this.node));
            star.active = true;
            star.parent = this.node;
            const basePos = {
                x: RandomInt(this.node.width / 2, -this.node.width / 2),
                y: RandomInt(this.node.height / 2, -500)
            };
            cc.tween(star)
                .to(0.5, { x: basePos.x, y: basePos.y }, { easing: 'quintIn' })
                .start();

            const rate = Math.random();

            cc.tween(star)
                .set({ scale: rate, opacity: parseInt(255 * rate) })
                .to((1 - rate), { scale: 1, opacity: 255 })
                .to(1, { scale: 0, opacity: 0 })
                .delay(Math.random() * 3)
                .to(rate, { scale: rate, opacity: parseInt(255 * rate) })
                .union()
                .repeatForever()
                .start();

        }
    },

    updatePlayer() {
        this._resultList.sort((a, b) => {
            return a.duration - b.duration;
        });

        this._resultList.forEach((player, idx) => {
            const headNode = cc.find(`jiangtaiNode/head_${idx}`, this.node);
            const headImg = cc.find(`mask/headImg`, headNode);
            const name = cc.find(`name`, headNode);
            const arrow = cc.find(`arrow`, headNode);

            if (player.isSelf) {
                arrow.active = true;
            } else {
                arrow.active = false;
            }

            name.getComponent(cc.Label).string = player.name;

            this.loadSpriteByUrl(headImg, player.headUrl, () => {
                const scale = Math.max(
                    headImg.parent.width / headImg.width,
                    headImg.parent.height / headImg.height
                );
                headImg.scale = scale;

                if (!headNode.active) {
                    headNode.active = true;
                    cc.tween(headNode)
                        .set({ scale: 0 })
                        .to(0.2, { scale: 1 }, { easing: 'backOut' })
                        .start();
                }
            });
        });
    },

    updateLabel(str) {
        const label = cc.find('label', this.node).getComponent(cc.Label);
        if (label.tweenAction) {
            label.tweenAction.stop();
        }
        label.tweenAction = cc.tween(label)
            .set({ string: `${str}` })
            .delay(0.4)
            .set({ string: `${str}.` })
            .delay(0.4)
            .set({ string: `${str}..` })
            .delay(0.4)
            .set({ string: `${str}...` })
            .delay(0.4)
            .union()
            .repeatForever()
            .start();
    },

    loadSpriteByUrl(node, url, cb) {
        cc.loader.load({
            url: url.toLowerCase()
        }, (err, img) => {
            if (!node) {
                cb && cb();
            }
            const spriteFrame = new cc.SpriteFrame(img)
            const spr = node.getComponent(cc.Sprite);
            spr.spriteFrame = spriteFrame;
            if (cb) {
                cb();
            }
        });
    },

    playAudioByUrl(audio_url, cb = null) {
        if (!audio_url) {
            if (cb) {
                cb();
            }
            return;
        }
        const url = audio_url
            .toLowerCase();

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