import StageSuccess from "./result/StageSuccess";
import StageFail from "./result/StageFail";
import StageInfo from "./info/StageInfo";
import MiniMap from "./scene/minimap/MiniMap";
import WorldMap from "./scene/WorldMap";
import WordTask from "./scene/WordTask";
import MiniMapItem from "./scene/minimap/MiniMapItem";
import ViewObject from "../../../main/ViewObject";
import { __SceneData, __StageData } from "../../data/sdata/SManage";
import { HttpStateType, ReveData } from "../../../util/CHttp";
import { AudioMgr, GameViewType } from "../../../main/ViewManage";
import FF, { FF_Result_Type } from "../../fight/FF";
import FLoad from "../../fight/FLoad";
import FSprite from "../../fight/object/FSprite";
import FObject, { GroupType } from "../../fight/object/FObject";
import Dungeon from "../dungeon/Dungeon";
import FSpriteTmpGood from "../../fight/object/FSpriteTmpGood";
import { StageGoodAttr } from "../../data/udata/Player";
import FFDialogBox from "../../fight/box/FFDialogBox";
import i18n from "../../../i18n/i18n";
import FqPay, { UM_EVENT_ID } from "../../../pay/FqPay";

/**
 * 关卡选择界面
 */
const { ccclass, property } = cc._decorator;

@ccclass
export default class Stage extends ViewObject {

    @property(cc.Prefab)
    mSuccess: cc.Prefab = null;

    @property(cc.Prefab)
    mFail: cc.Prefab = null;
    
    @property(cc.Node)
    mMiniNode: cc.Node = null;//场景地图层

    @property({
        displayName:'飞行的星星',
        type:cc.Prefab
    })
    mFlyStar: cc.Prefab = null;

    @property({
        displayName:'事件拦截层',
        type:cc.Node
    })
    mBlockInput: cc.Node = null;

    public tmpMMItem:MiniMapItem = null;//当前最后点击的关卡
    /**
     * 新手引导中
     */
    public inGuide = 0;

    public miniMap:MiniMap = null;
    /**
     * 载入
     * @param callback 
     */
    public load(callback:(ss)=>void){
        this.loadStageData((result:number)=>{
            if(result == 0){
                let player = this.main.player;
                let role = player.role;
                let manage = this.main.sManage;
                //获取当前进行的关卡
                let stageData:__StageData = manage.getStageByIndex(0);
                let sceneData:__SceneData = manage.getSceneByStage(stageData);
                this.loadMiniMap(sceneData,(t)=>{
                    callback(t);
                });
            }else{
                callback(result);
            }
        });
    }
    /**
     * 载入服务器数据
     */
    private loadStageData(callback:(result:number)=>void){
        if(this.main.player.stage == null){
            let msg = {
            }
            this.main.gameHttp.sendJson('stage/v1/stageData',msg,(state,reve:ReveData)=>{
                if(state == HttpStateType.SUCCESS){
                    if(reve.retCode == 0){
                        this.main.player.stage = reve.data;
                        callback(0);
                    }else{
                        this.main.showTips(reve.message);
                        callback(-2);
                    }
                }else{
                    this.main.showTips('网络异常');
                    callback(-1);
                }
            });
        }else{
            callback(0);
        }
    }
    public openWorldMap(){
        this.main.viewManage.loadFunc(GameViewType.worldMap,(viewObject:ViewObject)=>{
            let worldMap:WorldMap = viewObject as WorldMap;
            worldMap.stage = this;
            viewObject.show();
        });
    }
    public openWordTask(){
        this.main.viewManage.loadFunc(GameViewType.wordTask,(viewObject:ViewObject)=>{
            let wordTask:WordTask = viewObject as WordTask;
            viewObject.show();
        });
    }
    public opendungeon(){
        this.main.viewManage.loadFunc(GameViewType.dungeon,(viewObject:ViewObject)=>{
            let dungeon:Dungeon = viewObject as Dungeon;
            viewObject.show();
        });
    }
    public initMiniMap(){
        this.miniMap.setCallback((mmItem:MiniMapItem)=>{
            this.onclick(mmItem);
        });
    }
    

    public loadMiniMap(sceneData:__SceneData,callback:(result:number)=>void){
        cc.resources.load("prefab/home/stage/scene/minimap/"+sceneData.id, cc.Prefab, (err, prefab:cc.Prefab) =>{
            if(err){
                cc.error(err);
                callback(-4);
            }else{
                //加载结束
                let node:cc.Node = cc.instantiate(prefab);
                this.miniMap = node.getComponent(MiniMap);
                this.miniMap.stage = this;
                this.miniMap.sceneData = sceneData;
                node.parent = this.mMiniNode;
                this.initMiniMap();
                callback(0);
            }
            this.main.stopLoad();
        } );
    }

    public onclick(mmItem:MiniMapItem) {
        this.main.viewManage.loadFunc(GameViewType.stageInfo,
            (viewObject: ViewObject) => {
                let stateInfo:StageInfo = viewObject as StageInfo;
                stateInfo.stageData = mmItem._stageData;
                stateInfo.inGuide = this.inGuide
                this.inGuide = 0
                stateInfo.setCallback((info:StageInfo)=>{
                    this.tmpMMItem = mmItem
                    this.openFF(info.stageData);
                });
                viewObject.show();
            });
    }
    public openFF(stageData:__StageData){
        this.main.viewManage.loadFunc(GameViewType.fight,
            (viewObject: ViewObject) => {
                viewObject.show(this);
                let ff: FF = viewObject as FF;
                ff.mFFheader.init(ff,stageData);
                this.regEvent(ff);
                cc.tween(cc.delayTime(0.1)).call(()=>{
                    FLoad.loadMap(ff,stageData, (map) => {
                        ff.loadMap(map);
                        let player = this.main.player;
                        let ss = player.getFight(this.main);
                        FLoad.loadRole(ff,ss, (sprites: Array<FSprite>) => {
                            ff.loadRole(sprites);
                        });
                    });
                }).start();
            });
        // let msg = {
        //     id:stageData.id
        // }
        // this.main.gameHttp.sendJson('stage/v1/openStage',msg,(state,reve:ReveData)=>{
        //     this.main.stopLoad();
        //     if(state == HttpStateType.SUCCESS){
        //         if(reve.retCode == 0){
        //             this.main.topNode.active = false;
        //             this.main.viewManage.loadFunc(GameViewType.fight,
        //                 (viewObject: ViewObject) => {
        //                     viewObject.show(this);
        //                     let ff: FF = viewObject as FF;
        //                     ff.mFFheader.init(ff,stageData);
        //                     this.regEvent(ff);
        //                     cc.tween(cc.delayTime(0.1)).call(()=>{
        //                         this.main.startLoad()
        //                         FLoad.loadMap(ff,stageData, (map) => {
        //                             this.main.stopLoad()
        //                             ff.loadMap(map);
        //                             let player = this.main.player;
        //                             let ss = player.getFight(this.main);
        //                             FLoad.loadRole(ff,ss, (sprites: Array<FSprite>) => {
        //                                 ff.loadRole(sprites);
        //                             });
        //                         });
        //                     }).start();
        //                 });
        //         }else{
        //             this.main.showTips(reve.message);
        //         }
        //     }else{
        //         this.main.showTips('网络异常');
        //     }
        // });
    }
    /**
     * 注册战斗事件监听
     * @param ff 
     */
    private regEvent(ff:FF){
        ff.regClearCallback((fobject: FObject) => {
            if (fobject.node.group == GroupType.A) {
                let fs = fobject as FSprite;
                if (fs == ff.mainSprite) {//领队死了
                    ff.pauseSprite(true);
                    if(ff.isBack){//已经复活过
                        this.fail(ff);
                    }else{//没有复活过
                        ff.isBack = true
                        this.showFHDialog(ff)
                    }
                }
            }else{
                //打死怪物后的处理
                this.killMonster(fobject);
            }
        });
        ff.regExitCallback(()=>{
            //通过关卡
            ff.pauseSprite(true);
            this.success(ff);
        });
    }
    /**
     * 死亡弹出的对话框
     */
    private deadNode:StageFail;
    /**
     * 显示复活对话框
     * @param ff 
     */
    private showFHDialog(ff:FF){
        this.main.startLoad()
        this.main.viewManage.loadFunc(GameViewType.fight_dialog_box, (viewObject: ViewObject) => {
            this.main.stopLoad()
            let dialogBox = viewObject as FFDialogBox
            dialogBox.mContent.string = i18n.t('需要原地复活吗？')
            dialogBox.setOKCallback(()=>{
                dialogBox.exitDistroy()
                this.deadNode = this.fail(ff)
                this.showADVideo(ff)
            })
            dialogBox.setCancelCallback(()=>{
                dialogBox.exitDistroy()
                this.fail(ff)
            })
            viewObject.show();
        });
    }
    private showADVideo(ff:FF){
        let fqPay = new FqPay(this.main)
        let myself = this
        fqPay.adVideo((result: number)=>{
            if(result == 1){
                this.deadNode.exitDistroy()
                this.deadNode = null
                ff.fuhuo()
                ff.pauseSprite(false)
            }else if(result == -1){
                myself.main.showTips('广告还未加载好,请稍后在试')
            }else{
                myself.main.showTips('广告播放未完成')
            }
        },UM_EVENT_ID.ad_fuhuo_0,UM_EVENT_ID.ad_fuhuo_1)
    }

    public killMonster(fobject:FObject){
        let ff = fobject.ff;
        let msg = {
            stageId:ff.mFFheader.stageData.id,
            monsterId:fobject.id
        }
        let pos = fobject.node.getPosition();
       
        this.main.gameHttp.sendJson('stage/v2/stageMonster',msg,(state,reve:ReveData)=>{
            this.main.stopLoad();
            if(state == HttpStateType.SUCCESS){
                if(reve.retCode == 0){
                    let list = this.main.sManage.getRewards(reve);
                    ff.addGoods(list,pos);

                }else{
                    this.main.showTips(reve.message);
                }
            }else{
                this.main.showTips('网络异常');
            }
        });

        let tmpGood = fobject.node.getComponent(FSpriteTmpGood)
        if(tmpGood){
            fobject.ff.addGoodToMap(tmpGood.goodId,tmpGood.node.getPosition())
        }

    }


    public success(ff:FF){
        ff.ffResultType = FF_Result_Type.win;
        let msg = {
            stageId:ff.mFFheader.stageData.id
        }
        // this.main.startLoad();
        this.main.gameHttp.sendJson('stage/v1/beatStage',msg,(state,reve:ReveData)=>{
            // this.main.stopLoad();
            if(state == HttpStateType.SUCCESS){
                if(reve.retCode == 0){
                    if(reve.data.stageIndex != undefined){
                        this.main.player.stage.stageIndex = reve.data.stageIndex;
                    }
                    ff.exitDistroy();
                    this.getStarReward()
                }else{
                    ff.exitDistroy();
                    this.main.showTips(reve.message);
                }
            }else{
                ff.exitDistroy();
                this.main.showTips('网络异常');
            }
        });

       
    }
    public fail(ff:FF):StageFail{
        if(ff.ffResultType != FF_Result_Type.none){
            return;
        }
        ff.ffResultType = FF_Result_Type.fail;
        let node = cc.instantiate(this.mFail);
        let success = node.getComponent(StageFail);
        success.main = this.main;
        success.show();
        success.setCallback(()=>{
            ff.exitDistroy();
        });

        let msg = {
            stageId:ff.mFFheader.stageData.id
        }
        this.main.gameHttp.sendJson('stage/v1/dead',msg,(state,reve:ReveData)=>{
        });
        return success
    }
    /**
     * 获取通关星级奖励
     */
    private getStarReward(){
        let mmItem:MiniMapItem = this.tmpMMItem
        if(mmItem){
            let starCount = mmItem.starCount//当前已经获得的奖励
            let curCount = mmItem.getStarCount1()//达到的星级
            this.starFly(starCount,curCount)
        }
    }
    /**
     * 星星飞行
     */
    private starFly(starCount:number,curCount:number){
        this.mBlockInput.active = true
        if(starCount >= curCount){
            this.mBlockInput.active = false
            this.getReward()
            return
        }
        let mmItem:MiniMapItem = this.tmpMMItem
        
        let targetNode = mmItem.mStarNode.children[starCount]
        let pos = targetNode.convertToWorldSpaceAR(cc.v2(0,0))

        let node = cc.instantiate(this.mFlyStar)
        node.parent = this.mMiniNode
        node.x = pos.x - (cc.winSize.width/2)
        node.y = pos.y + (cc.winSize.height/2)
        this.main.playerEffectByPath(AudioMgr.star);
        cc.tween(node).sequence(
            cc.moveTo(0.3,pos).easing(cc.easeIn(0.3)),
            cc.callFunc(()=>{
                mmItem.setStar(starCount)
                cc.tween(mmItem.node).sequence(
                    cc.scaleTo(0.1,1.3).easing(cc.easeOut(0.1)),
                    cc.scaleTo(0.1,1).easing(cc.easeIn(0.1)),
                ).start()
            }),
            cc.delayTime(0.1),
            cc.callFunc(()=>{
                starCount ++
                this.starFly(starCount,curCount)
            }),
            cc.destroySelf()
        ).start()
    }

    private getReward(){
        let mmItem:MiniMapItem = this.tmpMMItem
        let starCount = mmItem.starCount//当前已经获得的奖励
        let curCount = mmItem.getStarCount1()//达到的星级
        if(starCount >= curCount){
            return
        }
        this.getReward1(starCount,curCount)
    }

    private getReward1(starCount:number,curCount:number){
        if(starCount >= curCount){
            return
        }
        let mmItem:MiniMapItem = this.tmpMMItem
        
        let msg = {
            stageId:mmItem._stageData.id
        }
        this.main.startLoad()
        this.main.gameHttp.sendJson('stage/v1/starReward',msg,(state,reve:ReveData)=>{
            this.main.stopLoad();
            if(state == HttpStateType.SUCCESS){
                if(reve.retCode == 0){
                    let main = this.main;
                    let stageData = main.player.stage;
                    stageData.data[mmItem._stageData.id] = reve.data._stage;
                    let stageGoodAttr:StageGoodAttr = stageData.data[mmItem._stageData.id];
                    
                    mmItem.starCount = stageGoodAttr.starCount
                    let strs = ['获得一星奖励','获得二星奖励','获得三星奖励']
                    this.main.showReward(reve,()=>{
                        starCount ++
                        this.getReward1(starCount,curCount)
                    },'通关奖励',strs[starCount])
                }else{
                    this.main.showTips(reve.message);
                }
            }else{
                this.main.showTips('网络异常');
            }
        });

    }


}
