using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using Unity.VisualScripting;
using UnityEngine;

/// <summary>
/// 挂载设备
/// </summary>
public class Device : MonoBehaviour
{
    public DeviceInfor mydata;

    public bool isPut = false;

    [ContextMenu("添加端口信息脚本")]
    public void addscript()
    {
        //添加端口信息脚本
        for (int i = 0; i < transform.childCount; i++)
        {
            var go = transform.GetChild(i);
            mydata.ports.Add(go);
            if (!go.GetComponent<LineInfor>()) go.AddComponent<LineInfor>();
            if (!go.GetComponent<PortQuery>()) go.AddComponent<PortQuery>();
        }
    }

    // Start is called before the first frame update
    private void Awake()
    {

    }
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (isPut)
        {
            isPut = false;
            refreshMyID();
            LineInforChecker();
            //自己的设备JSON
            var myjson = refreshJson();
            //更新设备JSON
            string machineID = string.Format("{0}-{1}-{2}", mydata.area, mydata.row, mydata.tier);
            lock (CombineJSON.jsonsDic)
            {
                if (CombineJSON.jsonsDic.ContainsKey(machineID))
                {
                    CombineJSON.jsonsDic.Remove(machineID);
                    CombineJSON.jsonsDic.Add(machineID, myjson);
                }
                else CombineJSON.jsonsDic.Add(machineID, myjson);
            }

        }
    }

    /// <summary>
    /// 生成所有设备JSON
    /// </summary>
    [ContextMenu("生成所有设备JSON")]
    public void AllDeviceJson()
    {
        string AllDeviceJson = CombineJSON.GetCombineJSON();
        Debug.Log(AllDeviceJson);
    }

    /// <summary>
    /// 刷新自己名字
    /// </summary>
    void refreshMyID()
    {
        for (int i = 0; i < mydata.ports.Count; i++)
        {
            var po = mydata.ports[i].GetComponent<PortQuery>();
            var li = mydata.ports[i].GetComponent<LineInfor>();
            li.myID = string.Format("{0}-{1}-{2}-{3}", mydata.area, mydata.row, mydata.tier, i + 1);
            li.transform.name = li.myID;
        }
    }

    /// <summary>
    /// 更新该设备下所有端口信息（JSON）
    /// </summary>
    string refreshJson()
    {
        List<List<string>> strings = new List<List<string>>();
        var _line = GetComponentsInChildren<LineInfor>().ToList();

        for (int i = 0; i < _line.Count; i++)
        {
            var line = new List<string>();
            line.Add(_line[i].myID);
            line.Add(_line[i].otherID);
            line.Add(_line[i].lineUID);
            strings.Add(line);
        }

        DeviceInfor person = new DeviceInfor();
        person.devtype = mydata.devtype;
        person.ports = null;
        person.area = mydata.area;
        person.row = mydata.row;
        person.tier = mydata.tier;
        person.lineInfors = new List<List<string>>(strings);

        string json = JsonConvert.SerializeObject(person);
        //Debug.Log(json);
        return json;
    }

    /// <summary>
    /// 遍历相同lineUID的物体
    /// </summary>
    /// <param name="uid">寻找具体某一UID</param>
    void LineInforChecker(string uid = null)
    {
        bool isfind = false;
        LineInfor[] lineInfors = FindObjectsOfType<LineInfor>();

        //记录相同lineUID
        Dictionary<string, List<LineInfor>> lineUIDDict = new Dictionary<string, List<LineInfor>>();

        foreach (var item in lineInfors)
        {
            if (string.IsNullOrEmpty(item.lineUID)) continue;
            // 判断lineUID是否存在于字典中
            if (lineUIDDict.ContainsKey(item.lineUID))
            {
                lineUIDDict[item.lineUID].Add(item);
            }
            else
            {
                List<LineInfor> newList = new List<LineInfor>();
                newList.Add(item);
                lineUIDDict.Add(item.lineUID, newList);
            }
        }

        // 输出相同lineUID
        foreach (var item in lineUIDDict)
        {
            if (item.Value.Count > 1)
            {
                //查找特定的GUID
                if (uid != null)
                {
                    if (item.Key == uid)
                    {
                        isfind = true;
                        Debug.Log(string.Format
                            ("lineUID: {0},GameA Name: {1},GameB Name: {2}", item.Key, item.Value[0].myID, item.Value[1].myID));
                        refreshLineInfor(item.Key, item.Value[0], item.Value[1]);
                        break;
                    }
                }
                //遍历
                else
                {
                    isfind = true;
                    Debug.Log(string.Format
                        ("lineUID: {0},GameA Name: {1},GameB Name: {2}", item.Key, item.Value[0].myID, item.Value[1].myID));
                    refreshLineInfor(item.Key, item.Value[0], item.Value[1]);
                }
            }
        }
        if (!isfind) Debug.Log("无匹配端口UID");
    }

    /// <summary>
    /// 刷新端口线条信息
    /// </summary>
    public void refreshLineInfor(string GUID, LineInfor A, LineInfor B)
    {
        A.lineUID = GUID;
        B.lineUID = GUID;
        A.otherID = B.myID;
        if (string.IsNullOrEmpty(B.otherID))
        {
            B.otherID = A.myID;
            //更新B端口的设备下所有端口信息
            var DeviceB = B.transform.parent.GetComponent<Device>();
            if (DeviceB != null)
            {
                DeviceB.isPut = true;
            }
        }
    }
}
