using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
using Random = System.Random;

public class BattleSceneDisplayController : DisplayController {

    DisplayControllerNav m_DisplayControllerNav;
    public DisplayControllerNav battleSceneNav
    {
        get
        {
            if (m_DisplayControllerNav == null)
            {
                m_DisplayControllerNav = new GameObject("BattleSceneNav").AddComponent<DisplayControllerNav>();
                this.m_DisplayControllerNav.transform.SetParent(transform);

                var UIChangeAnimPref = GameResourceManager.Load<MainSceneUIChangeAnim>(GameResourceManager.mainSceneUIChangeAnimPath);
                if(UIChangeAnimPref)
                    this.m_DisplayControllerNav.UIChangeAnimation = Instantiate<MainSceneUIChangeAnim>(UIChangeAnimPref);
            }
            return m_DisplayControllerNav;
        }
    }
    
    ///             BattleScene
    ///             /         \
    ///     BattleController BattleUI
    ///        /          
    /// Battle3DScene
    
    private BattleController m_Controller;
    public BattleController battleController => m_Controller;

    private Battle3DScene m_3DScene;

    public int mapId => m_Data.mapData.mapId;
    public int mode => m_Data.mapData.mode;

    private BattleData m_Data;

    public void Init(BattleData data)
    {
        m_Data = data;
    }
    
    public override void WillLoadDisplay()
    {
        base.WillLoadDisplay();
        
        /*if(Game.Instance)
            Game.Instance.analytics?.BattleStart(this.mapId);*/
        
        //开启多点触控
        Input.multiTouchEnabled = true;

        this.ClearAll();

        
        //PlayBattleMusic();
    }

    
    public override void DidLoadDisplay()
    {
        base.DidLoadDisplay();
        
        CreateBattle();
        
        GameDebug.LogShowy($"battle scnen  mapId:{m_Data.mapData.mapId}  mpde:{mode} ");

        this.InitBattle(m_Data);

        CreateUI();
    }


    public override void OnLoadedEndDisplay()
    {
        base.OnLoadedEndDisplay();
        
        ///改加载动画
        var prefab = GameResourceManager.Load<SceneLoadingAnim>(GameResourceManager.blackSceneLoadingAnimPath);
        var SceneLoadingAnim = Instantiate<SceneLoadingAnim>(prefab, null);

        if (this.parentNav.UIChangeAnimation)
        {
            DestroyImmediate(this.parentNav.UIChangeAnimation.gameObject);
        }
        this.parentNav.UIChangeAnimation = SceneLoadingAnim;
        
    }

    public void GotoResultScene(BattleResult result)
    {
        PersonalResultPanelData resultPanelData = new PersonalResultPanelData();
        resultPanelData.level = result.level;
        resultPanelData.win = result.win;
        resultPanelData.coin = result.score;
        resultPanelData.star = result.star;
        
        /*var resultScene = parentNav.LoadDisplay<ResultSceneDisplayController>();
        resultScene.Init(resultPanelData);*/
        var resultUI = this.battleSceneNav.LoadDisplay<ResultUIDisplayController>(null,false);
        
        if (result.win)
        {   
            Game.Instance.user.UpdateCoin(Game.Instance.user.coin + result.score);
        }
        Game.Instance.user.UpdateLevelStar(result.level,result.star);
        
        resultUI.Init(resultPanelData);
    }

    void PlayBattleMusic()
    {
        AudioManager.instance.StopAllMusic();
        var battleMusic = GameResourceManager.Load<AudioClip>(GameResourceManager.battleSceneMusic);
        AudioManager.instance.Play(battleMusic, Vector3.zero, true, null, true);
    }

    /// <summary>
    /// 创建
    /// </summary>
    void CreateBattle()
    {
        try
        {
            this.Create3DScene();
        }
        catch (Exception e)
        {
            GameDebug.LogError(e);
        }
    }
    void CreateUI ()
    {
        var battleUIDC = this.battleSceneNav.LoadDisplay<BattleUIDisplayController>();
        battleUIDC.Init(m_Controller);
    }
    
	
    void Create3DScene()
    {
        if (m_3DScene)
        {
            DestroyImmediate(m_3DScene.gameObject);
        }
        
        Battle3DScene staticPrefab = null;
        string staticPrefabPath = "";

        staticPrefabPath = Battle3DScene.GetMapPrefabPath(mapId);// string.Format("B_Battle/Battle/Maps/场景{0}/场景{0}", mapId);
        // 创建显示层静态物体 
        staticPrefab = GameResourceManager.Load<Battle3DScene>(staticPrefabPath);

        if (staticPrefab == null)
        {
            GameDebug.LogError("未找到静态物体 预设: " + staticPrefabPath);
            staticPrefabPath =  Battle3DScene.GetMapPrefabPath(1);
            staticPrefab = GameResourceManager.Load<Battle3DScene>(staticPrefabPath);
        }

        Battle3DScene battle = Instantiate(staticPrefab,transform);   
        m_3DScene = battle;
    }
    
    /// <summary>
    /// 初始化
    /// </summary>
    /// <param name="data"></param>
    void InitBattle(BattleData data)
    {
        if (m_Controller)
            Destroy(m_Controller.gameObject);

        m_Controller = Game.Instance.NewBattleController();// new GameObject("BattleController").AddComponent<BattleController>(); 
        m_Controller.transform.SetParent(this.transform);
        
        long myPlayerId = Game.Instance.user.id;
        myPlayerId = 0;
        try
        {
            m_3DScene.transform.SetParent(m_Controller.transform);
            m_3DScene.Init(AudioManager.instance,m_Controller);
            
            m_Controller.Init(data, myPlayerId, m_3DScene);
            //m_Controller.dataConfig = Game.Instance.dataConfig;
            m_Controller.onBattleFinish = ShowResult;
        }
        catch (Exception e)
        {
            GameDebug.LogError(e);
        }
    }
    
    
    private void ShowResult(BattleResult obj)
    {
        this.GotoResultScene(obj);
        
/*        DelayAction.DelayDo(1f, () =>
        {
            this.GotoResultScene(obj);
        });*/
        
        /*if(Game.Instance)
            Game.Instance.analytics?.BattleEnd(this.mapId,battleResult.score >= this.nPCs.Count,battleResult.score);*/
    }


    public override void WillHideDisplay()
    {
        base.WillHideDisplay();

        GameDebug.Log("battle OnRelease!");
        
        Release();
    }
    
    void Release()
    {  
        try
        {
            /*if (m_UI)
                DestroyImmediate(m_UI.gameObject);*/
            
            if (m_Controller != null)
            {
                GameObject.DestroyImmediate(m_Controller.gameObject);
                m_Controller = null;
            }
            
        }
        catch (Exception e)
        {
            GameDebug.LogError(e);
        }
        
        ClearAll();
    }
    
    public override void OnDelete()
    {
        base.OnDelete();
        
    }

    public void ClearAll()
    {
        for (int i = 0; i < transform.childCount; i++)
        {
            if (transform.GetChild(i))
            {
                DestroyImmediate(transform.GetChild(i).gameObject);
            }
        }
    }


    void OnDestroy()
    {
        
    }
 

}