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

public class CurPageItemInfo
{
    public int snatchId = -1;  //对应SnatchTreasure表的索引ID
    public int curHadCompletedCount = 0; //当前已经完成的组数(还要用来算当前正在出售第几组)
    public int curHadPutIntoCount = 0; //当前本组已经投入的份数
    public int selfHadPutIntoCount = 0;  //当前本组自身已经投入的份数

    public  CurPageItemInfo(int _SnatchId, int _CurHadCompletedGroupCouunt, int _CurHadPutIntoCount, int _SelfHadPutIntoCount)
    {
        snatchId = _SnatchId;
        curHadCompletedCount = _CurHadCompletedGroupCouunt;
        curHadPutIntoCount = _CurHadPutIntoCount;
        selfHadPutIntoCount = _SelfHadPutIntoCount;
    }
}

public class AucationingPanelCtr : MonoBehaviour
{
    #region 
    //类型MenuItem
    public GameObject classMenuItemPrefab;
    public Transform prefabParent;

    public GameObject aucationItemPrafab;
    public Transform aucationItemParent;

    //夺宝空间
    public Text aucationSpace;

    //信息面板
    public Text remainTime;
    public Text itemName;
    public Text hadBeenPutIntoCount;
    public Text shopPriceText;
    public Text onSellCount;
    public Text hasPutIntoCount;
    public Slider curGroupSlider;
    public Text sliderCountValue;  //Slider需要显示的数量
    public Button putIntoBtn;

    public UINumBoardInput numBoard;
    public UICurrencyItem total;
    public UICurrencyItem own;

    #endregion

    public Dictionary<int, int> MoneytypeNamesTableId = new Dictionary<int, int>()
    {
        {(int)MONEYTYPE.MONEYTYPE_COIN ,6003},
        {(int)MONEYTYPE.MONEYTYPE_YUANBAO ,6001},
        {(int)MONEYTYPE.MONEYTYPE_YUANBAO_BIND ,6002},
        {(int)MONEYTYPE.MONEYTYPE_COIN_BIND ,6004},
    };

    //最多可以参与的组数是20
    public int allCanPutIntoGroypCount = 20;

    private int curSelectedSnatchId = -1;
    private int selfTotalPutIntoCount = 1; //默认投入一份
    public static AucationingPanelCtr Instance;
    private void Awake()
    {
        Instance = this;
        GUIData.delMoneyChanged += RefreshRemainMoney;
    }

    private void OnDestroy()
    {
        Instance = null;
        GUIData.delMoneyChanged -= RefreshRemainMoney;
    }

    private void OnEnable()
    {
        LoadClassTypeToDic();  //读取全部的类型,并且作为Item推进去
        CountRemainTime();  //计算当前活动的剩余时间
    }
    private Dictionary<int, List<Tab_SnatchTreasure>> snatchAllItemDic = new Dictionary<int, List<Tab_SnatchTreasure>>();
    /// <summary>
    /// 遍历表 读取全部的类型 key值为对应的classTypeId  值为对应的文字描述 
    /// </summary>
    public void LoadClassTypeToDic()
    {
        foreach(var item in TableManager.GetSnatchTreasure())
        {
            if(snatchAllItemDic.ContainsKey(item.Key))
            {
                snatchAllItemDic[item.Key].Add(item.Value);
            }else
            {
                List<Tab_SnatchTreasure> list = new List<Tab_SnatchTreasure>();
                list.Add(item.Value); 
                snatchAllItemDic.Add(item.Key, list);
            }
        }

        PushMenuItem();
    }

    private List<GameObject> classMenuItemList = new List<GameObject>();
    public void PushMenuItem()
    {
        if (classMenuItemList.Count > 0)
        {
            return;
        }
        Dictionary<int, string> _MenuItemClassItemDic = new Dictionary<int, string>();
        foreach (var item in TableManager.GetSnatchTreasure().Values)
        {
            if (!IsHaveItemToSell(item.Id))
            {
                continue;
            }

            if (!_MenuItemClassItemDic.ContainsKey(item.ClassifyType))
                _MenuItemClassItemDic.Add(item.ClassifyType, item.ClassifyName);
        }

        foreach(var item in _MenuItemClassItemDic)
        {
            GameObject classMenuItem = GameObject.Instantiate(classMenuItemPrefab);

            classMenuItem.transform.SetParent(prefabParent);
            classMenuItem.transform.localPosition = Vector3.zero;
            classMenuItem.transform.localScale = Vector3.one;
            classMenuItem.transform.localRotation = Quaternion.Euler(Vector3.zero);

            classMenuItemList.Add(classMenuItem);
            classMenuItem.GetComponent<AucationClassItem>().InitItem(item.Key, item.Value);
        }


        if (classMenuItemList.Count > 0)
        {
            ShowClassPage(classMenuItemList[0].GetComponent<AucationClassItem>().classType);  //将第一个类型菜单设置为打开
            ClickFirstClassMenuItem();
        }
    }

    public void ClickFirstClassMenuItem()
    {
        if(classMenuItemList.Count > 0)
        {
            classMenuItemList[0].GetComponent<AucationClassItem>().OnItemClick();
            for (int index = 0; index < classMenuItemList.Count; index++)
            {
                classMenuItemList[index].GetComponent<AucationClassItem>().InitMenuItemState(index == 0);
            }
        }
    }

    public bool IsHaveItemToSell(int type)
    {
        foreach (var item in snatchAllItemDic)
        {
            if (/*type == item.Value[0].ClassifyType &&*/ IsInSellTime(item.Value[0].Time))
            {
                return true;
            }
        }
        return false;
    }


    private List<GameObject> autactionItemList = new List<GameObject>();
    //通过ClassType刷新Item
    private int curClassType = -1;
    public void ShowClassPage(int classsType)
    {
        curClassType = classsType;
        //先设置Toggle状态
        for (int index = 0; index < classMenuItemList.Count; index++)
        {
            classMenuItemList[index].GetComponent<AucationClassItem>().InitMenuItemState(
                classMenuItemList[index].GetComponent<AucationClassItem>().classType == classsType ? true : false);
        }
    }

    public void OnAucationItemClick(int snatchTresureId)
    {
        bool hasItemOn = false;
        for (int index = 0; index < autactionItemList.Count; index++)
        {
            autactionItemList[index].gameObject.GetComponent<AucationItem>().InitItemState(
                autactionItemList[index].gameObject.GetComponent<AucationItem>().snatchTreasureId == snatchTresureId ? true : false);
        }
        for (int index = 0; index < autactionItemList.Count; index++)
        {
            if (autactionItemList[index].gameObject.GetComponent<AucationItem>().itemState)
            {
                hasItemOn = true;
            }
        }

        if (hasItemOn)
        {
            curSelectedSnatchId = snatchTresureId;  //记录当前点击的ID 
        } else
        {
            autactionItemList[0].gameObject.GetComponent<AucationItem>().InitItemState(true);
            curSelectedSnatchId = autactionItemList[0].gameObject.GetComponent<AucationItem>().snatchTreasureId;
        }
        selfTotalPutIntoCount = 1;  //当前数量重置为1
        InitItemInfoPanel();//根据当前的点击设置Item信息

        Tab_SnatchTreasure snatchTab = TableManager.GetSnatchTreasureByID(curSelectedSnatchId, 0);
        if (snatchTab == null)
        {
            return;
        }
        InitNumBoard();
        SetMoneyInfo();
    }

    public void InitNumBoard()
    {
        Tab_SnatchTreasure snatchTab = TableManager.GetSnatchTreasureByID(curSelectedSnatchId, 0);
        if (snatchTab == null)
        {
            return;
        }
        int totalCanBetNum = snatchTab.TotalBetMaxNum;
        int remainBetNum = 0;
        int canBetNum = 1;
        if (itemInfoDic.ContainsKey(curSelectedSnatchId))
        { 
            remainBetNum = (totalCanBetNum - itemInfoDic[curSelectedSnatchId].curHadPutIntoCount);
            if(remainBetNum > (snatchTab.SelfBetMaxNum - itemInfoDic[curSelectedSnatchId].selfHadPutIntoCount))
            {
                canBetNum = snatchTab.SelfBetMaxNum - itemInfoDic[curSelectedSnatchId].selfHadPutIntoCount;
            }else
            {
                canBetNum = remainBetNum;
            }
            //canBetNum = snatchTab.SelfBetMaxNum - itemInfoDic[curSelectedSnatchId].selfHadPutIntoCount - (totalCanBetNum - itemInfoDic[curSelectedSnatchId].curHadCompletedCount);
        }
        if (canBetNum <= 0)
            canBetNum = 0;
        numBoard.Init(1, 1, canBetNum);
    }


    public void InitItemInfoPanel()
    {
        if (curSelectedSnatchId == -1)
        {
            return;
        }
        Tab_SnatchTreasure snatchTreasureTab = TableManager.GetSnatchTreasureByID(curSelectedSnatchId, 0);
        if (snatchTreasureTab == null)
        {
            return;
        }
        Tab_CommonItem commonItem = TableManager.GetCommonItemByID(snatchTreasureTab.ItemId, 0);
        if (commonItem == null)
        {
            return;
        }

        //初始化信息
        if (!itemInfoDic.ContainsKey(curSelectedSnatchId))
        {
            return;
        }
        itemName.text = commonItem.Name + "X" + snatchTreasureTab.ItemNum.ToString();//当前物品名称
        if(snatchTreasureTab.ShopMoenyNum == -1)
        {
            shopPriceText.text = StrDictionary.GetClientDictionaryString("#{1954}");
        }
        else
        {
            string moneyDicId = "#{" + MoneytypeNamesTableId[snatchTreasureTab.ShopMoneyType] + "}";
            shopPriceText.text = StrDictionary.GetClientDictionaryString("#{1953}", snatchTreasureTab.ShopMoenyNum, StrDictionary.GetClientDictionaryString(moneyDicId));
        }
        
        if (itemInfoDic[curSelectedSnatchId].curHadCompletedCount > snatchTreasureTab.MaxGropOpenPerDay)
            onSellCount.text = StrDictionary.GetClientDictionaryString("#{42300}");
        else
            onSellCount.text = StrDictionary.GetClientDictionaryString("#{42301}", itemInfoDic[curSelectedSnatchId].curHadCompletedCount.ToString(), snatchTreasureTab.MaxGropOpenPerDay.ToString());  //当前正在出售第几组

        hadBeenPutIntoCount.text = StrDictionary.GetClientDictionaryString("#{42302}", itemInfoDic[curSelectedSnatchId].curHadPutIntoCount.ToString(), snatchTreasureTab.TotalBetMaxNum.ToString());  //当前组份已经被投入了多烧份
        hasPutIntoCount.text = StrDictionary.GetClientDictionaryString("#{42303}", itemInfoDic[curSelectedSnatchId].selfHadPutIntoCount.ToString(), snatchTreasureTab.SelfBetMaxNum.ToString());

        //设置当前的Slider
        int totalCanPutIntoCount = snatchTreasureTab.TotalBetMaxNum;  //当前分组可以被投入的最大份数
        curGroupSlider.value = (float)itemInfoDic[curSelectedSnatchId].curHadPutIntoCount / (float)totalCanPutIntoCount;
        sliderCountValue.text = itemInfoDic[curSelectedSnatchId].curHadPutIntoCount + "/" + totalCanPutIntoCount;
        //设置当前的金钱标志
    }

    public Dictionary<int, CurPageItemInfo> itemInfoDic = new Dictionary<int, CurPageItemInfo>();
    private int selfHadTotalPutIntoGroup = 0;//当前的全部投入量

    private int curSeverTime = 0;
    public void GetCurPageItemInfo(GC_SNATCH_RET_CUR_PAGE_ITEM packet)
    {
        curSeverTime = packet.Tm;
        selfHadTotalPutIntoGroup = packet.SelfFinishGroup;
        aucationSpace.text = selfHadTotalPutIntoGroup + "/" + allCanPutIntoGroypCount;
        for (int index = 0; index < packet.itemsCount; index++)
        {
            CurPageItemInfo itemInfo = new CurPageItemInfo(packet.GetItems(index).Index,
                packet.GetItems(index).CurBet,
                packet.GetItems(index).TotalBet,
                packet.GetItems(index).SelfBet);

            if (itemInfoDic.ContainsKey(packet.GetItems(index).Index))
            {
                itemInfoDic[packet.GetItems(index).Index] = itemInfo;
            } else
            {
                itemInfoDic.Add(packet.GetItems(index).Index, itemInfo);
            }
        }


        ClearAllPrefabAndList();

        //创建Item
        foreach (var item in snatchAllItemDic)
        {
            if (item.Value[0].ClassifyType == curClassType && IsInSellTime(item.Value[0].Time))
            {
                GameObject aucationItem = GameObject.Instantiate(aucationItemPrafab);

                aucationItem.transform.SetParent(aucationItemParent);
                aucationItem.transform.localPosition = Vector3.zero;
                aucationItem.transform.localRotation = Quaternion.Euler(Vector3.zero);
                aucationItem.transform.localScale = Vector3.one;

                //初始化
                aucationItem.GetComponent<AucationItem>().InitItem(item.Value[0]);
                autactionItemList.Add(aucationItem);
            }
        }



        foreach (var info in itemInfoDic)
        {
            for (int index = 0; index < autactionItemList.Count; index++)
            {
                if (info.Key == autactionItemList[index].GetComponent<AucationItem>().snatchTreasureId)
                {
                    autactionItemList[index].GetComponent<AucationItem>().InitItemInfo(info.Value);
                }
            }
        }

        //默认显示第一个Item的信息
        if (curSelectedSnatchId <= 0)
        {
            curSelectedSnatchId = autactionItemList[0].GetComponent<AucationItem>().snatchTreasureId;
        }
        OnAucationItemClick(curSelectedSnatchId);
    }

    private int needCostMoney = -1;
    private int curOwnMoney = -1;

    private int curNeedMoneyCount = 0;
    private MONEYTYPE curNeedMoneyType;
    public void SetMoneyInfo()
    {
        Tab_SnatchTreasure snatchTab = TableManager.GetSnatchTreasureByID(curSelectedSnatchId, 0);
        if (snatchTab == null)
        {
            return;
        }
        curNeedMoneyCount = numBoard.Value * snatchTab.MoneyNumPerBet;
        curNeedMoneyType = (MONEYTYPE)snatchTab.BetMoneyType;
        total.ShowCurrency((MONEYTYPE)snatchTab.BetMoneyType, numBoard.Value * snatchTab.MoneyNumPerBet);
        own.ShowOwnCurrency((MONEYTYPE)snatchTab.BetMoneyType);
    }

    //个人金钱变动,刷新当前的面板
    public void RefreshRemainMoney()
    {
        own.ShowOwnCurrency(curNeedMoneyType);
    }

    //投入
    public void OnPutIntoBtnClick()
    {
        if (!JudgeMoneyLogic.IsMoneyEnough(curNeedMoneyType, curNeedMoneyCount))
        {
            GUIData.AddNotifyData(String.Format(StrDictionary.GetClientDictionaryString("#{42304}")));
            return;
        }

        Tab_SnatchTreasure snatachTab = TableManager.GetSnatchTreasureByID(curSelectedSnatchId, 0);
        if (snatachTab == null)
        {
            return;
        }

        if (!itemInfoDic.ContainsKey(curSelectedSnatchId))
        {
            return;
        }

        int selfRemainCount = snatachTab.SelfBetMaxNum - itemInfoDic[curSelectedSnatchId].selfHadPutIntoCount;
        int totalRemainCount = snatachTab.TotalBetMaxNum - itemInfoDic[curSelectedSnatchId].curHadPutIntoCount;
        int remainCanPutintoCount = selfRemainCount < totalRemainCount ? selfRemainCount : totalRemainCount;

        if(remainCanPutintoCount <= 0)
        {
            if (remainCanPutintoCount == selfRemainCount)
            {
                GUIData.AddNotifyData(StrDictionary.GetClientDictionaryString("#{37005}"));
            }else
            {
                GUIData.AddNotifyData(StrDictionary.GetClientDictionaryString("#{37010}"));
            }
            return;
        }

        CG_SNATCH_BET_ITEM putInto = (CG_SNATCH_BET_ITEM)PacketDistributed.CreatePacket(MessageID.PACKET_CG_SNATCH_BET_ITEM);
        putInto.SetBetNum(numBoard.Value);
        putInto.SetItemIndexId(curSelectedSnatchId);
        putInto.SendPacket();

    }

    private int lastShareTime = 0;
    public void OnShareBtnClick()
    {
        if(lastShareTime > 0)
        {
            if(GlobalData.ServerAnsiTime - lastShareTime < 60)
            {
                GUIData.AddNotifyData(StrDictionary.GetClientDictionaryString("#{37103}"));
                return;
            } 
        }
        lastShareTime = GlobalData.ServerAnsiTime;
        CG_SHARE_SNATCH_ITEM packet = (CG_SHARE_SNATCH_ITEM)PacketDistributed.CreatePacket(MessageID.PACKET_CG_SHARE_SNATCH_ITEM);
        packet.SetItemIndex(curSelectedSnatchId);
        packet.SendPacket();
    }
     
    //是否在出售时间
    public bool IsInSellTime(int day)
    {
        DateTime curServerTime = GCGame.Utils.GetServerDateTime();
        if (day == (int)curServerTime.DayOfWeek)
        {
            return true;
        }
        return false;
    }

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

    //计算当前活动的剩余时间
    private int remainSeconds = 0;
    private bool isNeedCountRemainTime = false;
    public void CountRemainTime()
    {
        var activityBaseDic = TableManager.GetActivityBase().Values;
        foreach (var activity in activityBaseDic)
        {
            //当前活动为寻宝任务
            if (activity.ActivityServerType == (int)ActivityDataManager.Activity_Type.ACTIVITY_TYPE_GRAB_TREASURE)
            {
                //记录当前活动的结束时间
                int endTimeFromTab = int.Parse(activity.GetTimebyIndex(0).Split('|')[1]);

                DateTime curServerTime = GCGame.Utils.GetServerDateTime();

                int endHour = endTimeFromTab / 100;
                int endMinute = endTimeFromTab % 100;

                int curHour = curServerTime.Hour;
                int curMinute = curServerTime.Minute;
                int curSecond = curServerTime.Second;

                remainSeconds = (endHour * 3600 + endMinute * 60 - curHour * 3600 - curMinute * 60 - curSecond);  //剩余秒数

                if (remainSeconds > 0)
                {
                    isNeedCountRemainTime = true;
                }
                else
                {
                    isNeedCountRemainTime = false;
                }
                break;
            }
        }
    }

    int remainHour = 0;
    int remainMinute = 0;
    int remainSecond = 0;
    string r_Hour = "";
    string r_Minute = "";
    string r_Second = "";
    float countTime = 0.0f;
    void Update()
    {
        if (isNeedCountRemainTime)
        {
            countTime += Time.deltaTime;
            if (countTime >= 1.0f)
            {
                countTime = 1 - countTime;
                remainSeconds -= 1;
                if (remainSeconds > 0)
                {
                    if(putIntoBtn.interactable == false)
                    {
                        putIntoBtn.interactable = true;
                    }
                    remainHour = (remainSeconds / 3600);
                    remainMinute = (remainSeconds - remainHour * 3600) / 60;
                    remainSecond = (remainSeconds - remainHour * 3600 - remainMinute * 60);

                    if (remainHour < 10)
                    {
                        r_Hour = "0" + remainHour.ToString();
                    }
                    else
                    {
                        r_Hour = remainHour.ToString();
                    }

                    if (remainMinute < 10)
                    {
                        r_Minute = "0" + remainMinute.ToString();
                    }
                    else
                    {
                        r_Minute = remainMinute.ToString();
                    }

                    if (remainSecond < 10)
                    {
                        r_Second = "0" + remainSecond.ToString();
                    }
                    else
                    {
                        r_Second = remainSecond.ToString();
                    }

                    remainTime.text = r_Hour + ":" + r_Minute + ":" +r_Second;
                }else
                {
                    isNeedCountRemainTime = false;
                    remainTime.text = "0:00:00";
                    putIntoBtn.interactable = false;
                }

            }
        }
    }

}