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

public class CreateRoomPanel : MonoBehaviour
{
    /// <summary>
    /// 创建名称界面
    /// </summary>
    public Transform CreateNameP;
    /// <summary>
    /// 选择想定界面
    /// </summary>
    public Transform ChoseThinkingP;
    /// <summary>
    /// 绑定岗位界面
    /// </summary>
    public Transform BindSeatP;

    public InputField inputName;
    public Toggle xunlianTog;
    public Toggle kaoheTog;
    public Button quxiaoBtn1;
    public Button nextBtn1;

    public VerticalLayoutGroup group2;
    public Button frontBtn2;
    public Button nextBtn2;

    public Button frontBtn3;
    public Button nextBtn3;
    public VerticalLayoutGroup group3seat;

    public Text thinkingName;
    public Text thinkingMode;

    public VerticalLayoutGroup group2_2;

    public Button closeBtn2;
    public Button closeBtn3;

    /// <summary>
    /// 房间名称
    /// </summary>
    string PracticeName;
    /// <summary>
    /// 考核训练
    /// </summary>
    string MissionModel;
    /// <summary>
    /// 选中的想定
    /// </summary>
    [HideInInspector]
    public thinkingfile choseThinkingfile;
    /// <summary>
    /// 岗位绑定的人员
    /// </summary>
    List<SeatBindUserData> seatBindUser=new List<SeatBindUserData>();

    [HideInInspector]
    public GameObject 选择想定thinkingItemPrefb;
    [HideInInspector]
    public GameObject 选择想定subjectItemPrefb;
    [HideInInspector]
    public GameObject 席位分配subjectItemPrefb;
    [HideInInspector]
    public GameObject 席位分配seatItemPrefb;
    [HideInInspector]
    public GameObject 席位分配seat2Prefb;
    [HideInInspector]
    public GameObject choseUserPrefb;

    public static CreateRoomPanel instance;

    private void Awake()
    {
        instance = this;
        if (选择想定thinkingItemPrefb==null)
        {
            选择想定thinkingItemPrefb = Resources.Load<GameObject>("UI/Item/选择想定/CreateRoomThinkingItem");
        }

        if(选择想定subjectItemPrefb==null)
        {
            选择想定subjectItemPrefb= Resources.Load<GameObject>("UI/Item/选择想定/CreateRoomSubjectItem");
        }

        if(席位分配subjectItemPrefb == null)
        {
            席位分配subjectItemPrefb = Resources.Load<GameObject>("UI/Item/席位分配/subject");
        }

        if (席位分配seatItemPrefb == null)
        {
            席位分配seatItemPrefb = Resources.Load<GameObject>("UI/Item/席位分配/seat");
        }

        if(席位分配seat2Prefb==null)
        {
            席位分配seat2Prefb= Resources.Load<GameObject>("UI/Item/席位分配/seatitem");
        }

        if (choseUserPrefb==null)
        {
            choseUserPrefb = Resources.Load<GameObject>("UI/ChoseUserPanel");
        }

        quxiaoBtn1.onClick.AddListener(()=> 
        {
            Destroy(gameObject);
        });

        closeBtn2.onClick.AddListener(() => 
        {
            Destroy(gameObject);
        });

        closeBtn3.onClick.AddListener(() =>
        {
            Destroy(gameObject);
        });

        //名字界面下一步按钮
        nextBtn1.onClick.AddListener(() => 
        {
            if(!string.IsNullOrEmpty(inputName.text))
            {
                PracticeName = inputName.text;
                MissionModel = xunlianTog.isOn ? "训练" : "考核";
                CreateNameP.gameObject.SetActive(false);
                ChoseThinkingP.gameObject.SetActive(true);
                BindSeatP.gameObject.SetActive(false);

                UpdataThinking();
            }
        });

        //选择想定界面下一步按钮
        nextBtn2.onClick.AddListener(() => 
        {
            if(choseThinkingfile!=null)
            {
                CreateNameP.gameObject.SetActive(false);
                ChoseThinkingP.gameObject.SetActive(false);
                BindSeatP.gameObject.SetActive(true);
                //初始化席位分配界面
                InitSeatPanel();
            }
        });

        //选择想定界面上一步按钮
        frontBtn2.onClick.AddListener(() => 
        {
            choseThinkingfile = null;
            CreateNameP.gameObject.SetActive(true);
            ChoseThinkingP.gameObject.SetActive(false);
            BindSeatP.gameObject.SetActive(false);
        });

        //绑定人员界面确定按钮
        nextBtn3.onClick.AddListener(() => 
        {
            List<SeatBindUserData> tmps = new List<SeatBindUserData>();
            group3seat.transform.GetComponentsInChildren<CreateRoomSeatItem>(true).ToList().ForEach(a=> 
            {
                if(a.useraccount.text!="999")
                {
                    tmps.Add(new SeatBindUserData { seatId = a.seat1.seatId, subjectId = a.seat1.subjectId, username = a.username.text, useraccount = a.useraccount.text });
                }
            });
            seatBindUser=tmps;
            Create();
        });

        //绑定人员界面上一步按钮
        frontBtn3.onClick.AddListener(() =>
        {
            CreateNameP.gameObject.SetActive(false);
            ChoseThinkingP.gameObject.SetActive(true);
            BindSeatP.gameObject.SetActive(false);
            group3seat.transform.GetComponentsInChildren<SeatBindSubjectItem>().ToList().ForEach(a => 
            {
                DestroyImmediate(a.gameObject);
            });
            group3seat.transform.GetComponentsInChildren<SeatBindSeatItem>().ToList().ForEach(a =>
            {
                DestroyImmediate(a.gameObject);
            });
        });
    }

    /// <summary>
    /// 更新想定文件
    /// </summary>
    private void UpdataThinking()
    {
        group2.transform.GetComponentsInChildren<CreateRoomThinkingItem>(true).ToList().ForEach(a=> 
        {
            DestroyImmediate(a.gameObject);
        });

        StartCoroutine(MyNetMQClient.CallGet("http://"+MyNetMQClient.CallIP+"/Handler/Thinkingfile.ashx?action=all", result => 
        {
            var json = JsonMapper.ToObject<CallResultList<thinkingfile>>(result);
            var jsondata = JsonMapper.ToObject(result)["data"];
            if (json.state)
            {
                jsondata.ValueAsArray().ToList().ForEach(a =>
                {
                    json.data.Find(b => b.Id == a["Id"].ToString()).CreateTime =DateTime.Parse(a["CreateTime"].ToString());
                });

                var thinkingfiles = json.data.OrderByDescending(a=>a.CreateTime).ToList();
                int index = 0;
                CreateRoomThinkingItem first=null;
                thinkingfiles.ForEach(a => 
                {
                    GameObject obj = Instantiate<GameObject>(选择想定thinkingItemPrefb, group2.transform);
                    obj.GetComponent<CreateRoomThinkingItem>().Init(a);
                    if(index==0)
                    {
                        //第一个
                        first = obj.GetComponent<CreateRoomThinkingItem>();
                    }
                    index++;
                });

                if (first != null)
                {
                    first.Chose();
                }
            }
            else
            {
                string msg = json.message;
                Debug.LogError(msg);
            }
        }));
    }


    /// <summary>
    /// 创建房间数据
    /// </summary>
    public void Create()
    {
        if(choseThinkingfile!=null && !string.IsNullOrEmpty(MissionModel))
        {
            KeyValuePair<string, string>[] datas = new KeyValuePair<string, string>[3];
            datas[0] = new KeyValuePair<string, string>("thinkingfile_id",choseThinkingfile.Id);
            datas[1] = new KeyValuePair<string, string>("SeatBindUserData",JsonMapper.ToJson(seatBindUser));
            datas[2] = new KeyValuePair<string, string>("data", JsonMapper.ToJson(new practice { Name= PracticeName, MissionModel= MissionModel }));

            StartCoroutine(MyNetMQClient.CallPost("http://"+MyNetMQClient.CallIP+"/Handler/Practice.ashx?action=add",datas, result => 
            {
                var json = JsonMapper.ToObject<CallResultObject>(result);
                if (json.state)
                {
                    string str =json.data.ToString();
                    //创建成功
                    Debug.Log("创建房间成功:" + PracticeName);
                    MessagePanel.ShowMessage("创建房间成功", RoomListPanel.instance.canvas.transform);

                    //房间列表刷新
                    RoomListPanel.instance.Refresh();

                    Destroy(gameObject);
                }
                else
                {
                    string msg = json.message;
                    Debug.LogError(msg);
                    MessagePanel.ShowMessage(msg, RoomListPanel.instance.canvas.transform);
                }
            }));
        }
    }

    /// <summary>
    /// 初始化席位分配页面
    /// </summary>
    private void InitSeatPanel()
    {
        ThinkingData data =JsonMapper.ToObject<ThinkingData>(choseThinkingfile.VirtualPath);
        data.subjectsInfo.ForEach(a => 
        {
            //创建科目
            GameObject obj = Instantiate<GameObject>(席位分配subjectItemPrefb, group3seat.transform);
            SeatBindSubjectItem subjectScript = obj.GetComponent<SeatBindSubjectItem>();
            subjectScript.Init(a);
            //创建席位容器框
            GameObject obj2 = Instantiate<GameObject>(席位分配seatItemPrefb, group3seat.transform);

            a.seatInfos.ForEach(b => 
            {
                //创建席位
                GameObject obj3 = Instantiate<GameObject>(席位分配seat2Prefb, obj2.transform);
                CreateRoomSeatItem createRoomSeatItem = obj3.GetComponent<CreateRoomSeatItem>();
                createRoomSeatItem.Init(b, subjectScript);
            });
        });
    }
}

public class SeatBindUserData
{
    public string subjectId;
    public string seatId;
    public string username;
    public string useraccount;
}