using Assets.scripts.Datas;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Assertions;

public class gameUserInfos : MonoBehaviour, IEventHandler
{
    private string gameSaveKey = "";
    private GameScenUserInfo gameScenUserInfo = null;
    private bool historyInfoFromNet = false;
    Dictionary<string, EventChildItemBack> childEventHandlers = new Dictionary<string, EventChildItemBack>();
    void onEvent(string name, EventChildItemBack func)
    {
        utilsTools.onEvent(this, name);
        childEventHandlers.Add(name, func);
    }
    void Start()
    {
        onEvent("showAreaEventOk", onSelectAreaEvent);
        onEvent("showAreaPalyerEnd", onShowAreaPalyerEndEvent);
        onEvent("inGameLoadingBarEnd", onInGameLoadingBarEndEvent);
        onEvent("CloseScenePrve", onCloseScenePrveHandler);
        utilsTools.addTimer_Update(gameObject, "first", (string name) =>
        {
            if (utilsTools.ContainsKeyGDataByKey("NativeGameData") == false)
            {
                loadTest();
            }
            else
            {
                netLableImageItem jsonData = utilsTools.getGDataByKey<netLableImageItem>("NativeGameData", null);
                if (jsonData == null)
                {
                    Debug.LogError("no valid data");
                    return false;
                }
                utilsTools.setGDataByKey("imgId", jsonData.sid.ToString());
                utilsTools.setGameScenUserInfo(jsonData.id, jsonData.getLineUrl(), jsonData.getColorUrl(), jsonData.getJsonUrl(), jsonData.file);
                utilsTools.removeGDataByKey("history");
                utilsTools.removeGDataByKey("historyNotify");
                if (historyInfoFromNet)
                {
                    utilsTools.httpGET(this, "{0}/app/v1/game/ts/imgSchedule?zygt=hzwz&tgtk=1&imgId={1}&uid={2}", true, (string id, string url, bool isSuccess, System.Object data) =>
                    {
                        if (isSuccess)
                        {
                            HistoryClick historyClick = JsonUtility.FromJson<HistoryClick>(data as string);
                            utilsTools.sendEvent("updateSchedules");
                            if (historyClick == null)
                            {
                                utilsTools.setGDataByKey("history", "");
                                return 0;
                            }
                            string history = historyClick.getHistory();
                            if (gameScenUserInfo == null)
                            {
                                utilsTools.setGDataByKey("history", history);
                                return 0;
                            }
                            gameScenUserInfo.setShowAreaids(history);
                            var back = utilsTools.getGDataByKey<NotifyEmptParam>("historyNotify", null);
                            if (back != null)
                            {
                                back();
                            }
                            return 0;
                        }
                        else
                        {
                            return 1;
                        }
                    }, utilsTools.getGDataByKey<String>("urlRoot", ""), jsonData.sid, utilsTools.getGDataByKey<String>("uid", "123456"));
                }
                if (historyInfoFromNet)
                {
                    //让上边的获取进度url先走，防止界面已经显示但是进度网络波动出现无法显示老的值
                    utilsTools.addTimer_Update(gameObject, "wait5fps", (String n) =>
                    {
                        startId(jsonData.id, jsonData);
                        return false;
                    }, 5);
                }
                else
                {
                    startId(jsonData.id, jsonData);
                }
                
            }
            return false;
        }, 2);


    }
    
    public void loadTest()
    {
        string id = "ccnKNH1bTLS-_Mg7A2";
        GameScenUserInfo gameScenUser = utilsTools.getGameScenUserInfo(id);
        if (gameScenUser == null)
        {
            //{"img":"https://d21z6ifg4bbv2v.cloudfront.net/tspng/ccNO7LSXpxA8GzQUHq.png","json":"https://d21z6ifg4bbv2v.cloudfront.net/tsjson/ccNO7LSXpxA8GzQUHq.json","finishImg":"https://d21z6ifg4bbv2v.cloudfront.net/tsgame/ccNO7LSXpxA8GzQUHq_pictureColorThn4.jpg","id":"ccNO7LSXpxA8GzQUHq","status":0,"progress":0.0,"areaInfoUseData":[]}
            //utilsTools.setGameScenUserInfo(id,"http://192.168.124.160:8795/srcImgs/colorFan/tuline.png","http://192.168.124.160:8795/srcImgs/colorFan/tucolor.png","http://192.168.124.160:8795/srcImgs/colorFan/tu.json");
            //utilsTools.setGameScenUserInfo(id, "http://192.168.124.160:8795/srcImgs/temp2/tuline.png", "http://192.168.124.160:8795/srcImgs/temp2/tucolor.jpg", "http://192.168.124.160:8795/srcImgs/temp2/tu.json");
            utilsTools.setGameScenUserInfo(id, "https://d21z6ifg4bbv2v.cloudfront.net/tspng/ccNO7LSXpxA8GzQUHq.png", "https://d21z6ifg4bbv2v.cloudfront.net/tsgame/ccNO7LSXpxA8GzQUHq_pictureColorThn4.jpg", "https://d21z6ifg4bbv2v.cloudfront.net/tsjson/ccNO7LSXpxA8GzQUHq.json", "https://d21z6ifg4bbv2v.cloudfront.net/tsgame/ccNO7LSXpxA8GzQUHq.zip");
            gameScenUser = utilsTools.getGameScenUserInfo(id);
        }
        if (gameScenUser == null)
        {
            Debug.Log("无法加载测试图片信息");
            return;
        }
        startId(id);
    }
    // Update is called once per frame
    void Update()
    {   
    }
    public void startId(string id,netLableImageItem jsondata = null)
    {
        GameBackJavaData gameBackJavaData = new GameBackJavaData();
        gameBackJavaData.name = "main";
        gameBackJavaData.schedule = 0;
        if(jsondata != null)
        {
            gameBackJavaData.sid = jsondata.sid.ToString();
        }
        else
        {
            gameBackJavaData.sid = id;
        }
        utilsTools.setGDataByKey("gameBackJavaData", gameBackJavaData);
        GameScenUserInfo gameScenUser = utilsTools.getGameScenUserInfo(id);
        if(gameScenUser == null)
        {
            return;
        }
        if(historyInfoFromNet == false)
        {
            string history = utilsDB.getDBStringDataByKey("history_"+id,"");
            gameScenUser.setShowAreaids(history);
        }
        
        if(jsondata != null)
        {
            gameScenUser.thumbnailUrl = jsondata.getSmallLineUrl();
        }
        utilsTools.sendEventObjectParams("initViewShowData", gameScenUser);
        if (utilsTools.ContainsKeyGDataByKey("history"))
        {
            gameScenUser.setShowAreaids(utilsTools.getGDataByKey<string>("history",""));
        }
        gameScenUserInfo = gameScenUser;
    }

    void IEventHandler.onEventHandler(string eventName, List<UnityEngine.Object> uobjects, List<System.Object> objects)
    {
        if (childEventHandlers.ContainsKey(eventName)) childEventHandlers[eventName](uobjects, objects);
    }
    //永久保存
    void onSelectAreaEvent(List<UnityEngine.Object> uobjects, List<System.Object> objects)
    {
        if(gameScenUserInfo != null)
        {
            gameAreaItem gameArea = (gameAreaItem)objects[0];
            short x = (short)objects[1];
            short y = (short)objects[2];
            float allAreaSize = (float)utilsTools.getGDataByKey<int>("allAreaSize", 0);
            float old = gameScenUserInfo.areaInfoUseData.Count / allAreaSize * 100;
            AreaInfoUseData areaInfoUseData = new AreaInfoUseData();
            areaInfoUseData.clickX = x;
            areaInfoUseData.clickY = y;
            areaInfoUseData.id = gameArea.id;
            gameScenUserInfo.areaInfoUseData.Add(areaInfoUseData);
            gameScenUserInfo.progress = gameScenUserInfo.areaInfoUseData.Count / allAreaSize;
            int now = Convert.ToInt32(gameScenUserInfo.areaInfoUseData.Count / allAreaSize * 100);
            if((now - Convert.ToInt32(old)) > 0)
            {
                utilsTools.sendEventObjectParams("changeGameUserProgress", now);
            }
        }
    }
    void onShowAreaPalyerEndEvent(List<UnityEngine.Object> uobjects, List<System.Object> objects)
    {
        if(gameScenUserInfo != null)
        {
            utilsTools.saveGameScenUserInfo(gameScenUserInfo);
            return;
        }
    }
    void onInGameLoadingBarEndEvent(List<UnityEngine.Object> uobjects,List<System.Object> objects)
    {
        if (gameScenUserInfo == null) return;
        float allAreaSize = (float)utilsTools.getGDataByKey<int>("allAreaSize", 0);
        int now = Convert.ToInt32(gameScenUserInfo.areaInfoUseData.Count / allAreaSize * 100);
        utilsTools.sendEventObjectParams("changeGameUserProgress", now);
    }
    void onCloseScenePrveHandler(List<UnityEngine.Object> uobject,List<System.Object> objects)
    {
        Debug.Log("onCloseScenePrveHandler 1");
        if (gameScenUserInfo != null)
        {
            utilsTools.saveGameScenUserInfo(gameScenUserInfo);
            float allAreaSize = (float)utilsTools.getGDataByKey<int>("allAreaSize", 0);
            float schedule1 = (int)(gameScenUserInfo.areaInfoUseData.Count * 100f / allAreaSize);
            int schedule = 0;
            if (schedule1 < 1.00001)
            {
                if (allAreaSize < 1)
                    schedule = 0;
                else
                    schedule = 1;
            }
            else if (schedule1 > 98.999999991)
            {
                if (utilsTools.getGDataByKey<int>("allAreaSize", 0).Equals(gameScenUserInfo.areaInfoUseData.Count))
                {
                    schedule = 100;
                }
                else
                {
                    schedule = 99;
                }
            }
            else
            {
                schedule = (int)schedule1;
            }
            var gameBackJavaData = utilsTools.getGDataByKey<GameBackJavaData>("gameBackJavaData", null);
            gameBackJavaData.schedule = schedule;
            utilsTools.setGDataByKey("gameBackJavaData", gameBackJavaData);
            updateProgress();
            
            gameScenUserInfo = null;//直接释放如果期间没有保存，就一起丢失
        }
    }
    public void updateProgress()
    {
        String urlRoot = utilsTools.getGDataByKey<String>("urlRoot", "");
        String url = String.Format("{0}/app/v1/game/ts/saveImgSchedule?zygt=hzwz&tgtk=1", urlRoot);
        Dictionary<String, System.Object> param1 = new Dictionary<string, System.Object>();
        param1.Add("imgId", utilsTools.getGDataByKey<string>("imgId","-1"));
        param1.Add("uid", utilsTools.getGDataByKey<string>("uid","123456"));
        float allAreaSize = (float)utilsTools.getGDataByKey<int>("allAreaSize", 0);
        float jindu = gameScenUserInfo.areaInfoUseData.Count / allAreaSize;
        param1.Add("schedule",jindu.ToString());
        string allShowAreaId = gameScenUserInfo.getAllShowAreaId();
        param1.Add("append",allShowAreaId);
        String jsonParam = "{";
        utilsDB.setDBStringDataByKey("history_" + gameScenUserInfo.id, allShowAreaId);
        foreach (var item in param1)
        {
            jsonParam = string.Format("{0}\"{1}\":\"{2}\",",jsonParam,item.Key,item.Value.ToString());
        }
        if (jsonParam.EndsWith(","))
        {
            jsonParam = jsonParam.Substring(0,jsonParam.Length-1);
        }
        jsonParam = jsonParam + "}";
        onUrlBackHandler back = (string id, string url, bool isSuccess, System.Object data) =>{
            if (isSuccess)
            {
                Debug.Log("onUpdateProgress " + data.ToString());
            }
            else
            {
                Debug.Log("error");
            }
            return 0;
        };
        Debug.Log("---------- " + url);
        utilsTools.httpPOST(this, url, jsonParam, true,back);
    }
    
    public void OnDestroy()
    {
        
        if(gameScenUserInfo != null)
        {
            utilsTools.saveGameScenUserInfo(gameScenUserInfo);
            
            updateProgress();
            gameScenUserInfo = null;//直接释放如果期间没有保存，就一起丢失
        }
        childEventHandlers.Clear();
        IRunEventManages.unOn(this, null);
    }
}
