import { asyncDelay, onHomeworkFinish } from "../script/util_jj15_zww";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_jj15_zww";
import pg from "./pg_jj15_zww";
import hw from "./hw_jj15_zww";
import ImgAuto from "./hwComponent/ImgAuto_jj15_zww";

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

    }
    onTouchReturn() {
        const middleLayer = cc.find('middleLayer');
        if (middleLayer) {
            const middleLayerComponent = middleLayer.getComponent('middleLayer');
            middleLayerComponent.exitGame({});
        }
    }
    async onLoadEnd() {
        pg.view.touchOn(pg.view.find(this, 'btn_return'), this.onTouchReturn, this);

        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
        this.initListener();
        this.initGame();
        this.initBottom();
        this.startGame();
    }
    protected onDestroy(): void {
        if (this.btn_voice_time_id) {
            clearTimeout(this.btn_voice_time_id)
            this.btn_voice_time_id = null;
        }
        pg.event.clear();
    }

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

    @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;

    _cantouch = null;
    private list: Array<{
        title, questionAudio, image, letterList, recordData, isChose//用于判定对错 right  wrong
    }>;
    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.showLastNext = 0;// 前后翻页按钮倒计时
        this.recordFlag = data.recordFlag;
        this.list = data.questions;
        this.scoreList = this.list.map(() => 3);
        this.maxCurrent = 0;
        this.layers = [];
        this.readyNext = false;
        this.readyTime = 99999;
        this.setTotalCount(this.list.length)
        // 处理数据 this.test[this.count][this.cardCount];
        this.cardCount = 0;
        this.recordData = [];
        this.checkCardsTime = 999999;
    }
    private cardCount: number;
    private recordData: Array<any>;
    private setRecordData(count, cardCount, data) {
        this.recordData[count] = this.recordData[count] || [];
        this.recordData[count][cardCount] = data;
    }
    private getRecrdData(count, cardCount) {
        return this.recordData[count] && this.recordData[count][cardCount];
    }


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

    resetView() {
        this.layout_item.removeAllChildren();
    }
    initListener() {
        pg.view.touchOn(this.btn_close, this.onTouchRecordClose, this);
        pg.view.touchOn(this.btn_last, this.lastPage, this);
        pg.view.touchOn(this.btn_next, this.nextPage, this);
        pg.view.touchMoveOn(this.layer_touch, this.onTouchPanelMove, this);
    }

    private voiceTouchForbid: boolean;
    private count: number;
    initGame() {
        cc.audioEngine.playMusic(this.bgmNode.getComponent(cc.AudioSource).clip, true);
        this.count = 0;
        this.touchForbid = true;
        this.voiceTouchForbid = true;
        if (!this.CurrentData.title) this.label_title.active = false;
        pg.view.setString(this.label_title, this.CurrentData.title)
        this.gou_node.orgPos = cc.v2(this.gou_node)
        let currentLayer = this.createLayer();
        this.updateLayer(currentLayer, this.CurrentData, this.count)
        this.layers.push(currentLayer)
        if (!this.NextData) return;
        let nextLayer = this.createLittleLayer();
        this.updateLayer(nextLayer, this.NextData, this.count + 1)
        this.layers.push(nextLayer)
        // 循环播放三个卡片的tips
        this.checkCardsTime = 0;
    }
    @property(cc.Node)
    label_title: cc.Node = null;
    startGame() {
        this.voiceTouchForbid = false;
        this.startPlay();
    }
    private currentAudioId: any;
    startPlay() {
        // 自动播放顶部音频
        this.touchForbid = true;

        cc.tween(this.btn_start).repeatForever(
            cc.tween().to(0.5, { scale: 1.1 }).to(0.5, { scale: 1.0 })
        ).start();

        this.scheduleOnce(() => {
            this.touchForbid = false;
        }, 0.1)
    }
    currentTipId: number;
    showCardsTip() {
        // let layout_card = this.CurrentLayer.getChildByName('layout_card');
        // let children = layout_card.children.filter(item => !item.data.isClick)
        // children.forEach((item, i) => {
        //     let tip = pg.view.find(item, 'back/tip');
        //     if (this.currentTipId % layout_card.children.length == i) {
        //         tip.active = true;
        //         tip.opacity = 0;
        //         // cc.tween 针对tip 闪烁两次
        //         cc.tween(tip).to(0.5, { opacity: 0 }).to(0.5, { opacity: 255 }).to(0.5, { opacity: 0 }).to(0.5, { opacity: 255 }).to(0.5, { opacity: 0 }).call(() => {
        //             this.currentTipId++;
        //             this.showCardsTip();
        //         }).start();
        //     } else {
        //         tip.active = false;
        //     }

        // })
    }
    hideCardsTip() {
        // let layout_card = this.CurrentLayer.getChildByName('layout_card');
        // layout_card.children.forEach((item, i) => {
        //     let tip = pg.view.find(item, 'back/tip');
        //     tip.active = false;
        //     cc.Tween.stopAllByTarget(tip);
        // })
    }
    // 检查卡片的状态
    checkCardsTime: number;
    isAllOver() {
        let isAllOver = true;
        let layer = this.CurrentLayer;
        let layout_card = pg.view.find(layer, 'layout_card')
        if (layout_card.children.length == 0) return true;
        return false;
    }
    checkCards(dt) {
        this.checkCardsTime -= dt;
        if (this.checkCardsTime <= 0) {
            this.checkCardsTime = 999999;
            if (this.isAllOver()) {
                this.nextLayer();
            } else {
                this.currentTipId = 0;
                this.showCardsTip();
            }
        }
    }

    private showLastNext: number;
    updateBtns(dt) {
        this.showLastNext -= dt;
        // 翻页按钮隐藏自动倒计时
        if (this.showLastNext > 0) {

        }
        pg.view.visible(pg.view.find(this.btn_last, 'img_0'), !this.LastData);
        pg.view.visible(pg.view.find(this.btn_last, 'img_1'), !!this.LastData);
        pg.view.visible(pg.view.find(this.btn_next, 'img_0'), !this.NextData);
        pg.view.visible(pg.view.find(this.btn_next, 'img_1'), !!this.NextData);
    }
    initBottom() {
        // let layout_bottom = pg.view.find(this, 'layout_bottom')
        // layout_bottom.removeAllChildren();
        // this.list.forEach((data, i) => {
        //     let item = pg.view.clone(pg.view.find(this, 'point'))
        //     item.data = {
        //         idx: i
        //     }
        //     item.x = 0;
        //     item.y = 0;
        //     layout_bottom.addChild(item);
        // })
    }
    updateBottom(dt) {
        // let layout_bottom = pg.view.find(this, 'layout_bottom')
        // layout_bottom.children.forEach((item, i) => {
        //     let data = item.data;
        //     let idx = data.idx;
        //     let dt = this.list[idx];
        //     // 每个游戏此处逻辑重写即可
        //     // let isRight = (dt.right && dt.isChose == "yes") || (!dt.right && dt.isChose == "no");
        //     let isRight = dt.isChose == "right";//

        //     let point_orange_normal = pg.view.find(item, 'point_orange_normal')
        //     let point_orange_right = pg.view.find(item, 'point_orange_right')
        //     let point_orange_wrong = pg.view.find(item, 'point_orange_wrong')

        //     let point_orange_select_normal = pg.view.find(item, 'point_orange_select_normal')
        //     let point_orange_select_right = pg.view.find(item, 'point_orange_select_right')
        //     let point_orange_select_wrong = pg.view.find(item, 'point_orange_select_wrong')

        //     if (this.count == idx) {
        //         point_orange_normal.active = false;
        //         point_orange_right.active = false;
        //         point_orange_wrong.active = false;

        //         if (dt.isChose) {
        //             point_orange_select_normal.active = false;
        //             point_orange_select_right.active = isRight;
        //             point_orange_select_wrong.active = !isRight;
        //         } else {
        //             point_orange_select_normal.active = true;
        //             point_orange_select_right.active = false;
        //             point_orange_select_wrong.active = false;
        //         }
        //     } else {
        //         point_orange_select_normal.active = false;
        //         point_orange_select_right.active = false;
        //         point_orange_select_wrong.active = false;

        //         if (dt.isChose) {
        //             point_orange_normal.active = false;
        //             point_orange_right.active = isRight;
        //             point_orange_wrong.active = !isRight;
        //         } else {
        //             point_orange_normal.active = true;
        //             point_orange_right.active = false;
        //             point_orange_wrong.active = false;
        //         }
        //     }
        // })
    }
    private readyNext: boolean;
    private readyTime: number;
    update(dt) {
        if (!this.list) return;
        this.updateBtns(dt);
        this.checkCards(dt);
        this.updateRound(dt);
        this.updateBottom(dt);
    }
    updateRound(dt) {
        pg.view.setString(this.label_round, `${this.count + 1}/${this.list.length}`);
    }
    //--------------------------------Record-----------------------------
    private recordAudio: string;
    private recording: boolean;



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

    //----------------------------------------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() {
        // 积分需要计算，未获取的内容
        this.checkCardsTime = 99999;
        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();

        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;
        }
        this.checkCardsTime = 99999;
        pg.hw.playLocalAudio('pagenext')
        // this.onTouchRecordEnd();
        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, this.count + 2)
            outLayer.x = 3500;
            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.count++;
            this.maxCurrent = Math.max(this.maxCurrent, this.count);
            this.startPlay();
        }, 1 / 3)
    }
    replay() {
        this.initData();
        this.resetView();
        this.initGame();
        this.initBottom();
        this.startGame();
    }

    private rightCount: number;
    private errorCount: number;
    private totalCount: number;
    addRightCount() {
        if (!this.rightCount) this.rightCount = 0;
        this.rightCount++;
    }
    addErrorCount() {
        if (!this.errorCount) this.errorCount = 0;
        this.errorCount++;
    }
    setTotalCount(val) {
        this.totalCount = val;
    }
    sendData() {
        return new Promise(res => {
            if (!this.totalCount) this.totalCount = this.rightCount + this.errorCount;
            if (!this.totalCount) console.error('未设置总计数');
            if (this.totalCount && !this.rightCount && !this.errorCount) {
                this.rightCount = this.totalCount;
                this.errorCount = 0;
            }
            let upData: any = {
                right_count: this.rightCount || 0,
                wrong_count: this.errorCount || 0,
                total_count: this.totalCount || 0,
            };
            upData.score = upData.right_count || 0;
            let recordList = pg.hw.getRecord();
            if (recordList && recordList.length > 0) {
                upData.result = recordList
            }
            console.log('upload->' + JSON.stringify(upData))
            if (!cc.find('middleLayer')) return;
            const middleLayer = cc.find('middleLayer').getComponent('middleLayer');
            middleLayer.onHomeworkFinish(upData, () => {
                res('');
            })
        })
    }

    gameOver() {
        this.touchForbid = true;
        this.scheduleOnce(() => {
            if (!this.node || !this.node.parent) return;
            if (!this.showFires) this.showFires = {};
            if (!this.showFires[`${this.count}`]) {
                this.showFires[`${this.count}`] = true;
                hw.util.playEndTrebleFirework();
            }
            this.sendData().then(() => {
                if (!cc.find('middleLayer')) return;
                const middleLayer = cc.find('middleLayer');
                if (middleLayer) {
                    const middleLayerComponent = middleLayer.getComponent('middleLayer');
                    middleLayerComponent.goNextPage();
                    return;
                } else {
                    console.log("[onFinish] middleLayer not found")
                }
            })
        }, 1)
    }

    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 btn_last: cc.Node = null;
    @property(cc.Node)
    public btn_next: cc.Node = null;
    @property(cc.Node)
    public card_pos: cc.Node = null;

    updateLayer(layer, data, i) {
        if (!layer || !data) return;
        layer.data = data;
        // 根据数据来渲染  这里来增加按钮部分
        console.log("items");
        let posList = {
            "4": [-445, -150, 150, 445],
            "3": [-400, -10, 380],
            "2": [-250, 250],
            "1": [-10]
        }
        let posArray = posList[data.options.length];
        let posY = this.card_pos.y;
        // 计算Y的值

        // let img = pg.view.find(layer, 'title/img')
        // pg.view.setNetImg(img, data.image, { w: 660, h: 320 })

        // 上层渲染
        let layout_card = pg.view.find(layer, 'layout_card')
        let list = data.options.concat();
        let card = pg.view.find(layer, 'card');
        list.forEach((dt, i) => {
            dt.idx = i;
            let item = pg.view.clone(card);
            item.active = true;
            item.x = posArray[i];
            item.y = posY;
            item.data = dt;
            layout_card.addChild(item);
            this.updateCard(item, dt);
        })
    }

    updateCard(item, data) {
        item.data = data;
        let text = pg.view.find(item, 'text');
        let image = pg.view.find(item, 'image');
        let image_text_image = pg.view.find(item, 'image_text_image');
        let image_text_text = pg.view.find(item, 'image_text_text');
        pg.view.visible(text, data.type == 'txt');
        pg.view.visible(image, data.type == 'img');
        pg.view.visible(image_text_image, data.type == 'img_txt');
        pg.view.visible(image_text_text, data.type == 'img_txt');
        if (data.type == "img") {
            pg.view.setNetImg(image, data.image, { w: 240, h: 350 })
        } else if (data.type == 'txt') {
            pg.view.setString(text, data.text)
        } else {
            pg.view.setString(image_text_text, data.text)
            pg.view.setNetImg(image_text_image, data.image, { w: 240, h: 270 })
        }
    }
    private currentDt: any;
    private currentItem: any;

    @property(cc.Node)
    private gou_node: cc.Node = null;
    @property(cc.Node)
    private btn_start: cc.Node = null;
    onTouchStart(e) {
        if (this.touchForbid) return;// 顶级禁止全部点击
        this.playLocalAudio("touch")
        cc.Tween.stopAllByTarget(this.btn_start)
        this.btn_start.scale = 1;
        this.touchForbid = true;
        // 处理问题
        let image = pg.view.find(this.btn_start, 'image');
        cc.tween(image).by(0.1, { y: -50 }).by(0.1, { y: 50 }).start();

        // 从剩余的item中取出一个执行。
        let layer = this.CurrentLayer;
        let layout_card = pg.view.find(layer, 'layout_card')
        let list = layout_card.children.concat()
            .sort((A, B) => Math.random() - 0.5)
            .sort((A, B) => Math.random() - 0.5)
            .sort((A, B) => Math.random() - 0.5)
            .sort((A, B) => Math.random() - 0.5)
            .sort((A, B) => Math.random() - 0.5);
        let item = list[0];
        this.onTouchCard({ target: item })
    }
    onTouchCard(e) {
        let item = e.target;
        let data = item.data;
        this.currentItem = item;
        this.currentDt = data;
        this.touchForbid = true;


        this.playLocalAudio("move")
        cc.tween(this.gou_node)
            // 移动钩子  
            .to(0.5, { x: item.x })
            // 下钩
            .to(0.5, { y: item.y + item.height / 2 })
            // 播放钩子动画
            .call(() => {
                pg.view.visible(pg.view.find(this.gou_node, 'img'), false);
                pg.view.visible(pg.view.find(this.gou_node, 'ani'), true);
                let ani = pg.view.playDBAnimation(pg.view.find(this.gou_node, 'ani'), 'newAnimation', 1);
                ani.timeScale = 1;
            })
            .delay(0.7)
            // 等待动画
            .call(() => {
                this.touchForbid = false;
                // showRecord 传递坐标  执行内部动画效果
                this.showRecord(item);
            })
            .to(0.3, { y: item.y + item.height / 2 + 50 })
            // 获取图片坐标后隐藏
            .call(() => {
                let ani = pg.view.playDBAnimation(pg.view.find(this.gou_node, 'ani'), 'newAnimation', 1);
                ani.timeScale = -1;
            })
            .delay(1)
            .call(() => {
                // pg.view.playDBAnimation(pg.view.find(this.gou_node, 'ani'), 'newAnimation', 1);
                pg.view.visible(pg.view.find(this.gou_node, 'img'), true);
                pg.view.visible(pg.view.find(this.gou_node, 'ani'), false);
            })
            // 钩子移动回去
            .to(0.5, { y: this.gou_node.orgPos.y })
            .to(0.5, { x: this.gou_node.orgPos.x })
            .start();
    }

    @property(cc.Node)
    private layout_record: cc.Node = null;
    @property(cc.Node)
    private btn_close: cc.Node = null;
    showRecord(item) {

        let startPos = cc.v2(item);
        cc.tween(item).to(0.3, { y: startPos.y + 50 }).call(() => {
            this.playBgmP10();

            item.active = false;
            item.y = startPos.y;

            this.layout_record.active = true;
            // 卡片显示
            let bg = pg.view.find(this.layout_record, 'bg')
            bg.opacity = 0;
            cc.tween(bg).to(0.5, { opacity: 155 }).start();


            let card = pg.view.find(this.layout_record, 'card')
            this.updateCard(card, this.currentDt)

            let endPos = cc.v2(card);
            let startScale = item.width / card.width
            card.scale = startScale;
            card.x = startPos.x;
            card.y = startPos.y + 50;

            cc.tween(card).delay(0.3).to(0.5, { x: endPos.x, y: endPos.y, scale: 1.7 }).start();

            // 音频处理
            let btn_voice = pg.view.find(this.layout_record, 'btn_voice')
            btn_voice.data = this.currentDt;
            // 展示待录音内容
            let normal = pg.view.find(btn_voice, 'normal')
            let ing = pg.view.find(btn_voice, 'ing')
            btn_voice.scale = 0;
            cc.tween(btn_voice).to(0.3, { scale: 1.5 }).start();
            pg.view.visible(normal, true)
            pg.view.visible(ing, false)
            cc.tween(normal)
                .repeatForever(
                    cc.tween()
                        .to(0.2, { angle: -18 })
                        .to(0.2, { angle: 0 })
                        .to(0.2, { angle: 18 })
                        .to(0.2, { angle: 0 })

                        .to(0.2, { angle: -18 })
                        .to(0.2, { angle: 0 })
                        .to(0.2, { angle: 18 })
                        .to(0.2, { angle: 0 })

                        .to(0.2, { angle: -18 })
                        .to(0.2, { angle: 0 })
                        .to(0.2, { angle: 18 })
                        .to(0.2, { angle: 0 })
                        .delay(1)
                )
                .start();
            pg.view.touchOn(btn_voice, this.onTouchCardRecord, this)

        }).start();


    }
    onTouchRecordClose() {
        this.playBgmP100();
        this.layout_record.active = false;
        this.currentItem && (this.currentItem.active = true)
    }
    // current  和 currentCard
    btn_voice_time_id: any;
    currentCard: cc.Node;
    // 此处处理将api封装至专用文件
    onTouchCardRecord(e) {
        if (this.touchForbid) return;// 顶级禁止全部点击
        if (this.btn_voice_time_id) {
            clearTimeout(this.btn_voice_time_id)
            this.btn_voice_time_id = null;
        }
        this.pauseBgm();
        // 录音
        let btn_voice = e.target;
        let normal = pg.view.find(btn_voice, 'normal')
        let ing = pg.view.find(btn_voice, 'ing')
        this.playLocalAudio("touch_voice")
        this.checkCardsTime = 999999;
        hw.record.startTest(this.currentDt.text).then((isSuccess) => {
            if (!isSuccess) {
                this.recording = false;
                // 录音中
                hw.record.endTest().then((recordData: any) => {
                    this.currentDt.recordData = recordData;
                    this.currentCard = null;
                    pg.view.visible(normal, true);
                    pg.view.visible(ing, false);
                    let ingBg = pg.view.find(ing, 'bg');
                    ingBg.getComponent(ImgAuto).playVoiceEnd();
                    let score = recordData.result.overall
                    this.updatePopAni(null, score);
                    this.checkCardsTime = 3;
                    this.scheduleOnce(() => {
                        this.resumeBgm();
                        this.playBgmP100();
                    }, 0.1)
                })
            } else {
                this.recording = true;
                pg.view.visible(normal, false);
                pg.view.visible(ing, true);
                let ingBg = pg.view.find(ing, 'bg');
                ingBg.getComponent(ImgAuto).playVoiceStart();
            }
        })
    }
    private showFires: any;
    updatePopAni(front, score) {
        // let btn_play = pg.view.find(front, 'btn_play')
        // let result = pg.view.find(btn_play, 'result')
        let layout_ani = pg.view.find(this, 'layout_ani')
        layout_ani.active = true;

        if (score >= 90) {
            hw.log.d("非常棒")
            let item = pg.view.find(layout_ani, 'JJ_Excellent_ske')
            item.active = true;
            pg.view.playDBAnimation(item, 'newAnimation', 1);
            this.playLocalAudio("record_right")
            this.recordExcellent();
        } else if (score >= 60) {
            hw.log.d("干的不错")
            let item = pg.view.find(layout_ani, 'JJ_Good_ske')
            item.active = true;
            pg.view.playDBAnimation(item, 'newAnimation', 1);
            this.playLocalAudio("record_right")
            this.recordExcellent();
        } else {
            hw.log.d("再试一次吧")
            let item = pg.view.find(layout_ani, 'JJ_Tryagain_ske')
            item.active = true;
            pg.view.playDBAnimation(item, 'better', 1);
            this.playLocalAudio("record_wrong")
            this.recordTryAgain();
        }
    }
    recordExcellent() {
        this.currentItem.parent = null;
        this.currentItem = null;
        // 卡片显示
        let bg = pg.view.find(this.layout_record, 'bg')
        let btn_voice = pg.view.find(this.layout_record, 'btn_voice')
        let card = pg.view.find(this.layout_record, 'card')

        cc.tween(btn_voice).to(0.3, { scale: 0 }).start();
        cc.tween(card).to(0.3, { scale: 0 }).start();
        cc.tween(bg).delay(0.2).to(0.3, { opacity: 0 }).call(() => {
            bg.opacity = 155;
            btn_voice.scale = 1;
            card.scale = 1;
            this.onTouchRecordClose();
        }).start();

        // 判定是否游戏结束
        if (this.isAllOver()) {
            this.gameOver();
        }
    }
    recordTryAgain() {
        // this.onTouchRecordClose();
    }

    private currentPlayAudioId: any;
    onTouchCardPlay(e) {
        if (this.touchForbid) return;// 顶级禁止全部点击
        // 播放
        let btn_play = e.target;
        let layer = btn_play.parent;
        let play = pg.view.find(btn_play, 'play');
        let stop = pg.view.find(btn_play, 'stop');
        let data = layer.data;
        let recordData = data.recordData;
        if (!recordData) return;
        if (this.onTouchCardPlayEnd(layer)) {
            this.currentCard = null;
            return;
        }
        // 播放音频
        play.active = false;
        stop.active = true;
        this.checkCardsTime = 9999999;
        pg.audio.playAudioByUrl(recordData.audioUrl, () => {
            this.currentCard = null;
            this.checkCardsTime = 3;
            this.onTouchCardPlayEnd(layer);
        }, (audioId) => {
            this.currentPlayAudioId = audioId;
        })
    }
    onTouchCardPlayEnd(layer) {
        let data = layer.data;
        let btn_play = pg.view.find(layer, 'btn_play');
        let play = pg.view.find(btn_play, 'play');
        let stop = pg.view.find(btn_play, 'stop');
        let recordData = data.recordData;
        if (!recordData) return false;
        if (!this.currentPlayAudioId) return false;
        pg.audio.stopAuidoByUrl(this.currentPlayAudioId);
        this.currentPlayAudioId = null;
        play.active = true;
        stop.active = false;
        return true;
    }

    // 顶部音频播放
    onTouchVoice(e) {
        return new Promise((resolve) => {
            // console.log(this.voiceTouchForbid)
            // if (this.voiceTouchForbid) return;
            // let btn_voice = e.target;
            // let com = btn_voice.getComponent(ImgAuto);
            // com.playVoiceStart();
            // pg.audio.playAudioByUrl(this.CurrentData.audio, () => {
            //     this.currentAudioId = null;
            //     com.playVoiceEnd();
            //     resolve(true);
            // }, (audioId) => {
            //     this.currentAudioId = audioId;
            // })
        })
    }


    //--------------------------------左右滑动----------------------------------
    // 播放中不让点
    // 录音中不让点
    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) {
            console.log("nextPage")
            this.nextPage();
        } else if (move.x > 10) {
            console.log("lastPage")
            this.lastPage();
        }
    }
    lastPage() {
        if (this.touchForbid) return;
        this.touchForbid = true;
        if (!this.LastData) {
            this.touchForbid = false;
            return;
        }
        if (this.recording) {
            this.scheduleOnce(() => {
                this.touchForbid = false;
            }, 0.1)
            hw.util.showTipNodeAuto(pg.view.find(this, 'tip_record'), 'tip')
            return;
        }
        pg.hw.playLocalAudio("arrow")
        // 停止当前所有动作
        this.preLayer();
    }
    nextPage() {
        if (this.touchForbid) return;
        this.touchForbid = true;
        if (!this.NextData) {
            this.touchForbid = false;
            return;
        }
        if (this.recording) {
            this.scheduleOnce(() => {
                this.touchForbid = false;
            }, 0.1)
            hw.util.showTipNodeAuto(pg.view.find(this, 'tip_record'), 'tip')
            return;
        }
        pg.hw.playLocalAudio("arrow")
        this.nextLayer();
    }

    //--------------------------------界面及数据入口
    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]
    }

    // 基础组件
    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);
            });
        })
    }


    @property(cc.Node)
    bgmNode: cc.Node = null;
    playBgmP10() {
        let vol = cc.audioEngine.getMusicVolume();
        if (vol < 0.7) return;
        this.scheduleOnce(() => {
            cc.audioEngine.setMusicVolume(0.8);
            this.scheduleOnce(() => {
                cc.audioEngine.setMusicVolume(0.6);
                this.scheduleOnce(() => {
                    cc.audioEngine.setMusicVolume(0.4);
                    this.scheduleOnce(() => {
                        cc.audioEngine.setMusicVolume(0.2);
                        this.scheduleOnce(() => {
                            cc.audioEngine.setMusicVolume(0.1);
                        }, 0.4)
                    }, 0.4)
                }, 0.4)
            }, 0.4)
        }, 0.4)
    }
    pauseBgm() {
        // cc.audioEngine.pauseMusic();
        cc.audioEngine.stopMusic();
    }
    resumeBgm() {
        // cc.audioEngine.resumeMusic();
        cc.audioEngine.playMusic(this.bgmNode.getComponent(cc.AudioSource).clip, true);
    }
    playBgmP100() {
        let vol = cc.audioEngine.getMusicVolume();
        if (vol > 0.9) return;
        this.scheduleOnce(() => {
            cc.audioEngine.setMusicVolume(0.2);
            this.scheduleOnce(() => {
                cc.audioEngine.setMusicVolume(0.4);
                this.scheduleOnce(() => {
                    cc.audioEngine.setMusicVolume(0.6);
                    this.scheduleOnce(() => {
                        cc.audioEngine.setMusicVolume(0.8);
                        this.scheduleOnce(() => {
                            cc.audioEngine.setMusicVolume(1);
                        }, 0.4)
                    }, 0.4)
                }, 0.4)
            }, 0.4)
        }, 0.4)
    }
}











