import { asyncDelay, onHomeworkFinish } from "../script/util_hy01_danci";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_hy01_danci";
import pg from "./pg_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 根据自己的配置预加载音频资源
        this._audioResList.push({ url: this.data.audio_url });
    }

    addPreloadAnima() {

    }

    async onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
        this.initListener();
        this.initGame();
    }

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

    private layer_record: cc.Node;
    private layer_game: cc.Node;
    private layer_word: cc.Node;
    private layer_word_little: 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')
    }

    initListener() {
        pg.event.on('layer_record_score', (score) => {
            this.onRecorScore(score);
        })
    }

    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 CurrentLayer() {
        return this.layers[0]
    }
    private get LittleLayer() {
        return this.layers[1]
    }
    private get OutLayer() {
        return this.layers[2]
    }

    private count: number;
    initGame() {
        this.count = 0;
        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)

        this.startPlay();
    }
    startPlay() {
        if (this.recordFlag) {
            this.layer_record.active = true;
        } else {
            if (this.CurrentData.type.indexOf('audio') > -1) {
                pg.event.emit('img_voice_play_voice_start')
                pg.audio.playAudioByUrl(this.CurrentData.audio, () => {
                    pg.event.emit('img_voice_play_voice_end')
                    this.nextLayer();
                })
            }
        }
    }
    onRecorScore(score) {
        this.layer_record.active = false;
        if (score < 10) {
            pg.event.on('layer_right_show_tryagain_end', () => {
                // alert('test')
                if (this.recordFlag) {
                    this.layer_record.active = true;
                }
            })
            pg.event.emit('layer_right_show_tryagain')
        } else if (score < 60) {
            pg.event.on('layer_right_show_good_end', () => {
                this.nextLayer();
            })
            pg.event.emit('layer_right_show_good')
        } else {
            pg.event.on('layer_right_show_excellent_end', () => {
                this.nextLayer();
            })
            pg.event.emit('layer_right_show_excellent')
        }
    }
    nextLayer() {
        if (!this.NextData) {
            this.gameOver();
            return;
        }

        if (this.OutData) {
            let outLayer = this.createLittleLayer();
            this.updateLayer(outLayer, this.OutData)
            outLayer.x = -1500;
            this.layers.push(outLayer)
        }

        cc.tween(this.CurrentLayer).to(3, { x: 2000 }).start();
        if (this.LittleLayer) {
            cc.tween(this.LittleLayer).to(3, { x: 0, y: 0, scale: 1 }).start();
        }
        if (this.OutLayer) {
            cc.tween(this.OutLayer).to(3, { x: this.layer_word_little.x, y: this.layer_word_little.y }).start();
        }
        this.scheduleOnce(() => {
            this.count++;
            this.layers.shift();
            this.startPlay();
        }, 3)
    }
    gameOver() {

    }

    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: 370 })
        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) {
        let layer = e.target.parent;
        if (layer === this.CurrentLayer) {
            pg.event.emit('img_voice_play_voice_start')
            pg.audio.playAudioByUrl(this.CurrentData.audio, () => {
                pg.event.emit('img_voice_play_voice_end')
            })
        }
    }

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

