import { asyncDelay, onHomeworkFinish } from "../script/util_dg28_drag";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_dg28_drag";
import pg from "./pg_dg28_drag";
import dg_xiaodi from "./dg28_drag_xiaodi";

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.initEvent();
        pg.view.find(this, 'layout_xiaodi').getComponent(dg_xiaodi).playEnter(this.data.npcAudio).then(() => {
            this.initGame();
        })
    }

    _cantouch = null;
    questions: Array<any>;
    current: number;
    initData() {
        // 所有全局变量 默认都是null 
        this._cantouch = true;
        this.current = 0;
        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] }



    // 5个音频播放，如果没有自动跳过

    // 结束
    get audioEnd() { return this.data.audioEnd }
    // 完成一个
    get auidoFinish() { return this.data.auidoFinish }
    // 肉饼拖拽下来
    get audioMeet() { return this.data.audioMeet }
    // 开始
    get audioStart() { return this.data.audioStart }
    // 蔬菜拖拽下来
    get audioVegetable() { return this.data.audioVegetable }


    @property(cc.Node) public item_main: cc.Node = null;
    @property(cc.Node) public item_vegetables: cc.Node = null;
    @property(cc.Node) public item_meat: cc.Node = null;
    @property(cc.Node) public item_pie: cc.Node = null;
    @property(cc.Node) public layout_main: cc.Node = null;
    @property(cc.Node) public layout_vegetables: cc.Node = null;
    @property(cc.Node) public layout_meat: cc.Node = null;
    @property(cc.Node) public layout_pie: cc.Node = null;

    // 初始化页面
    initView() {
        this.item_main.active = false;
        this.item_vegetables.active = false;
        this.item_meat.active = false;
        this.item_pie.active = false;
        this.hideGuide();
        this.updateBtns();
    }



    initEvent() {
        let layout_btn = pg.view.find(this, 'layout_btn');
        let btn_left = pg.view.find(layout_btn, 'btn_left');
        let btn_right = pg.view.find(layout_btn, 'btn_right');
        pg.view.touchOn(btn_left, this.onTouchLast, this);
        pg.view.touchOn(btn_right, this.onTouchNext, this);
    }
    initGame() {
        this.meetNodes = [];
        this.vegetableNodes = [];
        // 肉饼区域初始化
        this.initLayoutMeet();
        this.visibleMeetList();
        // 蔬菜部分初始化
        this.initLayoutVegetable();
        this.visibleVegetableList();
        // 开始第一题（中间初始化）
        this.initLayoutMain();
        pg.audio.playAudioByUrl(this.data.auidoStart).then(() => {
            // 初始化引导
            this.initGuide();
        })
    }
    static successPosArray: Array<cc.Vec2> = [cc.v2(50, -30), cc.v2(50, 0)];
    private successArr: Array<cc.Node>;
    get successPos() {
        return SceneComponent.successPosArray[this.successArr.length]
    }
    //-------------------------------肉饼区域---------------------------------
    static meetDefaultPos: cc.Vec2 = cc.v2(-655, 172);
    static meetSpace: cc.Vec2 = cc.v2(0, 30);
    private meetNodes: Array<cc.Node>;
    initLayoutMeet() {
        // 计算肉饼总数量
        this.questions.concat([]).reverse().forEach((question, i) => {
            this.createMeet(question, i)
        })
    }
    createMeet(question, i) {
        // 创建节点  
        let node = pg.view.clone(this.item_meat);
        this.layout_meat.addChild(node)
        // 刷新节点
        this.updateItemMeet(node, question);
        // 设定坐标
        let pos = this.getMeetPosByI(i);
        node.x = pos.x
        node.y = pos.y
        // 放入数组中便于引用
        this.meetNodes.push(node);
        return node;
    }
    visibleMeetList() {
        this.meetNodes.forEach((item, i) => {
            let content = pg.view.find(item, 'content');
            content.active = (this.questions.length - i - 1) === this.current
        })
    }
    // 左侧图片/文字 文字有多色高亮    文字默认颜色和高亮颜色都是不同的。 
    updateItemMeet(item, data) {
        item.data = data;
        item.active = true;
        let img = pg.view.find(item, 'content/img');
        if (data.meetType.indexOf('img') > -1) {
            img.active = true;
            pg.view.setNetImg(img, data.meetImage, { w: 330, h: 200 })
        } else {
            img.active = false;
        }

        let text = pg.view.find(item, 'content/text');
        if (data.meetType.indexOf('text') > -1) {
            text.active = true;
            let str = this.getText(data.meetTextArr, `#F7D63A`, `#FFFFFF`);
            text.getComponent(cc.RichText).string = str;
        } else {
            text.active = false;
        }

        item.on(cc.Node.EventType.TOUCH_START, this.onTouchMeetStart, this);
        item.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMeetMove, this);
        item.on(cc.Node.EventType.TOUCH_END, this.onTouchMeetEnd, this);
        item.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchMeetEnd, this);
    }


    getMeetPosByI(i) {
        let pos = cc.v2(SceneComponent.meetDefaultPos)
        pos.y += i * SceneComponent.meetSpace.y;
        return pos;
    }
    get meetCurrentNode() {
        return this.meetNodes[this.questions.length - 1 - this.current]
    }
    meetCurrentTouchNode: cc.Node;
    onTouchMeetStart(event) {
        this.playLocalAudio('dragdown')
        this.waitTime = 8;
        if (this.guide == 1) return;
        let node = event.target;
        if (!node.data) node = node.parent;
        if (!node || !node.data) return;
        if (node.data.id != this.currentQuestion.id) return;
        this.meetCurrentTouchNode = node;
        node.cPos = cc.v2(node);
    }
    onTouchMeetMove(event) {
        this.waitTime = 8;
        if (this.guide == 1) return;
        // 移动
        let node = event.target;
        if (!node.data) node = node.parent;
        if (!node || !node.data) return;
        if (node.data.id != this.currentQuestion.id) return;
        if (node != this.meetCurrentTouchNode) return;
        node.opacity = 255;
        let delta = event.touch.getDelta();
        let pos = cc.v2(delta);
        node.x += pos.x;
        node.y += pos.y;
    }
    onTouchMeetEnd(event) {
        this.waitTime = 8;
        if (this.guide == 1) return;
        let node = event.target;
        if (!node.data) node = node.parent;
        if (!node || !node.data) return;
        if (node.data.id != this.currentQuestion.id) return;
        if (node != this.meetCurrentTouchNode) return;
        this.hideGuide();
        let x = node.x;
        let y = node.y;
        // 碰撞  成功落地 
        if (x < 200 && x > -200 && y < 200 && y > -200) {
            // 成功
            this.onMeetSuccess(node);
        } else {
            // 失败
            this.onMeetFail(node);
        }
    }
    onMeetSuccess(node) {
        if (this.guide == 0) {
            this.guide = 1;
            this.showGuide();
            pg.audio.playAudioByUrl(this.data.audioVegetable)
        }
        node.scale = 1.4;
        node.x = this.successPos.x;
        node.y = this.successPos.y;
        this.meetCurrentTouchNode = null;
        node.off(cc.Node.EventType.TOUCH_START, this.onTouchMeetStart, this);
        node.off(cc.Node.EventType.TOUCH_MOVE, this.onTouchMeetMove, this);
        node.off(cc.Node.EventType.TOUCH_END, this.onTouchMeetEnd, this);
        node.off(cc.Node.EventType.TOUCH_CANCEL, this.onTouchMeetEnd, this);
        node.parent = this.currentMain;
        this.meetNodes.pop();
        this.successArr.push(node);
        if (this.successArr.length == 2) {
            this.showPie();
        }
    }
    onMeetFail(node) {
        node.x = node.cPos.x;
        node.y = node.cPos.y;
        this.meetCurrentTouchNode = null;
    }
    //-------------------------------蔬菜区域---------------------------------
    static vegetableDefaultPos: cc.Vec2 = cc.v2(660, 294);
    static vegetableAngle: number = 30;
    private vegetableNodes: Array<cc.Node>;
    initLayoutVegetable() {
        // 计算肉饼总数量
        this.questions.concat([]).reverse().forEach((question, i) => {
            this.createVegetable(question, i);
        })
    }
    createVegetable(question, i) {
        // 创建节点  
        let node = pg.view.clone(this.item_vegetables);
        this.layout_vegetables.addChild(node)
        // 刷新节点
        this.updateItemVegetable(node, question);
        // 设定坐标
        node.x = SceneComponent.vegetableDefaultPos.x
        node.y = SceneComponent.vegetableDefaultPos.y
        // 设定旋转
        node.angle = this.getVegetableAngleByI(i)
        // 放入数组中便于引用
        this.vegetableNodes.push(node);
        return node;
    }
    visibleVegetableList() {
        this.vegetableNodes.forEach((item, i) => {
            let content = pg.view.find(item, 'content');
            content.active = (this.questions.length - i - 1) === this.current
        })
    }
    // 右侧文字高亮   右上角菜叶子我给了一个，但是你展示在右上角时，每一片都需要有5-10度的转动。
    updateItemVegetable(item, data) {
        item.data = data;
        item.active = true;
        let img = pg.view.find(item, 'content/img');
        if (data.vegetableType.indexOf('img') > -1) {
            img.active = true;
            pg.view.setNetImg(img, data.vegetableImage, { w: 350, h: 220 })
        } else {
            img.active = false;
        }

        let text = pg.view.find(item, 'content/text');
        if (data.vegetableType.indexOf('text') > -1) {
            text.active = true;
            let str = this.getText(data.vegetableTextArr, `#00580A`, `#3E8E2C`);
            text.getComponent(cc.RichText).string = str;
        } else {
            text.active = false;
        }

        item.on(cc.Node.EventType.TOUCH_START, this.onTouchVegetableStart, this);
        item.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchVegetableMove, this);
        item.on(cc.Node.EventType.TOUCH_END, this.onTouchVegetableEnd, this);
        item.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchVegetableEnd, this);
    }

    getVegetableAngleByI(i) {
        let angle = SceneComponent.vegetableAngle * i
        return angle;
    }

    get vegetableCurrentNode() {
        return this.vegetableNodes[this.questions.length - 1 - this.current]
    }
    vegetableCurrentTouchNode: cc.Node;
    onTouchVegetableStart(event) {
        this.playLocalAudio('dragdown')
        this.waitTime = 8;
        if (this.guide == 0) return;
        let node = event.target;
        if (!node.data) node = node.parent;
        if (!node || !node.data) return;
        if (node.data.id != this.currentQuestion.id) return;
        this.vegetableCurrentTouchNode = node;
        node.cPos = cc.v2(node);
    }
    onTouchVegetableMove(event) {
        this.waitTime = 8;
        if (this.guide == 0) return;
        // 移动
        let node = event.target;
        if (!node.data) node = node.parent;
        if (!node || !node.data) return;
        if (node.data.id != this.currentQuestion.id) return;
        if (node != this.vegetableCurrentTouchNode) return;
        node.opacity = 255;
        let delta = event.touch.getDelta();
        let pos = cc.v2(delta);
        node.x += pos.x;
        node.y += pos.y;
    }
    onTouchVegetableEnd(event) {
        this.waitTime = 8;
        if (this.guide == 0) return;
        let node = event.target;
        if (!node.data) node = node.parent;
        if (!node || !node.data) return;
        if (node.data.id != this.currentQuestion.id) return;
        if (node != this.vegetableCurrentTouchNode) return;
        this.hideGuide();
        let x = node.x;
        let y = node.y;
        // 碰撞  成功落地 
        if (x < 200 && x > -200 && y < 200 && y > -200) {
            // 成功
            this.onVegetableSuccess(node);
        } else {
            // 失败
            this.onVegetableFail(node);
        }
    }
    onVegetableSuccess(node) {
        if (this.guide == 1) this.guide = 2;
        node.scale = 1.4;
        node.x = this.successPos.x;
        node.y = this.successPos.y;
        this.vegetableCurrentTouchNode = null;
        node.off(cc.Node.EventType.TOUCH_START, this.onTouchVegetableStart, this);
        node.off(cc.Node.EventType.TOUCH_MOVE, this.onTouchVegetableMove, this);
        node.off(cc.Node.EventType.TOUCH_END, this.onTouchVegetableEnd, this);
        node.off(cc.Node.EventType.TOUCH_CANCEL, this.onTouchVegetableEnd, this);
        node.parent = this.currentMain;
        this.successArr.push(node);
        this.vegetableNodes.pop();
        if (this.successArr.length == 2) {
            this.showPie();
        }
    }
    onVegetableFail(node) {
        node.x = node.cPos.x;
        node.y = node.cPos.y;
        this.vegetableCurrentTouchNode = null;
    }

    //-------------------------------派区域---------------------------------


    // 5.上面掉下来一个面包片   炸星星  上面那个面包片掉下来之后，需要弹起一下再落下。
    //面包片有图片+文字   或  文字
    static pieDefaultPos: cc.Vec2 = cc.v2(48.822, 58.632);
    static pieStartPos: cc.Vec2 = cc.v2(48.822, 693.308);
    showPie() {
        this.waitTime = 8;
        this.scheduleOnce(() => {
            let node = pg.view.clone(this.item_pie);
            this.layout_pie.addChild(node)
            node.x = SceneComponent.pieStartPos.x;
            node.y = SceneComponent.pieStartPos.y;
            this.updateItemPie(node, this.currentQuestion);
            this.playLocalAudio('pie_drop')
            cc.tween(node)
                .to(0.5, { x: SceneComponent.pieDefaultPos.x, y: SceneComponent.pieDefaultPos.y - 50 })
                .to(0.06, { x: SceneComponent.pieDefaultPos.x, y: SceneComponent.pieDefaultPos.y })
                .call(() => {
                    this.playLocalAudio('boom')
                    let ani = pg.view.find(node, 'ani')
                    ani.active = true;
                    pg.view.playDBAnimation(ani, 'normal', 1)
                    node.parent = this.currentMain
                }).delay(0.9).call(() => {
                    this.nextStage();
                })
                .start();
        }, 0.2)
    }
    //标题刷新 标题如果不配置，就不显示那个黄色标题小标签。 三种情况  题干无、题干有、题干图片+文字 文字默认颜色和高亮颜色都是不同的。超框体缩字。
    updateItemPie(item, data) {
        item.data = data;
        item.active = true;
        let img = pg.view.find(item, 'img');
        if (data.pieType.indexOf('img') > -1) {
            img.active = true;
            pg.view.setNetImg(img, data.pieImage, { w: 300, h: 200 })
        } else {
            img.active = false;
        }

        let img_text = pg.view.find(item, 'img_text');
        if (data.pieType == 'img_text') {
            img_text.active = true;
            let str = this.getText(data.pieTextArr, `#AF5725`, `#00580A`);
            img_text.getComponent(cc.RichText).string = str;
        } else {
            img_text.active = false;
        }

        let text = pg.view.find(item, 'text');
        if (data.pieType == 'text') {
            text.active = true;
            let str = this.getText(data.pieTextArr, `#AF5725`, `#00580A`);
            text.getComponent(cc.RichText).string = str;
        } else {
            text.active = false;
        }
    }
    //-------------------------------中间区域---------------------------------
    static mainDefaultPos: cc.Vec2 = cc.v2(0, 0);
    static mainStartPos: cc.Vec2 = cc.v2(0, 1000);
    private currentMain: cc.Node;
    initLayoutMain() {
        // init必定是第一个
        let node = this.createItemMain(this.currentQuestion);
        node.x = SceneComponent.mainDefaultPos.x;
        node.y = SceneComponent.mainDefaultPos.y;
        this.currentMain = node;
    }
    nextLayoutMain(data) {
        let node = this.createItemMain(data);
        node.x = SceneComponent.mainStartPos.x;
        node.y = SceneComponent.mainStartPos.y;
        cc.tween(node).to(0.3, { x: SceneComponent.mainDefaultPos.x, y: SceneComponent.mainDefaultPos.y }).start();
        return node;
    }
    createItemMain(data) {
        //item_main
        let node = pg.view.clone(this.item_main);
        this.layout_main.addChild(node)
        this.updateItemMain(node, data);
        return node;
    }
    //标题刷新 标题如果不配置，就不显示那个黄色标题小标签。 三种情况  题干无、题干有、题干图片+文字 文字默认颜色和高亮颜色都是不同的。超框体缩字。
    updateItemMain(item, data) {
        item.data = data;
        item.active = true;
        let img = pg.view.find(item, 'img');
        if (data.mainType.indexOf('img') > -1) {
            img.active = true;
            pg.view.setNetImg(img, data.mainImage, { w: 300, h: 200 })
        } else {
            img.active = false;
        }

        let text = pg.view.find(item, 'text');
        if (data.mainType.indexOf('text') > -1) {
            text.active = true;
            let str = this.getText(data.mainTextArr, `#AF5725`, `#00580A`);
            text.getComponent(cc.RichText).string = str;
        } else {
            text.active = false;
        }

        let bg_title = pg.view.find(item, 'bg_title');
        bg_title.active = !!data.title
        pg.view.setString(pg.view.find(bg_title, 'label'), data.title);
    }


    //----------------------------------通用部分-----------------------------------
    getText(list, colorNormal, colorLight) {
        // 列表处理
        let str = "";
        for (let i = 0; i < list.length; i++) {
            let li = list[i];
            let s = "";
            if (li.block) {
                s = `<color=${colorLight}> ${li.text} </c>`
            } else {
                s = `<color=${colorNormal}> ${li.text} </c>`
            }
            str += s;
        }
        return str;
    }
    // ----------------------------------题目切换---------------------------------
    // 下一题刷新选项
    nextStage() {
        if (!this.nextQuestion) {
            this.gameOver();
            return
        }
        this.waitTime = 8;
        this.hideGuide();
        // 两边丢弃
        this.discardCurrent();
        // 中间移出
        cc.tween(this.currentMain).by(0.3, { y: -1800 }).start();
        this.playLocalAudio('nextgame')
        // 中间移入
        let node = this.nextLayoutMain(this.nextQuestion);
        // 切换题目主体
        this.current += 1;
        this.successArr = [];
        // 
        this.currentMain = node;
        this.visibleMeetList();
        this.visibleVegetableList();
        this.updateBtns();
    }
    lastStage() {
        this.waitTime = 8;
        this.hideGuide();
        // 先把当前的还原
        this.resetCurrent();
        // 两边放入
        this.createCurrent();
        // 中间移出
        cc.tween(this.currentMain).by(1, { y: -1800 }).start();
        this.playLocalAudio('nextgame')
        // 中间移入
        let node = this.nextLayoutMain(this.preQuestion);
        // 切换题目主体
        this.current -= 1;
        this.successArr = [];

        this.currentMain = node;
        this.visibleMeetList();
        this.visibleVegetableList();
        this.updateBtns();
    }
    discardCurrent() {
        if (this.meetCurrentNode) {
            this.meetCurrentNode.parent = this.currentMain
            this.meetNodes.pop();
        }
        if (this.vegetableCurrentNode) {
            this.vegetableCurrentNode.parent = this.currentMain
            this.vegetableNodes.pop();
        }
    }
    resetCurrent() {
        let lastId = this.current;
        let questionId = this.questions.length - 1 - lastId;
        if (!this.meetCurrentNode) {
            let meet = this.createMeet(this.preQuestion, questionId)
            // let tPosMeet = cc.v2(meet);
            // meet.y += 1000
            // cc.tween(meet).to(1, { x: tPosMeet.x, y: tPosMeet.y - 30 }).to(0.1, { y: tPosMeet.y }).start()
        }
        if (!this.vegetableCurrentNode) {
            let vegetable = this.createVegetable(this.preQuestion, questionId)
            // let tPosVegetable = cc.v2(vegetable);
            // vegetable.y += 1000
            // cc.tween(vegetable).to(1, { x: tPosVegetable.x, y: tPosVegetable.y - 30 }).to(0.1, { y: tPosVegetable.y }).start()
        }
    }
    createCurrent() {
        // 创建两侧内容
        let lastId = this.current - 1;
        let questionId = this.questions.length - 1 - lastId;
        let meet = this.createMeet(this.preQuestion, questionId)
        let tPosMeet = cc.v2(meet);
        meet.y += 1000
        cc.tween(meet).to(1, { x: tPosMeet.x, y: tPosMeet.y - 30 }).to(0.1, { y: tPosMeet.y }).start()
        let vegetable = this.createVegetable(this.preQuestion, questionId)
        let tPosVegetable = cc.v2(vegetable);
        vegetable.y += 1000
        cc.tween(vegetable).to(1, { x: tPosVegetable.x, y: tPosVegetable.y - 30 }).to(0.1, { y: tPosVegetable.y }).start()
    }
    //-----------------------------------翻页部分------------------------------------
    updateBtns() {
        let layout_btn = pg.view.find(this, 'layout_btn');
        let btn_left = pg.view.find(layout_btn, 'btn_left');
        let btn_right = pg.view.find(layout_btn, 'btn_right');
        let img_left = pg.view.find(layout_btn, 'img_left');
        let img_right = pg.view.find(layout_btn, 'img_right');
        btn_left.active = !!this.preQuestion
        img_left.active = !this.preQuestion
        btn_right.active = !!this.nextQuestion
        img_right.active = !this.nextQuestion
    }


    // 用户点击下一页，  面包移出画面。  当不做题的时候点击。面包向下移出，蔬菜和肉饼乡下移动回来。
    onTouchNext() {
        if (this.guide < 2) return;
        // 前往下一页
        this.nextStage();
    }
    // 往前翻，向下移动上面下来一个新的内容。    天上掉落内容。
    onTouchLast() {
        if (this.guide < 2) return;
        // 
        this.lastStage();
    }
    //-----------------------------------引导部分------------------------------------

    // 先引导左边肉饼， 再引导菜叶子   引导动画虽然有顺序，但是用户第一题跟随引导完，自己做其他题时候拖拽顺序不被限制。
    // 停留时间8s以上，手指提示拖拽。
    private guide: number;
    initGuide() {
        this.guide = 0;
        this.showGuide();
        pg.audio.playAudioByUrl(this.data.audioMeet)
    }
    showGuide() {
        if (this.guide == 0) {
            this.showGuideLeft();
        } else if (this.guide == 1) {
            this.showGuideRight();
        } else {
            if (!this.successArr.length) {
                this.showGuideLeft();
            } else if (this.meetNodes.length >= this.vegetableNodes.length) {
                this.showGuideLeft();
            } else {
                this.showGuideRight();
            }
        }
    }
    hideGuide() {
        let layout_tip = pg.view.find(this, 'layout_tip');
        let line_left = pg.view.find(layout_tip, 'line_left');
        let line_right = pg.view.find(layout_tip, 'line_right');
        line_left.active = false;
        line_right.active = false;
    }
    showGuideLeft() {
        let layout_tip = pg.view.find(this, 'layout_tip');
        let line_left = pg.view.find(layout_tip, 'line_left');
        if (line_left.active) return;
        this.showGuideReal('left')
        let finger = pg.view.find(line_left, 'finger');
        cc.tween(finger).repeatForever(
            cc.tween().call(() => {
                finger.x = 310
                finger.y = 55
            }).to(0.8, { x: -45, y: -210 })
        ).start();
    }
    showGuideRight() {
        let layout_tip = pg.view.find(this, 'layout_tip');
        let line_right = pg.view.find(layout_tip, 'line_right');
        if (line_right.active) return;
        this.showGuideReal('right')
        let finger = pg.view.find(line_right, 'finger');
        cc.tween(finger).repeatForever(
            cc.tween().call(() => {
                finger.x = 390
                finger.y = 95
            }).to(0.8, { x: -90, y: -240 })
        ).start();
    }
    showGuideReal(type) {
        let layout_tip = pg.view.find(this, 'layout_tip');
        let line_left = pg.view.find(layout_tip, 'line_left');
        let line_right = pg.view.find(layout_tip, 'line_right');
        line_left.active = type == 'left';
        line_right.active = type == 'right';
    }


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


    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/txt'), 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() {
        pg.audio.playAudioByUrl(this.data.auidoEnd).then(() => {
            pg.audio.playAudioByUrl(this.data.auidoFinish).then(() => {
                // onHomeworkFinish(data)
                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);
            });
        })
    }
}
