import { ryw_Event } from "../../FrameWork/Event/EventEnum";
import EventMgr from "../../FrameWork/Event/EventMgr";
import GameReport from "../../FrameWork/Report/ZyZyReport";
import User from "../../FrameWork/User/User";
import AppPlatform from "../../FrameWork/Util/AppPlatform";
import { DateUtils } from "../../FrameWork/Util/DateUtils";
import Common5 from "../../Platform/th/Common5";
import TaskManager, { MainTaskIdEnum } from "../JuQingChat/TaskManager";
import BagManager from "../Manager/BagManager";
import LevelUpManager from "../Manager/LevelUpManager";
import PrefabManage, { GameType } from "../PrefabManager/PrefabManage";
import GameBase from "../SCommon/GameBase";
import GetAward from "../SCommon/GetAward";
import { HookClawState, hjyfManager } from "./HuangJinYuFuManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class HuangJinYuFu extends GameBase {

    @property(cc.Node)
    hookRodNode: cc.Node = null;    //钩杆节点

    @property(cc.Node)
    hookClawCheckNode: cc.Node = null;    //钩爪节点

    @property(cc.Node)
    ordHookClawIcon: cc.Node = null;    //普通钩爪

    @property(cc.Node)
    golHookClawIcon: cc.Node = null;    //黄金钩爪

    @property(cc.Node)
    fishsNode: cc.Node = null;

    @property(cc.Node)
    fishsNode2: cc.Node = null;
    @property(cc.Node)
    fishsNode3: cc.Node = null;

    @property(cc.Node)
    wallsNode: cc.Node = null;


    hookClawState: HookClawState = null;    //钩爪状态
    hookClawEvent: any = null;  //钩爪事件
    hookClawType: number = 0;    //钩爪类型

    roateSpeed: number = 60;    //钩爪旋转速度
    hookClawSpeed: number = 600;    //钩爪拉拽速度
    roateAngle: number = 50;    //钩爪旋转角度
    hookClawRecoverySpeed = 500;    //钩爪回收速度
    hookRodInitHeight: number = 0; //钩爪初始高度
    fishMoveRange: cc.Rect = null;  //鱼移动范围

    checkNodeList: cc.Node[] = [];  //碰撞节点列表
    fishTypeNodeMap: {} = {};  //鱼类型节点映射表
    curFishNode: cc.Node = null;  //当前鱼节点
    curFishInfo: any = null;  //当前鱼信息
    escapePoint: number = 0; //逃跑点 
    _dt: number = 0

    gameStop = false
    onLoad() {
        super.onLoad()
    }

    onDestroy() {
        
        super.onDestroy();
    }

    start() {
      
        //Common5.playMusic("sound/冰雪世界");
        this.initData();
        this.initComponent();


  
        let times = User.getHuangjinGouTime()
        if(times > 0){
            this.hookClawType = 1;
            this.ordHookClawIcon.active = false;
            this.golHookClawIcon.active = true;

            this.node.getChildByName('金钩抓').active = false
            this.node.getChildByName('金钩抓2').active = true
            this.node.getChildByName('金钩抓2').getChildByName('lab').getComponent(cc.Label).string = DateUtils.formatTime3_custom(times)
        }else{
            this.node.getChildByName('金钩抓2').active = false
            this.node.getChildByName('金钩抓').active = true
        }

        this.showHjTime()
        // EventMgr.onEvent_custom(ryw_Event.ryw_Video_Finish_custom,()=>{
        //     this.gameStop = false
        // },this) 

        // EventMgr.onEvent_custom(ryw_Event.ryw_Video_Start,()=>{
        //     this.gameStop = true
        // },this) 

        

        this.schedule(()=>{
            let dt = 0.016
            if(this.gameStop){
                return
            }
            this._dt += dt
            if (this._dt >= 1.0) {
                this._dt = 0
            
                this.showHjTime()
            }
    
            if (this.hookClawEvent[this.hookClawState]) {
                this.hookClawEvent[this.hookClawState](dt);
            }
            this.fishAnimation(dt);
            
        },0.016)


    }

    showHjTime(){
        let times = User.getHuangjinGouTime()
        if(times > 0){
       
            this.node.getChildByName('金钩抓2').getChildByName('lab').getComponent(cc.Label).string = DateUtils.formatTime3_custom(times)
        }else{
          
        }
    }

    //初始化数据
    initData() {
        this.hookClawType = 0;
        this.hookClawEvent = {};
        this.hookClawEvent[HookClawState.START] = this.hookClawRotate.bind(this);
        this.hookClawEvent[HookClawState.LAUNCH] = this.hookClawlaunch.bind(this);
        this.hookClawEvent[HookClawState.RECOVERY] = this.hookClawRecovery.bind(this);
        this.hookClawState = HookClawState.START;

        this.hookRodInitHeight = this.hookRodNode.height;
        this.fishMoveRange = new cc.Rect(-this.fishsNode2.width / 2 - 100, -this.fishsNode2.height / 2, this.fishsNode2.width + 200, this.fishsNode2.height);
    }

    //初始化组件
    initComponent() {
        for (const iterator of this.wallsNode.children) {
            iterator['checkType'] = 'wall';
            this.checkNodeList.push(iterator);
        }

        this.fishTypeNodeMap = {};
        this.fishsNode.children.forEach((value) => {
            value['checkType'] = 'fish';
            this.fishTypeNodeMap[value.name] = value;
        });

        if (this.hookClawType == 0) {
            this.ordHookClawIcon.active = true;
            this.golHookClawIcon.active = false;
        } else {
            this.ordHookClawIcon.active = false;
            this.golHookClawIcon.active = true;
        }

        // if (User.getSaveFishDataList().length > 0) {
        //     this.showFishList();
        //     return;
        // }

        // if (User.getGenerateFishQuantity() > 0) {
        //     this.showFishList();
        //     return;
        // }
      
        this.showFishList();
    }

    //展示鱼列表
    public showFishList() {

        let fishSizeMap: Map<string, cc.Size> = new Map();
        for (const key in this.fishTypeNodeMap) {
            if (Object.prototype.hasOwnProperty.call(this.fishTypeNodeMap, key)) {
                fishSizeMap.set(key, this.fishTypeNodeMap[key].getContentSize());
            }
        }

        let fishDataList = hjyfManager.getFishDataList(fishSizeMap, this.fishsNode2.getContentSize());
        for (const iterator of fishDataList) {
            let fishInfo = hjyfManager.getFishInfoById(iterator.id);
            let fish = cc.instantiate(this.fishTypeNodeMap[fishInfo.name]);
            fish.active = true;
            fish.setPosition(iterator.pos);
            fish['id'] = iterator.id;
            fish['fishData'] = iterator;
            fish['checkType'] = 'fish';
            fish['moveType'] = fishInfo.moveType;
            fish['moveSpeed'] = fishInfo.moveSpeed;
            if (fishInfo.moveType) {
                fish['moveState'] = true;
                if (fishInfo.moveType == 2) {
                    fish['moveSpeVec'] = new cc.Vec2(0, 0);
                    fish['moveSpeVec'].x = (Math.random() + 1) / 2;
                    if (Math.random() < 0.5) {
                        fish['moveSpeVec'].y = - (Math.random() + 1) / 2;
                    } else {
                        fish['moveSpeVec'].y = (Math.random() + 1) / 2;
                    }
                } else {
                    if (Math.random() < 0.5) {
                        fish.scaleX = -Math.abs(fish.scaleX);
                    }
                }
                this.fishsNode3.addChild(fish);
            } else {
                this.fishsNode2.addChild(fish);
            }
            this.checkNodeList.push(fish);
        }

        this.hookClawType = 0;
        this.ordHookClawIcon.active = true;
        this.golHookClawIcon.active = false;
        this.node.getChildByName('金钩抓').active = true;
    }

    update(dt) {

    }

    
    //钩爪旋转
    hookClawRotate(deltaTime: number) {
        this.hookRodNode.angle += this.roateSpeed * deltaTime;
        if (this.hookRodNode.angle >= this.roateAngle) {
            this.roateSpeed = -Math.abs(this.roateSpeed);
        } else if (this.hookRodNode.angle <= -this.roateAngle) {
            this.roateSpeed = Math.abs(this.roateSpeed);
        }
    }

    //钩爪发射
    hookClawlaunch(deltaTime: number) {
        this.hookRodNode.height += this.hookClawSpeed * deltaTime;

        //检测碰撞
        let checkNode: cc.Node = null;
        for (const iterator of this.checkNodeList) {
            if (Common5.checkIntersectsBox(this.hookClawCheckNode, iterator)) {
                checkNode = iterator;
            }
        }

        //碰撞判定
        if (checkNode) {
            if (checkNode['checkType'] === 'wall') {
                this.hookClawRecoverySpeed = this.hookClawSpeed;
                this.hookClawState = HookClawState.RECOVERY;
            } else if (checkNode['checkType'] === 'fish') {
                this.curFishNode = checkNode;
                this.curFishInfo = hjyfManager.getFishInfoById(checkNode['id']);
                this.curFishInfo.fishData = checkNode['fishData'];
                this.hookClawRecoverySpeed = this.hookClawSpeed * this.curFishInfo.recoverySpeed;
                let fishSpine = this.curFishNode.getChildByName('海鲜')
                if (fishSpine && fishSpine.getComponent(sp.Skeleton)) {
                    fishSpine.getComponent(sp.Skeleton).setAnimation(0, this.curFishInfo.skin + "挣扎", true);
                }
                if (this.hookClawType == 0) {
                    let random = Math.random();
                    if (random >= this.curFishInfo.catchPbl) {
                        console.log('钩子没有钩住:' + random + ">" + this.curFishInfo.catchPbl);
                        this.escapePoint = this.hookRodNode.height - this.hookRodInitHeight;
                        this.escapePoint = this.escapePoint * Math.random() + this.hookRodInitHeight;
                    }
                }
                this.curFishNode['prePos'] = this.curFishNode.position;
                this.curFishNode.parent = this.hookClawCheckNode;
                this.curFishNode.setPosition(cc.v2(0, -40));
                this.curFishNode['moveState'] = false;
                this.hookClawState = HookClawState.RECOVERY;
            }
        }
    }

    //钩爪回收
    hookClawRecovery(deltaTime: number) {
        this.hookRodNode.height -= this.hookClawRecoverySpeed * deltaTime;
        if (this.escapePoint && this.hookRodNode.height <= this.escapePoint) {
            this.fishEscape();
        }
        if (this.hookRodNode.height <= this.hookRodInitHeight) {
            this.hookRodNode.height = this.hookRodInitHeight;
            this.hookClawState = HookClawState.START;
            if (this.hookClawCheckNode.childrenCount > 0) {
                //展示钓鱼成功
                this.fishingSuccess();
            }
        }
    }

    //鱼动画
    fishAnimation(deltaTime: number) {
        for (const iterator of this.checkNodeList) {
            if (iterator['moveState']) {
                if (iterator['moveType'] == 1) {
                    if (iterator.scaleX > 0) {
                        iterator.x -= iterator['moveSpeed'] * deltaTime;
                    } else {
                        iterator.x += iterator['moveSpeed'] * deltaTime;
                    }
                    if (iterator.x >= this.fishMoveRange.xMax) {
                        iterator.scaleX = Math.abs(iterator.scaleX);
                    } else if (iterator.x <= this.fishMoveRange.xMin) {
                        iterator.scaleX = -Math.abs(iterator.scaleX);
                    }
                } else if (iterator['moveType'] == 2) {
                    iterator.x += iterator['moveSpeVec'].x * deltaTime * iterator['moveSpeed'];
                    iterator.y += iterator['moveSpeVec'].y * deltaTime * iterator['moveSpeed'];
                    if (iterator.x >= this.fishMoveRange.xMax) {
                        iterator['moveSpeVec'].x = -(Math.random() + 1) / 2;
                    } else if (iterator.x <= this.fishMoveRange.xMin) {
                        iterator['moveSpeVec'].x = (Math.random() + 1) / 2;
                    }
                    if (iterator.y >= this.fishMoveRange.yMax) {
                        iterator['moveSpeVec'].y = -(Math.random() + 1) / 2;
                    } else if (iterator.y <= this.fishMoveRange.yMin) {
                        iterator['moveSpeVec'].y = (Math.random() + 1) / 2;
                    }
                }
            }
        }
    }

    //鱼逃脱
    fishEscape() {
        let fishSpine =  this.curFishNode.getChildByName('海鲜')
        if (fishSpine && fishSpine.getComponent(sp.Skeleton)) {
            fishSpine.getComponent(sp.Skeleton).setAnimation(0, this.curFishInfo.skin, true);
        }
        let pos = this.fishsNode2.convertToNodeSpaceAR(this.curFishNode.convertToWorldSpaceAR(cc.v2(0, 0)));
        let parentNode = this.curFishNode['moveType'] ? this.fishsNode3 : this.fishsNode2;
        this.hookClawCheckNode.removeChild(this.curFishNode);
        const node = this.curFishNode;
        cc.tween(this.curFishNode)
            .set({ parent: parentNode, position: cc.v3(pos.x, pos.y) })
            .to(0.5, { position: this.curFishNode['prePos'] })
            .call(() => {
                node['moveState'] = true;
            })
            .start();
        this.hookClawRecoverySpeed = this.hookClawSpeed;
        this.curFishInfo = null;
        this.curFishNode = null;
        this.escapePoint = 0;
    }

    //钓鱼成功
    public fishingSuccess() {
        //把鱼从碰撞列表中移除
        if (this.checkNodeList.indexOf(this.curFishNode) != -1) {
            this.checkNodeList.splice(this.checkNodeList.indexOf(this.curFishNode), 1);
        }
        //移除鱼节点
        this.hookClawCheckNode.removeChild(this.curFishNode);
        this.curFishNode.destroy();
        this.curFishNode = null;

        if(this.curFishInfo.goodId == 4017 || this.curFishInfo.goodId == 4018 || this.curFishInfo.goodId == 4019){
            let level = this.curFishInfo.income
            LevelUpManager.peopleLevelUp(level)
            PrefabManage.showTextTips('等级增加'+level+'级') 
            //删除鱼数据
            this.deleteFish()

        }else{
            //展示奖励
            let goodArray = [{ goodId: this.curFishInfo.goodId, goodNum: 1 }]
            PrefabManage.loadPrefabByType(GameType.GetAward, null, (prefabNode) => {
                prefabNode.getComponent(GetAward).initView(goodArray, () => {
                    //删除鱼数据
                    this.deleteFish()
                });
            })
        }
   
    }


    deleteFish(){
        hjyfManager.deleteFishData(this.curFishInfo.fishData);
        this.curFishInfo = null;
        //展示结束页面
        if (hjyfManager.getFishDataListLength() <= 0) {
            // let nextFish = this.node.getChildByName('NextFish');
            // nextFish.active = true;
            // let next = nextFish.getChildByName('btnLayer').getChildByName('next'),
            // video = nextFish.getChildByName('btnLayer').getChildByName('video');
            // let gentQuat = User.getGenerateFishQuantity();
            // console.log(gentQuat, 'gentQuat++++++++++++===')
            // if (gentQuat > 0) {
            //     next.active = true;
            //     video.active = false;
            //     next.getChildByName("lab2").getComponent(cc.Label).string = "x" + gentQuat;
            // } else {
            //     next.active = false;
            //     video.active = true;
            // }   
        }
        
        let mainTaskInfo:any = TaskManager.getCurUnLockMainTaskInfo()
        let mainId = mainTaskInfo.Id
        if(mainId == MainTaskIdEnum.MainTask_516){
          
            let isAllGoods = BagManager.isHaveAllGood([1704,1705,1706,1707,1708])
            if(isAllGoods){
                TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_516)
                TaskManager.setCurTask(MainTaskIdEnum.MainTask_517)
                //跳转
                PrefabManage.loadPrefabByType(GameType.BoxTipNode, null, (prefab)=>{
                    prefab.getComponent('BoxTipScript').setViewData(1,'回家救助夕颜', ()=>{
                        this.node.removeAllChildren()
                        this.node.destroy()
                        PrefabManage.loadPrefabByType(GameType.MyRoom)
                    })
                    prefab.getComponent('BoxTipScript').setBtnStr('确定')
                    prefab.getComponent('BoxTipScript').setCloseBtnView(false)
                    prefab.zIndex = 100
                })

            }

        }
   
    }
    //点击发射钩子
    onLaunchClick() {
        if (this.hookClawState == HookClawState.START) {
            this.hookClawState = HookClawState.LAUNCH;
        }
    }

    //切换金钩抓
    onGoldHookClawClick(event) {
        //Common5.playEffect("sound/按键点击")
        if (this.hookClawState == HookClawState.START) {
            this.gameStop = true
            let target = event.target;
            target.active = false;
            let tab = {
                onClose: (finish) => {
                    if (finish) {
                        Common5.ReportDY("inLevel", "黄金渔夫-AD-金钩抓");
                        this.hookClawType = 1;
                        this.ordHookClawIcon.active = false;
                        this.golHookClawIcon.active = true;
                        this.hookRodNode.angle = 0
                        User.setHuangjinGouTime(1800)
                        this.node.getChildByName('金钩抓2').active = true
                        this.node.getChildByName('金钩抓').active = false
                        this.gameStop = false
                      
                    }else {
                        this.gameStop = false
                        target.active = true;
                        this.reportKey(() => {
                            GameReport.ADReport('黄金渔夫金钩抓', 0)
                        })
                        Common5.showTips_custom("广告未观看完");
                    }
                }, onFailed: () => {
                }
            }
            AppPlatform.playVideo_custom(tab);
        }
    }




    //换海域
    onChangeSeaClick(event) {
        //Common5.playEffect("sound/按键点击")
        let target = event.target;
        //target.parent.parent.active = false;
        this.showFishList();
    }

    //寻找新海域
    onFindNewSeaClick(event) {
        //Common5.playEffect("sound/按键点击")
        let target = event.target;
        this.gameStop = true
        let tab = {
            onClose: (finish) => {
                if (finish) {
                    Common5.ReportDY("inLevel", "黄金渔夫-AD-寻找新海域");
                  
                    hjyfManager.reSetFishQua();

                    PrefabManage.loadPrefabByType(GameType.HuangJinYuFu, null, ()=>{
                        console.log('黄金捕鱼关掉')
                        this.node.removeFromParent()
                        this.node.destroy()
                    });


                    this.hookRodNode.angle = 0
                    this.gameStop = false
            
                }
                else {
                    this.gameStop = false
                  
                    Common5.showTips_custom("广告未观看完");
                }
            }, onFailed: () => {
            }
        }
        AppPlatform.playVideo_custom(tab);
    }

    
}