using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using GCGame.Table;
using Games.Mission;
using Games.Item;

public class FinishTheCopyResultPanelCtr : MonoBehaviour {

    public static FinishTheCopyResultPanelCtr Instance;
    private void Awake()
    {
        Instance = this;
    }

    private void OnDestroy()
    {
        Instance = null;
    }

    private void OnEnable()
    {
        canClose = false;
        StopAllCoroutines();
        StartCoroutine("CountTime");
    }

    private IEnumerator CountTime()
    {
        yield return new WaitForSeconds(1.0f);
        canClose = true;
    }

    public GameObject SimpleWnd;
    public GameObject winPanel;
    public GameObject defeatPanel;

    public GameObject GuildWnd;
    public GameObject GuildWarWin;
    public GameObject GuildWarDefeat;

    public GameObject rewItemPrefab;
    public Transform rewItemPrefabParent;
    public GameObject _ScorePanel;

    private bool canClose = false;           // 能否关闭UI,现需要UI动画播放完毕后才可关闭。

    public void OnReceivePacket(GC_RET_FINISH_COPY_INFO packet)  //副本通用逻辑(newcopybase中存在的才会弹奖励)
    {
        Tab_NewCopyBase copyBase = TableManager.GetNewCopyBaseByID(GameManager.gameManager.PlayerDataPool.EnterSceneCache.EnterCopySceneID, 0);
        if(copyBase != null)
        {
            SimpleWnd.SetActive(true);
            GuildWnd.SetActive(false);
            if (packet.IsSuccess == 0)
            {
                ShowDefeatPanel();
            }
            else
            {
                ShowWinPanel(packet);
            }
        }
        else
        {
            SimpleWnd.SetActive(false);
            GuildWnd.SetActive(true);
            GuildWarWin.SetActive(packet.IsSuccess != 0);
            GuildWarDefeat.SetActive(packet.IsSuccess == 0);
            if (Singleton<ObjManager>.Instance.MainPlayer != null)
            {
                Singleton<ObjManager>.Instance.MainPlayer.LeveAutoCombat();
            }
        }

        Invoke("Close", 3.0f);
    }

    public void OnReceivePacket(RetDailyCopyFinish packet)  //副本通用逻辑(newcopybase中存在的才会弹奖励)
    {
        GuildWnd.SetActive(false);
        SimpleWnd.SetActive(true);
        if (packet.issuccess == 0)
        {
            ShowDefeatPanel();
        }
        else
        {
            ShowWinPanel(packet);
        }

        Invoke("Close", 3.0f);
    }

    private List<GameObject> rewItemList = new List<GameObject>();
    public void ShowWinPanel(object packet)
    {
        winPanel.SetActive(true);
        defeatPanel.SetActive(false);

        CreateAndInitRewItem(packet);
        //ShowScoreIcon(packet.Level);

        //开始倒计时
        StartExitCopyCount();
    }

    public void StartExitCopyCount()
    {
        if(TestingCopyInfoCtr.Instance && TestingCopyInfoCtr.Instance.gameObject.activeInHierarchy)
        {
            TestingCopyInfoCtr.Instance.CountExitTime();
        }
    }

    // 取消评分
    //public void ShowScoreIcon(int _Score)
    //{
    //    if(_Score == -1)
    //    {
    //        _ScorePanel.SetActive(false);
    //        return;
    //    }
    //    _ScorePanel.SetActive(true);
    //    for(int index = 0; index < _ScoreObj.Count; index++)
    //    {
    //        _ScoreObj[index].SetActive(_Score - 1 == index);
    //    }
    //}

    public void CreateAndInitRewItem(object packet)
    {
        ClearAllRew();
        StartCoroutine(CreateitemPrefabCoroutine(packet));
    }

    IEnumerator CreateitemPrefabCoroutine(object packet)
    {
        //按照品质排序
        Dictionary<int, int> _RewItemDataDic = new Dictionary<int, int>();
        List<int> _ItemDataIdList = new List<int>();

        GC_RET_FINISH_COPY_INFO pack_1 = packet as GC_RET_FINISH_COPY_INFO;
        if (pack_1 != null)
        {
            for (int index = 0; index < pack_1.itemsCount; index++)
            {
                Tab_CommonItem tab = TableManager.GetCommonItemByID(pack_1.GetItems(index).ItemId, 0);
                if (tab == null)
                {
                    continue;
                }

                if (tab.ClassID == (int)ItemClass.EQUIP && tab.Quality < (int)ItemQuality.QUALITY_BLUE)
                {
                    continue;
                }

                if (!_ItemDataIdList.Contains(pack_1.GetItems(index).ItemId))
                {
                    _ItemDataIdList.Add(pack_1.GetItems(index).ItemId);
                }
                if (_RewItemDataDic.ContainsKey(pack_1.GetItems(index).ItemId))
                {
                    _RewItemDataDic[pack_1.GetItems(index).ItemId] += pack_1.GetItems(index).ItemNum;
                }
                else
                {
                    _RewItemDataDic.Add(pack_1.GetItems(index).ItemId, pack_1.GetItems(index).ItemNum);
                }

            }
        }

        RetDailyCopyFinish pack_2 = packet as RetDailyCopyFinish;
        if (pack_2 != null)
        {
            for (int index = 0; index < pack_2.itemid.Count; index++)
            {
                Tab_CommonItem tab = TableManager.GetCommonItemByID(pack_2.itemid[index], 0);
                if (tab == null)
                {
                    continue;
                }

                if (tab.ClassID == (int)ItemClass.EQUIP && tab.Quality < (int)ItemQuality.QUALITY_BLUE)
                {
                    continue;
                }

                if (!_ItemDataIdList.Contains(pack_2.itemid[index]))
                {
                    _ItemDataIdList.Add(pack_2.itemid[index]);
                }

                if (_RewItemDataDic.ContainsKey(pack_2.itemid[index]))
                {
                    _RewItemDataDic[pack_2.itemid[index]] += pack_2.itemnum[index];
                }
                else
                {
                    _RewItemDataDic.Add(pack_2.itemid[index], pack_2.itemnum[index]);
                }
            }
        }

        _ItemDataIdList.Sort(delegate (int idA, int idB) {
            Tab_CommonItem commonItemA = TableManager.GetCommonItemByID(idA, 0);
            Tab_CommonItem commonItemB = TableManager.GetCommonItemByID(idB, 0);
            if (commonItemA == null || commonItemB == null)
            {
                return 0;
            }
            if (commonItemA.Quality == commonItemB.Quality)
            {
                return 0;
            }
            return commonItemA.Quality > commonItemB.Quality ? -1 : 1;
        });

        for (int index = 0; index < _ItemDataIdList.Count; index++)
        {
            GameObject item = GameObject.Instantiate(rewItemPrefab);

            item.transform.SetParent(rewItemPrefabParent);
            item.transform.localPosition = Vector3.zero;
            item.transform.localScale = Vector3.one;
            item.transform.localRotation = Quaternion.Euler(Vector3.zero);

            rewItemList.Add(item);
            item.GetComponent<CopyFinishRewItem>().InitItem(_ItemDataIdList[index], _RewItemDataDic.ContainsKey(_ItemDataIdList[index]) ? _RewItemDataDic[_ItemDataIdList[index]] : 1);
        }

        yield break;
    }

    private void DicSort(Dictionary<int, int> dic)
    {
        if(dic.Count > 0)
        {
            List<KeyValuePair<int, int>> lst = new List<KeyValuePair<int, int>>(dic);
            lst.Sort(delegate (KeyValuePair<int, int> lstA, KeyValuePair<int, int> lstB)
            {
                Tab_CommonItem commonItemA = TableManager.GetCommonItemByID(lstA.Key, 0);
                Tab_CommonItem commonItemB = TableManager.GetCommonItemByID(lstB.Key, 0);
                if (commonItemA == null || commonItemB == null)
                {
                    return 0;
                }
                if (commonItemA.Quality == commonItemB.Quality)
                {
                    return 0;
                }
                return commonItemA.Quality > commonItemB.Quality ? -1 : 1;
            });
        }
    }

    public void ClearAllRew()
    {
        for(int index = 0; index < rewItemList.Count; index++)
        {
            GameObject.Destroy(rewItemList[index].gameObject);
        }
        rewItemList.Clear();
    }

    public void ShowDefeatPanel()
    {
        winPanel.SetActive(false);
        defeatPanel.SetActive(true);
    }

    public void OnBackClick()
    {
        if(canClose)
        {
            Close();
        }
    }

    private void Close()
    {
        UIManager.CloseUI(UIInfo.FinishTheCopyResultPanel);
    }

    public void OnDisable()
    {
        //暂时先硬处理一下,帮会联赛的需要出它自己的结算界面
        if (GameManager.gameManager.PlayerDataPool.EnterSceneCache.EnterCopySceneID == (int)Games.GlobeDefine.GameDefine_Globe.SCENE_DEFINE.SCENE_GUILDWARMAIN)
        {
            UIManager.ShowUI(UIInfo.GuildWarInfo);
        }
    }

    public void OnPetClick()
    {
        UIManager.ShowUI(UIInfo.PetMainWndPath, delegate (bool bSuccess, object param)
        {

            if (bSuccess && PetMainWnd.Instance != null)
            {
                PetMainWnd.Instance.ShowPage(0, 0);
            }

        });
    }

    public void OnSkillClick()
    {
        UIManager.ShowUI(UIInfo.SkillInfo);
    }

    public void OnMakeClick()
    {
        UIManager.ShowUI(UIInfo.EquipEnhance);
    }
}