import { asyncDelay, onHomeworkFinish, RandomInt } from "../script/util_hy02_paopao";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_hy02_paopao";
import Game, { FISH_OUT, GAME_STATE, Option } from "./tool/Game_hy02_paopao";
import pg from "./tool/pg_hy02_paopao";

const { ccclass, property } = cc._decorator;

export function getDegree(p1, p2) {
    let vector = p2.sub(p1);
    let degree = Math.atan(vector.y / vector.x) / Math.PI * 180;
    if (vector.x >= 0) {
        if (vector.y < 0) {
            degree += 360;
        }
    } else {
        if (vector.y > 0) {
            degree += 180;
        } else {
            degree = 180 + degree;
        }
    }
    return -(-degree + 90);//角度计算方法
}

let win: any = window;
let courseware = win.courseware;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

    addPreloadImage() {
        // TODO 根据自己的配置预加载图片资源
        this._imageResList.push(...this.data.questions.map(question => {
            return { url: question.image };
        }));
    }

    addPreloadAudio() {
        // TODO 根据自己的配置预加载音频资源
        this._audioResList.push({ url: this.data.questionTextAudio });
        this._audioResList.push({ url: this.data.bgAudio });
        this._audioResList.push(...this.data.questions.map(question => {
            return { url: question.audio };
        }));
    }

    addPreloadAnima() {

    }

    onLoadEnd() {
        cc.audioEngine.stopAllEffects();
        cc.macro.ENABLE_MULTI_TOUCH = false;//禁用多指操作
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
        this.initEvent();
        this.showQuestion(false);

        pg.event.on('npc_voice_play_voice_end', () => {
            this.playOpAudio();
        })
        pg.event.emit('npc_layer_back_init', this.data)

        pg.event.on('layer_ending_touch_replay', () => {
            this.replay();
        })
        pg.event.on('layer_coin_show_coin_end', () => {
            this.checkRoundEnd();
        })
    }
    protected onDestroy(): void {
        pg.event.clear();
    }

    @property(cc.Node)
    layout_topic: cc.Node = null;
    @property(cc.Node)
    layout_option: cc.Node = null;
    @property(cc.Node)
    item: cc.Node = null;
    @property(cc.Node)
    item2: cc.Node = null;
    @property(cc.Node)
    layer_back: cc.Node = null;
    @property(cc.Node)
    layer_right: cc.Node = null;
    @property(cc.Node)
    layer_coin: cc.Node = null;



    initData() {
        Game.getIns().init(this.data);
        Game.getIns().reset();
        // 所有全局变量 默认都是null 
        this.touch = false;
    }
    private audioId: any;
    private touch: boolean;
    async initView() {
    }
    initEvent() {

    }


    sendData(score) {
        return new Promise(res => {
            let upData: any = {
                word_count: this.data.word_count || 0,
                sentence_count: this.data.sentence_count || 0,
                zi_count: this.data.zi_count || 0,
                score: score,
            };
            let recordList = pg.hw.getRecord();
            if (recordList && recordList.length > 0) {
                upData.recordList = recordList
            }
            const middleLayer = cc.find('middleLayer').getComponent('middleLayer');
            console.log('upload->' + JSON.stringify(upData))
            middleLayer.onHomeworkFinish(upData, () => {
                res('');
            })
        })
    }

    private gameOver() {
        // pg.event.emit("layer_ending_show", { coin: Game.getIns().len * 3 });
        const midd = cc.find('middleLayer');
        if (!midd) return this.log("no middleLayer");
        this.sendData(Game.getIns().len * 3).then(() => {
            let middleLayer = midd.getComponent('middleLayer');
            middleLayer.saveGolds(Game.getIns().len * 3); // 保存金币数量；num 是获得金币的数量，数字类型；
            middleLayer.goNextPage();  // 跳转到下一页
        })
    }


    private replay() {
        this.initData();
        this.initView();
        this.initEvent();
        this.showQuestion();
    }

    private topic = 220;
    private option = -280;

    private showQuestion(playAudio = true) {
        this.touch = false;
        Game.getIns().state = GAME_STATE.RUNNING;
        let question = Game.getIns().getCurrentPage();

        this.playLocalAudio("show");

        this.layout_topic.removeAllChildren();
        this.layout_topic.y = 600;
        let top = cc.instantiate(this.item2);
        if (question.type == "img") {
            let img = cc.find("img", top);
            pg.view.setNetImg(img, question.image, { w: 550, h: 400 });
        } else {
            let desc = cc.find("desc", top);
            desc.getComponent(cc.Label).string = "" + question.text;
        }
        let img_voice = cc.find("img_voice", top);
        if (question.audio == "") {
            img_voice.active = false;
        } else {
            img_voice.active = true;
        }


        top.active = true;
        top.parent = this.layout_topic;
        this.layout_option.removeAllChildren();
        this.layout_option.y = -600;
        question.optionList.forEach((dt) => {
            let item = cc.instantiate(this.item);
            let desc = cc.find("desc", item);
            desc.getComponent(cc.Label).string = "" + dt.txt;
            item.data = dt;
            item.on(cc.Node.EventType.TOUCH_END, this.onItem, this);
            item.active = true;
            item.parent = this.layout_option;
            this.paopaoAction(item);
        })

        cc.tween(this.layout_topic).to(0.5, { y: this.topic }).start();
        cc.tween(this.layout_option).to(0.5, { y: this.option }).call(() => { this.touch = true; }).start();

        img_voice.on(cc.Node.EventType.TOUCH_END, () => {
            cc.audioEngine.stopAllEffects();
            pg.event.emit("img_voice_play_voice_start");
            pg.audio.playAudioByUrl(question.audio).then(() => {
                pg.event.emit("img_voice_play_voice_end");
            })
        })
        if (playAudio) this.playOpAudio();
    }
    private playOpAudio() {
        let question = Game.getIns().getCurrentPage();
        pg.event.emit("img_voice_play_voice_start");
        pg.audio.playAudioByUrl(question.audio).then(() => {
            pg.event.emit("img_voice_play_voice_end");
        })
    }
    private async paopaoAction(target) {
        await pg.time.delay(Math.random() * 1);
        cc.tween(target).repeatForever(
            cc.tween().to(1.5 + Math.random() * 2, { y: 10 }).to(1, { y: -10 })
        ).start();
    }

    private onItem(e) {
        if (!this.touch) return;
        this.touch = false;
        let target = e.target;
        cc.Tween.stopAllByTarget(target);
        let data = target.data;
        if (!data.right) {
            this.playLocalAudio("error");
            cc.tween(target).to(0.1, { angle: 10 }).to(0.1, { angle: 0 }).to(0.1, { angle: -10 })
                .to(0.1, { angle: 10 }).to(0.1, { angle: 0 }).to(0.1, { angle: -10 }).to(0.1, { angle: 0 })
                .call(() => {
                    this.touch = true;
                })
                .start();
            return;
        }
        this.playLocalAudio("right");
        let bg = cc.find("pp", target);
        let pp = cc.find("pp2", target);
        bg.active = false;
        pp.active = true;

        cc.tween(pp).to(0.7, { opacity: 0 }).call(() => {
            pg.event.emit("layer_coin_show_coin", 3);
        }).start();

        // this.checkRoundEnd();


    }

    //根据两点获取距离
    private getDistance(p1, p2) {
        let temp = p1.sub(p2);
        let dis = Math.abs(temp.mag());
        return dis;
    }
    private getDistances(p1, p2) {
        //转换世界坐标查看距离
        let ps2 = p2.convertToWorldSpaceAR(cc.v2(0, 0));
        let ps1 = p1.convertToWorldSpaceAR(cc.v2(0, 0));
        let temp = ps1.sub(ps2);
        let dis = Math.abs(temp.mag());
        return dis;
    }
    private count: number;
    update(dt) {

    }







    //根据两点获取角度
    getDegree(p1, p2) {
        let vector = p2.sub(p1);
        let degree = Math.atan(vector.y / vector.x) / Math.PI * 180;
        if (vector.x >= 0) {
            if (vector.y < 0) {
                degree += 360;
            }
        } else {
            if (vector.y > 0) {
                degree += 180;
            } else {
                degree = 180 + degree;
            }
        }
        return -(-degree + 90) || 0;//角度计算方法
    }
    private checkRoundEnd() {
        Game.getIns().addPage();
        if (!Game.getIns().getCurrentPage()) {
            // pg.time.delayCall(1.2, () => {
            this.layer_right.active = true;
            this.gameOver();
            // });
        } else {
            this.playLocalAudio("next").then(() => {
                this.showQuestion();
            });
        }
    }



    playLocalAudio(audioName, cb = null) {
        const audio = cc.find(`Canvas/res/audio/${audioName}`).getComponent(cc.AudioSource);
        return new Promise((resolve, reject) => {
            const id = cc.audioEngine.playEffect(audio.clip, false);
            cc.audioEngine.setFinishCallback(id, () => {
                resolve(id);
            });
        })
    }

    async showOneFirework(pos, parentNode, nodeList) {

        for (let i = 0; i < 3; i++) {
            this.showFirework(pos, parentNode, nodeList, 200, 200, 25);
            await asyncDelay(0.1);
        }
    }

    showFirework(pos, parentNode, nodeList, width = 200, height = 500, number = 30) {
        for (let i = 0; i < number; i++) {
            const quad = this.createQuads(pos, parentNode, nodeList);
            const targetX = RandomInt(width / 2, -width / 2);
            const targetY = RandomInt(height);

            cc.tween(quad)
                .by(0.5, { x: targetX })
                .by(3, { x: targetX * 2 })
                .start();

            cc.tween(quad)
                .by(0.5, { y: targetY }, { easing: 'quadOut' })
                .to(4, { y: -parentNode.height * 2 }, { easing: 'quadIn' })
                .removeSelf()
                .start();

            cc.tween(quad)
                .delay(1)
                .to(0.5 + 1 * Math.random(), { opacity: 0 })
                .start();
        }
    }

    createQuads(pos, parentNode, nodeList) {
        const quadBase = cc.instantiate(nodeList[RandomInt(nodeList.length)]);
        // console.log('nodeList', nodeList);
        // console.log('quadBase', quadBase);
        quadBase.x = pos.x;
        quadBase.y = pos.y + 30;
        quadBase.z = pos.z;
        quadBase.angle = RandomInt(180);
        quadBase.parent = parentNode;

        const quad = quadBase.getChildByName('quad');
        quad.x = 0;
        quad.y = 0;
        quad.angle = RandomInt(180);

        const paper = quad.getChildByName('paper');
        paper.scaleX = Math.random() * 0.8 + 0.2;
        paper.scaleY = Math.random() * 0.8 + 0.2;

        quadBase.scaleX = Math.random();
        cc.tween(quadBase)
            .to((1 - quadBase.scaleX) * 0.3, { scaleX: 1 })
            .call(() => {
                const time = Math.random() * 0.2;
                cc.tween(quadBase)
                    .to(0.1 + time, { scaleX: -1 })
                    .to(0.1 + time, { scaleX: 1 })
                    .union()
                    .repeatForever()
                    .start();
            })
            .start();


        return quadBase;
    }
}




