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 UnityEngine;
using UnityEngine.UI;
using static Unity.VisualScripting.Member;
using static UnityEditor.Progress;

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 = 10;//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>>();
    private Dictionary<short, List<Vector2Short>> lines = 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 bool getLineByAid(short aid,ref List<Vector2Short> data)
    {
        if(lines.ContainsKey(aid))
            return false;
        data = lines[aid];
        return true;
    }
    public GroupByAreaPtInfos Clone()
    {
        GroupByAreaPtInfos ret = new GroupByAreaPtInfos();
        foreach (var item in datas)
        {
            ret.datas.Add(item.Key, item.Value);
        }
        return ret;
    }
    public short[] getDataAllKey()
    {
        return datas.Keys.ToArray();
    }
    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 appendLinePos(short aid,short x,short y)
    {
        if (lines.ContainsKey(aid) == false)
        {
            lines.Add(aid, new List<Vector2Short>());
        }
        lines[aid].Add(new Vector2Short(x, y));
        return;
    }
    public void removeAid(short aid)
    {
        datas.Remove(aid);
    }
    public int ContainsAidByPos(short aid,short x,short y) {
        return -1;
    }
    public bool removeAidInLineByIndex(short aid,int idx)
    {
        return true;
    }
}
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;
    private Texture2D lowImgTexture2d = null;
    private Texture2D colorTexure2d = null;
    protected short nowSelectgid = -1;
    private string[] initDigitMatrixs = { "", "","" };
    private Dictionary<short, short> aid2selectOrderIdx = new Dictionary<short, short>();
    private GameScenUserInfo gameScenUseInfo = null;
    //x,y aid 当前帧向量 起点终点 等宽度计算扩散
    private List<AreaAnimationDiffuse> showAreaAnimationDatas = new List<AreaAnimationDiffuse>();
    private Dictionary<short, GroupByAreaPtInfos> groupPtInfos = new Dictionary<short, GroupByAreaPtInfos>();
    private Dictionary<short, GroupByAreaPtInfos> groupPtInfos_All = new Dictionary<short, GroupByAreaPtInfos>();//不管是否涂色都会记录
    private short bianlun = -1;
    private short fullShow = -2;
    private Texture2D thumbnailTexture2d = null;
    private bool isDebugTestToEnd = false;
    [SerializeField]
    private int selectTextureIdx = 1;
    static private string[] allSelectTexturePaths = { };
    public int SelectTextureIdx
    {
        get { return selectTextureIdx; }
        set { 
            if(value >= 0 &&  value < allSelectTexturePaths.Length)
            {
                if (selectTextureIdx == value) return;
                selectTextureIdx = value;
                //修改
            }
        }
    }
    
    public void loopAddTaskBack(int count,int step,TaskItemBack back, System.Object[] param = null)
    {
        List<System.Object> newParams = null;
        if(param != null) 
            newParams = param.ToList();
        else
            newParams = new List<System.Object>();
        int idx1 = newParams.Count;
        newParams.Add(0);
        newParams.Add(0);
        System.Object[] newParamArray = newParams.ToArray();
        TaskManages tm = TaskManages.getInstance();
        for (int x = 0; ;)
        {
            newParamArray[idx1] = x;
            newParamArray[idx1 + 1] = step;
            tm.addTaskArray(this, back, newParamArray);
            x += step;
            if(x >= count - step)
            {
                if(x == (count + step))//最后整数
                {
                    return;
                }
                step = count - x;
                newParamArray[idx1] = x;
                newParamArray[idx1 + 1] = step;
                tm.addTaskArray(this, back, newParamArray);
                return;
            }
        }
    }
    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[1].Equals("") == false && initDigitMatrixs[2].Equals("")){
            if (thumbnailTexture2d == null)
            {
                onInitDigitMatrix("thumbnail");
                return;
            }
            var tm = TaskManages.getInstance();
            TaskItemBack taskItemBack = (System.Object[] param) =>
            {
                int start = (int)param[0];
                int step = (int)param[1];
                float x = 1.0f;
                float y = 1.0f;
                float width = gameidJsondata.width;
                float height = gameidJsondata.height;
                utilsTools.sendEventObjectParams("inGameLoadingValue", 6f, false);
                for (int i = start; i < (start + step); i++)
                {
                    x = i;
                    for (int j = 0; j < gameidJsondata.height; j++)
                    {
                        y = j;
                        var color = colorTexure2d.GetPixelBilinear(x/width,y/height);
                        short nowValue = digitMatrix.Data[i, j];
                        if (nowValue.Equals(bianlun) || nowValue < 0) // digitMatrix.Data[i, j].Equals(bianlun) || digitMatrix.Data[i,j].Equals(fullShow))
                        {
                            color.a = 1f;                            
                        }
                        else
                        {
                            color = lineTexture2d.GetPixel(i, j);
                        }
                        thumbnailTexture2d.SetPixel(i, j, color);
                    }
                }
            };
            loopAddTaskBack(gameidJsondata.width,340,taskItemBack);
            tm.addTask(this, (System.Object[] param) =>
            {
                onInitDigitMatrix("thumbnail");
                //utilsTools.saveByteToPath(utilsTools.ScaleTexture(thumbnailTexture2d, 120, 120).EncodeToPNG(), gameScenUseInfo.getLocalThumbnailPath() + "_bk.png");
            });
            return;
        }
        if (initDigitMatrixs[initDigitMatrixs.Length - 1].Equals("")) return;
        nowSelectgid = -1;
        resetSize();
        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 virtual short[] getDiffAids()
    {
        List<short> ret = new List<short>();
        Dictionary<short,bool> keyValuePairs = new Dictionary<short,bool>();
        foreach (var item in gameScenUseInfo.areaInfoUseData)
        {
            if (keyValuePairs.ContainsKey(item.id))
            {
                Debug.Log("重复----" + item.id);
            }
            keyValuePairs.Add(item.id, true);
        }
        foreach (var item in gameidJsondata.roomDatas)
        {
            if(keyValuePairs.ContainsKey(item.id) == false)
            {
                ret.Add(item.id);
            }
        }
        return ret.ToArray();
    }
    void digitMatrixData2GroupPtsInSelect(gameAreaItem gai)
    {
        Color color = new Color(1, 1, 1, 0);
        if (groupPtInfos_All.ContainsKey(gai.gid) == false)
        {
            groupPtInfos_All.Add(gai.gid, new GroupByAreaPtInfos());
        }
        digitMatrix.FloodFill8WithStack(gai.px, gai.py, fullShow, 0, (short x, short y, short c) => {
            if (digitMatrix.Data[x, y] == bianlun)
            {
                groupPtInfos_All[gai.gid].appendLinePos(gai.id, x, y);
            }
            else
            {
                lineTexture2d.SetPixel(x, y, color);//选中时候透明处理
                groupPtInfos_All[gai.gid].appendPos(gai.id, x, y);
            }

            return true;
        }, bianlun, true);
    }
    void digitMatrixData2GroupPtsNoSelect(gameAreaItem gai)
    {
        if (groupPtInfos.ContainsKey(gai.gid) == false)
        {
            groupPtInfos.Add(gai.gid, new GroupByAreaPtInfos());
        }
        if (groupPtInfos_All.ContainsKey(gai.gid) == false)
        {
            groupPtInfos_All.Add(gai.gid, new GroupByAreaPtInfos());
        }
        digitMatrix.FloodFill8WithStack(gai.px, gai.py, (short)(gai.id + 20), 0, (short x, short y, short c) => {
            
            if (digitMatrix.Data[x, y] == bianlun)
            {
                groupPtInfos[gai.gid].appendLinePos(gai.id, x, y);
                groupPtInfos_All[gai.gid].appendLinePos(gai.id, x, y);
            }
            else
            {
                groupPtInfos[gai.gid].appendPos(gai.id, x, y);
                groupPtInfos_All[gai.gid].appendPos(gai.id, x, y);
            }
            return true;
        }, bianlun, 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 height = (int)datas[0];
                int x = (int)datas[1];
                int setp = (int)datas[2];
                
                utilsTools.sendEventObjectParams("inGameLoadingValue", 4f, false);
                int lun = 0;
                int feilun = 0;
                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);//不合规图片的兼容处理
                            feilun++;
                        }
                        else if (color.r >= 0.97 && color.g >= 0.97 && color.b >= 0.97)
                        {
                            digitMatrix.Data[i, j] = 0;
                            feilun++;
                        }
                        else
                        {
                            digitMatrix.Data[i, j] = bianlun;
                            lun++;
                        }

                    }
                }
                Debug.Log("************   " + height.ToString() + " " + x.ToString() + " " + setp.ToString() + " lun " + lun.ToSafeString() + " feilun = "+feilun.ToString());
            };
            System.Object[] objects = { lineTexture2d.height };
            loopAddTaskBack(lineTexture2d.width, 200, taskItemBack,objects);
            taskManages.addTask(this, (System.Object[] a) =>
            {
                lineTexture2d.Apply();//将透明度转白色
                TaskItemBack taskItemBack1 = (System.Object[] param) =>
                {
                    gameAreaItem gai = (gameAreaItem)param[0];
                    if (aid2selectOrderIdx != null && aid2selectOrderIdx.ContainsKey(gai.id))
                    {
                        digitMatrixData2GroupPtsInSelect(gai);
                    }
                    else
                    {
                        digitMatrixData2GroupPtsNoSelect(gai);

                    }
                };
                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");
                });
            });
        }
        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);
        }else if(typeId == 2)
        {
            if(areaIdBase != null)
            {
                colorTexure2d = colorImg.GetComponent<Image>().sprite.texture;
                thumbnailTexture2d = new Texture2D(gameidJsondata.width, gameidJsondata.height, TextureFormat.RGBA32,false);
                    //utilsTools.ScaleTexture(colorTexure2d, gameidJsondata.width, gameidJsondata.height, TextureFormat.RGBA32);
            }
        }
    }
    protected void checkAddAreaId()
    {
        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;
        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_" + item.gid.ToString() + "_"+item.id.ToString();
                //转成物体坐标系?
                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 = areaIdBaseTransform;
                //坐标怎么设置？
                idValueTran.GetLocalPositionAndRotation(out localPosTemp, out quaternion);
                //严格居中 字体大小等问题 需要调整json的生成脚本生成逻辑后才能继续
                localPosTemp.x = (float)item.px / (float)width * rectTransform.rect.width - (rectTransform.rect.width / 2) * vector3.x;
                localPosTemp.y = (float)item.py / (float)height * rectTransform.rect.height - (rectTransform.rect.height / 2) * vector3.y;
                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);
                }
            }
        }
    }
    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);
                    utilsTools.setGDataByKey("allAreaSize", gameidJsondata.getAllValidAreaItemSize());
                    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()
    {
        GameScenUserInfo data = utilsTools.getGDataByKey<GameScenUserInfo>("nowSelectUseData", null);
        if(data == null) return false;
        if (this.gameScenUseInfo != null)
        {
            if (gameScenUseInfo.id.Equals(data.id))
            {
                return true;
            }
        }
        return loadGameImgId(data);
    }
    //重新加载线图
    public void reLoadLineTexture(LoadImageInfo back)
    {
        if (thumbnailTexture2d != null) Destroy(thumbnailTexture2d);
        thumbnailTexture2d = utilsTools.ScaleTexture(colorTexure2d, colorTexure2d.width, colorTexure2d.height, TextureFormat.RGBA32);
        lineImg.SetActive(true);
        Image image = lineImg.GetComponent<Image>();
        utilsTools.loadLocalImage(this, image, gameScenUseInfo.getLineImgLocalPath(), (bool isSuccess) => {
            if(isSuccess)
            {
                if(lineTexture2d !=null)
                {
                    Destroy(lineTexture2d);
                }
                lineTexture2d = image.sprite.texture;
            }
            back(isSuccess);
        });
    }
    public void showArea(int areaId, OnAreaHandler onAreaHandler = null)
    {
        if (areaId == -1)
        {
            lineImg.SetActive(false);
            return;
        }
        //显示指定区域
        if (digitMatrix !=null && lineTexture2d != null && gameidJsondata != null && areaId >= 0 && areaId < gameidJsondata.roomDatas.Count)
        {
            gameAreaItem areaItem1 = gameidJsondata.getAid((short)areaId);
            List<Vector2Short> areaAllPts = new List<Vector2Short>();
            Color color = new Color(1, 1, 1, 0);
            groupPtInfos_All[areaItem1.gid].getDataByAid(areaItem1.id, ref areaAllPts);            
            foreach (var item in areaAllPts)
            {
                lineTexture2d.SetPixel(item.x,item.y, color);//回放使用
            }
            //groupPtInfos_All[areaItem1.gid].getLineByAid(areaItem1.id, ref areaAllPts);
            //foreach (var item in areaAllPts)
            //{
            //    lineTexture2d.SetPixel(item.x, item.y, color);
            //}
            lineTexture2d.Apply();
        }
        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>();
        short bianlun = -1;
        if (nowSelectgid > 0)
        {
            jsonGroupInfo = gameidJsondata.getRoomGroup(nowSelectgid);
            groupPt = groupPtInfos[nowSelectgid];
            
            for (int i = 0; i < jsonGroupInfo.roomIds.Count; i++)
            {
                var aid = jsonGroupInfo.roomIds[i];
                var areamItem = gameidJsondata.getAid(aid);
                if (areamItem.tempExKey.Equals(""))
                {
                    continue;
                }
                groupPt.getDataByAid(aid, ref tempData);
                foreach (var pt in tempData)
                {
                    if (digitMatrix.Data[pt.x, pt.y] == bianlun) continue;
                    lowImgTexture2d.SetPixel(pt.x, pt.y, color);
                }
            }
        }
        else
        {
            utilsTools.sendEventObjectParams("inGameLoadingValue", 100f, true);
            utilsTools.setGDataByKey("enableZoomMove", 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];
            var areamItem = gameidJsondata.getAid(aid);
            if (areamItem.tempExKey.Equals(""))
            {
                continue;
            }
            groupPt.getDataByAid(aid, ref tempData);
            foreach (var pt in tempData)
            {
                if (digitMatrix.Data[pt.x, pt.y] == bianlun) continue;
                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());
                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 virtual 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)
        {
            var aids =  getDiffAids();
            if (showBack != null)
                showBack(-1, false);
            return false;
        }
        short aid = (short)(oldValue - 20);
        foreach (var item in showAreaAnimationDatas)//边界判定 卡顿并且尚未重置中心点时候
        {
            if(item.m_aid.Equals(aid))
            {
                if (showBack != null) showBack(-1, false);
                return false;
            }
        }
        var areaItem = gameidJsondata.roomDatas[aid];
        if(gameidJsondata.getRoomGroup(nowSelectgid).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();
    }
    //暂时不支持 不同组在同一帧率填充过程
    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 = 1f;
                int cout1 = 0;
                if (item.m_fpsStart > 10)
                {
                    setp = 1 / (item.m_fpsStart / 7f);
                }
                short gid = gameidJsondata.getAid(item.m_aid).gid;
                var groupPtInfo = groupPtInfos[gid];
                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.00000005f) == 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(fullShow)) continue;
                        if (!nowDataValue.Equals(nowcheckAid) && !nowDataValue.Equals(bianlun)) {                            
                            continue;
                        }
                        if (nowDataValue.Equals(bianlun))
                        {
                            continue;
                        }
                        digitMatrix.Data[x, y] = fullShow;
                        Color color = lineTexture2d.GetPixel(x, y);
                        color.a = 0;
                        lineTexture2d.SetPixel(x, y, color);//显示过程
                        lowImgTexture2d.SetPixel(x, y, color);
                        if (thumbnailTexture2d != null) {
                            Color color2 = colorTexure2d.GetPixelBilinear((float)x / (float)gameidJsondata.width, (float)y / (float)gameidJsondata.height);
                            thumbnailTexture2d.SetPixel(x,y,color2);
                        }
                        cout++;
                        cout1++;
                        
                    }
                }
                if(cout1 == 0)
                {
                    //没有可渲染区域
                    removeAids.Add(item.m_aid);
                    List<Vector2Short> tempLineColors = new List<Vector2Short>();
                    groupPtInfo.getLineByAid(item.m_aid,ref tempLineColors);
                    foreach (var item1 in tempLineColors)
                    {
                        if (digitMatrix.Data[item1.x,item1.y].Equals(bianlun))
                        {
                            digitMatrix.Data[item1.x, item1.y] = -2;
                            Color color = lineTexture2d.GetPixel(item1.x, item1.y);
                            color.a = 0;
                            lineTexture2d.SetPixel(item1.x, item1.y, color);//
                            lowImgTexture2d.SetPixel(item1.x, item1.y, color);
                            if (thumbnailTexture2d != null)
                            {
                                Color color2 = colorTexure2d.GetPixelBilinear(item1.x / (float)gameidJsondata.width, item1.y / (float)gameidJsondata.height);
                                thumbnailTexture2d.SetPixel(item1.x, item1.y, color2);
                            }
                        }
                    }
                    groupPtInfo.removeAid(item.m_aid);
                    if (groupPtInfo.getDataAllKey().Length.Equals(0))
                    {
                        groupPtInfos.Remove(gid);
                    }
                    
                }
                else
                {
                    short diff = (short)(item.m_fpsEnd - item.m_fpsStart);
                    item.m_fpsStart = item.m_fpsEnd;
                    item.m_fpsEnd += diff;
                }
            }
            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();
                    if(thumbnailTexture2d != null)
                    {
                        var sltTextureSize = utilsTools.getGDataByKey<Vector2>("sltTextureSize", Vector2.one);
                        utilsTools.saveByteToPath(utilsTools.ScaleTexture(thumbnailTexture2d, Convert.ToInt32(sltTextureSize.x),Convert.ToInt32(sltTextureSize.y)).EncodeToJPG(), path);
                    }
                    if (utilsTools.isEqualByValue(gameScenUseInfo.progress, 1.0, 0.0000002f))
                    {
                        TaskManages.getInstance().addTask(this, (System.Object[] parma) =>
                        {
                            utilsTools.setGDataByKey("enableZoomMove", false);
                            if (lowImg != null) lowImg.SetActive(false);
                            if(areaIdBase != null) areaIdBase.SetActive(false);
                            utilsTools.sendEventObjectParams("gamePlayerEndHandler");
                        });                        
                    }
                }
                
            }
        }
    }
    public void resetSize()
    {
        //怎么保持宽高比
        float width = lineTexture2d.width;
        float height = lineTexture2d.height;
        float bet = width / height;
        RectTransform rectTransform = lineImg.GetComponent<RectTransform>();
        RectTransform baseTransform = rectTransform.transform.parent.GetComponent<RectTransform>();
        Vector2 maxSize = new Vector2(baseTransform.rect.width * 0.95f,baseTransform.rect.height * 0.95f);
        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;
        }
        //确定好宽高后赋值
        GameObject[] gameObjects = { lineImg, colorImg, lowImg, areaIdBase };
        Vector3 tempPos = new Vector3();
        Quaternion quaternion;
        foreach (var item in gameObjects)
        {
            if (item == null) continue;
            var temp = item.GetComponent<RectTransform>();
            temp.sizeDelta = new Vector2(width,height);
        }
        checkAddAreaId();
        this.updateScaleView();
        if(lowImg != null)
        {
            utilsTools.setGDataByKey("sltTextureSize",new Vector2(lowImgTexture2d.width/4,lowImgTexture2d.height/4));
        }
    }
    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 onClear()
    {
        if(thumbnailTexture2d != null)
        {
            Destroy(thumbnailTexture2d);
            thumbnailTexture2d = null;
        }
        if (gameidJsondata != null) gameidJsondata = null;
        nowSelectgid = -1;
        aid2selectOrderIdx.Clear();
        gameScenUseInfo = null;
        showAreaAnimationDatas.Clear();
        groupPtInfos.Clear();
    }
    public void debugPos(int x,int y)
    {
    }

    public void onTipHandler()
    {
        if (isDebugTestToEnd == false)
        {
            if (nowSelectgid >= 0)
            {
                var roomGroup = gameidJsondata.getRoomGroup(nowSelectgid);
                if (groupPtInfos.ContainsKey(nowSelectgid) == false)
                {
                    return;
                }
                var aidpts = groupPtInfos[nowSelectgid];
                short[] noshowAids = aidpts.getDataAllKey();
                if (noshowAids.Length > 0)
                {
                    short aid = -1;
                    for (int i = 0; i < noshowAids.Length; i++)
                    {
                        aid = noshowAids[i];
                        foreach (var item in showAreaAnimationDatas)
                        {
                            if (aid.Equals(item.m_aid))
                            {
                                aid = -1;
                                break;
                            }
                        }
                        if (aid > -1)
                        {
                            break;
                        }
                    }
                    if (aid > -1)
                    {
                        var tipAidInfo = gameidJsondata.getAid(aid);
                        utilsTools.sendEventObjectParams("tipShowPosMaxScale", tipAidInfo, gameidJsondata.width, gameidJsondata.height);
                    }
                }
            }
        }
        else if (nowSelectgid >= 0)
        {
            var roomGroup = gameidJsondata.getRoomGroup(nowSelectgid);
            if (groupPtInfos.ContainsKey(nowSelectgid) == false)
            {
                return;
            }
            var aidpts = groupPtInfos[nowSelectgid];
            short[] noshowAids = aidpts.getDataAllKey();
            List<short> aids = new List<short>();
            if (noshowAids.Length > 0)
            {
                short aid = -1;
                for (int i = 0; i < noshowAids.Length; i++)
                {
                    aid = noshowAids[i];
                    foreach (var item in showAreaAnimationDatas)
                    {
                        if (aid.Equals(item.m_aid))
                        {
                            aid = -1;
                            break;
                        }
                    }
                    if (aid > -1)
                    {
                        aids.Add(aid);
                    }
                }
            }
            if (aids.Count > 0)
            {
                TaskManages.getInstance().addTask(this, (System.Object[] p) =>
                {
                    List<short> showAids = (List<short>)p[0];
                    foreach (var item in showAids)
                    {
                        var tipAidInfo = gameidJsondata.getAid(item);
                        showAreaByPos(tipAidInfo.px, tipAidInfo.py, null);
                    }
                }, aids);
            }

        }else{
            utilsTools.setGDataByKey("enableZoomMove", false);
            if (lowImg != null) lowImg.SetActive(false);
            if (areaIdBase != null) areaIdBase.SetActive(false);
            utilsTools.sendEventObjectParams("gamePlayerEndHandler");
        }
    }
}
