import DaDianScript from "../../../../FrameWork/Base/DaDianScript";
import WordGameBaseComponent from "../../../../FrameWork/Base/WordGameBaseComptent";
import { ryw_Event } from "../../../../FrameWork/Event/EventEnum";
import EventMgr from "../../../../FrameWork/Event/EventMgr";
import Common from "../../../../FrameWork/Util/Common";
import Common5 from "../../../../Platform/th/Common5";
import Game from "../../../../Scripts/WenZiRes/ui/Game";
import CccGame from "../../../WordGame/gameComScript/CccGame/CccGame";
import logPrefabScript from "../../../WordGame/gameComScript/logPrefabScript";

const { ccclass, property } = cc._decorator;

@ccclass
export default class GuGuaLaoRen extends WordGameBaseComponent {
    @property(cc.Node)
    layerNode: cc.Node[] = [];

    @property(cc.Node)
    operateNodeList: cc.Node[] = [];

    //当前层级下标
    curLayerIndex = 0;
    //当前进度
    curSchedule: number = 0;
    curScheduleL: number = 0;
    curScheduleR: number = 0;
    endIndex: string = null;

    //文本配置
    titleArrayConfig: string[] = [];
    duihuaArrayConfig: any[] = [];
    chadianArrayConfig: any[] = [];
    wrongAnswerConfig: string[] = [];
    answersIndexConfig: number[] = [];

    start() {
        super.start();
        DaDianScript.userEnterDaDian();
        //this.openTouchEvent(this.node.getChildByName('bg'));
        Common5.stopMusic();

        Common5.getJsonFromBundle(Common5.selectGameInfo.bundle, 'script/GuGuaLaoRenConfig', (assest) => {
            this.jsonData = assest.json;
            this.initParameters();
            this.initComponent();
        })

    }

    //初始化参数
    initParameters() {
        this.curLayerIndex = 0;
        this.curSchedule = 0;
        this.curScheduleL = 0;
        this.curScheduleR = 0;

        this.titleArrayConfig = this.jsonData.titleArray;
        this.duihuaArrayConfig = this.jsonData.duihuaArray;
        this.chadianArrayConfig = this.jsonData.chadianArray;
        this.wrongAnswerConfig = this.jsonData.wrongAnswer;
        this.answersIndexConfig = this.jsonData.answersIndex;

        Common.Type = 0
        Common.subLevel = this.curLayerIndex;
        Common.GameSubTipConfigs = this.jsonData.tipsArray;
        Common.GameSubAnswerConfigs = this.jsonData.answersArray;

        EventMgr.onEvent_custom(ryw_Event.NormalTouchMoveCheck, (data_) => {
            this.normalTouchCallback(data_.targetNode);
        }, this);

        EventMgr.onEvent_custom(ryw_Event.NormalTouchEndCheck, (data_) => {
            this.normalTouchCallback(data_.targetNode);
        }, this);

        EventMgr.onEvent_custom(ryw_Event.DirectTouchMoveCheck, (data_) => {
            this.normalTouchCallback(data_.targetNode);
        }, this);

        EventMgr.onEvent_custom(ryw_Event.timeOut, (tab) => {
            this.endGameView(0);
        }, this);
    }

    //初始化组件
    initComponent() {
        for (const node of this.layerNode) {
            node.active = false;
        }
        let node = this.layerNode[this.curLayerIndex];
        node.active = true;

        Game.ins.setGameTitle(this.titleArrayConfig[0]);
        //Common5.playMusicCustom(Common5.selectGameInfo.bundle, 'sound/背景音');

        this.refreshLayer();
    }

    refreshLayer() {
        let node = this.layerNode[this.curLayerIndex];
        node.active = true;

        if (this.curLayerIndex == 0) {
            this.node.getChildByName('inputBlock').active = true;
            this.showDuiHua(this.duihuaArrayConfig[0], () => {
                this.node.getChildByName('inputBlock').active = false;
            });

            const checkNodeList1 = [
                this.getLayerChild('chadianNodeList', '儿子'),
                this.getLayerChild('chadianNodeList', '地面'),
                this.getLayerChild('chadianNodeList', '吊灯'),
                this.getLayerChild('chadianNodeList', '杜宾'),
                this.getLayerChild('chadianNodeList', '水缸'),
                this.getLayerChild('chadianNodeList', '外套老大爷'),
                this.getLayerChild('chadianNodeList', '外套老大爷馒头'),
                this.getLayerChild('chadianNodeList', '羽绒服老大爷'),
                this.getLayerChild('chadianNodeList', '羽绒服老大爷牛肉')
            ]
            const checkNodeList2 = [
                this.getLayerChild('chadianNodeList', '女儿'),
                this.getLayerChild('chadianNodeList', '地面2'),
                this.getLayerChild('chadianNodeList', '凳子'),
                this.getLayerChild('chadianNodeList', '窗户'),
                this.getLayerChild('chadianNodeList', '金项链'),
                this.getLayerChild('chadianNodeList', '外套老大爷'),
                this.getLayerChild('chadianNodeList', '外套老大爷馒头'),
                this.getLayerChild('chadianNodeList', '羽绒服老大爷'),
                this.getLayerChild('chadianNodeList', '羽绒服老大爷牛肉')
            ]
            for (const iterator of this.getLayerChild('money1').children) {
                let callbacks = CccGame.onNodeTouchMoreCheckEvent(iterator, checkNodeList1);
                callbacks.setSuccessListener((data_) => {
                    this.nodeCheckSuccessCallback1(data_.targetNode);
                });
            }
            for (const iterator of this.getLayerChild('money2').children) {
                let callbacks = CccGame.onNodeTouchMoreCheckEvent(iterator, checkNodeList2);
                callbacks.setSuccessListener((data_) => {
                    this.nodeCheckSuccessCallback2(data_.targetNode);
                });
            }
        } else if (this.curLayerIndex == 1) {
            this.getLayerChild(this.endIndex).active = true;
            if (this.endIndex == "end1") {
                this.showDuiHua(this.duihuaArrayConfig[5], () => {
                    this.endGameView(0);
                });
            } else if (this.endIndex == "end2") {
                this.showDuiHua(this.duihuaArrayConfig[6], () => {
                    this.endGameView(0);
                });
            } else if (this.endIndex == "end3") {
                this.showDuiHua(this.duihuaArrayConfig[7], () => {
                    this.endGameView(0);
                });
            } else if (this.endIndex == "end4") {
                this.showDuiHua(this.duihuaArrayConfig[8]);
                this.showDuiHua(this.duihuaArrayConfig[9], () => {
                    this.endGameView(1);
                });
            }
        }
    }

    nodeCheckSuccessCallback1(targetNode: cc.Node) {
        const others = ['外套老大爷', '外套老大爷馒头', '羽绒服老大爷', '羽绒服老大爷牛肉'];
        const checkLogic = {
            儿子: () => {
                this.getLayerChild('左边破烂背景', '破旧人物男').active = false;
                this.getLayerChild('左边破烂背景', '正常人物男').active = true;
                this.curScheduleL++;
                this.determine();
            },
            地面: () => {
                this.getLayerChild('左边破烂背景', '左边豪华背景').active = true;
                this.curScheduleL++;
                this.determine();
            },
            吊灯: () => {
                this.getLayerChild('左边破烂背景', '灯泡').active = false;
                this.getLayerChild('左边破烂背景', '吊灯').active = true;
                this.curScheduleL++;
                this.determine();
            },
            杜宾: () => {
                this.getLayerChild('左边破烂背景', '瘦狗').active = false;
                this.getLayerChild('左边破烂背景', '胖狗').active = true;
                this.curScheduleL++;
                this.determine();
            },
            水缸: () => {
                this.getLayerChild('左边破烂背景', '水缸').active = false;
                this.getLayerChild('左边破烂背景', '冰箱').active = true;
                this.curScheduleL++;
                this.determine();
            },
            default: (nodeName: string) => {
                console.log("[GameReport]++++++++++++++++++++++>" + nodeName);
                const index = others.indexOf(nodeName);
                if (index < 3) {
                    this.getLayerChild('chadianNodeList', others[index + 1]).active = true;
                }
                CccGame.playAnimation2(this.getLayerChild('老人'), nodeName, true);
                this.determine();
            }
        }

        console.log("[GameReport]++++++++++++++++++++++>" + targetNode['checkNode'].name);
        if (others.includes(targetNode['checkNode'].name)) {
            checkLogic.default(targetNode['checkNode'].name);
        } else {
            checkLogic[targetNode['checkNode'].name]?.();
        }
    }

    nodeCheckSuccessCallback2(targetNode: cc.Node) {
        const others = ['外套老大爷', '外套老大爷馒头', '羽绒服老大爷', '羽绒服老大爷牛肉'];
        const checkLogic = {
            女儿: () => {
                this.getLayerChild('右边破烂背景', '破旧人物女').active = false;
                this.getLayerChild('右边破烂背景', '正常人物女').active = true;
                this.getLayerChild('chadianNodeList', '金项链').active = true;
                this.curScheduleR++;
                this.determine();
            },
            地面2: () => {
                this.getLayerChild('右边破烂背景', '右边豪华背景').active = true;
                this.curScheduleR++;
                this.determine();
            },
            凳子: () => {
                this.getLayerChild('右边破烂背景', '木凳子').active = false;
                this.getLayerChild('右边破烂背景', '沙发').active = true;
                this.curScheduleR++;
                this.determine();
            },
            窗户: () => {
                this.getLayerChild('右边破烂背景', '旧窗户').active = false;
                this.getLayerChild('右边破烂背景', '新窗户').active = true;
                this.curScheduleR++;
                this.determine();
            },
            金项链: () => {
                this.getLayerChild('右边破烂背景', '正常人物女').active = false;
                this.getLayerChild('右边破烂背景', '豪华人物女').active = true;
                this.curScheduleR++;
                this.determine();
            },
            default: (nodeName: string) => {
                console.log("[GameReport]++++++++++++++++++++++>" + nodeName);
                const index = others.indexOf(nodeName);
                if (index < 3) {
                    this.getLayerChild('chadianNodeList', others[index + 1]).active = true;
                }
                CccGame.playAnimation2(this.getLayerChild('老人'), nodeName, true);
                this.determine();
            }
        }

        console.log("[GameReport]++++++++++++++++++++++>" + targetNode['checkNode'].name);
        if (others.includes(targetNode['checkNode'].name)) {
            checkLogic.default(targetNode['checkNode'].name);
        } else {
            checkLogic[targetNode['checkNode'].name]?.();
        }
    }

    //触摸回调
    normalTouchCallback(targetNode: cc.Node) {
        const itemLogic = {
            default: () => {
            },
        }

        console.log("+++++++++++++++++++++>" + targetNode.name);
        itemLogic[targetNode.name]?.();
    }

    determine() {
        this.curSchedule++;
        if (this.curSchedule < 10) {
            return;
        }

        this.node.getChildByName("inputBlock").active = true;
        if (this.curScheduleL > this.curScheduleR) {
            this.showDuiHua(this.duihuaArrayConfig[1], () => {
                this.showDuiHua(this.duihuaArrayConfig[2], () => {
                    this.endIndex = "end1";
                    this.nextLayer();
                });
            });
        } else if (this.curScheduleL < this.curScheduleR) {
            this.showDuiHua(this.duihuaArrayConfig[3], () => {
                this.showDuiHua(this.duihuaArrayConfig[4], () => {
                    this.endIndex = "end2";
                    this.nextLayer();
                });
            });
        } else {
            if (this.curScheduleL > 3) {
                this.endIndex = "end3";
                this.nextLayer();
            } else {
                this.endIndex = "end4";
                this.nextLayer();
            }
        }
    }

    //显示对话
    showDuiHua(curLog, func?) {
        console.log("curLog==", curLog);

        if (curLog.effectUrl) {
            Common5.playEffectCustom(Common5.selectGameInfo.bundle, curLog.effectUrl);
        }

        let string_ = curLog.str;
        let qiPaoPos_ = curLog.qiPaoPos;
        let delayTime_ = curLog.delayTime || 3;

        let node = this.layerNode[this.curLayerIndex];
        if (qiPaoPos_ != -1) {
            let qiPao = node.getChildByName("qiPao").getChildByName("qiPao_" + qiPaoPos_);
            qiPao.stopAllActions()
            qiPao.getChildByName("str").getComponent(cc.Label).string = string_
            cc.tween(qiPao)
                .set({ active: true, scale: 0 })
                .to(0.2, { scale: 1 })
                .delay(delayTime_)
                .set({ active: false })
                .start();
        }
        else {
            let logPrefab = this.node.getChildByName('logPrefab');
            let script_: logPrefabScript = logPrefab.getComponent('logPrefabScript');
            script_.setDailogShow(string_, delayTime_);
        }

        this.scheduleOnce(() => {
            if (func) {
                func();
            }
        }, delayTime_);
    }

    //获取当前场景下的节点
    getLayerChild(...path: string[]) {
        let child = this.layerNode[this.curLayerIndex];
        if (path.length > 1) {
            for (const name of path) {
                child = child.getChildByName(name);
            }
            return child;
        }
        return child.getChildByName(path[0]);
    }

    //跳转场景
    nextLayer() {
        this.curLayerIndex++;
        for (let i = 0; i < this.layerNode.length; i++) {
            if (this.layerNode[i].active) {
                cc.tween(this.layerNode[i])
                    .delay(1.0)
                    .to(1, { opacity: 0 })
                    .call(() => {
                        this.layerNode[i].active = false;
                        this.refreshLayer();
                    })
                    .start();
            } else {
                this.layerNode[i].active = false;
            }
        };
    }

    //结束弹窗
    endGameView(touchIndex) {
        this.node.getChildByName("inputBlock").active = true;
        Game.ins.stopTime();
        if (touchIndex == 0) {
            Game.ins.showFail();
        } else {
            Game.ins.showSuccess();
        }
    }

    //解锁提示
    unlockLevel(sublevel) {
        Game.ins.tipUnlock(sublevel)
    }

    openTouchEvent(node) {
        node.on(cc.Node.EventType.TOUCH_START, this.touchStartNode, this)
        node.on(cc.Node.EventType.TOUCH_MOVE, this.touchMoveNode, this)
        node.on(cc.Node.EventType.TOUCH_CANCEL, this.touchEndNode, this)
        node.on(cc.Node.EventType.TOUCH_END, this.touchEndNode, this)
    }

    closeTouchEvent(node: cc.Node) {
        node.off(cc.Node.EventType.TOUCH_START, this.touchStartNode, this)
        node.off(cc.Node.EventType.TOUCH_MOVE, this.touchMoveNode, this)
        node.off(cc.Node.EventType.TOUCH_CANCEL, this.touchEndNode, this)
        node.off(cc.Node.EventType.TOUCH_END, this.touchEndNode, this)
    }

    touchStartNode(event) {
        let target = event.target;
        console.log('touchStartNode');
    }

    touchMoveNode(event) {

    }

    touchEndNode(event) {
        let target = event.target;
        let logPrefab = this.node.getChildByName('logPrefab');
        logPrefab.getChildByName('duihua').active = false;
    }

    onClick(event) {
        let target = event.target as cc.Node;
        console.log("+++++++++++++++++++++>" + target.name);
        Common5.playEffect("点击音效");
        switch (target.name) {
            case "BtnAddTimes":
            default:
                break;
        }
    }

    //update(dt) { }
}