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;
enum Flag {
    Listen = 1,
    Record = 2,
    Check = 3
}
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 }>;
    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);
    }

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

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

                this.letter = this.CurrentData.content;
                this.targetTime = this.CurrentData.duration;
                this.scheduleOnce(() => {
                    this.onTouchRecord();
                }, 1)
            }, (audioId) => {
                this.currentAudioId = audioId;
            })
        } else {
            if (this.CurrentData.type.indexOf('audio') > -1) {
                let com = this.btn_voice.getComponent(ImgAuto);
                com.playVoiceStart();
                pg.audio.playAudioByUrl(this.CurrentData.audio, () => {
                    this.currentAudioId = null;
                    com.playVoiceEnd();
                    this.scheduleOnce(() => {
                        this.touchForbid = false;
                        if (this.touchAuto) this.nextLayer();
                    }, 0.5)
                }, (audioId) => {
                    this.currentAudioId = audioId;
                })
            }
        }
    }

    updateBtns() {
        if (this.CurrentData) {
            pg.view.setString(this.label_title, this.CurrentData.text);
            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();
        // this.updateCountdown(dt);
        this.showTimeUpdate();
    }
    //--------------------------------Record-----------------------------
    private letter: string;
    private targetTime: number;
    private recordAudio: string;
    private startTime: number;
    private recording: boolean;
    private microPhoneChange: boolean;


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

    showTimeStart() {
        if (!this.targetTime) return;
        let nowTime = new Date().getTime();
        this.startTime = nowTime;
    }
    showTimeUpdate() {
        if (!this.startTime) return;
        let nowTime = new Date().getTime();
        let subTime = this.targetTime - (nowTime - this.startTime) / 1000 + 1;
        if (subTime < 0) subTime = 0;

        pg.view.setString(this.label_time, `${Math.floor(subTime)}`)
        if (subTime == 0) {
            this.onTouchRecordEnd(false);
        }
    }
    showTimeEnd() {
        this.startTime = null;
    }
    showVoiceFlash() {
        pg.view.visible(this.btn_record, true)
        this.btn_record.y = -550;
        cc.tween(this.btn_record).to(0.3, { y: 0 }).start();
        let com = this.btn_record.getComponent(ImgAuto4);
        com.playVoiceStart();
    }
    hideVoiceFlash() {
        pg.view.visible(this.btn_record, false)
        let com = this.btn_record.getComponent(ImgAuto4);
        com.playVoiceEnd();
    }

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

    //按钮触发，使用的方法
    async onTouchRecord() {
        if (this.recording) return;
        if (this.recordAudio) return;
        this.recording = true;
        this.recordAudio = '';
        this.voiceTouchForbid = true;
        this.showTimeStart();
        this.showVoiceFlash();

        this.log("-----------------------startTest")
        cc.audioEngine.stopAllEffects();
        courseware && courseware.startTest(this.letter); //开始录音
    }
    async onTouchRecordEnd(isClear) {
        if (!this.recording) return;
        this.showTimeEnd();
        this.hideVoiceFlash();
        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.hideVoiceFlash();
        let score = data.result.overall;
        this.log("---------------recrodEnd score:" + score)
        this.recording = false;
        if (isClear) return;
        this.onRecorScore(score, data);
    }

    @property(cc.Node) item_ani: cc.Node = null;
    @property(cc.Node) layout_ani: cc.Node = null;
    @property(cc.Node) pos_tip: cc.Node = null;
    onShowTipAni(score) {
        this.onHideTipAni();
        return new Promise(resolve => {
            let item = pg.view.clone(this.item_ani);
            item.active = true;
            if (score < 10) {
                pg.view.visible(pg.view.find(item, 'img_tryagain'), true)
                pg.view.visible(pg.view.find(item, 'img_good'), false)
                pg.view.visible(pg.view.find(item, 'img_excellent'), false)
            } else if (score < 60) {
                pg.view.visible(pg.view.find(item, 'img_tryagain'), false)
                pg.view.visible(pg.view.find(item, 'img_good'), true)
                pg.view.visible(pg.view.find(item, 'img_excellent'), false)
            } else {
                pg.view.visible(pg.view.find(item, 'img_tryagain'), false)
                pg.view.visible(pg.view.find(item, 'img_good'), false)
                pg.view.visible(pg.view.find(item, 'img_excellent'), true)
            }
            this.layout_ani.addChild(item);

            let wordPos = this.pos_tip.convertToWorldSpaceAR(cc.v2(0, 0))
            let nodePos = this.layout_ani.convertToNodeSpaceAR(wordPos);
            cc.tween(item).to(0.3, { x: nodePos.x, y: nodePos.y })
                .delay(0.15)
                .call(() => {
                    resolve('')
                }).start();
        })

    }
    onHideTipAni() {
        this.layout_ani.removeAllChildren();
    }
    onRecorScore(score, data) {
        this.log("---------------onRecorScore flag|data|touchAuto:" + `${this.recordFlag}|${data}|${this.touchAuto}`)
        if (score < 10) {
            this.tempCount += 1;
            if (this.tempCount == 2) {
                this.addScore(1);
                this.layer_tip.getComponent(LayoutTip).open(this.recordFlag, data, this.touchAuto).then(() => {
                    if (!this.touchAuto) return;
                    this.onShowTipAni(score).then(() => {
                        this.nextLayer();
                    })
                })
            } else {
                this.layer_tip.getComponent(LayoutTip).open(this.recordFlag, data, this.touchAuto).then(() => {
                    this.onShowTipAni(score).then(() => {
                        this.onTouchRecord();
                    })
                })
            }
        } else if (score < 60) {
            this.addScore(2);
            this.layer_tip.getComponent(LayoutTip).open(this.recordFlag, data, this.touchAuto).then(() => {
                if (!this.touchAuto) return;
                this.onShowTipAni(score).then(() => {
                    this.nextLayer();
                })
            })
        } else {
            this.addScore(3);
            this.layer_tip.getComponent(LayoutTip).open(this.recordFlag, data, this.touchAuto).then(() => {
                if (!this.touchAuto) return;
                this.onShowTipAni(score).then(() => {
                    this.nextLayer();
                })
            })
        }
    }
    //----------------------------------------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() {
        // 积分需要计算，未获取的内容
        if (!this.LastData) {
            this.touchForbid = false;
            return;
        }
        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.onHideTipAni();
        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() {
        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 label_title: cc.Node = null;
    @property(cc.Node)
    public btn_voice: cc.Node = null;
    updateLayer(layer, data) {
        let img = pg.view.find(layer, 'img');
        // 根据数据来渲染
        img.active = true;
        pg.view.setNetImg(img, data.image, { w: 1330, h: 655 })
    }
    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("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();
        }
    }

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




