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 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() {

    }

    @property(dg_xiaodi) xiaodi: dg_xiaodi = null;
    async onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
        this.initEvent();
        this.initVideoPlayer();

        // this.xiaodi.playEnter(this.data.npcAudio).then(() => {
        this.initGame();
        // })
        // 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;
        this.layout_video.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);
    }
    // 初始化游戏
    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.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------------------------------
    @property(cc.Node) barTag: cc.Node = null;
    @property(cc.Node) ProgressBar: cc.Node = null;
    @property(cc.VideoPlayer) videoPlayer: cc.VideoPlayer = null;
    @property(cc.Label) currentTimeLabel: cc.Label = null;


    @property(cc.Node) layout_video: cc.Node = null;
    @property(cc.Node) videoControls: cc.Node = null;
    @property(cc.Node) pauseButton: cc.Node = null;
    @property(cc.Node) playButton: cc.Node = null;
    private _isReadyToPlay: boolean;

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

    @property(cc.Node) video_canvas: cc.Node = null;
    hideVideoPlayer() {
        this.layout_video.active = true;
        this.videoPlayer.stayOnBottom = true;
        this.videoPlayer.node.x = 0;
        this.videoPlayer.node.y = 0;
        this.videoPlayer.node.width = 100;
        this.videoPlayer.node.height = 100;
    }
    showVideoPlayer() {
        this.layout_video.active = true;
        this.videoPlayer.stayOnBottom = true;
        this.videoPlayer.node.x = this.video_canvas.x;
        this.videoPlayer.node.y = this.video_canvas.y;
        this.videoPlayer.node.width = this.video_canvas.width;
        this.videoPlayer.node.height = this.video_canvas.height;


        if (!this._isReadyToPlay) {
            //首次播放
            this._isReadyToPlay = false;
            this.videoPlayer.remoteURL = this.data.video;

            pg.view.touchOn(this.playButton, this.play, this);
            pg.view.touchOn(this.pauseButton, this.pause, this);
        } else {
            //重复播放
            this.videoPlayer.currentTime = 0;
            this._isPlayComplated = false;
            this.play();
        }
        this.hideUI();
        setTimeout(() => {
            this.videoPlayer.stayOnBottom = false;
            this.videoControls.active = false;
        }, 3000);
    }

    private timeCtrl: TimeCtrl;
    showVideo() {
        return new Promise(async (reslove) => {
            this.showVideoPlayer();
            this.timeCtrl = pg.time.delayCtrl()
            this.timeCtrl.fillTime(99999);
            await this.timeCtrl.wait();
            reslove('')
        })
    }
    hideVideo() {
        this.timeCtrl.reset();
        this.videoPlayer.node.x = -10000;
        this.videoPlayer.node.y = -10000;
        this.layout_video.active = false;
        this.showUI();
    }
    initVideoPlayer() {
        this.videoPlayer.node.x = -10000;
        this.videoPlayer.node.y = -10000;
        this.layout_video.active = false;
        this.videoPlayer.node.on('ready-to-play', () => {
            console.log('ready-to-play');
            this._isReadyToPlay = true;
            this._isPlayComplated = false;
            this.videoPlayer.currentTime = 0;
            this.play();
        });
        this.videoPlayer.node.on('meta-loaded', () => {
            console.log('meta-loaded');
        });
        this.videoPlayer.node.on('clicked', () => {
            this.videoPlayer.stayOnBottom = true;
            this.videoControls.active = true;
            if (this.time1) {
                clearTimeout(this.time1);
            }
            this.time1 = setTimeout(() => {
                this.videoPlayer.stayOnBottom = false;
                this.videoControls.active = false;
            }, 6000);
        });
        this.videoPlayer.node.on('touchstart', () => {
            this.videoPlayer.stayOnBottom = true;
            this.videoControls.active = true;
            if (this.time1) {
                clearTimeout(this.time1);
            }
            this.time1 = setTimeout(() => {
                this.videoPlayer.stayOnBottom = false;
                this.videoControls.active = false;
            }, 6000);
        });
        this.videoPlayer.node.on('playing', () => {
            this.playButton.active = false;
            this.pauseButton.active = true;
        });
        this.videoPlayer.node.on('paused', () => {
            console.log('paused');
            this.playButton.active = true;
            this.pauseButton.active = false;
        });
        this.videoPlayer.node.on('stopped', () => {
            console.log('stopped');
            this.playButton.active = true;
            this.pauseButton.active = false;
        });
        this.videoPlayer.node.on('completed', async () => {
            console.log('completed');
            this._isPlayComplated = true;
            this.playButton.active = false;
            this.pauseButton.active = false;
            // 循环播放下一个
            this.hideVideo();
        });
        cc.view.setResizeCallback((params) => {
            console.log('Resize', params);
            this.initdDrag()
        });

        this.initdDrag();
    }

    initdDrag() {
        const maxX = this.ProgressBar.width;
        const minX = 0;

        this.barTag.off(cc.Node.EventType.TOUCH_START);
        this.barTag.on(cc.Node.EventType.TOUCH_START, (e) => {
            if (!this._isReadyToPlay) {
                return;
            }
            console.log("TOUCH_START");
        });
        this.barTag.off(cc.Node.EventType.TOUCH_MOVE);
        this.barTag.on(cc.Node.EventType.TOUCH_MOVE, (e) => {
            if (!this._isReadyToPlay) {
                return;
            }
            const worldPos = e.getLocation();
            const localPos = this.barTag.parent.convertToNodeSpaceAR(worldPos);
            let newX = localPos.x;
            newX = Math.min(maxX, Math.max(newX, minX));
            this.barTag.x = newX;
            const percent = newX / maxX;
            const dur = this.videoPlayer.getDuration();
            this.currentTimeLabel.string = this.formatTime(percent * dur);
            this.videoPlayer.currentTime = percent * dur;
        });
        this.barTag.off(cc.Node.EventType.TOUCH_END);
        this.barTag.on(cc.Node.EventType.TOUCH_END, (e) => {
            if (!this._isReadyToPlay) {
                return;
            }
            console.log("TOUCH_ENDED");
            this.updateBarByPos(this.barTag.x);
        });
        this.barTag.off(cc.Node.EventType.MOUSE_UP);
        this.barTag.on(cc.Node.EventType.MOUSE_UP, (e) => {
            if (!this._isReadyToPlay) {
                return;
            }
            console.log("MOUSE_UP");
            this.updateBarByPos(this.barTag.x);
        });
    }
    updateBarByPos(newX) {
        const maxX = this.ProgressBar.width;
        const minX = 0;

        let percent = newX / maxX;
        if (percent > 1) {
            percent = 1
        }
        const dur = this.videoPlayer.getDuration();
        this.videoPlayer.currentTime = percent * dur
    }

    private _isPlayComplated: boolean
    updateBarByTime(ct) {
        if (this._isPlayComplated) {
            return;
        }
        this.currentTimeLabel.string = this.formatTime(ct);
        const dur = this.videoPlayer.getDuration();
        let percent = ct / dur;
        if (percent > 1) {
            percent = 1
        }
        this.ProgressBar.getComponent(cc.ProgressBar).progress = percent;
        const maxX = this.ProgressBar.width;
        const minX = 0;
        let newX = percent * maxX;
        newX = Math.min(maxX, Math.max(newX, minX));
        this.barTag.x = newX;
    }

    formatTime(time) {
        if (time === undefined) {
            return '';
        }
        let hh = "" + Math.floor(time / 60 / 60);
        if (Number(hh) > 0) {
            hh = `${hh.toString().padStart(2, '0')}:`;
        } else {
            hh = '';
        }

        const mm = Math.floor(time / 60).toString().padStart(2, '0');
        const ss = Math.round(time % 60).toString().padStart(2, '0');

        return `${hh}${mm}:${ss}`;
    }


    play() {
        if (!this._isReadyToPlay) {
            return;
        }
        this.videoPlayer.play();
    }
    pause() {
        this.videoPlayer.pause();
    }
    forward() {
    }
    backward() {
    }
    replay() {
        this._isPlayComplated = false;
        this.videoPlayer.currentTime = 0;
        this.videoPlayer.play();
    }

    private time1: any;
    private isVideoFull: boolean;//false,
    private tempPos: any;
    fullScreen() {
        // setTimeout(() => {
        //     // IOS下视频的全屏适配比例有问题，所以做一个计算
        //     this.videoPlayer.node.width = Math.min(this.node.width, this.node.height * 16 / 9);
        // }, 100);
    }

    updateVideo() {
        if (!this._isReadyToPlay) {
            return;
        }
        if (this.videoPlayer) {
            const ct = this.videoPlayer.currentTime;
            if (ct) {
                this.updateBarByTime(ct);
            }
            if (this.videoPlayer.isPlaying()) {
                if (this.playButton.active) {
                    this.playButton.active = false;
                }
                if (!this.pauseButton.active) {
                    this.pauseButton.active = true;
                }
            } else {
                if (!this.playButton.active) {
                    this.playButton.active = true;
                }
                if (this.pauseButton.active) {
                    this.pauseButton.active = false;
                }
            }
        }
    }
    //----------------------------------------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 gameOver() {
        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);
            });
        })
    }
}



