using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using TMPro;
using Unity.VisualScripting;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

public class TempGroupInfos
{
    public Color rgb;
    public int gid;
    
    public short size = 0;
    public short show = 0;
    public float Jindu
    {
        get { return (float)show / (float)size; }
    }

}
class AreaAnimationDiffuse
{
    public short m_x;
    public short m_y;
    public short m_aid;
    public short m_fpsStart = 1;//r 开始
    public short m_fpsEnd = 20;//r 结束
    public AreaAnimationDiffuse(short x,short y,short aid)
    {
        m_x = x;
        m_y = y;
        m_aid = aid;
    }
}
class Vector2Short
{
    public short x;
    public short y;
    public Vector2Short(short x,short y)
    {
        this.x = x;
        this.y = y;
    }
}
class GroupByAreaPtInfos
{
    private Dictionary<short, List<Vector2Short>> datas = new Dictionary<short, List<Vector2Short>>();
    public bool getDataByAid(short aid,ref List<Vector2Short> data)
    {
        if(datas.ContainsKey(aid))
        {
            data = datas[aid];
            return true;
        }
        return false;
    }
    public void appendPos(short aid,short x,short y) {
        if(datas.ContainsKey(aid) == false)
        {
            datas.Add(aid, new List<Vector2Short>());
        }
        datas[aid].Add(new Vector2Short(x, y));
        return;
    }
    public void removeAid(short aid)
    {
        datas.Remove(aid);
    }
}
public class mainGameView : MonoBehaviour
{
    private gameIdJsonData gameidJsondata = null;
    private string progresName = "";
    public GameObject lineImg = null;//线图
    public GameObject colorImg = null;//颜色图
    public GameObject lowImg = null;//底图
    public GameObject areaIdBase = null;
    [Header("区域id的预制体")]
    public string perfabPath = "";
    private GameObject areaIdperfabObj = null;
    public DigitMatrixShort digitMatrix = null;
    public float minShowFontSize = 15f;
    public float showFontSizeMax = 30f;
    protected Texture2D lineTexture2d = null;
    public Texture2D lowImgTexture2d = null;
    protected short nowSelectgid = -1;
    private string[] initDigitMatrixs = { "", "" };
    private Dictionary<short, short> aid2selectOrderIdx = new Dictionary<short, short>();
    private Vector3 prveAreaIdScale = new Vector3(-100, -100);
    private GameScenUserInfo gameScenUseInfo = null;
    //x,y aid 当前帧向量 起点终点 等宽度计算扩散
    private List<AreaAnimationDiffuse> showAreaAnimationDatas = new List<AreaAnimationDiffuse>();
    private Dictionary<short, GroupByAreaPtInfos> groupPtInfos = new Dictionary<short, GroupByAreaPtInfos>();

    public void onInitDigitMatrix(string name)
    {
        
        Debug.Log("onInitDigitMatrix >> " + name);
        if (lowImg == null && name.Equals("select") == false) 
            onInitDigitMatrix("select");
        for (int i = 0; i < initDigitMatrixs.Count(); i++)
        {
            if (initDigitMatrixs[i].Equals(""))
            {
                initDigitMatrixs[i] = name;
                break;
            }
            else if (initDigitMatrixs[i].Equals(name)) return;
        }
        if (initDigitMatrixs[initDigitMatrixs.Length - 1].Equals("")) return;
        nowSelectgid = -1;
        onInitEndHandler();
    }
    protected string getSelectPathByGid(int gid)
    {
        return gameScenUseInfo.getPathByFormath("groupId_{0}.png",gid);
    }
    public void saveGroupTexture(int pgid,Texture2D nowGroupIdTexture,bool isDestroy = true)
    {
        string temppath = getSelectPathByGid(pgid);
        utilsTools.saveByteToPath(nowGroupIdTexture.EncodeToPNG(), temppath);
        utilsTools.saveImageDefaultMetaInfoToPath(temppath);
        if (isDestroy)
        {
            GameObject.Destroy(nowGroupIdTexture);
            nowGroupIdTexture = null;
        }
    }
    public bool addTaskInMakeGroupMap(int i, Texture2D lowImgTexture2dFirst,bool isNowShow)
    {
        var tm = TaskManages.getInstance();
        var group = gameidJsondata.roomGroupsData[i];
        short pgid = group.id;
        if (group.isComplete) return false;
        string temppath = getSelectPathByGid(pgid);
        if (utilsTools.IsExistIO(temppath))
        {
            Debug.Log("已经存在所以跳过 " + pgid.ToSafeString());
            return false;
        }
        Texture2D nowGroupIdTexture = null;
        Tuple<bool, int, Texture2D> tuple = new Tuple<bool, int, Texture2D>(isNowShow, i, nowGroupIdTexture);
        for (int i1 = 0; i1 < gameidJsondata.roomGroupsData[i].roomIds.Count(); i1++)
        {
            var aid1 = gameidJsondata.roomGroupsData[i].roomIds[i1];
            System.Object[] taskParams = { aid1, pgid,isNowShow, temppath };
            tm.addTask(this, (System.Object[] listparam) =>
            {
                bool isGameShow = (bool)listparam[2];
                if(isGameShow == true && utilsTools.IsExistIO(temppath) == true)
                {
                    if(nowGroupIdTexture != null)
                    {
                        GameObject.Destroy(nowGroupIdTexture);
                        nowGroupIdTexture = null;
                    }
                    return;
                }
                if (nowGroupIdTexture == null)
                {
                    nowGroupIdTexture = new Texture2D(lowImgTexture2dFirst.width, lowImgTexture2dFirst.height, lowImgTexture2dFirst.format, false);
                    nowGroupIdTexture.LoadRawTextureData(lowImgTexture2dFirst.GetRawTextureData());
                }
                int aid = (short)listparam[0];
                var areaInfo = gameidJsondata.roomDatas[aid];
                short tempgid = (short)listparam[1];
                
                int setcout = 0;
                digitMatrix.PeekFloodFill8WithStack(areaInfo.px, areaInfo.py, -5, (short)(aid + 20), (short x1, short y1, short c) =>
                {
                    nowGroupIdTexture.SetPixel(x1, y1, Color.white);
                    setcout = setcout + 1;
                    return true;
                });
                
            }, taskParams);
        }
        System.Object[] param1 = { pgid,isNowShow};
        tm.addTask(this, (System.Object[] listparam) =>
        {
            bool isGameShow = (bool)listparam[1];
            if (isGameShow == true && utilsTools.IsExistIO(temppath) == true)
            {
                if (nowGroupIdTexture != null)
                {
                    GameObject.Destroy(nowGroupIdTexture);
                    nowGroupIdTexture = null;
                }
                return;
            }
            if (nowGroupIdTexture != null)
            {
                saveGroupTexture((short)listparam[0], nowGroupIdTexture);
                if (isGameShow == false) utilsTools.sendEventObjectParams("inGameLoadingValue", 6f, false);
                
            }
        }, param1);
        return true;
    }
    public void onLoadFileOk(int typeId)
    {
        if (typeId == 1)
        {
            Debug.Log("begin init lunkuo");
            Image image = lineImg.GetComponent<Image>();
            lineTexture2d = image.sprite.texture;
            digitMatrix = new DigitMatrixShort(lineTexture2d.width, lineTexture2d.height);
            TaskManages taskManages = TaskManages.getInstance();
            TaskItemBack taskItemBack = (System.Object[] datas) => {
                int x = (int)datas[0];
                int setp = (int)datas[1];
                int height = (int)datas[2];
                utilsTools.sendEventObjectParams("inGameLoadingValue", 4f, false);
                for (int i = x; i < (x + setp); i++)
                {
                    for (int j = 0; j < height; j++)
                    {
                        Color color = lineTexture2d.GetPixel(i, j);
                        if (color.a == 0)
                        {
                            digitMatrix.Data[i, j] = 0;
                            lineTexture2d.SetPixel(i, j, Color.white);
                            if (x == 0)
                            {
                                TaskManages.getInstance().addTask(this, (System.Object[] params1) =>
                                {
                                    lineTexture2d.Apply();
                                    utilsTools.saveByteToPath(lineTexture2d.EncodeToPNG(), gameScenUseInfo.getLineImgLocalPath());
                                });
                            }
                        }
                        else if (color.r >= 0.97 && color.g >= 0.97 && color.b >= 0.97)
                        {
                            digitMatrix.Data[i, j] = 0;
                        }
                        else
                        {
                            digitMatrix.Data[i, j] = -1;
                        }

                    }
                }
                if((x + setp) >= (lineTexture2d.width - 1))
                {
                    TaskItemBack taskItemBack1 = (System.Object[] param) =>
                    {
                        gameAreaItem gai = (gameAreaItem)param[0];
                        if (aid2selectOrderIdx != null && aid2selectOrderIdx.ContainsKey(gai.id))
                        {
                            Color color = new Color(1, 1, 1, 0);
                            digitMatrix.FloodFill8WithStack(gai.px, gai.py, (short)(-1), 0, (short x, short y, short c) => {
                                lineTexture2d.SetPixel(x, y, color);                                
                                return true;
                            });
                        }
                        else
                        {
                            if (groupPtInfos.ContainsKey(gai.gid) == false)
                            {
                                groupPtInfos.Add(gai.gid, new GroupByAreaPtInfos());
                            }
                            digitMatrix.FloodFill8WithStack(gai.px, gai.py, (short)(gai.id + 20), 0, (short x, short y, short c) => {
                                groupPtInfos[gai.gid].appendPos(gai.id, x, y);
                                return true;
                            });

                        }
                    };
                    //给每一个空白设置 区域id
                    for (int i = 0; i < gameidJsondata.roomDatas.Count; i++)
                    {
                        var item = gameidJsondata.roomDatas[i];
                        if (digitMatrix.Data[item.px,item.py] == 0){
                            System.Object[] temps = { item };
                            taskManages.addTask(this, taskItemBack1, temps);
                        }
                    }
                    taskManages.addTask(this, (System.Object[] objects) =>
                    {
                        lineTexture2d.Apply();
                    });
                    onInitDigitMatrix("line");

                }
            };
            int tempsetp = 200;
            for (int i = 0; i < lineTexture2d.width; i+=tempsetp)
            {
                System.Object[] objects = { i, tempsetp, lineTexture2d.height };
                if(i + tempsetp + tempsetp > lineTexture2d.width)
                {
                    objects[1] = lineTexture2d.width - i;
                    taskManages.addTask(this, taskItemBack, objects);
                    break;
                }
                taskManages.addTask(this, taskItemBack,objects);
            }
        }else if(typeId == 4)
        {
            TaskManages tm = TaskManages.getInstance();
            TaskItemBack checkPtNextHandler = null;
            checkPtNextHandler = (System.Object[] listparam) =>
            {
                var checkPt = gameidJsondata.roomDatas[gameidJsondata.roomDatas.Count-1];
                if(digitMatrix == null)
                {
                    tm.addTask(this, checkPtNextHandler, listparam);
                    return;
                }
                Debug.Log(checkPt.ToString());
                float flg = digitMatrix.Data[checkPt.px,checkPt.py];
                if(flg == 0)
                {
                    tm.addTask(this, checkPtNextHandler);
                    return;
                }
                utilsTools.sendEventObjectParams("inGameLoadingValue", 5f, false);
                gameidJsondata.roomGroupsData.Sort(gameAreaGroupItem.sortByIsComplete);
                if (areaIdBase != null && perfabPath.Equals("") == false)
                {
                    //创建一堆节点
                    TaskItemBack onUpdateByIdNode = (System.Object[] listparam) =>
                    {
                        utilsTools.sendEventObjectParams("inGameLoadingValue", 5f, false);
                        checkAddAreaId();
                        onInitDigitMatrix("select");
                    };
                    tm.addTask(this, onUpdateByIdNode);
                }
                else
                {
                    onInitDigitMatrix("select");
                }
            };
            tm.addTask(this, checkPtNextHandler);
            
        }else if(typeId == 3)
        {
            TaskManages tm = TaskManages.getInstance();
            TaskItemBack firstHandlGid = (System.Object[] temp) => {
                utilsTools.sendEventObjectParams("inGameLoadingValue", 2f, false);
                for (int i = 0; i < gameidJsondata.roomGroupsData.Count; i++)
                {
                    var group = gameidJsondata.roomGroupsData[i];                    
                    for (int i1 = 0; i1 < group.roomIds.Count(); i1++)
                    {
                        gameidJsondata.roomDatas[group.roomIds[i1]].gid = group.id;
                    }
                }
                return;
            };
            tm.addTask(this, firstHandlGid);
        }
    }
    protected void checkAddAreaId()
    {
        int j = 0;
        float width = gameidJsondata.width;
        float height = gameidJsondata.height;
        Vector3 localPosTemp = new Vector3();
        Quaternion quaternion = new Quaternion();
        var areaIdBaseTransform = areaIdBase.transform.GetComponent<RectTransform>();
        Vector3 vector3 = areaIdBase.transform.localScale;
        prveAreaIdScale = vector3;
        for (int i = 0; i < gameidJsondata.roomDatas.Count; i++)
        {
            var item = gameidJsondata.roomDatas[i];
            if (digitMatrix.Data[item.px, item.py] >= 20)
            {
                item.tempExKey = "idFlg_" + j.ToSafeString();
                j++;
                //转成物体坐标系?
                Transform idValueTran = areaIdBase.transform.Find(item.tempExKey);
                if (idValueTran == null)
                {
                    if (areaIdperfabObj == null)
                    {
                        areaIdperfabObj = Resources.Load<GameObject>(perfabPath);
                    }
                    GameObject idGameObject = Instantiate(areaIdperfabObj);
                    idValueTran = idGameObject.transform;
                    idValueTran.parent = areaIdBase.transform;
                    idGameObject.name = item.tempExKey;
                }
                //怎么转换坐标
                RectTransform rectTransform = areaIdBase.transform.parent.GetComponent<RectTransform>();
                //坐标怎么设置？
                idValueTran.GetLocalPositionAndRotation(out localPosTemp, out quaternion);
                //严格居中 字体大小等问题 需要调整json的生成脚本生成逻辑后才能继续
                localPosTemp.x = (float)item.px / (float)width * rectTransform.rect.width - (rectTransform.rect.width / 2);
                localPosTemp.y = (float)item.py / (float)height * rectTransform.rect.height - (rectTransform.rect.height / 2);
                idValueTran.SetLocalPositionAndRotation(localPosTemp, quaternion);
                TextMeshProUGUI textMesh = idValueTran.GetComponent<TextMeshProUGUI>();
                textMesh.text = (item.gid).ToString();
                float fontSize = item.pr;

                if (fontSize > showFontSizeMax) fontSize = showFontSizeMax;
                textMesh.fontSize = fontSize;
                
                if ((fontSize * vector3.x) < minShowFontSize)
                {
                    idValueTran.gameObject.SetActive(false);
                }
                else
                {
                    idValueTran.gameObject.SetActive(true);
                }
            }
        }
        for (int i = j; i < short.MaxValue; i++)
        {
            Transform idValueTran = areaIdBase.transform.Find("idFlg_" + i.ToSafeString());
            if (idValueTran == null) break;
            idValueTran.SetParent(null);
            GameObject.Destroy(idValueTran.gameObject);
        }
    }
    public void updateScaleView()
    {
        Vector3 vector3 = lineImg.transform.localScale;
        if (areaIdBase != null && perfabPath.Equals("") == false)
        {
            //倍数怎么弄
            for (int i = 0; i < gameidJsondata.roomDatas.Count; i++)
            {
                var item = gameidJsondata.roomDatas[i];
                if (item.tempExKey.Equals("") == false)
                {
                    Transform idValueTran = areaIdBase.transform.Find(item.tempExKey);
                    if (idValueTran == null) continue;
                    float fontSize = item.pr * vector3.x;
                    if(fontSize < minShowFontSize)
                    {
                        idValueTran.gameObject.SetActive(false);
                    }
                    else
                    {
                        idValueTran.gameObject.SetActive(true);
                    }
                }
            }
        }
    }
    protected void onInitEndHandler()
    {
        utilsTools.sendEvent("gameViewOnInitEnd");
        if(lowImg == null)
        {
            utilsTools.sendEventObjectParams("inGameLoadingValue", 100f, true);
        }
    }
    public void loadFileInfo(string url,string localpath,int typeId)
    {
        if (typeId == 1 || typeId == 2)
        {
            
            utilsTools.httpDOWNIMG(this, url, localpath, (string id, string url1, bool isSuccess, System.Object data) =>
            {
                if(isSuccess == false)
                {
                    utilsTools.addTimer_Sec(gameObject, url1, (string name1) =>
                    {
                        loadFileInfo(url1, localpath, typeId);
                        return false;
                    },5);
                    return 0;
                }
                else
                {
                    utilsTools.saveImageDefaultMetaInfoToPath(localpath);
                    utilsTools.sendEventObjectParams("inGameLoadingValue", 8f, false);
                    Image image = null;
                    if(typeId == 1)
                    {
                        image = this.lineImg.GetComponent<Image>();
                    }else if(typeId == 2)
                    {
                        image = this.colorImg.GetComponent<Image>();
                    }
                    Texture2D texture2d = data as Texture2D;
                    image.sprite = Sprite.Create(texture2d, new Rect(0, 0, texture2d.width, texture2d.height), new Vector2(0.5f, 0.5f));
                    if(lowImg != null && typeId == 1)
                    {
                        string lowPath = gameScenUseInfo.getPathByFormath("../{0}_{1}X{2}.png","bule",texture2d.width,texture2d.height);
                        if(utilsTools.IsExistIO(lowPath) == false)
                        {
                            Texture2D lowTexture = new Texture2D(texture2d.width, texture2d.height, TextureFormat.RGBA32, false);
                            Color color = new Color(1, 1, 1, 0);
                            for (int x = 0; x < texture2d.width; x++)
                            {
                                for(int y = 0;y < texture2d.height; y++)
                                {
                                    lowTexture.SetPixel(x, y, color);
                                }
                            }
                            utilsTools.saveByteToPath(lowTexture.EncodeToPNG(), lowPath);
                            utilsTools.saveImageDefaultMetaInfoToPath(lowPath);
                        }
                        Image lowImgView = lowImg.GetComponent<Image>();
                        utilsTools.loadLocalImage(this, lowImgView, lowPath, (bool isOk) => {
                            if (isOk)
                            {
                                utilsTools.sendEventObjectParams("inGameLoadingValue", 10f, false);
                                lowImgTexture2d = lowImgView.sprite.texture;
                                onLoadFileOk(4);
                            }
                        });
                    }
                    onLoadFileOk(typeId);
                    return 1;
                }
            });
        }else if(typeId == 3)
        {
            utilsTools.httpDownText(this, url, localpath, (string id, string url1, bool isSuccess, System.Object data) =>
            {
                if(isSuccess == false)
                {
                    utilsTools.addTimer_Sec(gameObject, url1, (string name1) =>
                    {
                        loadFileInfo(url1, localpath, typeId);
                        return false;
                    }, 5);
                    return 0;
                }
                else
                {
                    utilsTools.sendEventObjectParams("inGameLoadingValue", 8f, false);
                    string jsondata = data as string;
                    this.gameidJsondata = JsonUtility.FromJson<gameIdJsonData>(jsondata);
                    int centerSize = gameidJsondata.roomDatas.Count();
                    foreach (var item in aid2selectOrderIdx)
                    {
                        gameidJsondata.roomDatas[item.Key].isShow = true;
                    }
                    for(int i = 0;i < gameidJsondata.roomGroupsData.Count(); i++)
                    {
                        var group = gameidJsondata.roomGroupsData[i];
                        group.isComplete = true;
                        for (int j = 0; j < group.roomIds.Count(); j++)
                        {
                            if (gameidJsondata.roomDatas[group.roomIds[j]].isShow == false)
                            {
                                group.isComplete = false;
                                break;
                            }
                        }
                    }
                    onLoadFileOk(typeId);
                    return 0;
                }
            });
        }
    }
    public bool loadGameImgId(GameScenUserInfo gameUserInfo)
    {
        string linePath = gameUserInfo.getLineImgLocalPath();
        string colorPath = gameUserInfo.getColorImgLocalPath();
        string jsonPath = gameUserInfo.getJsonLocalPath();
        string thumbnail = gameUserInfo.getLocalThumbnailPath();
        if(jsonPath.Equals("") || linePath.Equals("") || colorPath.Equals("") || thumbnail.Equals(""))
        {
            return false;
        }
        if (false == gameUserInfo.createWorkDirectory())return false;
        utilsTools.sendEventObjectParams("inGameLoadingValue", 3f, false);
        this.gameScenUseInfo = gameUserInfo;
        for (short i = 0; i < gameUserInfo.areaInfoUseData.Count; i++)
        {
            var userAreaData = gameUserInfo.areaInfoUseData[i];
            aid2selectOrderIdx.Add(userAreaData.id, i);
        }
        loadFileInfo(gameUserInfo.json, jsonPath, 3);
        loadFileInfo(gameUserInfo.img,linePath, 1);
        loadFileInfo(gameUserInfo.finishImg, colorPath, 2);
        return true;
    }
    public bool loadGameImgId(string lineUrl,string colorUrl,string jsonUrl,string gid,List<short> selectIds = null)
    {
        throw new NotImplementedException();
    }
    public void showArea(int areaId, OnAreaHandler onAreaHandler = null)
    {
        //显示指定区域
        if(digitMatrix !=null && lineTexture2d != null && gameidJsondata != null && areaId >= 0 && areaId < gameidJsondata.roomDatas.Count)
        {   
            gameAreaItem areaItem1 = gameidJsondata.roomDatas[areaId];
            short oldValue = digitMatrix.Data[areaItem1.px, areaItem1.py];
            if (oldValue == -2)
            {
                if(onAreaHandler != null)
                    onAreaHandler(areaItem1.id, true);
                return;
            }
            if (!areaItem1.tempExKey.Equals(""))
            {
                var nowIdNode = areaIdBase.transform.Find(areaItem1.tempExKey);
                nowIdNode.SetParent(null);
                GameObject.Destroy(nowIdNode.gameObject);
                areaItem1.tempExKey = "";
            }
            TaskManages task = TaskManages.getInstance();
            TaskItemBack taskItemBack = (System.Object[] param) =>
            {
                Color color = new Color(0, 0, 0, 0);
                gameAreaItem areaItem = (gameAreaItem)param[0];
                short oldValue1 = digitMatrix.Data[areaItem.px, areaItem.py];
                digitMatrix.FloodFill8WithStack(areaItem.px, areaItem.py, -2, oldValue1, (short x1, short y1, short v) => {
                    color = lineTexture2d.GetPixel(x1, y1);
                    color.a = 0;
                    lineTexture2d.SetPixel(x1, y1, color);
                    color = lowImgTexture2d.GetPixel(x1, y1);
                    color.a = 0;
                    lowImgTexture2d.SetPixel(x1, y1, color);
                    return false;
                }, -1, true);

                lineTexture2d.Apply();
                lowImgTexture2d.Apply();
                //string path = gameScenUseInfo.getLocalThumbnailPath();
                //utilsTools.saveByteToPath(utilsTools.ScaleTexture(lineTexture2d,500,500).EncodeToPNG(), path);
                if (onAreaHandler != null) onAreaHandler(areaItem.id, true);
            };
            task.addTask(this, taskItemBack, areaItem1);
        }
        else if (onAreaHandler != null)
        {
            onAreaHandler(areaId, false);
        }

        
    }
    public bool switchShowAreaGroup(short gid, OnAreaHandler onAreaHandler = null)
    {
        if (gid == nowSelectgid)
        {
            if(onAreaHandler != null)
                onAreaHandler(gid, true);            
            return true;
        }
        if (lowImg == null)
        {
            if (onAreaHandler != null)
                onAreaHandler(gid, false);
            return false;
        }
        if (!(digitMatrix != null && lineTexture2d != null && gameidJsondata != null && gameidJsondata.findGid(gid)))
        {
            if (onAreaHandler != null)
                onAreaHandler(gid, false);
            return false;
        }
        Color color = new Color(1, 1, 1, 0);
        gameAreaGroupItem jsonGroupInfo = null;
        GroupByAreaPtInfos groupPt = null;
        List<Vector2Short> tempData = new List<Vector2Short>();
        if (nowSelectgid > 0)
        {
            jsonGroupInfo = gameidJsondata.getRoomGroup(nowSelectgid);
            groupPt = groupPtInfos[nowSelectgid];
            
            for (int i = 0; i < jsonGroupInfo.roomIds.Count; i++)
            {
                var aid = jsonGroupInfo.roomIds[i];
                groupPt.getDataByAid(aid, ref tempData);
                foreach (var pt in tempData)
                {
                    lowImgTexture2d.SetPixel(pt.x, pt.y, color);
                }
            }
        }
        else
        {
            utilsTools.sendEventObjectParams("inGameLoadingValue", 100f, true);
        }
        nowSelectgid = gid;
        jsonGroupInfo = gameidJsondata.getRoomGroup(nowSelectgid);
        groupPt = groupPtInfos[gid];
        color = new Color(1, 1, 1, 1);
        for (int i = 0; i < jsonGroupInfo.roomIds.Count; i++)
        {
            var aid = jsonGroupInfo.roomIds[i];
            groupPt.getDataByAid(aid, ref tempData);
            foreach (var pt in tempData)
            {
                lowImgTexture2d.SetPixel(pt.x, pt.y, color);
            }
        }
        lowImgTexture2d.Apply();
        lowImg.SetActive(true);
        if (onAreaHandler != null)
            onAreaHandler(gid, true);
        return true;
    }
    
    public List<TempGroupInfos> getGroups()
    {
        List<TempGroupInfos> ret = new List<TempGroupInfos>();
        if (digitMatrix != null && lineTexture2d != null && gameidJsondata != null)
        {
            foreach (var item in gameidJsondata.roomGroupsData)
            {
                TempGroupInfos tempGroupInfos = new TempGroupInfos();
                item.getRGB(out tempGroupInfos.rgb);
                tempGroupInfos.gid = item.id;
                tempGroupInfos.size = (short)(item.roomIds.Count() - 1);
                if (item.isComplete) tempGroupInfos.show = tempGroupInfos.size ;
                else
                {
                    short cout = 0;
                    for (int i = 0; i < item.roomIds.Count(); i++)
                    {
                        if (gameidJsondata.roomDatas[item.roomIds[i]].isShow)
                        {
                            cout++;
                        }
                    }
                    tempGroupInfos.show = cout;
                }
                ret.Add(tempGroupInfos);
            }
        }
        return ret;
    }
    public bool showAreaByPos(short x,short y,OnAreaHandler showBack)
    {
        if (x >= digitMatrix.RowCount || y >= digitMatrix.ColumnCount || this.nowSelectgid < 0 || x < 0 || y < 0)
        {
            if(showBack!= null)
                showBack(-1, false);
            return false;
        }
        short oldValue = digitMatrix.Data[x, y];
        if (oldValue < 20)
        {
            if (showBack != null)
                showBack(-1, false);
            return false;
        }
        short aid = (short)(oldValue - 20);
        var areaItem = gameidJsondata.roomDatas[aid];
        if(gameidJsondata.roomGroupsData[nowSelectgid-1].roomIds.IndexOf(aid) < 0)
        {
            if (showBack != null) showBack(aid, false);
            return false;
        }
        if (areaItem.isShow)
        {
            if (showBack != null)
                showBack(-1, false);
            return false;
        }
        areaItem.isShow = true;
        if (areaItem.tempExKey.Equals("") == false)
        {
            var node = areaIdBase.transform.Find(areaItem.tempExKey);
            if (node != null)
            {
                node.SetParent(null);
                GameObject.Destroy(node.gameObject);
            }
            areaItem.tempExKey = "";
        }
        AreaAnimationDiffuse areaAnimationDiffuse = new AreaAnimationDiffuse(x, y, aid);
        areaAnimationDiffuse.m_fpsStart = 0;
        showAreaAnimationDatas.Add(areaAnimationDiffuse);
        utilsTools.sendEventObjectParams("showAreaEventOk", areaItem,x,y);
        if (showBack != null)
            showBack(aid, true);
        return true;
    }
    // Update is called once per frame
    void Update()
    {
        TaskManages.getInstance().updateTask(this);
        onShowAnimationHandler();  
        if(prveAreaIdScale.x > 0)
        {
            Vector3 vector3 = areaIdBase.transform.localScale;
            if(prveAreaIdScale.Equals(vector3) == false)
            {
                updateScaleView();
                prveAreaIdScale = vector3;
            }
        }
    }
    //暂时不支持 不同组在同一帧率填充过程
    void onShowAnimationHandler()
    {
        
        if (showAreaAnimationDatas.Count > 0)
        {
            int cout = 0;
            int width = lineTexture2d.width;
            int height = lineTexture2d.height;
            Texture2D selectTexture = null;
            if(lowImg != null)
            {
                selectTexture = lowImg.GetComponent<Image>().sprite.texture;
            }
            List<short> removeAids = new List<short>();
            foreach (var item in showAreaAnimationDatas)
            {
                float setp = 0.35f;
                int cout1 = 0;
                if(item.m_fpsStart > 10)
                {
                    setp = 1 / (item.m_fpsStart / 5f);
                }
                short nowcheckAid = (short)(item.m_aid + 20);
                bool isChange = nowSelectgid.Equals(gameidJsondata.roomDatas[item.m_aid].gid);
                for (float angle = 0; angle < 360; angle += setp) {
                    Vector2 direct = new Vector2(Mathf.Sin(angle), Mathf.Cos(angle));
                    for (short r = item.m_fpsStart; r < item.m_fpsEnd; r++)
                    {
                        //下标0就只需要一个点就可以了，不需要360都算一遍
                        if (r == 0 && utilsTools.isEqualByValue(angle, 0.0f, 0.000003f) == false) continue;
                        Vector2 scale = direct * r;
                        short x = Convert.ToInt16(scale.x+ item.m_x);
                        short y = Convert.ToInt16(scale.y + item.m_y);
                        if (x < 0 || y < 0 || x >= width || y >= height) continue;
                        short nowDataValue = digitMatrix.Data[x, y];
                        if (nowDataValue.Equals(nowcheckAid) == false) {
                            continue;
                        }
                        string key = x.ToString() + "_" + y.ToString();
                        digitMatrix.Data[x, y] = -1;
                        Color color = lineTexture2d.GetPixel(x, y);
                        color.a = 0;
                        lineTexture2d.SetPixel(x, y, color);
                        lowImgTexture2d.SetPixel(x, y, color);
                        cout++;
                        cout1++;
                    }
                }
                if(cout1 == 0)
                {
                    //没有可渲染区域
                    removeAids.Add(item.m_aid);
                    short gid = gameidJsondata.getAid(item.m_aid).gid;
                    groupPtInfos[gid].removeAid(item.m_aid);
                }
                else
                {
                    short diff = (short)(item.m_fpsEnd - item.m_fpsStart);
                    item.m_fpsStart = item.m_fpsEnd;
                    item.m_fpsEnd += diff;
                }
            }
            if(cout == 0)
            {
                showAreaAnimationDatas.Clear();
                return;
            }
            if(selectTexture != null)
            {
                selectTexture.Apply();
            }
            lineTexture2d.Apply();
            if(removeAids.Count > 0)
            {
                //移除已经播放完成
                foreach (var aid in removeAids)
                {
                    for (int i = 0; i < showAreaAnimationDatas.Count; i++)
                    {
                        if (showAreaAnimationDatas[i].m_aid.Equals(aid) == true)
                        {
                            showAreaAnimationDatas.RemoveAt(i);
                            break;
                        }
                    }
                }
                if(showAreaAnimationDatas.Count == 0)
                {
                    //保存一次缩略遮罩图
                    string path = gameScenUseInfo.getLocalThumbnailPath();
                    utilsTools.saveByteToPath(utilsTools.ScaleTexture(lineTexture2d, 500, 500).EncodeToPNG(), path);
                }
            }
        }
    }
    public void resetSize()
    {
        if(lineTexture2d != null)
        {
            RectTransform rectTransform = lineImg.GetComponent<RectTransform>();
            float scale = ((float)lineTexture2d.width) / ((float)rectTransform.rect.width);
            float height = ((float)lineTexture2d.height) / scale;
            float width = ((float)rectTransform.rect.width);
            //将所有节点都按照这个尺寸处理
            rectTransform.sizeDelta = new Vector2(width, height);
            rectTransform = colorImg.GetComponent<RectTransform>();
            rectTransform.sizeDelta = new Vector2(width, height);

            if(lowImg != null)
            {
                rectTransform = lowImg.GetComponent<RectTransform>();
                rectTransform.sizeDelta = new Vector2(width, height);
            }
            if(areaIdBase != null)
            {
                rectTransform = areaIdBase.GetComponent<RectTransform>();
                rectTransform.sizeDelta = new Vector2(width, height);
            }
        }
    }
    public bool getSize(out int width,out int height)
    {
        width = -1;
        height = -1;
        if (lineTexture2d == null)
            return false;
        width = lineTexture2d.width;
        height = lineTexture2d.height;
        return true;
    }
    
    public void debugPos(int x,int y)
    {
    }
}
