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";
// import JingDiaoXiaBaConfig from "./JingDiaoXiaBaConfig";

const { ccclass, property } = cc._decorator;

@ccclass
export default class TuDingShengFa extends WordGameBaseComponent {

    //当前层级下标
    curLayerIndex = 100;

    //当前进度
    curSchedule: number = 0;

    //文本配置
    titleArrayConfig: string[] = [];
    duihuaArrayConfig: any[] = [];
    chadianArrayConfig: any[] = [];
    isshowSuccess: boolean = false;
    kuZiNum:number = 0
    isDaiYanJing:boolean = false
    isMaoMiZaYun:boolean = false
    curWenDu:number = -50
    tw = null
    bundle = null
    start() {
        this.bundle = Common5.gameConfig.zmGameConfig[Common5.selectGameNum].bundle
        super.start();
        DaDianScript.userEnterDaDian();
        
        // this.openTouchEvent(this.node.getChildByName('bg'));
        Common5.getJsonFromBundle(Common5.selectGameInfo.bundle,'script/TuDingShengFaConfig',(assest)=>{
            this.jsonData = assest.json
            this.initParameters();
            this.initComponent();
        })
    
    }

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

        this.titleArrayConfig =  this.jsonData.titleArray //JingDiaoXiaBaConfig.getInstance().getGameConfig('titleArray') as string[];
        this.chadianArrayConfig = this.jsonData.chadianArray //JingDiaoXiaBaConfig.getInstance().getGameConfig('chadianArray') as any[];
        this.duihuaArrayConfig = this.jsonData.duihuaArray //JingDiaoXiaBaConfig.getInstance().getGameConfig('duihuaArray') as any[];

        Common.Type = 3;
        Common.subLevel = 0;
        Common.GameSubTipConfigs = this.jsonData.tipsArray //JingDiaoXiaBaConfig.getInstance().getGameConfig('tipsArray');
        // Common.GameSubAnswerConfigs = this.jsonData.answersArray //JingDiaoXiaBaConfig.getInstance().getGameConfig('answersArray');

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


    //初始化组件
    initComponent() {
        // let lab = this.node.getChildByName("标题").getChildByName("lab");
        // lab.getComponent(cc.Label).string = this.titleArrayConfig[0];

        Game.ins.setGameTitle(this.titleArrayConfig[0])

        for(let i=0;i<this.node.getChildByName('mainNode').childrenCount;i++){
            this.node.getChildByName('mainNode').children[i].zIndex = i
            this.node.getChildByName('mainNode').children[i].attr({bindZIndex:i})
        }
        let touchConfig = {
            touchNode:['花瓶','狗绳子','蜘蛛网','拖把','螺蛳粉',
            '盆栽','柳树1','狗毛','大葱','毛球'],

            fixedNode:['花瓶','狗绳','蜘蛛网','拖把','螺蛳粉',
            '盆栽','树枝','狗毛','大葱','毛球'],

            rightStepIndex:[
                '0','1','2','3','4',
                '5','6','7','8','9'
            ]
        }
        let girlNode = this.node.getChildByName('mainNode').getChildByName('光头女')
        for(let i=0;i<touchConfig.touchNode.length;i++){
            
            let touchArea = null
            // if(touchConfig.touchNode[i] == '纸箱'){
            //     touchArea = girlNode.getChildByName('touTouchArea')
            // }else if(touchConfig.touchNode[i] == '拖鞋1'){
            //     touchArea = girlNode.getChildByName('jiaoTouchArea')
            // }else{
            touchArea = girlNode.getChildByName('touTouchArea')
            // }
            this.openTouchEvent(this.node.getChildByName('mainNode').getChildByName(touchConfig.touchNode[i]),[touchArea],
            girlNode.getChildByName(touchConfig.fixedNode[i]),true,touchConfig.rightStepIndex[i])
        }
        this.openTouchEvent(this.node.getChildByName('mainNode').getChildByName('剪刀'),[this.node.getChildByName('mainNode').getChildByName('初始狗')],null,true,-1)
        this.openTouchEvent(this.node.getChildByName('mainNode').getChildByName('梳子'),[girlNode.getChildByName('touTouchArea')],null,true,-1)
        // this.openTouchEvent(this.node.getChildByName('mainNode').getChildByName('锤子'),[this.node.getChildByName('mainNode').getChildByName('锤子TouchArea')],null,true,-1)
        //this.showDuiHua(this.duihuaArrayConfig[0])
        // this.startTween()

        cc.tween(this.node.getChildByName('mainNode'))
            .delay(0.5)
            .call(()=>{
                Common5.playEffectCustom(this.bundle,'sound/手机消息')
                this.node.getChildByName('mainNode').getChildByName('shouJiFangDa').getChildByName('手机').active = true
            })
        .start()
    }
    startTween () {
        if (null == this.tw){
            let girlNode = this.node.getChildByName('mainNode').getChildByName('girlNode')
            this.tw = cc.tween(girlNode)
            .repeatForever(
                cc.tween()
                .by(0.1, { x: -3})
                .by(0.1, { x: 3})
            )
            .start()
        }
    }
    stopTween(){
        if (this.tw !=null){
            this.tw.stop();
            this.tw = null;
        }
    }

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

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

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

        let node = this.node.getChildByName('layerNode');
        if (qiPaoPos_ != -1) {
            let qiPao = node.getChildByName("qiPao").getChildByName("qiPao_" + qiPaoPos_);
            qiPao.stopAllActions()
            qiPao.getChildByName("str").getComponent(cc.Label).string = string_
            qiPao.active = true
            qiPao.scale = 0
            cc.tween(qiPao)
                .to(0.2, { scale: 1 })
                .delay(delayTime_)
                .call(() => {
                    qiPao.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_);
    }

    endGameView(touchIndex) {
        // this.node.getChildByName("mask").active = true;
        Game.ins.stopTime();
        if (touchIndex == 0) {
            this.scheduleOnce(() => {
                Game.ins.showFail();
            }, 3);
        } else {
            if(this.isshowSuccess){
                return
            }
            this.isshowSuccess = true
            
            this.scheduleOnce(() => {
                Game.ins.showSuccess();
            }, 5);
        }
    }

    openTouchEvent(node,checkNode,fixedNode,isCanMove,stepIndex) {
        console.log('nodeName==',node.name)
        var attrs = {
            isCanMove:isCanMove,
            checkNode: checkNode,
            fixedNode:fixedNode,
            stepIndex:stepIndex,
            startPos: node.getPosition(),//初始位置
        };
        node.attr(attrs)
        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) {
        event.target.zIndex = 100
        Common5.playEffect("click")
        if(event.target.name == '宠物衣服node'){
            event.target.getChildByName('宠物衣服1').active = false
            event.target.getChildByName('宠物衣服2').active = true
        }else if(event.target.name == '棉被node'){
            event.target.getChildByName('棉被1').active = false
            event.target.getChildByName('棉被2').active = true
        }
        
        //this.curLayerIndex++
    }

    touchMoveNode(event) {
        if(!event.target.isCanMove){
            return
        }
        let posi = event.getLocation()//世界坐标
        let target = event.target
        posi = target.parent.convertToNodeSpaceAR(posi)
        target.setPosition(posi)
    }

    touchEndNode(event) {
        event.target.zIndex = event.target.bindZIndex
        if(!event.target.isCanMove){
            return
        }
        let target = event.target
        let checkNode = this.checkArea(target,target.checkNode)
        if (checkNode) {
            target.fixedNode && (target.fixedNode.active = true)
            if(target.name == '剪刀'){
                if(checkNode.name == '初始狗'){
                    target.setPosition(checkNode.getPosition())
                    target.getChildByName('spine').getComponent(sp.Skeleton).setAnimation(0,'剪刀',true)
                    cc.tween(this.node)
                        .delay(1.5)
                        .call(()=>{
                            this.node.getChildByName('mainNode').getChildByName('剪刀').getChildByName('spine').getComponent(sp.Skeleton).setAnimation(0,'000',false)
                            this.node.getChildByName('mainNode').getChildByName('狗毛').active = true

                            this.node.getChildByName('mainNode').getChildByName('初始狗').active = false
                            this.node.getChildByName('mainNode').getChildByName('被剪掉的狗毛').active = true
                            target.setPosition(target.startPos)
                        })
                    .start()
                    return
                }
            }else if(target.name == '梳子'){
                if(this.curSchedule >= 9){
                    target.active = false
                    this.node.getChildByName('mainNode').getChildByName('girlEnd').active = true
                    Common5.playEffectCustom(this.bundle,'sound/结束动画音效')
                    this.endGameView(1)
                    return
                }
            }else{
                target.active = false
                this.checkIsFinish(target,true)
                
            }
        }
        target.setPosition(target.startPos)
    }
    checkArea(node,checkNodeTab){
        let checkIndex = null
        for(let i=0;i<checkNodeTab.length;i++){
            let target = checkNodeTab[i]

            if(target && target.active && Common5.checkContainsNode(target,node)){
                checkIndex = target
                break
            }
        }
        return checkIndex
    }
    checkIsFinish(target,bFixedScale){
        // target.fixedNode.zIndex = this.curLayerIndex++
        this.unlockLevel(target.stepIndex)
        this.showDuiHua(this.duihuaArrayConfig[target.stepIndex])
        this.curSchedule ++
        // if(this.curSchedule >= 10){
        //     // this.stopTween()
        //     this.endGameView(1)
        // }
    }
    unlockLevel(sublevel){
        Game.ins.tipUnlock(sublevel)
    }
    //触摸回调
    normalTouchCallback(targetNode: cc.Node) {
        console.log("+++++++++++++++++++++>" + targetNode.name);
        switch (targetNode.name) {
            case '手机':
                this.showDuiHua(this.duihuaArrayConfig[10])
                break;
            default:
                break;
        }
    }
}