import { asyncDelay, onHomeworkFinish } from "../script/util_hy01_danci";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_hy01_danci";
import pg from "./pg_hy01_danci";
import ImgVoice from "../common/script/ImgVoice_hy01_danci";

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() {
        // TODO 根据自己的配置预加载音频资源
        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() {

    }

    async onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
        this.initListener();
        this.initGame();
        pg.event.on('npc_voice_play_voice_end', () => {
            this.startGame();
        })
        pg.event.emit('npc_layer_back_init', this.data)
    }
    protected onDestroy(): void {
        pg.event.clear();
    }

    _cantouch = null;
    private list: Array<{ type, text, right, imgage, duration, content, audio }>;
    private recordFlag: boolean;//录音模式
    private score: number;
    private scoreList: Array<number>;
    private tempCount: number;
    private maxCurrent: number;
    initData() {
        // 所有全局变量 默认都是null 
        this._cantouch = true;
        let data = this.data;
        this.score = 0;
        this.tempCount = 0;
        this.recordFlag = data.recordFlag;
        this.list = data.questions[0].options;
        this.scoreList = this.list.map(() => 3);
        this.maxCurrent = 0;
        this.layers = [];
    }

    private layer_record: cc.Node;
    private layer_game: cc.Node;
    private layer_word: cc.Node;
    private layer_word_little: cc.Node;
    private layer_touch: cc.Node;
    private layers: Array<cc.Node>;
    initView() {
        this.layer_record = pg.view.find(this, 'layer_record')
        this.layer_game = pg.view.find(this, 'layer_game')
        this.layer_word = pg.view.find(this, 'layer_word')
        this.layer_word_little = pg.view.find(this, 'layer_word_little')

        this.layer_touch = pg.view.find(this, 'layer_touch')
        pg.view.touchMoveOn(this.layer_touch, this.onTouchPanelMove, this);
    }
    // 播放中不让点
    // 录音中不让点
    private touchForbid: boolean;
    onTouchPanelMove(e: cc.Event.EventTouch) {
        if (this.touchForbid) return;
        //加一些限制
        let touchPoint = e.getLocation();
        let startPoint = e.getStartLocation();
        let move = touchPoint.clone().subtract(startPoint);
        console.log(move.toString());
        if (move.x < -10) {
            this.touchForbid = true;
            console.log("lastPage")
            this.lastPage();
        } else if (move.x > 10) {
            this.touchForbid = true;
            console.log("nextPage")
            this.nextPage();
        }
    }
    lastPage() {
        // 停止当前所有动作
        this.preLayer();
    }
    nextPage() {
        if (this.recordFlag) {
            if (this.count + 1 <= this.maxCurrent) {
                this.nextLayer();
            } else {
                this.touchForbid = false;
            }
        } else {
            this.nextLayer();
        }
    }
    resetView() {
        this.layer_game.removeAllChildren();
    }
    initListener() {
        pg.event.on('layer_record_score', (score) => {
            this.onRecorScore(score);
        })
        pg.event.on('layer_record_start_record', () => {
            this.touchForbid = true;
        });
        pg.event.on('layer_record_end_record', () => {
            this.touchForbid = false;
        });
    }

    private get LastData() {
        return this.list[this.count - 1]
    }
    private get CurrentData() {
        return this.list[this.count]
    }
    private get NextData() {
        return this.list[this.count + 1]
    }
    private get OutData() {
        return this.list[this.count + 2]
    }
    private get LastLayer() {
        return this.layers[this.count - 1]
    }
    private get CurrentLayer() {
        return this.layers[this.count]
    }
    private get LittleLayer() {
        return this.layers[this.count + 1]
    }
    private get OutLayer() {
        return this.layers[this.count + 2]
    }
    private voiceTouchForbid: boolean;
    private count: number;
    initGame() {
        this.count = 0;
        this.touchForbid = true;
        this.voiceTouchForbid = true;
        let currentLayer = this.createLayer();
        this.updateLayer(currentLayer, this.CurrentData)
        this.layers.push(currentLayer)
        let nextLayer = this.createLittleLayer();
        this.updateLayer(nextLayer, this.NextData)
        this.layers.push(nextLayer)
    }
    startGame() {
        this.touchForbid = false;
        this.voiceTouchForbid = false;
        this.startPlay();
    }
    private currentAudioId: any;
    startPlay() {
        this.touchForbid = false;
        if (this.recordFlag) {
            if (this.CurrentData.type.indexOf('audio') > -1) {
                let img_voice = pg.view.find(this.CurrentLayer, 'voice/img_voice');
                let com = img_voice.getComponent(ImgVoice);
                com.playVoiceStart();
                pg.audio.playAudioByUrl(this.CurrentData.audio, () => {
                    this.currentAudioId = null;
                    com.playVoiceEnd();
                    this.touchForbid = false;
                    pg.event.emit('layer_record_open', {
                        letter: this.CurrentData.content,
                        targetTime: this.CurrentData.duration,
                        reset: true
                    })
                }, (audioId) => {
                    this.currentAudioId = audioId;
                })
            } else {
                pg.event.emit('layer_record_open', {
                    letter: this.CurrentData.content,
                    targetTime: this.CurrentData.duration,
                    reset: true
                })
            }
        } else {
            if (this.CurrentData.type.indexOf('audio') > -1) {
                let img_voice = pg.view.find(this.CurrentLayer, 'voice/img_voice');
                let com = img_voice.getComponent(ImgVoice);
                com.playVoiceStart();
                pg.audio.playAudioByUrl(this.CurrentData.audio, () => {
                    this.currentAudioId = null;
                    com.playVoiceEnd();

                    this.scheduleOnce(() => {
                        this.touchForbid = false;
                        this.nextLayer();
                    }, 0.5)// 动画过来播放之后等待三秒

                    // pg.event.once('layer_coin_show_coin_end', () => {
                    //     this.touchForbid = false;
                    //     this.nextLayer();
                    // })  // 动画回调\
                    // this.score += 3;
                    // pg.event.emit('layer_coin_show_coin', 3)   //1 2 3硬币数量
                }, (audioId) => {
                    this.currentAudioId = audioId;
                })
            }
        }
    }
    addScore(num) {
        if (num >= 3 && this.scoreList[this.count] >= 3) {
            this.score += 3;
            this.scoreList[this.count] -= 3;
        } else if (num >= 2 && this.scoreList[this.count] >= 2) {
            this.score += 2;
            this.scoreList[this.count] -= 2;
        } else if (num >= 1 && this.scoreList[this.count] >= 1) {
            this.score += 1;
            this.scoreList[this.count] -= 1;
        }
    }
    onRecorScore(score) {
        if (score < 10) {
            pg.event.once('layer_right_show_tryagain_end', () => {
                this.tempCount += 1;
                if (this.tempCount == 2) {
                    this.addScore(1);
                    pg.event.once('layer_coin_show_coin_end', () => {
                        this.nextLayer();
                    })  // 动画回调
                    pg.event.emit('layer_coin_show_coin', 1)   //1 2 3硬币数量
                } else {
                    if (this.recordFlag) {
                        pg.event.emit('layer_record_open', {
                            letter: this.CurrentData.content,
                            targetTime: this.CurrentData.duration,
                            reset: false
                        })
                    }
                }
            })
            pg.event.emit('layer_right_show_tryagain')
        } else if (score < 60) {
            pg.event.once('layer_right_show_good_end', () => {
                this.addScore(2);
                pg.event.once('layer_coin_show_coin_end', () => {
                    this.nextLayer();
                })  // 动画回调
                pg.event.emit('layer_coin_show_coin', 2)   //1 2 3硬币数量
            })
            pg.event.emit('layer_right_show_good')
        } else {
            pg.event.once('layer_right_show_excellent_end', () => {
                this.addScore(3);
                pg.event.once('layer_coin_show_coin_end', () => {
                    this.nextLayer();
                })  // 动画回调
                pg.event.emit('layer_coin_show_coin', 3)   //1 2 3硬币数量
            })
            pg.event.emit('layer_right_show_excellent')
        }
    }
    preLayer() {
        // 积分需要计算，未获取的内容
        if (!this.LastData) {
            this.touchForbid = false;
            return;
        }
        this.tempCount = 0;
        cc.audioEngine.stopEffect(this.currentAudioId);
        pg.event.emit('img_voice_play_voice_end');
        pg.event.emit('layer_record_close');

        cc.tween(this.LastLayer).to(1, { x: 0, y: 0, scale: 1 }).start();
        cc.tween(this.CurrentLayer).to(1, { x: this.layer_word_little.x, y: this.layer_word_little.y, scale: this.layer_word_little.scale }).start();
        if (this.LittleLayer) {
            cc.tween(this.LittleLayer).to(1, { x: -1500 }).start();
        }
        this.scheduleOnce(() => {
            this.count--;
            this.startPlay();
        }, 1)
    }
    nextLayer() {
        this.touchForbid = true;
        if (!this.NextData) {
            this.gameOver();
            return;
        }
        this.tempCount = 0;
        pg.event.emit('layer_record_close');
        this.currentAudioId && cc.audioEngine.stopEffect(this.currentAudioId);
        pg.event.emit('img_voice_play_voice_end');
        // 停止当前所有动作
        if (this.OutData && !this.OutLayer) {
            let outLayer = this.createLittleLayer();
            this.updateLayer(outLayer, this.OutData)
            outLayer.x = -1500;
            this.layers.push(outLayer)
        }

        cc.tween(this.CurrentLayer).to(1/3, { x: 2000 }).start();
        if (this.LittleLayer) {
            cc.tween(this.LittleLayer).to(1/3, { x: 0, y: 0, scale: 1 }).start();
        }
        if (this.OutLayer) {
            cc.tween(this.OutLayer).to(1/3, { x: this.layer_word_little.x, y: this.layer_word_little.y }).start();
        }
        this.scheduleOnce(() => {
            this.touchForbid = false;
            this.count++;
            this.maxCurrent = Math.max(this.maxCurrent, this.count);
            this.startPlay();
        }, 1/3)
    }
    replay() {
        this.initData();
        this.resetView();
        this.initGame();
        this.startGame();
    }

    sendData() {
        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: this.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('');
            })
        })
    }
    gameOver() {
        this.sendData().then(() => {
            pg.event.once('layer_ending_touch_replay', () => {
                this.replay();
            })
            const middleLayer = cc.find('middleLayer').getComponent('middleLayer');
            middleLayer.saveGolds(this.score); // 保存金币数量；num 是获得金币的数量，数字类型；
            middleLayer.goNextPage();  // 跳转到下一页
            // pg.event.emit('layer_ending_show', { coin: this.score })
        })
    }

    createLayer() {
        let layer = pg.view.clone(this.layer_word);
        layer.active = true;
        this.layer_game.addChild(layer)
        return layer;
    }
    createLittleLayer() {
        let layer = pg.view.clone(this.layer_word);
        layer.active = true;
        layer.x = this.layer_word_little.x;
        layer.y = this.layer_word_little.y;
        layer.scale = this.layer_word_little.scale;
        this.layer_game.addChild(layer)
        return layer;
    }

    updateLayer(layer, data) {
        let bg = pg.view.find(layer, 'bg');
        let c1 = pg.view.find(bg, 'c1');
        let c2 = pg.view.find(bg, 'c2');
        let c3 = pg.view.find(bg, 'c3');
        let c4 = pg.view.find(bg, 'c4');
        let img = pg.view.find(layer, 'img');
        let label = pg.view.find(layer, 'label');
        let voice = pg.view.find(layer, 'voice');
        // 根据数据来渲染
        img.active = true;
        pg.view.setNetImg(img, data.image, { w: 600, h: 340 })
        label.active = data.type == 'img_txt' || data.type == 'img_txt_audio'
        pg.view.setString(label, data.text);
        voice.active = data.type == 'img_audio' || data.type == 'img_txt_audio'
        pg.view.touchOn(voice, this.onTouchVoice, this);
        if (this.recordFlag) {
            c1.active = false;
            c2.active = false;
            c3.active = false;
            c4.active = false;
        }
    }
    onTouchVoice(e) {
        if (this.voiceTouchForbid) return;
        let layer = e.target.parent;
        if (layer === this.CurrentLayer) {
            let img_voice = pg.view.find(this.CurrentLayer, 'voice/img_voice');
            let com = img_voice.getComponent(ImgVoice);
            com.playVoiceStart();
            pg.audio.playAudioByUrl(this.CurrentData.audio, () => {
                com.playVoiceEnd();
            })
        }
    }

    playLocalAudio(audioName) {
        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);
            });
        })
    }
}



