import { asyncDelay, onHomeworkFinish } from "../script/util_jj16_lianci";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_jj16_lianci";
import pg from "./pg_jj16_lianci";
import hw from "./hw_jj16_lianci";
import ImgAuto from "./hwComponent/ImgAuto_jj16_lianci";

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

    }

    async onLoadEnd() {
        // 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<{
        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_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() {
        this.count = 0;
        this.touchForbid = true;
        this.voiceTouchForbid = true;
        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;
        if (!this.data.title) this.label_title.active = false;
        pg.view.setString(this.label_title, this.data.title)
    }
    @property(cc.Node)
    label_title: cc.Node = null;
    startGame() {
        this.voiceTouchForbid = false;
        this.startPlay();
    }
    private currentAudioId: any;
    startPlay() {
        // 自动播放顶部音频
        this.touchForbid = true;

        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_up = pg.view.find(layer, 'layout_up')
        layout_up.children.forEach(item => {
            if (item.data.state != "collider") isAllOver = false;
        })
        return isAllOver;
    }
    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.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")
            }
        })
    }

    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;

    updateLayer(layer, data, i) {
        if (!layer || !data) return;
        layer.data = data;
        // 根据数据来渲染  这里来增加按钮部分
        console.log("items");

        let btn_voice = pg.view.find(layer, "btn_voice");
        let btn_play = pg.view.find(layer, "btn_play");
        pg.view.touchOn(btn_voice, this.onTouchCardRecord, this);
        pg.view.touchOn(btn_play, this.onTouchCardPlay, this);

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

        // 上层渲染
        let layout_up = pg.view.find(layer, 'layout_up')
        let list = data.letterList.concat();
        let card = pg.view.find(layer, 'card');
        list.forEach((dt, i) => {
            dt.idx = i;
            dt.type = "up";
            let item = pg.view.clone(card);
            item.active = true;
            item.x = 0;
            item.y = 0;
            item.data = dt;
            layout_up.addChild(item);
            this.updateCard(item, dt);
        })

        this.scheduleOnce(() => {
            // 获取顶部得总长度，然后依次设定下方的坐标，

            let upWidth = layout_up.width;
            // 后期可以改造成按照宽度累加计算
            function getPos(itemParent, i) {
                let node = layout_up.children[i];
                // 转换成世界坐标后 转换回来
                let pos = pg.pos.getNodePosByTargetNode(itemParent, node)
                return pos;
            }

            // 下层渲染
            let layout_down = pg.view.find(layer, 'layout_down')
            let downList = layer.data.letterList.concat();
            downList.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)
                .sort((a, b) => Math.random() - 0.5)
            downList.forEach((dt, i) => {
                dt.idx = i;
                dt.type = "down";
                let item = pg.view.clone(card);
                item.active = true;
                item.x = getPos(layout_down, i).x;
                item.y = 0;
                item.orgPos = cc.v2(item.x, item.y)
                layout_down.addChild(item);
                this.updateCard(item, dt);
                item.data = dt;
                item.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
                item.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
                item.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
            })
        }, 0.1)
    }

    private currentItem: cc.Node;
    onTouchStart(event) {
        if (this.currentItem) return;
        console.log('1')
        let node = event.target;
        this.currentItem = node;
        this.startCurrentItemAni();
    }
    onTouchMove(event) {
        let node = event.target;
        if (node != this.currentItem) return;
        node.opacity = 255;
        let delta = event.touch.getDelta();
        let pos = cc.v2(delta);
        let scale = 1;
        pos.x /= scale;
        pos.y /= scale;
        node.x += pos.x;
        node.y += pos.y;
    }
    onTouchEnd(event) {
        let node = event.target;
        if (node != this.currentItem) return;
        this.stopCurrentItemAni();
        this.currentItem = null;
        // 跟字母区域进行碰撞检测
        let colliderNode = this.collider(node);
        // 获取当前待碰撞区域
        if (!!colliderNode) {
            // 碰撞的是当前item
            colliderNode.data.state = "collider"
            node.data.state = "collider"
            // // 正确了 需要处理效果
            this.playLocalAudio("right")
            let right = pg.view.find(colliderNode, "right");
            right.active = true;
            pg.view.playDBAnimation(right, "newAnimation", 1)
            // 移除node item更变状态
            this.updateCard(colliderNode, colliderNode.data);
            node.off(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
            node.off(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
            node.off(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
            node.parent = null;
            // 判定是否所有词都ok了
            if (this.isAllOver()) {
                this.showRecord(this.CurrentLayer);
            }
        } else {
            // pg.audio.playLocalAudio(pg.view.find(this.res_audio, "fail"))
            let subX = node.x - node.orgPos.x;
            let subY = node.y - node.orgPos.y;
            node.x -= subX;
            node.y -= subY;
        }
    }

    startCurrentItemAni() {
        let child = this.currentItem;
        cc.tween(child).to(0.15, { scaleX: 1.1, scaleY: 0.9 }).to(0.15, { scaleX: 1, scaleY: 1 }).delay(0.25).union().repeatForever().start();
    }
    stopCurrentItemAni() {
        let child = this.currentItem;
        cc.Tween.stopAllByTarget(child)
    }
    collider(node) {
        // 当前节点和库中所有节点进行碰撞
        let layer = this.CurrentLayer;
        let layout_up = pg.view.find(layer, 'layout_up')
        let layout_down = pg.view.find(layer, 'layout_down')
        let itemList = layout_up.children;

        let nodePos = cc.v2(node);
        let colliderItem = null;
        itemList.forEach(item => {
            if (!node.parent) return;
            if (item.data.state == "collider") return;
            let pos = pg.pos.getNodePosByTargetNode(node.parent, item);
            let width = item.width;
            let height = item.height;
            let maxX = pos.x + width / 2;
            let minX = pos.x - width / 2;
            let maxY = pos.y + height / 2;
            let minY = pos.y - height / 2;
            if (nodePos.x < maxX && nodePos.x > minX && nodePos.y < maxY && nodePos.y > minY) {
                if (item.data.text == node.data.text) {
                    colliderItem = item;
                }
            }
        })
        return colliderItem;
    }

    updateCard(item, data) {
        let item_0 = pg.view.find(item, 'item_0');
        let item_1 = pg.view.find(item, 'item_1');
        let item_0_text = pg.view.find(item_0, 'text');
        let item_1_text = pg.view.find(item_1, 'text');
        pg.view.setString(item_0_text, data.text);
        pg.view.setString(item_1_text, data.text);
        if (data.state == "collider") {
            pg.view.visible(item_0, false);
            pg.view.visible(item_1, true);
        } else {
            pg.view.visible(item_0, data.type == 'up');
            pg.view.visible(item_1, data.type == 'down');
        }
    }

    showRecord(layer) {
        // 展示待录音内容
        this.updateRecordBtns(layer);

        let btn_voice = pg.view.find(layer, "btn_voice");
        let normal = pg.view.find(btn_voice, 'normal')
        cc.tween(normal)
            .repeatForever(
                cc.tween()
                    .to(0.7, { scale: 1.1 })
                    .delay(0.3)
                    .to(0.7, { scale: 1.00 })
                    .delay(0.3)
            )
            .start();
        this.btn_voice_time_id = setTimeout(() => {
            if (!this.node || !this.node.parent) return;
            // 摇晃mic
            this.playLocalAudio("wait")
            cc.tween(normal).to(0.25, { angle: -15 }).to(0.25, { angle: 0 }).to(0.25, { angle: 15 }).to(0.25, { angle: 0 }).start();
        }, 3000);
    }
    // 前后切换一共有
    updateRecordBtns(layer) {
        let btn_voice = pg.view.find(layer, "btn_voice");
        let btn_play = pg.view.find(layer, "btn_play");
        let recordData = layer.data.recordData;
        if (recordData) {
            btn_voice.x = -60;
            pg.view.visible(btn_voice, true);
            pg.view.visible(btn_play, true);
        } else {
            btn_voice.x = 0;
            pg.view.visible(btn_voice, true);
            pg.view.visible(btn_play, false);
        }
    }
    // 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;
        }
        // 录音
        let btn_voice = e.target;
        let layer = btn_voice.parent;
        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(layer.data.text).then((isSuccess) => {
            if (!isSuccess) {
                this.recording = false;
                // 录音中
                hw.record.endTest().then((recordData: any) => {
                    layer.data.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();
                    this.updateRecordBtns(layer);
                    let score = recordData.result.overall
                    this.updatePopAni(layer, score);
                    this.checkCardsTime = 3;
                })
            } 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("非常棒")
            front.data.isChose = "right"
            pg.view.visible(pg.view.find(result, 'excellent'), true)
            pg.view.visible(pg.view.find(result, 'good'), false)
            pg.view.visible(pg.view.find(result, 'tryagain'), false)
            let item = pg.view.find(layout_ani, 'JJ_Excellent_ske')
            item.active = true;
            pg.view.playDBAnimation(item, 'newAnimation', 1);
            this.playLocalAudio("record_right")
        } else if (score >= 60) {
            hw.log.d("干的不错")
            front.data.isChose = "right"
            pg.view.visible(pg.view.find(result, 'excellent'), false)
            pg.view.visible(pg.view.find(result, 'good'), true)
            pg.view.visible(pg.view.find(result, 'tryagain'), false)
            let item = pg.view.find(layout_ani, 'JJ_Good_ske')
            item.active = true;
            pg.view.playDBAnimation(item, 'newAnimation', 1);
            this.playLocalAudio("record_right")
        } else {
            hw.log.d("再试一次吧")
            front.data.isChose = "wrong"
            pg.view.visible(pg.view.find(result, 'excellent'), false)
            pg.view.visible(pg.view.find(result, 'good'), false)
            pg.view.visible(pg.view.find(result, 'tryagain'), true)
            let item = pg.view.find(layout_ani, 'JJ_Tryagain_ske')
            item.active = true;
            pg.view.playDBAnimation(item, 'better', 1);
            this.playLocalAudio("record_wrong")
        }
        if (!this.showFires) this.showFires = {};
        if (!this.showFires[`${this.count}`]) {
            this.showFires[`${this.count}`] = true;
            hw.util.playEndTrebleFirework();
        }
    }
    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);
            });
        })
    }
}










