import macro from '../script/A_Macro_dg29_museum'
import { asyncDelay, onHomeworkFinish } from "../script/util_dg29_museum";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_dg29_museum";
import pg, { TimeCtrl } from "./pg_dg29_museum";
import dg_xiaodi from "./dg29_museum_xiaodi";

let win: any = window;
let courseware = win.courseware;
const { ccclass, property } = cc._decorator;

@ccclass
export default class dg29_museum_game extends cc.Component {
    @property(dg_xiaodi) xiaodi: dg_xiaodi = null;
    private data: any;
    init(data) {
        this.data = data;
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
        this.initEvent();
        // this.initVideoPlayer();

        this.initGame();
    }

    _cantouch = null;
    questions: Array<any>;
    successArr: Array<any>;
    current: number;
    initData() {
        // 所有全局变量 默认都是null 
        this._cantouch = true;
        this.current = -1;
        this.successArr = [];
        this.questions = this.data.questions.map((question, id) => {
            question.id = id;
            return question;
        });
    }
    // 当前数据
    get currentQuestion() { return this.questions[this.current] }
    get preQuestion() { return this.questions[this.current - 1] }
    get nextQuestion() { return this.questions[this.current + 1] }


    @property(cc.Node) question_img: cc.Node = null;
    @property(cc.Node) label_title: cc.Node = null;
    @property(cc.Node) btn_vioce: cc.Node = null;
    @property(cc.Node) btn_vioce_ing: cc.Node = null;
    @property(cc.Node) btn_restart: cc.Node = null;
    @property(cc.Node) label_tip_wait: cc.Node = null;
    @property(cc.Node) label_tip_ing: cc.Node = null;
    @property(cc.Node) rich_content: cc.Node = null;
    @property(cc.Node) btn_go: cc.Node = null;

    // 初始化页面
    initView() {
        this.btn_vioce.active = false;
        this.btn_vioce_ing.active = false;
        this.btn_restart.active = false;
        this.label_tip_wait.active = false;
        this.label_tip_ing.active = false;
        this.rich_content.active = false;
    }
    // 事件监听
    initEvent() {
        pg.view.touchOn(this.btn_go, this.onTouchNext, this);
        pg.view.touchOn(this.btn_restart, this.onTouchRestart, this);
        pg.view.touchOn(this.btn_vioce, this.onTouchRecord, this);
        pg.view.touchOn(this.btn_vioce_ing, this.onTouchRecordEnd, this);

        pg.event.on('play_video_end', () => { this.playVideoEnd() })
    }
    // 初始化游戏
    initGame() {
        this.nextStage();
    }

    //4. 右下角角色的音频播放动作
    //5. 视频播放

    nextStage() {
        this.rich_content.active = false;
        const richText = this.rich_content.getComponent(cc.RichText);
        richText.string = "";
        // 处理下一个数
        if (!this.nextQuestion) {
            this.gameOver();
            return;
        }
        this.current++
        this.successArr = [];
        this.targetTime = 10//this.currentQuestion.targetTime
        this.updateQuestion();
    }
    updateQuestion() {
        // 图片部分
        pg.view.setNetImg(this.question_img, this.currentQuestion.img, { w: 1030, h: 720 })
        pg.view.setString(this.label_title, this.currentQuestion.title);

        this.btn_vioce.active = true;
        pg.view.visible(this.btn_vioce_ing, false)
        this.label_tip_wait.active = true;

        // 展示下一题
        this.btn_go.active = true;
        if (!this.nextQuestion) {
            pg.view.setString(pg.view.find(this.btn_go, 'text'), '看影像')
        } else {
            pg.view.setString(pg.view.find(this.btn_go, 'text'), '下一题')
        }

        this._cantouch = false;

        if (this.current == 0) {
            this.xiaodi.playEnter(this.currentQuestion.startAudio).then(() => {
                this._cantouch = true;
            })
        } else {
            this.xiaodi.playQuestionVoice(this.currentQuestion.startAudio).then(() => {
                this._cantouch = true;
            })
        }
    }

    //按钮触发，使用的方法
    private targetTime: number;
    private recordAudio: string;
    private startTime: number;
    private recording: boolean;
    private voiceTouchForbid: boolean;
    private count: number;

    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;

        console.log('subTime->' + subTime)

        this.label_tip_wait.active = false
        this.label_tip_ing.active = true;
        pg.view.visible(this.btn_vioce_ing, true)
        let img_ing = pg.view.find(this.btn_vioce_ing, 'img_ing')
        img_ing.getComponent(cc.Sprite).fillRange = subTime / this.targetTime;
        if (subTime == 0) {
            this.onTouchRecordEnd();
        }
    }
    showTimeEnd() {
        this.startTime = null;
        this.label_tip_wait.active = false
        this.label_tip_ing.active = false;
        pg.view.visible(this.btn_vioce_ing, false)
    }
    async onTouchRecord() {
        if (!this._cantouch) return;
        if (this.recording) return;
        if (this.recordAudio) return;
        this.recording = true;
        this.recordAudio = '';
        this.voiceTouchForbid = true;
        this.showTimeStart();

        this.log("-----------------------startTest")
        cc.audioEngine.stopAllEffects();
        courseware && courseware.startRecord(1); //开始录音
    }
    async onTouchRecordEnd() {
        if (!this.recording) return;
        this.recording = false;
        this.showTimeEnd();
        let testData = {
            "text": "somewhere else to find food",
            "audio": "https://staging-teach.cdn.ireadabc.com/6ee3ccaa831a884f02c6a75c6f647cb5.wav"
        }
        if (!courseware) {
            return this.recordEnd(testData)
        }
        this.log("---------------courseware.stopTest:")
        courseware && courseware.stopRecord(0, (data) => {
            this.log("---------------stopRecord:" + data)
            // res = JSON.parse(res);
            // res.exampleAudio = this.currentQuestion.startAudio ? this.currentQuestion.startAudio : "";
            // res.exampleText = this.currentQuestion.keyword ? this.currentQuestion.keyword : "";
            // this.recrodEnd(isClear, res);
            data = JSON.parse(data);
            console.log("data: " + JSON.stringify(data));
            this.recordEnd(data);
        });//结束录音
    }
    recordEnd(data) {
        let keyTextArr = this.currentQuestion.keyword.split(",");
        keyTextArr = keyTextArr.map(key => {
            return key.trim();
        })

        let colorNormal = '#313131';
        let colorRight = '#1D8B38';
        let str = '';
        let isRight = false;

        // 整句识别判断对错 如果需要特殊的方式就是，把整个句子拆分开来，
        // 1.识别当前句子中哪些是整句匹配的标绿
        // 2.识别当前句子中哪些是小词匹配的标绿
        // 3.整理修改方案（整段句子不进行拆分，哪一部分标绿就把哪一部分拆出来，产生一个数组，A -> A G A , A => A G A G A,依次类推通过递归拆分数组）
        // 4.最后抛出一个调整之后的数组。 或者每一个拆分出去的瞬间，做一个下标记录，识别一个，下标一个，按顺序来。
        if (keyTextArr[0] == data.text) {
            let color = colorNormal;
            color = colorRight;
            str += `<color=${color}>${data.text}</color> `
        } else {
            // 拆散判断对错
            const dataTextArr = data.text.split(" ");
            for (let i = 0; i < dataTextArr.length; i++) {
                const word = dataTextArr[i];
                let color = colorNormal;
                if (keyTextArr.indexOf(word) != -1) {
                    color = colorRight;
                    isRight = true;
                }
                str += `<color=${color}>${word}</color> `
            }
        }

        this.rich_content.active = true;
        const richText = this.rich_content.getComponent(cc.RichText);
        richText.string = str;

        // 处理正确错误
        this.scheduleOnce(() => {
            if (isRight) {
                this.xiaodi.playQuestionVoice(this.currentQuestion.rightAudio).then(() => {
                    this.scheduleOnce(() => {
                        this._cantouch = true;
                    }, 0.5)
                })
            } else {
                this.xiaodi.playQuestionVoice(this.currentQuestion.errorAudio).then(() => {
                    this.scheduleOnce(() => {
                        this._cantouch = true;
                    }, 0.5)
                })
            }
        }, 0.5)
    }
    onTouchRestart() {
        // 处理展示视频内容
        this.showVideo().then(() => {
            // 底部显示为重新查看
            this.btn_restart.active = true;
            // 播放小迪结束的动作与gameOver相关内容
            this.gameOver();
        })
    }
    onTouchNext() {
        console.log('next')
        if(this.gameEnd){
            this.onTouchExit();
            return
        }
        if (this.recording) return;
        if (!this.nextQuestion) {
            pg.view.find(this, 'layout_game/layout_record/img_question').active = false;
            this.btn_vioce.active = false;
            this.label_tip_wait.active = false;
            this.label_tip_ing.active = false;

            // 处理展示视频内容
            this.showVideo().then(() => {
                // 底部显示为重新查看
                this.btn_restart.active = true;
                // 播放小迪结束的动作与gameOver相关内容
                this.gameOver();
            })
        } else {
            this.xiaodi.playQuestionVoiceEnd();

            this.nextStage();
        }
    }

    //-----------------------------------------Video------------------------------
    showUI() {
        pg.view.visible(pg.view.find(this, 'bg'), true)
        pg.view.visible(pg.view.find(this, 'layout_game'), true)
        pg.view.visible(pg.view.find(this, 'layout_xiaodi'), true)
        this.xiaodi.showAll();
    }
    hideUI() {
        pg.view.visible(pg.view.find(this, 'bg'), false)
        pg.view.visible(pg.view.find(this, 'layout_game'), false)
        pg.view.visible(pg.view.find(this, 'layout_xiaodi'), false)
        this.xiaodi.hideAll();
    }

    private timeCtrl: TimeCtrl;
    showVideo() {
        return new Promise(async (reslove) => {
            this.hideUI();
            pg.event.emit("play_video")
            this.timeCtrl = pg.time.delayCtrl()
            this.timeCtrl.fillTime(99999);
            await this.timeCtrl.wait();
            reslove('')
        })
    }
    hideVideo() {
        this.timeCtrl.reset();
        this.showUI();
    }
    
    playVideoEnd() {
        this.hideVideo();
    }

    onVideoPlayerEvent(sender, event) {

        cc.log(event)
    }

    //----------------------------------------VideoEND-------------------------

    showData(data) {
        let list = data.result.sentences[0].details;
        // 列表处理
        let str = "";
        let keystr = "";
        for (let i = 0; i < list.length; i++) {
            let li = list[i];
            let s = "";
            if (li.overall > 40) {
                s = `<color=#000000> ${li.word} </c>`
            } else {
                s = `<color=#FF0000> ${li.word} </c>`
            }
            keystr += li.word + 2
            str += s;
        }
        // this.label_rich.getComponent(cc.RichText).fontSize = num;
        // this.label_rich.getComponent(cc.RichText).lineHeight = num;
        // this.label_rich.getComponent(cc.RichText).string = str;
    }

    private waitTime: number;
    update(dt) {
        this.showTimeUpdate();
        // this.updateVideo();
        if (!this.waitTime) this.waitTime = 8;
        this.waitTime -= dt;
        if (this.waitTime < 0) {
            this.waitTime = 8
        }
    }

    showXiaodi() {
        if (!this.data.npcAudioEnd) return;
        pg.view.find(this, 'layout_xiaodi/btn_go').active = false;
        if (this.data.npcAudioText) {
            this.scheduleOnce(() => {
                pg.view.find(this, 'layout_xiaodi/btn_go').active = true;
            }, 0.5)
        }
        // pg.view.touchOn(pg.view.find(this, 'layout_xiaodi/btn_go'), this.onTouchExit, this);
        pg.view.setString(pg.view.find(this, 'layout_xiaodi/btn_go/text'), this.data.npcAudioText)
        pg.view.find(this, 'layout_xiaodi').active = true;
        pg.view.find(this, 'layout_xiaodi').getComponent(dg_xiaodi).playOver(this.data.npcAudioEnd)
    }
    hideXiaodi() {
        if (!this.data.npcAudioEnd) return;
        pg.view.find(this, 'layout_xiaodi').active = false;
        pg.view.find(this, 'layout_xiaodi').getComponent(dg_xiaodi).playOverEnd()
    }
    private gameEnd : boolean;
    private gameOver() {
        this.gameEnd = true;
        this.rich_content.active = false;
        // 按钮显示未下一题的显示内容
        this.showXiaodi();
    }
    onTouchExit() {
        const middleLayer = cc.find('middleLayer')?.getComponent('middleLayer');
        if (middleLayer) {
            middleLayer.goNextPage();  // 跳转到下一页
            // middleLayer.exitGame(null);
        } else {
            console.log("==触发返回事件==");
        }
    }

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

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




