import { asyncDelay, onHomeworkFinish } from "../script/util_sn14_dds";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_sn14_dds";
import pg from "./pg_sn14_dds";
import ImgVoice from "./Voice_sn14_dds";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {
    addPreloadImage() {
        // TODO 根据自己的配置预加载图片资源
        this._imageResList.push({ url: this.data.pic_url });
        this._imageResList.push({ url: this.data.pic_url_2 });
    }

    addPreloadAudio() {
        let audios = [];
        function checkAudio(obj) {
            for (let idx in obj) {
                if (typeof obj[idx] == "object") {
                    checkAudio(obj[idx]);
                } else if (typeof obj[idx] == "string") {
                    if (obj[idx].indexOf(".mp3") > -1) audios.push(obj[idx]);
                }
            }
        }
        checkAudio(this.data)
        this._audioResList = audios;
    }

    addPreloadAnima() {

    }
    protected onDestroy(): void {
        pg.event.clear();
    }
    async onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData()
        this.initView()
        this.initEvent()
        this.initGame()
    }
    initData() {
        this.current = -1;
        this.data.questions.forEach(question => {
            question.options.sort((A, B) => Math.random() - 0.5)
                .sort((A, B) => Math.random() - 0.5)
                .sort((A, B) => Math.random() - 0.5)
                .sort((A, B) => Math.random() - 0.5)
                .sort((A, B) => Math.random() - 0.5)
                .sort((A, B) => Math.random() - 0.5)
                .sort((A, B) => Math.random() - 0.5)
                .sort((A, B) => Math.random() - 0.5)
        })
        this.setTotalCount(this.data.questions.length)
    }
    initView() { }
    initEvent() {
        pg.view.touchOn(this.btn_laba, this.onTouchAudio, this);
    }

    resetView() { };
    initGame() {
        // pg.audio.playLocalBgm(pg.view.find(this, "res/audio/fly"))
        this.nextQuestion();
    }
    replay() {
        this.initData();
        this.resetView();
        this.initGame();
    }

    private rightCount: number;
    private errorCount: number;
    private totalCount: number;

    addRightCount() {
        if (!this.rightCount) this.rightCount = 0;
        this.rightCount++;
    }
    addErrorCount() {
        if (!this.errorCount) this.errorCount = 0;
        this.errorCount++;
    }
    setTotalCount(val) {
        this.totalCount = val;
    }
    sendData() {
        return new Promise(res => {
            if (!this.totalCount) this.totalCount = this.rightCount + this.errorCount;
            if (!this.totalCount) console.error('未设置总计数');
            if (this.totalCount && !this.rightCount && !this.errorCount) {
                this.rightCount = this.totalCount;
                this.errorCount = 0;
            }
            let upData: any = {
                right_count: this.rightCount || 0,
                wrong_count: this.errorCount || 0,
                total_count: this.totalCount || 0,
            };
            upData.score = upData.right_count || 0;
            let recordList = pg.hw.getRecord();
            if (recordList && recordList.length > 0) {
                upData.result = recordList
            }
            console.log('upload->' + JSON.stringify(upData))
            if (!cc.find('middleLayer')) return;
            const middleLayer = cc.find('middleLayer').getComponent('middleLayer');
            middleLayer.onHomeworkFinish(upData, () => {
                res('');
            })
        })
    }

    gameOver() {
        this.sendData().then(() => {
            if (!cc.find('middleLayer')) return;
            const middleLayer = cc.find('middleLayer');
            if (middleLayer) {
                const middleLayerComponent = middleLayer.getComponent('middleLayer');
                middleLayerComponent.goNextPage();
                return;
            } else {
                console.log("[onFinish] middleLayer not found")
            }
        })
    }
    private rightList: Array<any>;
    private startCreate: boolean;
    private lastTime: number;
    private dataList: Array<any>;
    nextQuestion() {
        if (this.loopId) cc.audioEngine.stopEffect(this.loopId);
        this.loopId = null;
        this.current++;// 自动切换下一题
        if (!this.currentQuestion) {
            this.gameOver();
            return;
        }
        //TODO: 需要增加总倒计时
        this.currentQuestion.options = this.currentQuestion.options.map((op, i) => {
            op.id = i;
            return op;
        })
        this.dataList = this.currentQuestion.options.concat();
        this.itemList = this.freeArea.concat();
        this.lastTime = new Date().getTime();
        this.rightList = [];

        this.onTouchAudio(false).then(() => {
            this.canTouch = true;
            this.inited = true;
            this.startQuestion();
        })
    }

    @property(cc.Node)
    btn_laba: cc.Node = null;

    private inited: boolean;
    onTouchAudio(isClick) {
        return new Promise(res => {
            if (isClick && !this.inited) {
                return;
            }
            this.btn_laba.getComponent(ImgVoice).playVoiceStart();
            pg.audio.playAudioByUrl(this.currentQuestion.questionAudio).then(() => {
                this.btn_laba.getComponent(ImgVoice).playVoiceEnd();
                res('');
            })
        })
    }
    private loopId: any;
    // 制造气泡
    private canTouch: boolean;
    startQuestion() {
        this.startCreate = true;
        this.time = 1;
        this.count = 0;
    }
    private current: number;
    get currentQuestion() {
        return this.data.questions[this.current];
    }
    get currentRightList() {
        return this.currentQuestion.options.filter(op => op.right);
    }


    // 点击泡泡
    touchPaoPao(e: any) {
        // 点击之后不能再次点击
        if (!this.canTouch) return;
        console.log("canTouch 0:" + this.canTouch)
        this.canTouch = false;
        // 如果泡泡没有到指定位置不允许点击
        let item = e.target;
        let data = e.target.data;
        if (!data) {
            this.canTouch = true;
            return;
        }
        if (data.right) {
            pg.hw.playLocalAudio('right2');
            this.scheduleOnce(() => {
                pg.hw.playLocalAudio('right')
            }, 0.2)
            let right = pg.view.find(item, 'right');
            right.active = true;
            pg.view.playDBAnimation(right, 'newAnimation', 1);

            this.rightList.push(data);
            this.updatePaoPaoRight(item, data).then(() => {
                console.log("canTouch 1:" + this.canTouch)
                this.canTouch = true;
                if (this.rightList.length == this.currentRightList.length) {
                    this.freeArea.forEach((item) => {
                        this.udpatePaoPaoHide(item);
                    })
                    cc.Tween.stopAll();
                    this.startCreate = false;
                    this.nextQuestion();
                }
            })
        } else {
            // 失败 
            pg.hw.playLocalAudio('error')
            this.updatePaoPaoError(item, data).then(() => {
                console.log("canTouch 2:" + this.canTouch)
                this.canTouch = true;
            })
        }
    }
    udpatePaoPaoHide(item) {
        return new Promise(resolve => {
            let bg_question = item.getChildByName("bg_question")
            let img_mouse = bg_question.getChildByName("img_mouse")
            let bg_pic = bg_question.getChildByName("bg_pic")
            let bg_word = bg_question.getChildByName("bg_word")
            pg.view.visible(bg_pic, false)
            pg.view.visible(bg_word, false)
            pg.view.visible(img_mouse, false)
            resolve("");
        })
    }
    updatePaoPaoRight(item, data) {
        return new Promise(resolve => {
            let bg_question = item.getChildByName("bg_question")
            let img_mouse = bg_question.getChildByName("img_mouse")
            let bg_pic = bg_question.getChildByName("bg_pic")
            let bg_word = bg_question.getChildByName("bg_word")

            let normal = img_mouse.getChildByName("normal")
            let wrong = img_mouse.getChildByName("wrong")
            let right = img_mouse.getChildByName("right")
            let img = bg_pic.getChildByName("img")
            let text = bg_word.getChildByName("text")
            pg.view.visible(normal, false)
            pg.view.visible(wrong, false)
            pg.view.visible(right, true)

            // 判断是显示图片还是文字
            if (data.type === 'img') {
                let defaultPicY = -170;
                let outPicY = 105;
                cc.Tween.stopAllByTarget(bg_pic);
                cc.tween(bg_pic).delay(1 / 3).to(1 / 3, { y: defaultPicY }).start();
            } else {
                let defaultPicY = -170;
                let outPicY = 80;
                cc.Tween.stopAllByTarget(bg_word);
                cc.tween(bg_word).delay(1 / 3).to(1 / 3, { y: defaultPicY }).start();
            }

            let defaultMouseY = -110;
            cc.Tween.stopAllByTarget(img_mouse);
            cc.tween(img_mouse).delay(1 / 3).to(1 / 3, { y: defaultMouseY }).call(() => {
                this.itemList.push(item);
                item.data = null;
                resolve("");
            }).start();
        })
    }
    updatePaoPaoError(item, data) {
        return new Promise(resolve => {
            let bg_question = item.getChildByName("bg_question")
            let img_mouse = bg_question.getChildByName("img_mouse")
            let bg_pic = bg_question.getChildByName("bg_pic")
            let bg_word = bg_question.getChildByName("bg_word")

            let normal = img_mouse.getChildByName("normal")
            let wrong = img_mouse.getChildByName("wrong")
            let right = img_mouse.getChildByName("right")
            let img = bg_pic.getChildByName("img")
            let text = bg_word.getChildByName("text")
            pg.view.visible(normal, false)
            pg.view.visible(wrong, true)
            pg.view.visible(right, false)

            // 判断是显示图片还是文字
            if (data.type === 'img') {
                let defaultPicY = -170;
                let outPicY = 105;
                cc.Tween.stopAllByTarget(bg_pic);
                cc.tween(bg_pic).delay(1).to(1, { y: defaultPicY }).start();
            } else {
                let defaultPicY = -170;
                let outPicY = 80;
                cc.Tween.stopAllByTarget(bg_word);
                cc.tween(bg_word).delay(1).to(1, { y: defaultPicY }).start();
            }


            let defaultMouseY = -110;
            cc.Tween.stopAllByTarget(img_mouse);
            cc.tween(img_mouse).delay(1).to(1, { y: defaultMouseY }).call(() => {
                this.itemList.push(item);
                this.dataList.push(data);
                item.data = null;
                resolve("");
            }).start();
        })
    }

    private count: number;
    @property([cc.Node])
    private freeArea: Array<cc.Node> = [];
    private itemList: Array<cc.Node> = [];
    updateTime() {
        let rand = Math.floor(Math.random() * this.itemList.length);
        let item = this.itemList[rand];

        let rand2 = Math.floor(Math.random() * this.dataList.length);
        let data = this.dataList[rand2];
        if (!item) return;
        if (!data) return;
        this.itemList.splice(rand, 1);
        this.dataList.splice(rand2, 1);

        // 1.选择某一个区域
        // 2.出现老鼠，移除。
        // 被打
        // 1.停止动作，老鼠
        // 2.继续播放动作，老鼠
        // 
        this.updatePaoPao(item, data);
    }
    updatePaoPao(item, data) {
        let bg_question = item.getChildByName("bg_question")
        let img_mouse = bg_question.getChildByName("img_mouse")
        let bg_pic = bg_question.getChildByName("bg_pic")
        let bg_word = bg_question.getChildByName("bg_word")

        let normal = img_mouse.getChildByName("normal")
        let wrong = img_mouse.getChildByName("wrong")
        let right = img_mouse.getChildByName("right")
        let img = bg_pic.getChildByName("img")
        let text = bg_word.getChildByName("text")
        pg.view.visible(normal, true)
        pg.view.visible(wrong, false)
        pg.view.visible(right, false)
        pg.view.visible(img_mouse, true)

        // 判断是显示图片还是文字
        if (data.type === 'img') {
            pg.view.setNetImg(img, data.image, { w: 295, h: 195 })
            let defaultPicY = -170;
            let outPicY = 105;
            bg_pic.active = true;
            cc.tween(bg_pic).to(1, { y: outPicY }).delay(1).to(1, { y: defaultPicY }).start();
        } else {
            pg.view.setString(text, data.text);
            let defaultPicY = -170;
            let outPicY = 80;
            bg_word.active = true;
            cc.tween(bg_word).to(1, { y: outPicY }).delay(1).to(1, { y: defaultPicY }).start();
        }
        // 点击泡泡
        item.data = data;
        pg.view.touchOn(item, this.touchPaoPao, this)


        let defaultMouseY = -110;

        img_mouse.y = defaultMouseY;
        let posX = [-100, 0, 100];
        img_mouse.x = posX[Math.floor(Math.random() * posX.length)]
        pg.hw.playLocalAudio('create')
        cc.tween(img_mouse).to(1, { y: 0 }).delay(1).to(1, { y: defaultMouseY }).call(() => {
            this.itemList.push(item);
            this.dataList.push(data);
            item.data = null;
        }).start();
    }

    private time: number;
    update(dt) {
        if (!this.currentQuestion) return;
        if (!this.startCreate) return;
        if (this.time -= dt) {
            if (this.time < 0) {
                this.time = 1;
                this.updateTime();
            }
        }
    }

    //----------------------------动画相关---------------------------------------------
    aniShake(item) {
        return new Promise((resolve, reject) => {
            cc.tween(item)
                .to(0.1, { x: -5 }).to(0.1, { x: 0 }).to(0.1, { x: 5 }).to(0.1, { x: 0 })
                .to(0.1, { x: -5 }).to(0.1, { x: 0 }).to(0.1, { x: 5 }).to(0.1, { x: 0 })
                .call(() => {
                    resolve('');
                }).start()
        });
    }
}



