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 taskState from "../../Scripts/DH/taskState";
import TaskManager, { MainTaskIdEnum } from "../../Scripts/JuQingChat/TaskManager";
import PrefabManage, { GameType } from "../../Scripts/PrefabManager/PrefabManage";
import Game from "../../Scripts/WenZiRes/ui/Game";
import CccGame from "../../WenZiRes/WordGame/gameComScript/CccGame/CccGame";
import logPrefabScript from "../../WenZiRes/WordGame/gameComScript/logPrefabScript";
import tishi from "./tishi";




const { ccclass, property } = cc._decorator;

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

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

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

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

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

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

    //初始化参数
    initParameters() {
        this.curLayerIndex = 0;
        this.curSchedule = 0;
        this.curlayerIndex = 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 = 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;
        }
        let node = this.layerNode[this.curLayerIndex];
        node.active = true;

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

        this.node.getChildByName("inputBlock").active = true;
        this.showDuiHua(this.duihuaArrayConfig[10], () => {
            this.node.getChildByName("inputBlock").active = false;
        });

        this.getLayerChild('背景1', 'chadianNodeList').active = true;
    }

    //触摸回调
    normalTouchCallback(targetNode: cc.Node) {
        console.log("+++++++++++++++++++++>" + targetNode.name);

        // const targetNameList = ['窗帘', '水管', '卫生纸', '短裤', '风筝', '水管2', '蛇绳', '电线', '狗绳子', '丝袜绳'],
        const targetNameList = ['窗帘', '水管', '卫生纸', '短裤', '风筝', '水管2', '蛇绳', '电线', '狗绳子'],
            failNodeNameList = ['泡面', '藤蔓', '鞭炮'];
        const itemLogic = {
            男生1: (target: cc.Node) => {
                this.curSchedule++;
                if (this.curSchedule >= 10) {
                    this.getLayerChild('layout', 'role', '下滑女生').active = true;
                }
            },
            下滑女生: (target: cc.Node) => {
                this.getLayerChild('背景4', '男生2').active = false;
                this.getLayerChild('背景4', '公主抱').active = true;
                this.unlockLevel(this.answersIndexConfig[10]);
                this.showDuiHua(this.duihuaArrayConfig[9], () => {
                    this.endGameView(1);
                });
            },
            default: (target: cc.Node) => {
                const index = targetNameList.indexOf(target.name);
                this.unlockLevel(this.answersIndexConfig[index]);
                Common5.playEffectCustom('jiuzhumeinv', 'sound/物品放上去的音效');
                const prop = this.getLayerChild('道具栏', target.name);
                cc.tween(prop)
                    .set({ active: true, scale: 0.1, parent: this.getLayerChild('layout', 'props') })
                    .to(0.5, { scale: 1 })
                    .call(() => {
                        this.curSchedule++;
                        this.showDuiHua(this.duihuaArrayConfig[index]);
                        if (this.curSchedule >= 10) {
                            this.getLayerChild('layout', 'role', '下滑女生').active = true;
                            return;
                        }
                        const propNumbers = [3, 6, 8],
                            layerY = [0, 1050, 2100, 3150],
                            bg = ['背景1', '背景2', '背景3', '背景4'];
                        if (this.curSchedule >= propNumbers[this.curlayerIndex]) {
                            this.curlayerIndex++;
                            cc.tween(this.layerNode[0])
                                .to(0.5, { y: layerY[this.curlayerIndex] })
                                .call(() => {
                                    this.getLayerChild(bg[this.curlayerIndex], 'chadianNodeList').active = true;
                                })
                                .start();
                        }
                    })
                    .start();
                this.node.getChildByName("tipPrefab").getComponent(tishi).subLevel++
            },
            fail: (target: cc.Node) => {
                this.getLayerChild('layout', 'role', '呼吸').active = false;
                CccGame.playAnimation2(this.getLayerChild('layout', 'role', target.name), target.name, false);
                if (target.name == '鞭炮') {
                    Common5.playEffectCustom('jiuzhumeinv', 'sound/鞭炮');
                }
                this.scheduleOnce(() => {
                    Common5.playEffectCustom('jiuzhumeinv', 'sound/女惨叫');
                }, 1);
                this.scheduleOnce(() => {
                    // this.node.getChildByName("失败").active = true;
                    PrefabManage.loadPrefabByType(GameType.taskState, this.node, (node) => {
                        node.getComponent(taskState).showFail("任务失败", () => {
                            this.node.removeFromParent();
                            this.node.destroy()
                            PrefabManage.loadPrefabByType(GameType.JiuZhuMeiNv)
                        }, () => {
                            this.endGameView(1);
                        })
                    })
                    Common5.playEffectCustom('jiuzhumeinv', 'sound/错误');
                }, 2);
                // this.scheduleOnce(() => {
                //     // Game.ins.onRestartCallFunc();
                //     this.node.removeFromParent();
                // }, 3);

            }
        }

        if (failNodeNameList.includes(targetNode.name)) {
            itemLogic.fail(targetNode);
        } else if (targetNameList.includes(targetNode.name)) {
            itemLogic.default(targetNode);
        } else {
            itemLogic[targetNode.name]?.(targetNode);
        }
    }

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

        if (curLog.effectUrl) {
            Common5.playEffectCustom('jiuzhumeinv', 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]);
    }

    //结束弹窗
    endGameView(touchIndex) {
        if (touchIndex == 1) {
            PrefabManage.loadPrefabByType(GameType.taskState, this.node, (node) => {
                node.getComponent(taskState).showSuccess("", () => {
                    this.node.getChildByName("inputBlock").active = true;
                    let mainTaskInfo: any = TaskManager.getCurUnLockMainTaskInfo()
                    let mainId = mainTaskInfo.Id
                    if (mainId == MainTaskIdEnum.MainTask_543_2) {
                        TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_543_2)
                        TaskManager.setCurTask(MainTaskIdEnum.MainTask_544_1)
                        PrefabManage.showBlackGuoDu(() => {
                            PrefabManage.loadPrefabByType(GameType.DH_34)
                            this.node.removeFromParent()
                            this.node.destroy()
                        })
                    }
                })
            })
        }
        // Game.ins.stopTime();
        // PrefabManage.loadPrefabByType(GameType.DH_33)
        // 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;
        }
    }

    onTouchTips() {
        this.node.getChildByName("tipPrefab").active = true
        this.node.getChildByName("tipPrefab").getComponent(tishi).initText()
    }

    //update(dt) { }
}