import { asyncDelay, onHomeworkFinish } from "../script/util_sn17_danci";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_sn17_danci";
import pg from "./pg_sn17_danci";
import ImgVoice from "../common/script/ImgVoice_sn17_danci";
import ImgAuto from "./ImgAuto_sn17_danci";
import ImgAuto4 from "./ImgAuto4_sn17_danci";
import LayoutTip from "./LayoutTip_sn17_danci";

const { ccclass, property } = cc._decorator;
let win: any = window;
let courseware = win.courseware;
@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();
        this.startGame();
    }
    protected onDestroy(): void {
        pg.event.clear();
    }

    @property(cc.Node)
    public layout_item: cc.Node = null;
    @property(cc.Node)
    public layer_item: cc.Node = null;
    @property(cc.Node)
    public layer_item_little: cc.Node = null;
    @property(cc.Node)
    public layer_tip: cc.Node = null;
    @property(cc.Node)
    public btn_auto: cc.Node = null;
    @property(cc.Node)
    public layout_unauto: cc.Node = null;
    @property(cc.Node)
    public layout_auto: cc.Node = null;

    _cantouch = null;
    private list: Array<{ type, text, right, imgage, duration, content, audio, npcAudio }>;
    private recordFlag: number;//录音模式
    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.touchAuto = true;
        this.layers = [];
    }

    private layers: Array<cc.Node>;
    initView() {
        pg.view.touchOn(this.btn_auto, this.onTouchAuto, this);
        pg.view.visible(pg.view.find(this, 'tip_record'), false);
        pg.view.visible(pg.view.find(this, 'tip_nopic'), false);
    }

    resetView() {
        this.layout_item.removeAllChildren();
    }
    initListener() {
        pg.view.touchOn(this.btn_last, this.preLayer, this);
        pg.view.touchOn(this.btn_next, this.nextLayer, this);
        pg.view.touchOn(this.btn_voice, this.onTouchVoice, this);
        pg.view.touchOn(this.btn_record, this.onTouchRecord, this);
        pg.view.touchOn(this.ani_npc, this.onPlayNpc, this);

        let layout_btns = pg.view.find(this.btn_record, "mask/layout_btns");
        let btn_right = pg.view.find(layout_btns, 'btn_right')
        let btn_play = pg.view.find(layout_btns, 'btn_play')
        let btn_stop = pg.view.find(layout_btns, 'btn_stop')
        pg.view.touchOn(btn_right, this.onTouchRecordRight, this);
        pg.view.touchOn(btn_play, this.onTouchRecordPlay, this);
        pg.view.touchOn(btn_stop, this.onTouchRecordStop, this);

        pg.view.touchMoveOn(this.layer_touch, this.onTouchPanelMove, this);
    }

    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.label_word.active = false;
        this.touchForbid = false;
        let com = this.btn_voice.getComponent(ImgAuto);
        com.playVoiceStart();
        pg.audio.playAudioByUrl(this.CurrentData.audio, () => {
            this.currentAudioId = null;
            com.playVoiceEnd();
            this.touchForbid = false;

            this.scheduleOnce(() => {
                this.showRecordWait();
            }, 1)
        }, (audioId) => {
            this.currentAudioId = audioId;
        })
    }

    updateBtns() {
        if (this.CurrentData) {
            pg.view.setString(this.label_round, `${this.count + 1}/${this.list.length}`);
        }

        pg.view.visible(pg.view.find(this.btn_auto, 'icon_hand'), !this.touchAuto);
        pg.view.visible(pg.view.find(this.btn_auto, 'icon_auto'), this.touchAuto);

        if (this.touchAuto) {
            pg.view.visible(this.btn_last, false);
            pg.view.visible(this.btn_next, false);
        } else {
            pg.view.visible(this.btn_last, this.count > 0);
            pg.view.visible(this.btn_next, this.count < this.list.length - 1);
        }
    }
    update() {
        if (!this.list) return;
        this.updateBtns();
    }
    //--------------------------------Record-----------------------------
    private recordAudio: string;
    private recording: boolean;


    @property(cc.Node)
    public btn_record: cc.Node = null;

    @property(cc.Node)
    public layer_touch: cc.Node = null;

    log(str) {
        const node = cc.find('middleLayer');
        if (node) {
            node.getComponent('middleLayer').log(str);
        } else {
            console.log(str);
        }
    }

    // 展示点击效果
    async showRecordWait() {
        pg.view.find(this.btn_record, 'bg/ani').active = true;
    }
    async showRecordWaitEnd() {
        pg.view.find(this.btn_record, 'bg/ani').active = false;
    }


    async showRecordIng() {
        let img_voice = pg.view.find(this.btn_record, "img_voice");
        img_voice.active = true;
        img_voice.getComponent(ImgAuto).playVoiceStart();
        // 按钮区域显示  显示对应的对错
        let layout_btns = pg.view.find(this.btn_record, "mask/layout_btns");
        layout_btns.x = -160
        cc.tween(layout_btns).to(0.5, { x: 160 }).start();

        let btn_right = pg.view.find(layout_btns, 'btn_right')
        let btn_play = pg.view.find(layout_btns, 'btn_play')
        let btn_stop = pg.view.find(layout_btns, 'btn_stop')
        btn_right.active = true;
        btn_play.active = false;
        btn_stop.active = false;
    }
    async showRecordEnd() {
        let img_voice = pg.view.find(this.btn_record, "img_voice");
        img_voice.active = false;
        img_voice.getComponent(ImgAuto).playVoiceEnd();
        // 按钮区域显示
        let layout_btns = pg.view.find(this.btn_record, "mask/layout_btns");
        let btn_right = pg.view.find(layout_btns, 'btn_right')
        let btn_play = pg.view.find(layout_btns, 'btn_play')
        let btn_stop = pg.view.find(layout_btns, 'btn_stop')
        btn_right.active = false;
        btn_play.active = false;
        btn_stop.active = false;
    }
    private recordAudioId: any;
    async showRecorAudioPlay() {
        if (!this.recordAudio) return;

        let layout_btns = pg.view.find(this.btn_record, "mask/layout_btns");
        let btn_right = pg.view.find(layout_btns, 'btn_right')
        let btn_play = pg.view.find(layout_btns, 'btn_play')
        let btn_stop = pg.view.find(layout_btns, 'btn_stop')
        btn_right.active = false;
        btn_play.active = false;
        btn_stop.active = true;

        pg.audio.playAudioByUrl(this.recordAudio, () => {
            this.recordAudioId = null;
            this.showRecorAudioPlayEnd().then(() => {
                this.showNpcAudioPlay().then(() => {
                    this.showNpcAudioPlayEnd();
                    this.nextLayer();
                })
            })
        }, audioId => {
            this.recordAudioId = audioId;
        })
    }
    showRecorAudioPlayEnd() {
        return new Promise((resolve, reject) => {
            if (!this.recordAudio) return;

            let layout_btns = pg.view.find(this.btn_record, "mask/layout_btns");
            let btn_right = pg.view.find(layout_btns, 'btn_right')
            let btn_play = pg.view.find(layout_btns, 'btn_play')
            let btn_stop = pg.view.find(layout_btns, 'btn_stop')
            btn_right.active = false;
            btn_play.active = true;
            btn_stop.active = false;

            if (this.recordAudioId) {
                cc.audioEngine.stopEffect(this.recordAudioId)
                this.recordAudioId = null;
            }

            // 播放文字内容
            this.label_word.active = true;
            pg.view.setString(this.label_word, this.recordAudioWord);
            // 播放鼓励
            this.ani_good.active = true;
            pg.view.playDBAnimation(this.ani_good, 'newAnimation', 1);
            this._cantouch = false;
            this.scheduleOnce(() => {
                this._cantouch = true;
                this.ani_good.active = false;
                resolve('');
            }, 1)
        });
    }

    @property(cc.Node)
    label_word: cc.Node = null;
    @property(cc.Node)
    ani_good: cc.Node = null;
    @property(cc.Node)
    ani_npc: cc.Node = null;

    private npcAudioId: any;
    showNpcAudioPlay() {
        return new Promise((resolve, reject) => {
            pg.view.playDBAnimation(this.ani_npc, 'newAnimation', 0);
            pg.audio.playAudioByUrl(this.CurrentData.npcAudio, () => {
                pg.view.playDBAnimation(this.ani_npc, 'newAnimation', 1);
                this.npcAudioId = null;
                resolve('');
            }, audioId => {
                this.npcAudioId = audioId;
            })
        });
    }
    showNpcAudioPlayEnd() {
        if (this.npcAudioId) {
            cc.audioEngine.stopEffect(this.npcAudioId)
            this.npcAudioId = null;
        }
    }

    // 停止录音
    onTouchRecordRight() {
        this.onTouchRecordEnd(false);
        // 开始播放录音音频
    }
    // 停止播放录音
    onTouchRecordStop() {
        this.showRecorAudioPlayEnd().then(() => {
            this.showNpcAudioPlay().then(() => {
                this.showNpcAudioPlayEnd();
                this.nextLayer();
            })
        })
    }
    // 手动播放录音
    onTouchRecordPlay() {
        if (!this._cantouch) return;
        this.showRecorAudioPlay();
    }
    onPlayNpc() {
        this.showNpcAudioPlayEnd();
        this.showNpcAudioPlay().then(() => {
            this.showNpcAudioPlayEnd();
            this.nextLayer();
        })
    }
    //按钮触发，使用的方法
    async onTouchRecord() {
        if (this.recording) return;
        if (this.recordAudio) return;
        this.recording = true;
        this.recordAudio = '';
        this.voiceTouchForbid = true;
        this.showRecordWaitEnd();
        this.showRecordIng();

        this.log("-----------------------startTest")
        cc.audioEngine.stopAllEffects();
        courseware && courseware.startTest(''); //开始录音
    }
    async onTouchRecordEnd(isClear) {
        if (!this.recording) return;
        this.showRecordEnd();
        let testData = {
            "audioUrl": "https://staging-teach.cdn.ireadabc.com/bea0ba87bcf8bc09815f34b4790ffac9.mp3",
            "eof": 1, "file": "/storage/emulated/0/Android/data/com.example.oxford/cache/shengtong/gradeVoice.mp3",
            "result": {
                "duration": "2.670", "fluency": 86,
                "integrity": 50, "kernel_version": "3.7.1", "overall": 7,
                "pronunciation": 28, "resource_version": "2.3.11", "rhythm": 28,
                "sentences": [
                    {
                        "beginIndex": 0,
                        "details": [
                            {
                                "charType": 0, "end": 0, "overall": 56, "prominence": 0, "start": 0, "word": "Good"
                            }, {
                                "charType": 0, "end": 0, "overall": 0, "prominence": 0, "start": 0, "word": "morning"
                            }],
                        "end": 0, "endIndex": 0, "overall": 28,
                        "sentence": "Good morning", "start": 0
                    }],
                "speed": 28
            }, "tokenId": "62d7a2343327934258000009"
        }
        if (!courseware) {
            return this.recrodEnd(isClear, testData)
        }
        this.log("---------------courseware.stopTest:")
        courseware && courseware.stopTest((res) => {
            this.log("---------------stopTest:" + res)
            res = JSON.parse(res);
            this.recrodEnd(isClear, res);
        });//结束录音
    }
    async recrodEnd(isClear, data) {
        this.voiceTouchForbid = false;
        this.recordAudio = data.audioUrl;
        this.showData(data);
        let score = data.result.overall;
        this.log("---------------recrodEnd score:" + score)
        this.recording = false;
        if (isClear) return;
        this.showRecorAudioPlay();
    }
    private recordAudioWord: string;
    showData(data) {
        let list = data.result.sentences[0].details;
        // 列表处理
        let str = "";
        for (let i = 0; i < list.length; i++) {
            let li = list[i];
            let s = "";
            s += li.word;
            // if (li.overall > 40) {
            //     s = `<color=#000000>${li.word}</c>`
            // } else {
            //     s = `<color=#FF0000> ${li.word} </c>`
            // }
            str += s;
        }
        this.recordAudioWord = str;
    }

    @property(cc.Node) item_ani: cc.Node = null;
    @property(cc.Node) layout_ani: cc.Node = null;
    @property(cc.Node) pos_tip: cc.Node = null;

    //----------------------------------------Record-End---------------------------------
    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;
        }
    }
    preLayer() {
        // 积分需要计算，未获取的内容
        pg.hw.playLocalAudio('pagenext')
        this.tempCount = 0;
        cc.audioEngine.stopEffect(this.currentAudioId);
        pg.event.emit('img_voice_play_voice_end');
        pg.event.emit('layer_record_close');
        this.onTouchRecordEnd(true);

        cc.tween(this.LastLayer).to(1 / 3, { x: 0, y: 0, scale: 1 }).start();
        cc.tween(this.CurrentLayer).to(1 / 3, { x: this.layer_item_little.x, y: this.layer_item_little.y, scale: this.layer_item_little.scale }).start();
        if (this.LittleLayer) {
            cc.tween(this.LittleLayer).to(1 / 3, { x: 2000 }).start();
        }
        this.scheduleOnce(() => {
            this.count--;
            this.startPlay();
        }, 1 / 3)
    }
    nextLayer() {
        this.touchForbid = true;
        if (!this.NextData) {
            this.gameOver();
            return;
        }
        pg.hw.playLocalAudio('pagenext')
        this.onTouchRecordEnd(true);
        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_item_little.x, y: this.layer_item_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 => {
            if (!cc.find('middleLayer')) return;
            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() {
        console.warn("gameOver")
        this.sendData().then(() => {
        })
        this.scheduleOnce(() => {
            pg.event.once('layer_ending_touch_replay', () => {
                this.replay();
            })
            if (!cc.find('middleLayer')) return;
            const middleLayer = cc.find('middleLayer').getComponent('middleLayer');
            middleLayer.saveGolds(this.score); // 保存金币数量；num 是获得金币的数量，数字类型；
            middleLayer.goNextPage();  // 跳转到下一页
        }, 0.5)
    }

    createLayer() {
        this.layer_item.active = false;
        let layer = pg.view.clone(this.layer_item);
        layer.active = true;
        this.layout_item.addChild(layer)
        return layer;
    }
    createLittleLayer() {
        let layer = pg.view.clone(this.layer_item);
        layer.active = true;
        layer.x = this.layer_item_little.x;
        layer.y = this.layer_item_little.y;
        layer.scale = this.layer_item_little.scale;
        this.layout_item.addChild(layer)
        return layer;
    }

    @property(cc.Node)
    public label_round: cc.Node = null;
    @property(cc.Node)
    public btn_last: cc.Node = null;
    @property(cc.Node)
    public btn_next: cc.Node = null;

    @property(cc.Node)
    public btn_voice: cc.Node = null;
    updateLayer(layer, data) {
        // 根据数据来渲染
        let itemBg1 = pg.view.find(layer, 'bg_1')
        let itemBg2 = pg.view.find(layer, 'bg_2')
        let itemBg3 = pg.view.find(layer, 'bg_3')
        let item = null;
        let wh = [];
        if (data.imageBig == 1) {
            item = itemBg1;
            wh = [960, 720]
        } else if (data.imageBig == 2) {
            item = itemBg2;
            wh = [1164, 656]
        } else {
            item = itemBg3;
            wh = [1246, 624]
        }
        itemBg1.active = false;
        itemBg2.active = false;
        itemBg3.active = false;
        item.active = true;
        let img = pg.view.find(item, 'img');
        img.active = true;
        pg.view.setNetImg(img, data.image, { w: wh[0], h: wh[1] })

    }
    onTouchVoice(e) {
        if (this.voiceTouchForbid) return;
        let com = this.btn_voice.getComponent(ImgAuto);
        com.playVoiceStart();
        pg.audio.playAudioByUrl(this.CurrentData.audio, () => {
            com.playVoiceEnd();
        })
    }


    //--------------------------------左右滑动----------------------------------
    // 播放中不让点
    // 录音中不让点
    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("nextPage")
            this.nextPage();
        } else if (move.x > 10) {
            this.touchForbid = true;
            console.log("lastPage")
            this.lastPage();
        }
    }
    lastPage() {

        if (!this.LastData) {
            this.touchForbid = false;
            let tip = pg.view.find(this, 'tip_nopic');
            pg.view.visible(tip, true);
            tip.opacity = 255;
            cc.Tween.stopAllByTarget(tip)
            cc.tween(tip).delay(0.8).to(0.5, { opacity: 0 }).start();
            return;
        }
        if (this.recording) {
            this.touchForbid = false;
            // 显示提示
            let tip = pg.view.find(this, 'tip_record');
            pg.view.visible(tip, true);
            tip.opacity = 255;
            cc.Tween.stopAllByTarget(tip)
            cc.tween(tip).delay(0.8).to(0.5, { opacity: 0 }).start();
            return;
        }
        // 停止当前所有动作
        this.preLayer();
    }
    nextPage() {
        if (!this.NextData) {
            this.touchForbid = false;
            let tip = pg.view.find(this, 'tip_nopic');
            pg.view.visible(tip, true);
            tip.opacity = 255;
            cc.Tween.stopAllByTarget(tip)
            cc.tween(tip).delay(0.8).to(0.5, { opacity: 0 }).start();
            return;
        }
        if (this.recording) {
            this.touchForbid = false;
            // 显示提示
            let tip = pg.view.find(this, 'tip_record');
            pg.view.visible(tip, true);
            tip.opacity = 255;
            cc.Tween.stopAllByTarget(tip)
            cc.tween(tip).delay(0.8).to(0.5, { opacity: 0 }).start();
            return;
        }
        if (this.recordFlag) {
            if (this.count + 1 <= this.maxCurrent) {
                this.nextLayer();
            } else {
                this.touchForbid = false;
            }
        } else {
            this.nextLayer();
        }
    }

    private touchAuto: boolean;
    onTouchAuto() {
        // 展示tips
        pg.hw.playLocalAudio('tip')
        this.touchAuto = !this.touchAuto
        console.log("touchAuto->" + this.touchAuto)
        if (this.touchAuto) {
            this.layout_unauto.active = false;
            this.layout_auto.active = true;
            this.layout_auto.x = 550;
            this.layout_auto.opacity = 255;
            cc.tween(this.layout_auto).to(0.3, { x: 0 }).delay(0.3).to(0.3, { opacity: 0 }).start();
        } else {
            this.layout_unauto.active = true;
            this.layout_auto.active = false;
            this.layout_unauto.x = 550;
            this.layout_unauto.opacity = 255;
            cc.tween(this.layout_unauto).to(0.3, { x: 0 }).delay(0.3).to(0.3, { opacity: 0 }).start();
        }
    }

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




