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 HuaZi extends WordGameBaseComponent {
    @property(cc.Node)
    layerNode: cc.Node[] = [];

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

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

    start() {
        super.start();
        DaDianScript.userEnterDaDian();
        Common5.stopMusic();

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

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

        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 = 3;
        Common.subLevel = 0;
        Common.GameSubTipConfigs = 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;
        }

        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.showDuiHua(this.duihuaArrayConfig[1], () => {
                    this.node.getChildByName('inputBlock').active = false;
                });
            });
        } else if (this.curLayerIndex == 1) {
            const checkNodeList = [
                this.getLayerChild('chadianNodeList', '小花'),
                this.getLayerChild('chadianNodeList', '婶娘')
            ]

            for (let index = 0; index < this.getLayerChild('prop').childrenCount; index++) {
                const element = this.getLayerChild('prop').children[index];
                let callbacks = CccGame.onNodeTouchMoreCheckEvent(element, checkNodeList, { touchIndex: index });
                callbacks.setSuccessListener((data_) => {
                    this.nodeCheckSuccessCallback(data_.targetNode);
                });
            }

            this.node.getChildByName('inputBlock').active = true;
            this.showDuiHua(this.duihuaArrayConfig[4], () => {
                this.node.getChildByName('inputBlock').active = false;
                this.getLayerChild('prop').children[this.curSchedule].active = true;
            });

            Common5.playMusicCustom(Common5.selectGameInfo.bundle, 'sound/场景二背景音');
        } else if (this.curLayerIndex == 2) {
            this.showDuiHua(this.duihuaArrayConfig[5], () => {
                this.endGameView(1);
            });
        }
    }

    //节点检测成功回调
    nodeCheckSuccessCallback(targetNode: cc.Node) {

        targetNode['checkNode'].active = true;
        console.log("+++++++++++++++++++++>" + targetNode.name);

        if (targetNode.name == '护肤品') {
            if (targetNode['checkNode'].name == '小花') {
                this.getLayerChild('role', '小花', "脸1").active = true;
            } else {
                this.getLayerChild('婶娘', "脸1").active = true;
            }
        } else if (targetNode.name == '新衣服') {
            if (targetNode['checkNode'].name == '小花') {
                this.getLayerChild('role', '小花', "衣服").active = true;
                this.getLayerChild('role', '小花', "手1", '袖子1').active = true;
                this.getLayerChild('role', '小花', "手2", '袖子2').active = true;
            } else {
                this.getLayerChild('婶娘', "新衣服").active = true;
                this.getLayerChild('婶娘', "袖子1").active = false;
                this.getLayerChild('婶娘', "袖子2").active = true;
            }
        } else if (targetNode.name == '花') {
            if (targetNode['checkNode'].name == '小花') {
                this.getLayerChild('role', '小花', "花").active = true;
                this.getLayerChild('role', '小花', "手1").active = false;
                this.getLayerChild('role', '小花', "手2").active = true;
            } else {
                this.getLayerChild('婶娘', "花").active = true;
            }
        }

        const correctChooseList = ['小花', '小花', '婶娘', '小花', '婶娘', '小花', '婶娘', '婶娘'];
        if (targetNode['checkNode'].name != correctChooseList[this.curSchedule]) {
            this['fail'] = true;
            Common.SpeTip = this.wrongAnswerConfig[0] || '';
        } else {
            this.unlockLevel(this.answersIndexConfig[this.curSchedule + 1]);
        }

        let log = this.chadianArrayConfig[targetNode['touchIndex']][0];
        if (targetNode['checkNode'].name == '小花') {
            log = this.chadianArrayConfig[targetNode['touchIndex']][1];
        }
        this.showDuiHua(log, () => {
            this.curSchedule++;
            if (this.curSchedule == correctChooseList.length) {
                if (this['fail']) {
                    this.showDuiHua(this.duihuaArrayConfig[6], () => {
                        this.endGameView(0);
                    });
                } else {
                    this.getLayerChild('chadianNodeList2').active = true;
                }
            } else {
                this.getLayerChild('prop').children[this.curSchedule].active = true;
            }
        });
    }

    //触摸回调
    normalTouchCallback(targetNode: cc.Node) {
        const targetNameList = [''];
        const itemLogic = {
            领养协议: (target: cc.Node) => {
                if (target['checkNode'].name == '爷爷') {
                    target.active = false;
                    target['checkNode'].active = false;
                    this.unlockLevel(this.answersIndexConfig[0]);
                    this.showDuiHua(this.duihuaArrayConfig[2], () => {
                        this.nextLayer();
                    });
                } else {
                    this.showDuiHua(this.duihuaArrayConfig[3]);
                }
            },
            role: (target: cc.Node) => {
                this.unlockLevel(this.answersIndexConfig[8]);
                this.nextLayer();
            },
        }

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

    determine() {
        if (this["success"]) {
            this.showDuiHua(this.duihuaArrayConfig[12], () => {
                this.endIndex = '成功'
                this.nextLayer();
            });
        } else {
            this.showDuiHua(this.duihuaArrayConfig[11], () => {
                this.getLayerChild('chooseLayer').active = true;
            });
        }
    }

    //显示对话
    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)
    }

    //update(dt) { }
}