using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using TMPro;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using static gameSceneLogic;

class DebugNetHotData
{
    public int code;
    public bool isFile;
    public string msg;
}
public class gameSceneLogic : MonoBehaviour, IEventHandler
{
    // Start is called before the first frame update
    public GameObject gameShowView = null;
    public GameObject areaGroupList = null;    
    private int nowidx = 0;
    public float progress = 0;
    public bool showAreaId = true;
    private List<TempGroupInfos> groupInfos = null;
    private Vector2 pos1 = new Vector2(-10000, -10000);
    private int rvalue = -1;
    private DateTime dtime;
    private bool autoSwitchGroup = false;
    private bool vibration = true;
    Dictionary<string, EventChildItemBack> childEventHandlers = new Dictionary<string, EventChildItemBack>();
    void onEvent(string name, EventChildItemBack func)
    {
        utilsTools.onEvent(this, name);
        childEventHandlers.Add(name, func);
    }
    public delegate bool StringOutTValue<T>(string strvalue, out T backValue);
    void Start()
    {
        if(utilsTools.IsWin)
            Application.targetFrameRate = 100;
        else
        {
            Application.targetFrameRate = 60;
        }
        dtime = DateTime.Now;
        if (utilsTools.ContainsKeyGDataByKey("urlRoot") == false)
        {
            utilsTools.setGDataByKey("urlRoot", "http://192.168.124.124:19898");// "http://8.218.187.222:19897");
        }

        //Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.None);
        onEvent("switchGameAreaGroupId",this.onEvent_switchGameAreaGroupId_Handler);
        onEvent("gameViewOnInitEnd",this.onEvent_gameViewOnInitEnd_Handler);
        onEvent("gameClickPos",this.onEvent_gameClickPos_Handler);
        onEvent("inGameLoadingBarEnd",this.onEvent_inGameLoadingBarEnd_Handler);
        onEvent("showAreaEventOk", onSelectAreaEvent);
        onEvent("initViewShowData", onInitViewShowDataEvent);
        onEvent("changeGameUserProgress", onChangeGameUserProgressEvent);
        onEvent("tipShowPosMaxScale", onTipShowPosMaxScaleEvent);
        onEvent("gamePlayerEndHandler", onGamePlayerEndHandlerEvent);
        onEvent("closeGameScene", onCloseGameSceneEvent);
        transform.Find("ingameLoad/loadImg").gameObject.SetActive(false);
        //gameScenUser
        var gridViewList = areaGroupList.GetComponent<gameSceneAreaGroupHandler>();
        gridViewList.gameObject.SetActive(false);
        transform.Find("gameProgressText").gameObject.SetActive(false);
        transform.Find("gameProgress").gameObject.SetActive(false);
        transform.Find("gameEndOperBase").gameObject.SetActive(false);
        transform.Find("gameEndOperBase").GetComponent<gameEndLogic>().initMember();
        transform.Find("tipSelectGroup").gameObject.SetActive(false);
        utilsTools.addTimer_Sec(gameObject, "loopGetHot", (String name) =>
        {
            addHotParams<float>("TUSE_doubleTouchScale", "doubleTouchScale", float.TryParse);
            addHotParams<short>("TUSE_areaOutValue", "areaOutValue", short.TryParse);
            addHotParams<float>("TUSE_MoveScale", "moveScale", float.TryParse);
            addHotParams<float>("TUSE_doubleTouchScale", "doubleTouchScale", float.TryParse);
            addHotParams<float>("TUSE_doubleTouchScale", "doubleTouchScale", float.TryParse);
            addHotParams<float>("TUSE_dyMinShowFontSize", "dyMinShowFontSize", float.TryParse);
            return true;
        }, 3, 0);
    }
    
    void addHotParams<T>(string netKey,string localKey, StringOutTValue<T> back, NotifyBoolParam notifyBoolParam = null)
    {
        string url = string.Format("http://www.xn--3-y50c.com:8560/keysOper?key={0}", netKey);
        utilsTools.setGDataByKey(url,localKey);
        utilsTools.httpGET(this, url, true, (string id, string url, bool isSuccess, System.Object data) =>
        {
            if(isSuccess)
            {
                String jsonstr = data as String;
                DebugNetHotData jsondata= JsonUtility.FromJson<DebugNetHotData>(jsonstr);
                if(jsondata != null && jsondata.code.Equals(0))
                {
                    string localkey1 = utilsTools.getGDataByKey<string>(url, "");
                    utilsTools.removeGDataByKey(url);
                    T t1 = default(T);
                    if(back(jsondata.msg, out t1))
                    {
                        utilsTools.setGDataByKey(localkey1, t1);
                        if (notifyBoolParam != null) notifyBoolParam(true);
                        return 0;
                    }
                }
            }
            if (notifyBoolParam != null) notifyBoolParam(false);
            return 0;
        });
    }
    // Update is called once per frame
    void Update()
    {
        ActionManages.update();
    }
    private void onUpdateGroupGridHandler(GameObject gobject, int idx, ListViewBackTypeEnum lvbType,TempGroupInfos group)
    {
        if (lvbType == ListViewBackTypeEnum.create || ListViewBackTypeEnum.update == lvbType)
        {
            var item = gobject.GetComponent<colorItem>();
            bool oldIsSelect = item.IsSelect;
            bool isSelect = idx == nowidx;
            item.IsSelect = isSelect;
            item.index = idx;
            item.UseColor = group.rgb;
            item.IdName = (group.gid).ToString();
            item.NowProgress = group.Jindu;
            if(lvbType == ListViewBackTypeEnum.create || isSelect != oldIsSelect)
            {
                item.updateOneUI();
                if(lvbType == ListViewBackTypeEnum.update)
                    item.switchPlayAnimation();
            }
            if(lvbType == ListViewBackTypeEnum.create)
            {
                utilsTools.addTimer_Update(gameObject, "temp_" + idx.ToString(), (String name1) => {
                    if (item != null && item.IsDestroyed() == false)
                    {
                        item.switchPlayAnimation();
                    }
                    return false;
                }, 20 * idx);
            }
        }
    }
    
    public void onEventHandler(string eventName, List<UnityEngine.Object> uobjects, List<System.Object> objects)
    {
        if (childEventHandlers.ContainsKey(eventName))
        {
            childEventHandlers[eventName](uobjects, objects);
        }
    }
    private void onEvent_switchGameAreaGroupId_Handler(List<UnityEngine.Object> uobjects, List<System.Object> objects)
    {
        Vector3 vector3;
        Quaternion quaternion;
        var gridViewList = areaGroupList.GetComponent<gameSceneAreaGroupHandler>();
        colorItem item = null;
        if (nowidx >= 0)
        {
            item = gridViewList.getObjectById(nowidx).GetComponent<colorItem>();
            item.IsSelect = false;
            item.transform.GetLocalPositionAndRotation(out vector3, out quaternion);
            vector3.y = vector3.y - 14;
            item.transform.SetLocalPositionAndRotation(vector3, quaternion);
            item.updateOneUI();
            item.switchPlayAnimation();
        }
        var maingameView = gameShowView.GetComponent<mainGameView>();
        int idx = (int)objects[0];
        nowidx = idx;
        var nowSelectGroupId = groupInfos[idx].gid;
        item = gridViewList.getObjectById(idx).GetComponent<colorItem>();
        item.IsSelect = true;
        item.transform.GetLocalPositionAndRotation(out vector3, out quaternion);
        vector3.y = vector3.y + 14;
        item.transform.SetLocalPositionAndRotation(vector3, quaternion);
        item.switchPlayAnimation();
        maingameView.switchShowAreaGroup((short)nowSelectGroupId, (int id, bool isOk) => {
            if (isOk)
            {
                transform.Find("tipSelectGroup").gameObject.SetActive(false);
            }
        });
    }
    private void onEvent_gameViewOnInitEnd_Handler(List<UnityEngine.Object> uobjects, List<System.Object> objects)
    {
        var gridViewList = areaGroupList.GetComponent<gameSceneAreaGroupHandler>();
        
        var maingameView = gameShowView.GetComponent<mainGameView>();
        var groupInfos1 = maingameView.getGroups();
        groupInfos = new List<TempGroupInfos>();
        
        for (int i = 0; i < groupInfos1.Count; i++)
        {
            if (groupInfos1[i].Jindu == 1)
            {
                continue;
            }

            groupInfos.Add(groupInfos1[i]);
        }
        if(groupInfos.Count == 0)
        {
            utilsTools.sendEventObjectParams("inGameLoadingValue", 100f, true);
            utilsTools.setGDataByKey("enableZoomMove", false);
            return;
        }
        areaGroupList.SetActive(true);
        if (autoSwitchGroup == false) nowidx = -1;
        gradViewBack gradView = (GameObject gobject, int idx, ListViewBackTypeEnum lvbType) => {
            this.onUpdateGroupGridHandler(gobject, idx, lvbType, groupInfos[idx]);
        };
        gridViewList.setDataNoGrid(groupInfos.Count, gradView);
        if (nowidx >= 0)
        {
            maingameView.switchShowAreaGroup((short)(groupInfos[nowidx].gid), (int id, bool isOk) => {
            });
        }
        RectTransform rectTransform1 = gridViewList.GetComponent<RectTransform>();
        RectTransform rectTransform2 = transform.Find("tipSelectGroup").GetComponent<RectTransform>();
        float y = (utilsTools.DisplaySize.y / 2 - rectTransform1.rect.height / 2) * -1 + rectTransform2.rect.height + 25;
        rectTransform2.localPosition = new Vector3(rectTransform2.localPosition.x, y);
        if (autoSwitchGroup == false)
        {
            rectTransform2.gameObject.SetActive(true);
            maingameView.GetComponent<mainGameScaleMove>().setCheckInput();
            utilsTools.sendEventObjectParams("inGameLoadingValue", 100f, true);
        }
    }
    private void onEvent_gameClickPos_Handler(List<UnityEngine.Object> uobjects, List<System.Object> objects)
    {
        short x = (short)objects[0];
        short y = (short)objects[1];
        if(nowidx < 0)
        {
            transform.Find("tipSelectGroup").gameObject.SetActive(true);
            return;
        }
        var maingameView = gameShowView.GetComponent<mainGameView>();
        if(utilsTools.IsPhone == false)
        {
            maingameView.showAreaByPos(x, y, null);
        }
        else//手机不容易点中
        {
            int faulTolerant = 12;
            for (int i = 0; i < faulTolerant; i++)
            {
                if(i.Equals(0))
                {
                    if (maingameView.showAreaByPos(x, y, null) == true) return;
                    continue;
                }
                if (maingameView.showAreaByPos((short)(x + i), (short)(y + i), null) == true) return;
                if (maingameView.showAreaByPos((short)(x + i), (short)(y - i), null) == true) return;
                if (maingameView.showAreaByPos((short)(x - i), (short)(y + i), null) == true) return;
                if (maingameView.showAreaByPos((short)(x - i), (short)(y - i), null) == true) return;
            }
        }
        
    }
    private void onEvent_inGameLoadingBarEnd_Handler(List<UnityEngine.Object> uobjects, List<System.Object> objects)
    {
        areaGroupList.SetActive(true);
        RectTransform rectTransform = areaGroupList.GetComponent<RectTransform>();
        transform.Find("ingameLoad").gameObject.SetActive(false);
        utilsTools.setGDataByKey("loadingEnd", utilsTools.getTotalMillisecond());
        RectTransform transform1 = transform.Find("gameProgressText").GetComponent<RectTransform>();
        float offsetY = 0 - utilsTools.DisplaySize.y/2 + rectTransform.rect.yMax;
        transform1.localPosition = new Vector2(transform1.localPosition.x, offsetY + 15);
        transform1.gameObject.SetActive(true);
        transform1 = transform.Find("gameProgress").GetComponent<RectTransform>();
        transform1.gameObject.SetActive(true);
        transform1.localPosition = new Vector2(transform1.localPosition.x, offsetY + 35);
        gameShowView.GetComponent<mainGameScaleMove>().setCheckInput();
        gameShowView.GetComponent<mainGameView>().showTimes();
        
    }
    private void handlerLoadingPosition(Image image)
    {
        Debug.Log("handlerLoadingPosition hand endl");
        transform.Find("ingameLoad/loadImg").gameObject.SetActive(true);
        //utilsTools.setGDataByKey("downGaoQingBack", utilsTools.getTotalMillisecond());
        //float width = image.sprite.texture.width;
        //float height = image.sprite.texture.height;
        //float bet = width / height;
        //RectTransform rectTransform = image.GetComponent<RectTransform>();
        //RectTransform baseTransform = rectTransform.transform.parent.GetComponent<RectTransform>();
        //Vector2 maxSize = new Vector2(baseTransform.rect.width * 0.9f, baseTransform.rect.height * 0.9f);
        //float bet1 = 1.0f;
        //while (true)
        //{
        //    float tempWidth = rectTransform.rect.width * bet1 * rectTransform.localScale.x;
        //    float tempHeight = rectTransform.rect.width / bet * bet1 * rectTransform.localScale.y;
        //    if (tempWidth < maxSize.x && tempHeight < maxSize.y)
        //    {
        //        width = tempWidth;
        //        height = tempHeight;
        //        break;
        //    }
        //    bet1 = bet1 * 0.95f;
        //}
        //rectTransform.sizeDelta = new Vector2(width, height);
        //rectTransform.localPosition = new Vector2(0, 10f);
        //var rectTransform1 = transform.Find("ingameLoad/loadingbar").GetComponent<RectTransform>();
        //rectTransform1.localPosition = new Vector2(0, rectTransform.rect.yMin - 45f);
        //rectTransform1.sizeDelta = new Vector2(width * 0.85f, 35f);
    }
    int onDownColorImgHandler(string id, string url, bool isSuccess, System.Object data, string localpath)
    {
        if(isSuccess == false)
        {
            utilsTools.addTimer_Update(gameObject, "tryDownColorImg", (String name1) =>
            {
                utilsTools.httpDOWNIMG(this, url, localpath, (string id, string url, bool isSuccess, System.Object data) =>
                {
                    return onDownColorImgHandler(id, url, isSuccess, data,localpath);
                });
                return false;
            }, 60);
        }
        else
        {
            utilsTools.delTimeHandler(gameObject, "tryDownColorImg");
            Image image = transform.Find("ingameLoad/loadImg").GetComponent<Image>();
            Texture2D texture2d = data as Texture2D;
            Sprite sprite = Sprite.Create(texture2d, new Rect(0, 0, texture2d.width, texture2d.height), new Vector2(0.5f, 0.5f));
            image.sprite = sprite;
            image.color = Color.white;
            autoSwitchGroup = Boolean.Parse(utilsTools.getGDataByKey<string>("auto_switch", autoSwitchGroup.ToString()));
            if (autoSwitchGroup == false) nowidx = -1;
            vibration = Boolean.Parse(utilsTools.getGDataByKey<string>("vibration", vibration.ToString()));
            gameShowView.GetComponent<mainGameView>().loadGameImgId();
            this.handlerLoadingPosition(image);
        }
        return 0;
    }
    void onZipFileHandler(GameScenUserInfo gameScenUser)
    {
        Debug.Log("handlerLoadingPosition hand begin");
        string zpath = utilsTools.getWritableByPath("outFiles/" + gameScenUser.id + ".zip");
        if (utilsTools.IsPhone == false)
            zpath = zpath.Replace("/", "\\");
        gameScenUser.createWorkDirectory();
        string outPath = GameScenUserInfo.getAllRoot();
        if(utilsTools.IsPhone == false)
        {
            outPath = outPath.Replace("/", "\\");
        }
        utilsTools.setGDataByKey("beginUnZip", utilsTools.getTotalMillisecond());
        ZipUtility.UnzipFile(zpath, outPath, "tuse" + gameScenUser.id);
        utilsTools.setGDataByKey("endUnZip", utilsTools.getTotalMillisecond());

        utilsTools.setGDataByKey("nowSelectUseData", gameScenUser);
        Image image = transform.Find("ingameLoad/loadImg").GetComponent<Image>();
        image.color = new Color(1, 1, 1, 0);//未加载出来时候就透明化
        string lineImg = gameScenUser.getLineImgLocalPath();

        utilsTools.setGDataByKey("downGaoQing", utilsTools.getTotalMillisecond());
        if (utilsTools.IsExistIO(lineImg) == false)
        {
            utilsTools.httpDOWNIMG(this, gameScenUser.img, lineImg, (string id, string url, bool isSuccess, System.Object data) =>
            {
                return onDownColorImgHandler(id, url, isSuccess, data, lineImg);
            });
        }
        else
        {
            gameShowView.GetComponent<mainGameView>().loadGameImgId();
            string suoluetu = gameScenUser.getLocalThumbnailPath();
            if (utilsTools.IsExistIO(suoluetu) == false)
            {
                utilsTools.loadLocalImage(this, image, lineImg, (bool isOk) =>
                {
                    if (isOk)
                    {
                        image.color = Color.white;
                        handlerLoadingPosition(image);
                    }
                });
            }
            else
            {
                utilsTools.loadLocalImage(this, image, suoluetu, (bool isOk) =>
                {
                    if (isOk)
                    {
                        image.color = Color.white;
                        handlerLoadingPosition(image);
                    }
                });
            }
        }
    }
    void onInitViewShowDataEvent(List<UnityEngine.Object> uobjects, List<System.Object> objects)
    {
        utilsTools.setGDataByKey("firstT", utilsTools.getTotalMillisecond());
        GameScenUserInfo gameScenUser = (GameScenUserInfo)objects[0];
        string zpath = utilsTools.getWritableByPath("outFiles/" + gameScenUser.id+".zip");
        if (utilsTools.IsPhone == false)
            zpath = zpath.Replace("/", "\\");
        if (utilsTools.IsExistIO(zpath) == false)
        {
            string dir1 = utilsTools.getWritableByPath("outFiles");
            utilsTools.CreateDirectory(dir1);
            utilsTools.setGDataByKey("downZipBegin", utilsTools.getTotalMillisecond());
            //https://cdn.zhangxingames.com/file/ccNO7LSXpxA8GzQUHq1.zip in
            //"https://d21z6ifg4bbv2v.cloudfront.net/files/ccNO7LSXpxA8GzQUHq1.zip" wwww
            StartCoroutine(LoadAndBytesUnzipWithWeb(gameScenUser.file, zpath,(bool isOk) =>
            {
                if (isOk)
                {
                    utilsTools.addTimer_Update(gameObject, "unZipNext", (String _) =>{
                        utilsTools.setGDataByKey("downZipEnd", utilsTools.getTotalMillisecond());
                        onZipFileHandler(gameScenUser);
                        return false;
                    });
                }
            }));
        }
        else
        {
            onZipFileHandler(gameScenUser);
        }

    }
    IEnumerator LoadAndBytesUnzipWithWeb(string url, string exportPath,NotifyBoolParam back)
    {

        Debug.Log("exportPath : " + exportPath);

        using (UnityWebRequest uwr = UnityWebRequest.Get(url))
        {

            yield return uwr.SendWebRequest();
            if (uwr.isHttpError == true || uwr.isNetworkError == true)
            {
                Debug.Log("www.error : " + uwr.error);
                back(false);
            }
            else if (uwr.isDone == true)
            {
                var data = uwr.downloadHandler.data;
                File.WriteAllBytes(exportPath, data);
                back(true);
                // 酌情使用即可
                //File.Delete(zipPath);
                //Directory.Delete(exportPath, true);
            }
        }
    }

    void onChangeGameUserProgressEvent(List<UnityEngine.Object> uobjects,List<System.Object> objects) {
        int pro = (int)objects[0];
        transform.Find("ingameLoad").gameObject.SetActive(false);
        TextMeshProUGUI textMeshPro = transform.Find("gameProgressText").GetComponent<TextMeshProUGUI>();
        textMeshPro.text = pro.ToString() + "%";
        UnityEngine.UI.Slider slider = transform.Find("gameProgress").GetComponent<UnityEngine.UI.Slider>();
        slider.value = pro;
    }
    void onTipShowPosMaxScaleEvent(List<UnityEngine.Object> uobjects, List<System.Object> objects)
    {
        System.Object obj = objects[0];
        float width =Convert.ToInt16(objects[1]);
        float height = Convert.ToInt16(objects[2]);
        gameAreaItem gameAreaItem1 = obj as gameAreaItem;
        gameShowView.GetComponent<mainGameScaleMove>().onTipShowPosMaxScale(gameAreaItem1,width,height);
    }
    void onGamePlayerEndHandlerEvent(List<UnityEngine.Object> uobjects,List<System.Object> objects)
    {
        Debug.Log("游戏完成，播放结束动画");
        transform.Find("gameProgressText").gameObject.SetActive(false);
        transform.Find("gameProgress").gameObject.SetActive(false);
        this.areaGroupList.SetActive(false);
        gameEndLogic gameEndlogic = transform.Find("gameEndOperBase").GetComponent<gameEndLogic>();
        gameEndlogic.initView();
    }
    void onSelectAreaEvent(List<UnityEngine.Object> uobjects, List<System.Object> objects)
    {
        gameAreaItem gameArea = (gameAreaItem)objects[0];
        short x = (short)objects[1];
        short y = (short)objects[2];
        if (groupInfos != null)
        {
            var gridViewList = areaGroupList.GetComponent<gameSceneAreaGroupHandler>();
            colorItem item = null;
            groupInfos[nowidx].show++;
            if (groupInfos[nowidx].show.Equals(groupInfos[nowidx].size))//直接移除
            {
                if(nowidx == groupInfos.Count - 1)
                {
                    groupInfos.RemoveAt(nowidx);
                    nowidx--;
                }else
                    groupInfos.RemoveAt(nowidx);
                //切换组
                gradViewBack gradView = (GameObject gobject, int idx, ListViewBackTypeEnum lvbType) => {
                    this.onUpdateGroupGridHandler(gobject, idx, lvbType, groupInfos[idx]);
                };
                gridViewList.setDataNoGrid(groupInfos.Count, gradView);
                //震动
                if (vibration)
                {
                    Handheld.Vibrate();
                }
                if (nowidx >= 0)
                {
                    if(autoSwitchGroup == false)
                    {
                        nowidx = -1;
                        return;
                    }
                    var maingameView = gameShowView.GetComponent<mainGameView>();
                    maingameView.switchShowAreaGroup((short)(groupInfos[nowidx].gid), (int id, bool isOk) => {
                    });
                }
            }
            else
            {
                item = gridViewList.getObjectById(nowidx).GetComponent<colorItem>();
                item.NowProgress = groupInfos[nowidx].Jindu;
            }
        }
    }
    public void onCloseGameSceneEvent(List<UnityEngine.Object> uobjects, List<System.Object> objects)
    {

        gameShowView.GetComponent<mainGameView>().onClear();
        //SceneManager.LoadScene("Scenes/MainHallGame");
        utilsTools.setGDataByKey("NativeTempData", "main");
        SceneManager.LoadScene("Scenes/MainGame");
    }
    public void onTestTemp1()
    {
        //Image image = transform.Find("ingameLoad/loadImg").GetComponent<Image>();
        //handlerLoadingPosition(image);
        gameShowView.GetComponent<gameUserInfos>().updateProgress();
    }
    public void skipToHome()
    {
        utilsTools.sendEvent("closeGameScene");
    }
    public void OnDestroy()
    {
        IRunEventManages.unOn(this, null);
        ActionManages.clearAllAction();
    }
}
