using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DataModel.Model;
using UnityEngine.UI;
using System.Linq;
using LitJson;
using TMPro;

public class CheckPanel : MonoBehaviour
{
    practice practice1;
    List<practicesubject> practicesubjects;

    [HideInInspector]
    public GameObject subejctItemPrefb;
    [HideInInspector]
    public GameObject seatItemPrefb;

    public VerticalLayoutGroup subjectGroup;
    public VerticalLayoutGroup seatGroup;
    public Button JoinBtn;
    public Button CloseBtn;
    public Text practiceNameText;
    public Text subejctText;
    public Text 训练方式Text;
    public Text 操作流程Text;

    public Sprite 选中sprite;
    public Sprite 未选中sprite;


    public static CheckPanel instance;
    public void Init(practice practice)
    {
        instance = this;
        practice1 = practice;
        practiceNameText.text = practice1.Name;
        if (subejctItemPrefb == null)
        {
            subejctItemPrefb = Resources.Load<GameObject>("UI/Item/CheckPanelSubjectItem");
        }

        if (seatItemPrefb == null)
        {
            seatItemPrefb = Resources.Load<GameObject>("UI/Item/CheckPanelSeatItem");
        }

        JoinBtn.onClick.AddListener(Join);
        CloseBtn.onClick.AddListener(() =>
        {
            Destroy(gameObject,0.2f);
        });

        //获取所有practiceSubejct
        StartCoroutine(MyNetMQClient.CallGet("http://" + MyNetMQClient.CallIP + "/Handler/Practice.ashx?action=querypracticesubject&PracticeId=" + practice1.Id, str =>
        {
            var json = JsonMapper.ToObject<CallResultList<practicesubject>>(str);
            if (json.state)
            {
                //生成科目
                practicesubjects = json.data.OrderBy(a => a.OrderIndex).ToList();
                int index = 0;
                foreach (var item in practicesubjects)
                {
                    GameObject obj = Instantiate<GameObject>(subejctItemPrefb, subjectGroup.transform);
                    obj.GetComponent<CheckPanelSubjectItem>().Init(item, index);
                    index++;
                }


                Invoke("SetInteractable", 2);
            }
            else
            {
                Debug.LogError(json.message);
            }
        })); ;
    }

    /// <summary>
    /// 允许点击加入房间
    /// </summary>
    public void SetInteractable()
    {
        JoinBtn.interactable = true;
    }
    private void Join()
    {
        //检查本人是否选择了岗位
        var list = subjectGroup.transform.GetComponentsInChildren<CheckPanelSubjectItem>(true).ToList().FindAll(a=>a.MyChose!=null);
        if (list!=null && list.Count>0)
        {
            List<BindData> bindDatas = new List<BindData>();
            list.ForEach(b =>
            {
                if (b.MyChose.userAccount.text == LoadManage.Instance.me.user.user_name)
                {
                    bindDatas.Add(new BindData { practiceSeatId = b.MyChose.practiceseat1.Id, userAccount = b.MyChose.userAccount.text, userName = b.MyChose.userName.text });
                }
            });

            //更新选择的岗位
            StartCoroutine(MyNetMQClient.CallPost("http://" + MyNetMQClient.CallIP + "/Handler/PracticeSeat.ashx?action=UpdatePracticeSeatUser", new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("BindData", JsonMapper.ToJson(bindDatas)) }, str =>
            {
                var json = JsonMapper.ToObject<CallResultObject>(str);
                if (json.state)
                {
                    if ((int)json.data == 0)
                    {
                        //更新成功,加入房间
                        LoadManage.Instance.currentPractice = practice1;
                        LoadManage.Instance.psubjects = practicesubjects;
                        Debug.Log("选择岗位成功");

                        //获取syncid
                        StartCoroutine(MyNetMQClient.CallGet("http://"+MyNetMQClient.CallIP+"/Handler/Practice.ashx?action=getAccountIndex&PracticeId="+practice1.Id+"&Account="+LoadManage.Instance.me.user.user_name,str2=>  
                        {
                            var json2 = JsonMapper.ToObject<CallResultObject>(str2);
                            if (json2.state)
                            {
                                int syncid=(int)json2.data;
                                if(syncid==0)
                                {
                                    Debug.LogError("未找到syncid");
                                    MessagePanel.ShowMessage("未找到syncid", RoomListPanel.instance.canvas.transform);
                                }
                                else
                                {
                                    //创建mq连接
                                    Debug.Log("syncid为" + syncid);
                                    try
                                    {
                                        LoadManage.Instance.CreateRoomServerClient(practice1.SubIP, practice1.PubIP, practice1.RoomArea, syncid);
                                    }
                                    catch (System.Exception e)
                                    {

                                        GameObject.Find("Text (TMP)").GetComponent<TextMeshProUGUI>().text = e.Message;
                                    }

                                    if (LoadManage.Instance.systemMode == SystemMode.PC)
                                    {
                                        UnityEngine.SceneManagement.SceneManager.LoadScene("GameSencePC");
                                    }
                                    else if(LoadManage.Instance.systemMode == SystemMode.MR)
                                    {
                                        UnityEngine.SceneManagement.SceneManager.LoadScene("GameSenceMR");
                                    }
                                }
                            }
                            else
                            {
                                string msg = json2.message;
                                Debug.LogError(msg);
                                MessagePanel.ShowMessage(msg, RoomListPanel.instance.canvas.transform);
                            }

                        }));
                    }
                    else
                    {
                        Debug.Log("有岗位未绑定成功,请重新选择");
                        MessagePanel.ShowMessage("有岗位未绑定成功,请重新选择", RoomListPanel.instance.canvas.transform);
                        Destroy(gameObject);
                    }
                }
                else
                {
                    string msg = json.message;
                    Debug.LogError(msg);
                    MessagePanel.ShowMessage(msg, RoomListPanel.instance.canvas.transform);
                }
            }));
        }
        else
        {
            Debug.Log("请选择岗位");
            MessagePanel.ShowMessage("请选择岗位", RoomListPanel.instance.canvas.transform);
        }
    }
}

public struct BindData
{
    public string practiceSeatId;
    public string userName;
    public string userAccount;
}