using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using XFrame.Core.UI;
using RDate;
using UnityEngine.Networking;
using System.Threading;

[Serializable]
public class ReturnRoomID
{
    public bool state;
    public string message;
    public string data;
}
public class RoomInfo
{
    public string Name;
    public string MissionModel;
    public string ThinkingId;
}

public class View_Panel2 : XUIPanel
{
    public Button training_task_btn;//训练任务按钮


    public Image append_room_panl;//添加房间页面
    public InputField room_input;//输入房间名字
    public Button Fork_off_btn;//叉掉添加房间页面
    public Button verify_btn;//添加房间确认按钮
    public Button cancel_btno;//取消添加房间按钮
    public Text tips_txt;//提示文本
    public Image distribution_panl;//席位分配面板
    public Button off_btn;//席位分配叉掉页面
    public Button seatSubmit_btn;//席位分配提交按钮
    public Image selector_panl;//选择人员页面
    public Button off3_btn;//选择人员页面叉掉按钮

    public Button tijiao_btn;//提交按钮
    public Button quxiao_btn;//取消按钮
    public GameObject Storm_and_capture_panl;//红方蓝方
    public Button Cancel4_btn;//红蓝方叉掉页面

    public Transform place;//需要生成地方
    public GameObject root_pan;//需要生成房间预设体
    public List<Text> roomnamelist = new List<Text>();//创建房间的名字
    public List<string> rootlist = new List<string>();//存入房间的名字
    public List<Button> buttonlist = new List<Button>();//克隆出来房间按钮


    public string roomUrl = "http://111.229.30.246:48888/Handler/Practice.ashx?action=query&state=0,1,2";
    public string userUrl = "http://111.229.30.246:48888/Handler/User.ashx?action=all&role_code=04";
    public RoomData roomdata = new RoomData();
    public UserData userData = new UserData();
    public Dropdown roomModelDropdown;//房间模式
    public Dropdown thinkingDropdown;//选择想定
    public Transform reveal;
    public Transform subjectContent;
    public GameObject revealPrefab;
    public GameObject subjectItem;
    public string currentThinkName;
    public GameObject userItem;
    public Transform userConent;
    public InputField nameInputField;
    public InputField jobInputField;
    public string currentRoomName;
    public string currentMissionModel;
    public string currentThinkingId;
    public GameObject currentRoomSubjectItem;
    public Transform currentRoomSubjectItemConnect;
    public Dictionary<int, string> currentThinkingIds = new Dictionary<int, string>();
    public List<CurrentEditorAccount> currentEditorAccounts = new List<CurrentEditorAccount>();
    public string currentSubjectID;
    public string currentSeatID;
    public string currentAccount;
    public Text currentAccountText;
    public Transform greenSubjectInfoParent;
    public Transform redSubjectInfoParent;
    public GameObject redSubjectInfoItem;
    public GameObject greenSubjectInfoItem;
    public GameObject submitView;
    public Button svSubmitBtn;
    public Button svCancelBtn;
    public Text submitInstruct;
    public Button append_btn;//添加房间按钮
    public Button start_training_btn;//开始训练按钮
    public Button entering_key_btn;//进入导调按钮
    public Button scenario_btn;//想定编辑
    public View_Panel2() : base(UIType.Normal, UIMode.HideOther, UICollider.Normal)
    {
        uiPath = "UIPanel/View_Panel2";
    }
    public override void Awake(GameObject go)
    {
        roomModelDropdown = this.transform.Find("append_room_panl/roomModelDropdown").GetComponent<Dropdown>();
        thinkingDropdown = this.transform.Find("append_room_panl/thinkingDropdown").GetComponent<Dropdown>();

        append_room_panl = GameObject.Find("View_Panel2(Clone)").transform.GetChild(2).GetComponent<Image>();
        Fork_off_btn = GameObject.Find("View_Panel2(Clone)").transform.GetChild(2).transform.GetChild(1).GetComponent<Button>();
        room_input = GameObject.Find("View_Panel2(Clone)").transform.GetChild(2).transform.GetChild(3).GetComponent<InputField>();
        scenario_btn = GameObject.Find("View_Panel2(Clone)").transform.GetChild(0).transform.GetChild(2).GetComponent<Button>();
        verify_btn = GameObject.Find("View_Panel2(Clone)").transform.GetChild(2).transform.GetChild(8).GetComponent<Button>();
        cancel_btno = GameObject.Find("View_Panel2(Clone)").transform.GetChild(2).transform.GetChild(9).GetComponent<Button>();
        tips_txt = GameObject.Find("View_Panel2(Clone)").transform.GetChild(2).transform.GetChild(10).GetComponent<Text>();
        distribution_panl = GameObject.Find("View_Panel2(Clone)").transform.GetChild(3).GetComponent<Image>();
        off_btn = GameObject.Find("View_Panel2(Clone)").transform.GetChild(3).transform.GetChild(1).GetComponent<Button>();
        selector_panl = GameObject.Find("View_Panel2(Clone)").transform.GetChild(4).GetComponent<Image>();
        off3_btn = GameObject.Find("View_Panel2(Clone)").transform.GetChild(4).transform.GetChild(1).GetComponent<Button>();
        place = GameObject.Find("View_Panel2(Clone)").transform.GetChild(1).transform.GetChild(0).transform.GetChild(0).GetComponent<Transform>();


        Storm_and_capture_panl = this.transform.Find("Storm_and_capture_panl").gameObject;
        submitView = Storm_and_capture_panl.transform.Find("SubmitView").gameObject;
        submitInstruct = submitView.transform.Find("Bg/Instruct").GetComponent<Text>();
        svSubmitBtn = submitView.transform.Find("SubmitBtn").GetComponent<Button>();
        svCancelBtn = submitView.transform.Find("CancelBtn").GetComponent<Button>();
        start_training_btn = Storm_and_capture_panl.transform.Find("Bottom/start_training_btn").GetComponent<Button>();
        entering_key_btn = Storm_and_capture_panl.transform.Find("Bottom/entering_key_btn").GetComponent<Button>();
        svCancelBtn.onClick.AddListener(() =>
        {
            svSubmitBtn.onClick.RemoveAllListeners();
            submitInstruct.text = "请确认是否选择当前席位";
            submitView.SetActive(false);
        });
        submitView.SetActive(false);
        Cancel4_btn = GameObject.Find("View_Panel2(Clone)").transform.GetChild(5).transform.GetChild(1).GetComponent<Button>();
        root_pan = Resources.Load<GameObject>("UIPanel/generate_panl");

        this.transform.Find("UPBG/Refresh_btn").GetComponent<Button>().onClick.AddListener(() =>
        {
            GetAllRoomData();
        });
        tijiao_btn = GameObject.Find("View_Panel2(Clone)").transform.GetChild(4).transform.GetChild(8).GetComponent<Button>();
        quxiao_btn = GameObject.Find("View_Panel2(Clone)").transform.GetChild(4).transform.GetChild(9).GetComponent<Button>();
        currentRoomSubjectItemConnect = Storm_and_capture_panl.transform.Find("Campsite_iamg/Subjects").GetComponent<ScrollRect>().content;
        redSubjectInfoParent = Storm_and_capture_panl.transform.Find("red_panl/Seat").GetComponent<ScrollRect>().content;
        greenSubjectInfoParent = Storm_and_capture_panl.transform.Find("green_panl/Seat").GetComponent<ScrollRect>().content;
        redSubjectInfoItem = redSubjectInfoParent.GetChild(0).gameObject;
        greenSubjectInfoItem = greenSubjectInfoParent.GetChild(0).gameObject;
        redSubjectInfoItem.SetActive(false);
        greenSubjectInfoItem.SetActive(false);
        currentRoomSubjectItem = currentRoomSubjectItemConnect.GetChild(0).gameObject;
        currentRoomSubjectItem.SetActive(false);
        seatSubmit_btn = distribution_panl.transform.Find("submit_btn").GetComponent<Button>();
        subjectContent = distribution_panl.transform.Find("SubjectsScrollView").GetComponent<ScrollRect>().content;
        subjectItem = subjectContent.GetChild(0).gameObject;
        revealPrefab = Resources.Load<GameObject>("Prefabs/reveal1_iam");
        userConent = selector_panl.transform.Find("ID_panl/Personnel").GetComponent<ScrollRect>().content;
        nameInputField = selector_panl.transform.Find("NameInputField").GetComponent<InputField>();
        jobInputField = selector_panl.transform.Find("JobInputField").GetComponent<InputField>();
        userItem = userConent.GetChild(0).gameObject;
        thinkingDropdown.options.Clear();
        tijiao_btn.onClick.AddListener(() =>
        {
            if (!string.IsNullOrEmpty(currentAccount))
            {
                currentAccountText.text = currentAccount;
                TiJiaoBtn();
            }

        });
        for (int i = 0; i < UIBootstrap.Instance.traininginformations.Count; i++)
        {
            int index = i;
            Dropdown.OptionData data = new Dropdown.OptionData();
            data.text = UIBootstrap.Instance.traininginformations[index].Name;
            if (!currentThinkingIds.ContainsKey(index))
                currentThinkingIds.Add(index, UIBootstrap.Instance.traininginformations[index].Id);
            thinkingDropdown.options.Add(data);
        }
        thinkingDropdown.onValueChanged.AddListener((index) =>
        {
            currentThinkName = thinkingDropdown.options[index].text;
            currentThinkingId = currentThinkingIds[index];
            CreateSubject();
        });
        roomModelDropdown.onValueChanged.AddListener((index) =>
        {
            currentMissionModel = roomModelDropdown.options[index].text;
        });

        append_btn = this.transform.Find("UPBG/append_btn").GetComponent<Button>();
        append_btn.onClick.AddListener(() =>
        {
            append_room_panl.gameObject.SetActive(true);
        });

        nameInputField.onValueChanged.AddListener((info) =>
        {
            Debug.Log("onValueChanged" + info);
            FuzzySearch(info);
        });
        jobInputField.onValueChanged.AddListener((info) =>
        {
            FuzzySearch(info);
        });

        nameInputField.onEndEdit.AddListener((info) =>
        {
            Debug.Log("onEndEdit" + info);
        });

        Forkoffbtn();
        Verify();
        Submit();
        Cance();
        Scenejump();//场景跳转按钮
        append_room_panl.gameObject.SetActive(false);
        GetAllRoomData();
        GetAllUserData();
        subjectItem.SetActive(false);
        userItem.SetActive(false);
        thinkingDropdown.onValueChanged.Invoke(0);
        roomModelDropdown.onValueChanged.Invoke(0);

        CreateSubject();
        Debug.Log("GlobalFlag.currentUser==" + GlobalFlag.currentUser.role_code);
        switch (GlobalFlag.currentUser.role_code)
        {
            //超级管理员	00
            //一般管理员	01
            //导调人员	02
            //教师	03
            //学员	04
            case "00":
                break;
            case "01":
                break;
            case "02":
                start_training_btn.gameObject.SetActive(false);
                break;
            case "03":
                start_training_btn.gameObject.SetActive(false);
                break;
            case "04":
            case "05":
                entering_key_btn.gameObject.SetActive(false);
                append_btn.interactable = false;
                scenario_btn.interactable = false;
                break;
        }
        OnRegisterFunction();
    }

    public void OnRegisterFunction()
    {
        //AdamSync.SyncCreateRoom.createRoomRequset += OnCreateRoom;
        AdamSync.SyncCreateRoom.joinRoomRequset += OnJoinRoom;
        //AdamSync.SyncCreateRoom.getRoomsRequset += OnGetRooms;
    }

    //public void OnGetRooms(string msg)
    //{
    //    Debug.Log("OnGetRooms====" + msg);
    //}
    //public void OnCreateRoom(string msg)
    //{
    //    Debug.Log("OnCreateRoom====" + msg);
    //}
    public void OnJoinRoom(string msg)
    {
        Debug.Log("OnJoinRoom===" + msg);
        SceneManager.LoadScene("AdamTraining_pilot_terminal_panl 1");
    }
    public async void GetAllRoomData()
    {
        roomdata = await AsyncWebReq.Post<RoomData>(roomUrl, null);
        if (place.childCount > 0)
        {
            for (int i = 0; i < place.childCount; i++)
            {
                GameObject.Destroy(place.GetChild(i).gameObject);
            }
        }
        CreateRoom();
    }

    public async void GetAllUserData()
    {
        userData = await AsyncWebReq.Post<UserData>(userUrl, null);
    }
    public List<GameObject> currentAllAccount = new List<GameObject>();
    public void CreateAllUser(List<DataItem> userInfo)
    {
        if (userConent.childCount > 1)
        {
            for (int i = 1; i < userConent.childCount; i++)
            {
                GameObject.Destroy(userConent.GetChild(i).gameObject);
            }
            currentAllAccount.Clear();
        }

        for (int i = 0; i < userInfo.Count; i++)
        {
            int index = i;
            GameObject obj = GameObject.Instantiate(userItem, userConent);
            obj.SetActive(true);
            obj.name = userData.data[index].login_name + "," + currentSubjectID;
            obj.transform.GetChild(0).GetComponent<Text>().text = userData.data[index].login_name;
            obj.transform.GetChild(1).GetComponent<Text>().text = userData.data[index].job_number;
            userConent.GetComponent<ToggleGroup>().allowSwitchOff = true;
            obj.transform.GetChild(2).GetComponent<Toggle>().group = userConent.GetComponent<ToggleGroup>();
            obj.transform.GetChild(2).GetComponent<Toggle>().isOn = false;
            obj.transform.GetChild(2).GetComponent<Toggle>().onValueChanged.AddListener((isOn) =>
            {
                if (isOn)
                {
                    currentAccount = userData.data[index].login_name;
                }
                else
                {
                    currentAccount = "";
                }
                Debug.Log($"currentAccount{currentAccount}");
            });
            currentAllAccount.Add(obj);
        }
    }
    public void EliminateAccount()
    {
        if (currentEditorAccounts.Count > 0 && currentAllAccount.Count > 0)
        {
            for (int i = 0; i < currentEditorAccounts.Count; i++)
            {
                for (int j = 0; j < currentAllAccount.Count; j++)
                {
                    if (currentAllAccount[j].name.Contains(currentEditorAccounts[i].account) && currentAllAccount[j].name.Contains(currentEditorAccounts[i].subjectID))
                    {
                        GameObject.Destroy(currentAllAccount[j]);
                    }
                }
            }
        }
    }

    /// <summary>
    /// 席位分配提交按钮
    /// </summary>
    public void TiJiaoBtn()
    {
        CurrentEditorAccount ced = new CurrentEditorAccount();
        if (currentEditorAccounts.Count > 0)
        {
            for (int i = 0; i < currentEditorAccounts.Count; i++)
            {
                int index = i;
                if (currentEditorAccounts[index].subjectID.Equals(currentSubjectID) && currentEditorAccounts[index].SeatID.Equals(currentSeatID))
                {
                    currentEditorAccounts[index].account = currentAccount;
                    selector_panl.gameObject.SetActive(false);
                }
                else
                {
                    ced.subjectID = currentSubjectID;
                    ced.SeatID = currentSeatID;
                    ced.account = currentAccount;
                    if (!currentEditorAccounts.Contains(ced))
                        currentEditorAccounts.Add(ced);
                }
            }
        }
        else
        {
            ced.subjectID = currentSubjectID;
            ced.SeatID = currentSeatID;
            ced.account = currentAccount;
            if (!currentEditorAccounts.Contains(ced))
                currentEditorAccounts.Add(ced);
        }
        selector_panl.gameObject.SetActive(false);
        Debug.Log(currentEditorAccounts.Count);
    }

    /// <summary>
    /// 创建 新建房间的科目
    /// </summary>
    public void CreateSubject()
    {
        if (subjectContent.childCount > 1)
        {
            for (int i = 1; i < subjectContent.childCount; i++)
            {
                GameObject.Destroy(subjectContent.GetChild(i).gameObject);
            }
        }
        for (int i = 0; i < UIBootstrap.Instance.traininginformations.Count; i++)
        {
            if (currentThinkName.Equals(UIBootstrap.Instance.traininginformations[i].Name))
            {
                for (int j = 0; j < UIBootstrap.Instance.traininginformations[i].subjectsInfo.Count; j++)
                {
                    GameObject subjectTemp = GameObject.Instantiate(subjectItem, subjectContent);
                    subjectTemp.SetActive(true);
                    subjectTemp.name = UIBootstrap.Instance.traininginformations[i].subjectsInfo[j].subjectId;
                    subjectTemp.transform.Find("Text").GetComponent<Text>().text = UIBootstrap.Instance.traininginformations[i].subjectsInfo[j].subjectName;
                    subjectTemp.transform.Find("Text").GetComponent<Text>().enabled = true;
                    if (UIBootstrap.Instance.traininginformations[i].subjectsInfo[j].TrainDestList.Count < 2)
                    {
                        subjectTemp.transform.GetChild(2).gameObject.SetActive(false);
                    }
                    if (subjectTemp != null)
                    {
                        Transform redParent = subjectTemp.transform.Find("red_panl/RedReveal");
                        Transform greenParent = subjectTemp.transform.Find("green_paml/GreenReveal");
                        if (redParent.childCount > 0)
                        {
                            for (int ii = 0; ii < redParent.childCount; ii++)
                            {
                                GameObject.Destroy(redParent.GetChild(ii).gameObject);
                            }
                        }
                        if (greenParent.childCount > 0)
                        {
                            for (int ii = 0; ii < greenParent.childCount; ii++)
                            {
                                GameObject.Destroy(greenParent.GetChild(ii).gameObject);
                            }
                        }
                        for (int k = 0; k < UIBootstrap.Instance.traininginformations[i].subjectsInfo[j].seatInfos.Count; k++)
                        {
                            ///0 红方 1 蓝方
                            if (UIBootstrap.Instance.traininginformations[i].subjectsInfo[j].seatInfos[k].role.Equals("0"))
                            {
                                CreateSeatInfo(i, j, k, redParent, subjectTemp.name);
                            }
                            else
                            {
                                CreateSeatInfo(i, j, k, greenParent, subjectTemp.name);
                            }
                        }
                    }

                }
            }
        }
    }
    /// <summary>
    /// 新建房间 想定编辑里的科目信息
    /// </summary>
    /// <param name="indexI"></param>
    /// <param name="indexJ"></param>
    /// <param name="indexK"></param>
    /// <param name="parent"></param>
    /// <param name="subjectName"></param>
    private void CreateSeatInfo(int indexI, int indexJ, int indexK, Transform parent, string subjectName)
    {
        GameObject seatTemp = GameObject.Instantiate(revealPrefab, parent);
        seatTemp.name = UIBootstrap.Instance.traininginformations[indexI].subjectsInfo[indexJ].seatInfos[indexK].seatId;
        seatTemp.transform.GetChild(0).GetComponent<Text>().text = Spilt(UIBootstrap.Instance.traininginformations[indexI].subjectsInfo[indexJ].seatInfos[indexK].seatName, 0, 1);
        seatTemp.transform.GetChild(1).GetComponent<Text>().text = Spilt(UIBootstrap.Instance.traininginformations[indexI].subjectsInfo[indexJ].seatInfos[indexK].seatName, 2, 2);
        //obj.transform.GetChild(2).GetComponent<Text>().text = UIBootstrap.Instance.traininginformations[i].subjectsInfo[j].seatInfos[k].seatno;
        seatTemp.transform.GetChild(3).GetComponent<Button>().onClick.AddListener(() =>
        {
            currentSubjectID = subjectName;
            currentSeatID = seatTemp.name;
            currentAccountText = seatTemp.transform.GetChild(2).GetComponent<Text>();
            GetAllUserData();
            selector_panl.gameObject.SetActive(true);
            CreateAllUser(userData.data);
            EliminateAccount();
            Debug.Log($"currentSubjectID+currentSeatID=" + currentSubjectID + "=" + currentSeatID);
        });
        if (GlobalFlag.currentUser.role_code.Equals("04") || GlobalFlag.currentUser.role_code.Equals("05"))
        {
            seatTemp.transform.GetChild(3).GetComponent<Button>().interactable = false;
        }
    }

    public string Spilt(string data, int startIndex, int endIndex)
    {
        string msg = data.Substring(startIndex, endIndex);
        return msg;
    }

    private void Scenejump()
    {
        ///进入训练
        start_training_btn.onClick.AddListener(() =>
        {
            GameMain.model = false;
            //SceneManager.LoadScene("AdamTraining_pilot_terminal_panl 1");
            //加入房间
            string RoomName = "joinroom " + currentRoomName;
            _ = AdamSync.SyncCreateRoom.SendMessageAsync(RoomName);
        });
        ///进入导调
        entering_key_btn.onClick.AddListener(() =>
        {
            //GameMain.model = true;
            //SceneManager.LoadScene("Training_pilot_terminal_panl");

            string RoomName = "joinroom " + currentRoomName;
            _ = AdamSync.SyncCreateRoom.SendMessageAsync(RoomName);
        });
        ///想定编辑
        scenario_btn.onClick.AddListener(() =>
        {
            SceneManager.LoadScene("Contingenc_yediting_panl");
        });
    }

    /// <summary>
    /// 红蓝作战叉掉按钮
    /// </summary>
    /// <exception cref="NotImplementedException"></exception>
    private void Cance()
    {
        Cancel4_btn.onClick.AddListener(() =>
        {
            Storm_and_capture_panl.gameObject.SetActive(false);
        });
    }


    public void CreateRoom()
    {
        for (int i = 0; i < roomdata.data.Count; i++)
        {
            if (roomdata.data[i].State != 2)
            {
                CreateRoomBase(roomdata.data[i].Id, roomdata.data[i].Name);
            }

        }
    }

    public RSData.RoomSubjectData currentRoomData = new RSData.RoomSubjectData();

    public void CreateRoomBase(string roomId, string name)
    {
        GameObject roomItem = GameObject.Instantiate(root_pan, place);
        roomItem.name = roomId;
        roomItem.transform.Find("Text").GetComponent<Text>().text = name;
        roomItem.transform.Find("view_btn").GetComponent<Button>().onClick.AddListener(async () =>
        {
            Storm_and_capture_panl.gameObject.SetActive(true);
            currentRoomData = await AsyncWebReq.Get<RSData.RoomSubjectData>("http://111.229.30.246:48888/Handler/Practice.ashx?action=querypracticesubject&PracticeId=" + roomItem.name);
            currentRoomName = roomItem.name;
            GlobalFlag.roomID = roomItem.name;
            GlobalFlag.practiceId = roomItem.name;
            GlobalFlag.currentThinkId = roomItem.name;
            UIBootstrap.Instance.GetSceneData(GlobalFlag.practiceId);
            UIBootstrap.Instance.GetAllDeviceData();
            Debug.Log(" roomItem.nameID==" + roomItem.name);
            CreateSubjectItem(currentRoomData.data);
        });
    }
    public RSData.SubjectInfo currentSubjectInfo = new RSData.SubjectInfo();
    public string currentDIPracticeID;
    public string currentDISubjectID;
    /// <summary>
    /// 创建查看房间的科目
    /// </summary>
    /// <param name="t"></param>
    public void CreateSubjectItem(List<RSData.DataItem> di)
    {
        if (currentRoomSubjectItemConnect.childCount > 1)
        {
            for (int i = 1; i < currentRoomSubjectItemConnect.childCount; i++)
            {
                GameObject.Destroy(currentRoomSubjectItemConnect.GetChild(i).gameObject);
            }
        }
        DestorySubjectSeatInfo();

        for (int i = 0; i < di.Count; i++)
        {
            int index = i;
            GameObject subjectTemp = GameObject.Instantiate(currentRoomSubjectItem, currentRoomSubjectItemConnect);
            subjectTemp.SetActive(true);
            subjectTemp.name = di[index].Id;
            GlobalFlag.practiceSubjectID = subjectTemp.name;
            subjectTemp.transform.GetChild(0).GetComponent<Text>().text = di[index].Name;
            subjectTemp.GetComponent<Button>().onClick.AddListener(async () =>
            {
                currentDIPracticeID = di[index].PracticeId;
                currentDISubjectID = subjectTemp.name;
                currentSubjectInfo = await AsyncWebReq.Get<RSData.SubjectInfo>("http://111.229.30.246:48888/Handler/Practice.ashx?action=querypracticeseat&PracticeId=" + currentDIPracticeID + "&PracticeSubjectId=" + currentDISubjectID);
                CreateSubjectInfo(currentSubjectInfo.data);
            });
        }
        if (currentRoomSubjectItemConnect.childCount > 0)
        {
            currentRoomSubjectItemConnect.GetChild(1).GetComponent<Button>().onClick.Invoke();
        }
    }
    /// <summary>
    /// 删除科目席位信息
    /// </summary>
    public void DestorySubjectSeatInfo()
    {
        if (redSubjectInfoParent.childCount > 1)
        {
            for (int i = 1; i < redSubjectInfoParent.childCount; i++)
            {
                GameObject.Destroy(redSubjectInfoParent.GetChild(i).gameObject);
            }
        }
        if (greenSubjectInfoParent.childCount > 1)
        {
            for (int i = 1; i < greenSubjectInfoParent.childCount; i++)
            {
                GameObject.Destroy(greenSubjectInfoParent.GetChild(i).gameObject);
            }
        }
    }
    /// <summary>
    /// 创建科目席位信息
    /// </summary>
    /// <param name="sdi"></param>
    public void CreateSubjectInfo(List<RSData.SubjectDataItem> sdi)
    {
        UIBootstrap.Instance.GetSubjectInfo(sdi);
        DestorySubjectSeatInfo();
        List<Toggle> allToggles = new List<Toggle>();
        bool isAssigned = false;
        ///0 红方 1 蓝方
        for (int i = 0; i < sdi.Count; i++)
        {
            int index = i;
            if (sdi[i].Role.Equals("0"))
            {
                GameObject item = GameObject.Instantiate(redSubjectInfoItem, redSubjectInfoParent);
                item.SetActive(true);
                item.name = sdi[index].Id;
                item.transform.GetChild(0).GetComponent<Text>().text = sdi[index].SeatName.Substring(0, 2);
                item.transform.GetChild(1).GetComponent<Text>().text = sdi[index].SeatName.Substring(2, 2);
                item.transform.GetChild(2).GetComponent<Toggle>().isOn = false;
                item.transform.GetChild(2).GetComponent<Toggle>().group.SetAllTogglesOff();
                if (sdi[index].UserAccount != "999")
                {
                    item.transform.GetChild(2).GetComponent<Toggle>().isOn = true;
                    item.transform.GetChild(2).GetComponent<Toggle>().interactable = false;
                    item.transform.GetChild(2).GetComponent<Toggle>().enabled = false;
                    if (sdi[index].UserAccount == GlobalFlag.currentUser.login_name)
                    {
                        item.transform.GetChild(2).GetComponent<Toggle>().graphic.color = Color.green;
                        isAssigned = true;
                    }
                }
                else
                {

                }
                item.transform.GetChild(2).GetComponent<Toggle>().onValueChanged.AddListener((isOn) =>
                {
                    if (isOn)
                    {
                        if (sdi[index].UserAccount != GlobalFlag.currentUser.login_name)
                        {
                            submitView.SetActive(true);
                            svSubmitBtn.interactable = true;
                            svSubmitBtn.onClick.AddListener(() =>
                            {
                                OnEditorSeatInfo(item.name, GlobalFlag.currentUser.login_name);
                                svSubmitBtn.interactable = false;
                            });
                        }
                    }
                });
                allToggles.Add(item.transform.GetChild(2).GetComponent<Toggle>());
            }
            if (sdi[index].Role.Equals("1"))
            {
                GameObject item = GameObject.Instantiate(greenSubjectInfoItem, greenSubjectInfoParent);
                item.SetActive(true);
                item.name = sdi[index].Id;
                item.transform.GetChild(0).GetComponent<Text>().text = sdi[index].SeatName.Substring(0, 2);
                item.transform.GetChild(1).GetComponent<Text>().text = sdi[index].SeatName.Substring(2, 2);
                item.transform.GetChild(2).GetComponent<Toggle>().isOn = false;
                item.transform.GetChild(2).GetComponent<Toggle>().group.SetAllTogglesOff();
                if (sdi[index].UserAccount != "999")
                {
                    item.transform.GetChild(2).GetComponent<Toggle>().isOn = true;
                    item.transform.GetChild(2).GetComponent<Toggle>().interactable = false;
                    item.transform.GetChild(2).GetComponent<Toggle>().enabled = false;
                    if (sdi[index].UserAccount == GlobalFlag.currentUser.login_name)
                    {
                        item.transform.GetChild(2).GetComponent<Toggle>().graphic.color = Color.green;
                        isAssigned = true;
                    }
                }
                else
                {

                }
                item.transform.GetChild(2).GetComponent<Toggle>().onValueChanged.AddListener((isOn) =>
                {
                    if (isOn)
                    {
                        if (sdi[index].UserAccount != GlobalFlag.currentUser.login_name)
                        {
                            submitView.SetActive(true);
                            svSubmitBtn.interactable = true;
                            svSubmitBtn.onClick.AddListener(() =>
                            {
                                OnEditorSeatInfo(item.name, GlobalFlag.currentUser.login_name);
                                svSubmitBtn.interactable = false;
                            });
                        }
                    }
                });
                allToggles.Add(item.transform.GetChild(2).GetComponent<Toggle>());
            }

        }

        if (isAssigned || !GlobalFlag.currentUser.role_code.Equals("04"))
        {
            if (allToggles.Count > 0)
            {
                for (int i = 0; i < allToggles.Count; i++)
                {
                    allToggles[i].enabled = false;
                }
            }
        }
    }

    public async void OnEditorSeatInfo(string practiceSeatId, string accout)
    {
        PData.UpdatePracticeSeatData upsd = new PData.UpdatePracticeSeatData();
        upsd = await AsyncWebReq.Post<PData.UpdatePracticeSeatData>("http://111.229.30.246:48888/Handler/PracticeSeat.ashx?action=UpdatePracticeSeatOne&practiceseatId=" + practiceSeatId + "&Account=" + accout, null);
        if (upsd.state)
        {
            submitInstruct.text = "提交成功";
            GlobalFlag.practiceSeatId = practiceSeatId;
            Debug.LogError(GlobalFlag.practiceSeatId);
        }
        else
        {
            submitInstruct.text = "提交失败,席位已经被占用";
        }
        currentSubjectInfo = await AsyncWebReq.Get<RSData.SubjectInfo>("http://111.229.30.246:48888/Handler/Practice.ashx?action=querypracticeseat&PracticeId=" + currentDIPracticeID + "&PracticeSubjectId=" + currentDISubjectID);
        CreateSubjectInfo(currentSubjectInfo.data);

        UIBootstrap.Instance.GetSubjectInfo(currentSubjectInfo.data);
    }


    /// <summary>
    /// 分配面板提交按钮和取消人员选择按钮
    /// </summary>
    private void Submit()
    {
        seatSubmit_btn.onClick.AddListener(async () =>
        {
            append_room_panl.gameObject.SetActive(false);
            distribution_panl.gameObject.SetActive(false);
            selector_panl.gameObject.SetActive(false);
            string accountInfo = AccountsInfo();
            ReturnRoomID returnRoomId = await AsyncWebReq.Post<ReturnRoomID>("http://111.229.30.246:48888/Handler/Practice.ashx?action=add&Name=" + currentRoomName + "&MissionModel=" + currentMissionModel + "&ThinkingId=" + currentThinkingId + "&AccountsInfo=" + accountInfo, null);
            if (returnRoomId.state)
            {
                CreateRoomBase(returnRoomId.data, currentRoomName);
                //创建房间
                string RoomName = "createroom " + returnRoomId.data;

                _ = AdamSync.SyncCreateRoom.SendMessageAsync(RoomName);
            }
            else
            {
                Debug.Log(returnRoomId.message);
            }
        });


        off3_btn.onClick.AddListener(() =>
        {
            selector_panl.gameObject.SetActive(false);
        });
    }


    public string AccountsInfo()
    {
        string info = "";
        for (int i = 0; i < currentEditorAccounts.Count; i++)
        {
            string ss = currentEditorAccounts[i].subjectID + "," + currentEditorAccounts[i].SeatID + "," + currentEditorAccounts[i].account + ";";
            info += ss;
        }
        return info;
    }

    /// <summary>
    /// 添加分配面板和取消
    /// </summary>
    private void Verify()
    {

        verify_btn.onClick.AddListener(() =>
        {
            if (room_input.text.Length >= 1)
            {
                distribution_panl.gameObject.SetActive(true);
                currentRoomName = room_input.text;
            }
            else
            {
                tips_txt.text = "请输入房间名称";
            }
        });
        off_btn.onClick.AddListener(() =>
        {
            distribution_panl.gameObject.SetActive(false);
        });
    }



    /// <summary>
    /// 叉掉房间按钮
    /// </summary>
    private void Forkoffbtn()
    {
        Fork_off_btn.onClick.AddListener(() =>
        {
            append_room_panl.gameObject.SetActive(false);
        });
        cancel_btno.onClick.AddListener(() =>
        {
            append_room_panl.gameObject.SetActive(false);
        });
    }
    private char[] _specialChar = { '_', ' ', '\'', '\\', };

    private List<DataItem> dataItemTemp = new List<DataItem>();

    public void FuzzySearch(string searchName)
    {
        dataItemTemp.Clear();
        string name = searchName.Trim(_specialChar).Replace(" ", "");
        for (int i = 0; i < userData.data.Count; i++)
        {
            if (userData.data[i].login_name.Contains(name) || userData.data[i].job_number.Contains(name))
            {
                if (!dataItemTemp.Contains(userData.data[i]))
                    dataItemTemp.Add(userData.data[i]);
            }
        }

        if (dataItemTemp.Count > 0)
        {
            CreateAllUser(dataItemTemp);
        }
    }

    private void OnDisable()
    {
        Debug.Log("OnDisable");
        //AdamSync.SyncCreateRoom.createRoomRequset -= OnCreateRoom;
        AdamSync.SyncCreateRoom.joinRoomRequset += OnJoinRoom;
        //AdamSync.SyncCreateRoom.getRoomsRequset += OnGetRooms;
    }
    private void OnDestory()
    {
        Debug.Log("OnDestory");
        //AdamSync.SyncCreateRoom.createRoomRequset -= OnCreateRoom;
        AdamSync.SyncCreateRoom.joinRoomRequset -= OnJoinRoom;
        //AdamSync.SyncCreateRoom.getRoomsRequset -= OnGetRooms;
    }
}

public class CurrentEditorAccount
{
    public string subjectID;
    public string SeatID;
    public string account;
}