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;
    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);
        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.setGameScenUserInfo(jsonData.id, jsonData.getLineUrl(), jsonData.getColorUrl(), jsonData.getJsonUrl(), jsonData.file);
                startId(jsonData.id);
            }
            return false;
        }, 2);


    }
    
    public void loadTest()
    {
        string id = "ccNO7LSXpxA8GzQUHq";
        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)
    {
        GameScenUserInfo gameScenUser = utilsTools.getGameScenUserInfo(id);
        if(gameScenUser == null)
        {
            return;
        }
        utilsTools.sendEventObjectParams("initViewShowData", gameScenUser);
        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);
    }
    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<int>("imgId",-1).ToString());
        param1.Add("uid", utilsTools.getGDataByKey<string>("uid","-1"));
        float allAreaSize = (float)utilsTools.getGDataByKey<int>("allAreaSize", 0);
        float jindu = gameScenUserInfo.areaInfoUseData.Count / allAreaSize;
        param1.Add("schedule",jindu.ToString());
        param1.Add("append", gameScenUserInfo.getAllShowAreaId());
        String jsonParam = "{";
        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) =>{
            return 0;
        };
        
        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);
    }
}
