using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Net;
using System.Reflection;
using UnityEngine;
using UnityEngine.EventSystems;



public class Dodge
{
    const string loginNewKey = "DodgeLoginNewKey";
    public static bool loginNew
    {
        get => PlayerPrefs.GetInt(loginNewKey) > 0;
        set => PlayerPrefs.SetInt(loginNewKey,value?1:0);
    } 
    
}

public class GameData
{
    public virtual GameUser user { get; set; }
}

public abstract class Game : MonoBehaviour {

	  /// 单例
    private static Game _instance;
    public static Game Instance { get { return _instance; } }
    
    /// <summary>
    /// 游戏设置（音乐音效等）
    /// </summary>
    GameSetting m_GameSettting;
    public GameSetting gameSetting { get { return m_GameSettting; } }
    
    /// <summary>
    /// 显示层管理
    /// </summary>
    DisplayControllerNav m_RootDisplayControllerNav;
    public DisplayControllerNav rootNav => m_RootDisplayControllerNav;

    /// <summary>
    /// 用户数据
    /// </summary>
    public GameUser user => data.user;

    /// <summary>
    /// 保存在内存的全局数据
    /// </summary>
    
    protected virtual GameData data { get; set; }

    GameObject m_ModelSceneParent;
    public GameObject modelSceneParent
    {
        get
        {
            if (m_ModelSceneParent == null)
                m_ModelSceneParent = new GameObject("ModelSceneParent");

            return m_ModelSceneParent;
        }
    }
    
    public abstract  DataConfig dataConfig { get; }

    void PreInit ()
    {
        m_GameSettting = new GameSetting();
        m_GameSettting.Load();
        m_GameSettting.AddAudioSettingListener( AudioManager.instance);

        data = InitGameData();
    }

    protected abstract GameData InitGameData();
    
    public const string LocalUserDataKey = "LocalUserData";

    void Awake()
    {
        if (_instance == null)
        {
            _instance = this;
        }
        else
        {
            GameDebug.LogError("GameInstance Not null");
        }
        
        this.PreInit();
        
        Screen.sleepTimeout = SleepTimeout.NeverSleep;
    }

    void Start()
    {
        GameStart();
    }

    
    void GameStart()
    {
        Application.targetFrameRate = 60;

        //关闭多点触控
        //Input.multiTouchEnabled = false;

        //添加事件组件
        var eventSystem = FindObjectOfType<EventSystem>();
        if (eventSystem == null)
        {
            var es = new GameObject("EventSystem");
            es.AddComponent<EventSystem>();
            es.AddComponent<StandaloneInputModule>();
        }

        this.m_RootDisplayControllerNav = new UnityEngine.GameObject("DisplayControllerRoot").AddComponent<DisplayControllerNav>();

        var prefab = GameResourceManager.Load<SceneLoadingAnim>(GameResourceManager.blackSceneLoadingAnimPath);
        var SceneLoadingAnim = Instantiate<SceneLoadingAnim>(prefab, null);
        this.m_RootDisplayControllerNav.UIChangeAnimation = SceneLoadingAnim;
        
        LaunchSceneDisplayController splashImg = this.m_RootDisplayControllerNav.LoadDisplay<LaunchSceneDisplayController>(false);
    }
    
    /// <summary>
    /// 获取渠道ID
    /// </summary>
    /// <returns></returns>
    string GetChannelId()
    {
        string channelId = "";
        
#if UNITY_EDITOR
        channelId = "Editor";
            
#elif UNITY_ANDROID
            channelId = "Android";

#elif UNITY_IOS
            channelId = "IOS";

#endif

        return channelId;
    }

    #region game level
    
    private static int minLevel = 1;

    public static int maxLevel
    {
         get
         {
             return Instance.dataConfig.maxLevel;
         }
    }

    
    public BattleSceneDisplayController LoadCurLevelGame()
    {
        return LoadCurLevelGame(true);
    }
    public BattleSceneDisplayController LoadCurLevelGame(bool useDefaultLoadingAnim)
    {
        int toPlayLevel = user.level;
        
        if (toPlayLevel > maxLevel)
            toPlayLevel = maxLevel;
        
        return LoadGame(toPlayLevel,useDefaultLoadingAnim);
    }

    public void NextLevel()
    {
        int nextLv = user.level + 1;
        if (nextLv > maxLevel)
            nextLv = minLevel;//重新开始
        
        user.UpdateLevel(nextLv);
    }
    
    /// <summary>
    /// 加载关卡场景
    /// </summary>
    /// <param name="mapId"></param>
    /// <param name="useDefaultLoadingAnim"></param>
    /// <returns></returns>
    public BattleSceneDisplayController LoadGame(int mapId,bool useDefaultLoadingAnim = true)
    {        
        if (mapId > maxLevel)
            mapId = maxLevel;
        if (mapId < minLevel)
            mapId = minLevel;

        GameDebug.LogError($"mapId:{mapId}");
        
        BattleData battleData = new BattleData();
        
        battleData.mapData = Battle3DScene.LoadLocalData(mapId);
       
        //GameDebug.LogShowy($"mapEdit count:{battleData.mapData?.mapEditWidgets?.Count} ");

        battleData.players = new List<BattlePlayerData>();
        battleData.players.Add(new BattlePlayerData()
        {
            playerId = user.id,
            name = user.name,
        });
        battleData.dataConfig = this.dataConfig;
        return EnterBattleScene(battleData,useDefaultLoadingAnim);
    }
    

    public BattleSceneDisplayController EnterBattleScene(BattleData battleData,bool useDefaultLoadingAnim = true)
    {
        var rootNav = this.rootNav;

        if (useDefaultLoadingAnim)
        {
            if (rootNav.UIChangeAnimation != null)
                Destroy(rootNav.UIChangeAnimation.gameObject);

            var prefab = GameResourceManager.Load<SceneLoadingAnim>(GameResourceManager.sceneLoadingAnimPath);
            var SceneLoadingAnim = Instantiate<SceneLoadingAnim>(prefab, null);
            rootNav.UIChangeAnimation = SceneLoadingAnim;
        }

        var battle = this.rootNav.LoadDisplay<BattleSceneDisplayController>();
        battle.Init(battleData);
        return battle;
    }
    
    #endregion
    
    /// <summary>
    /// 获取游戏的当前场景控制器
    /// </summary>
    /// <returns></returns>
    public DisplayController GetActiveScene()
    {
        var activeScene = rootNav.GetPeek();
        if (activeScene == null)
        {
            Debug.LogError("activeScene == null!");
        }
        return activeScene;
    }

    /// <summary>
    /// 获取场景自己的界面管理器
    /// </summary>
    /// <returns></returns>
    public DisplayControllerNav GetActiveSceneNav()
    {
        var activeScene = GetActiveScene();
        if (activeScene == null)
        {
            Debug.LogError("activeScene == null!");
            return rootNav;
        }

        var nav = activeScene.GetComponentInChildren<DisplayControllerNav>();
        if (nav == null)
            return rootNav;

        return nav;
    }

    public void ClearModelScene()
    {
        for (int i = 0; i < modelSceneParent.transform.childCount; i++)
        {
            if(modelSceneParent.transform.GetChild(i))
                Destroy(modelSceneParent.transform.GetChild(i).gameObject);
        }
    }
    
    #region notice
     /// <summary>
    /// 通知面板
    /// </summary>
    NoticePanel m_NoticePanel;
    public NoticePanel noticePanel
    {
        get
        {
            if (m_NoticePanel == null)
            {
                var pref = GameResourceManager.Load<NoticePanel>(DisplayDefine.NoticePanel);
                m_NoticePanel = Instantiate(pref, m_RootDisplayControllerNav.transform);
                
                GameDebug.LogError("New Notice Panel");
            }
            return m_NoticePanel;
        }
    }
    public NoticePanel ShowNoticePanel(string content)
    {
        GameDebug.LogShowy("content：" + content);

        noticePanel.Init(new NoticePanelData("Message", content, "OK"/*new MultiLangKey("confirm")*/, "", null, null));//提示

        return noticePanel;
    }
    public NoticePanel ShowNoticePanel(string content, Action onConfirm )
    {
        GameDebug.LogShowy("content：" + content);

        noticePanel.Init(new NoticePanelData("Message", content, "OK"/*new MultiLangKey("confirm")*/, "" , onConfirm, null));//提示

        return noticePanel;
    }
    public NoticePanel ShowNoticePanelWithTwoBtn(string content, Action onConfirm ,Action onCancel)
    {
        GameDebug.LogShowy("content：" + content);      
        
        noticePanel.Init(new NoticePanelData("Message", content, "OK"/*new MultiLangKey("confirm")*/, "Cancel", onConfirm, onCancel));//提示//取消

        return noticePanel;
    }
 
    #endregion

    public abstract BattleController NewBattleController();
}

