using System;
using LitJson;
using System.Collections.Generic;
using UnityEngine;
/// 
/// 宝箱功能 + 获取奖励界面
/// 
public class BoxGetItemModel : GameSystemManager
{
    List commonShowAwardEvents = new List();    //获取奖励的展示事件
    public override void Init()
    {
        var config = FuncConfigConfig.Get("CommonShowAwards");
        commonShowAwardEvents = JsonMapper.ToObject>(config.Numerical1);
    }
    // void OnBeforePlayerDataInitialize()
    // {
    //     getItems = null;
    //     getCoinsType = 0;
    //     getCoinsCnt = 0;
    // }
    #region 处理服务器数据
    // public BoxGetItemInfo[] getItems { get; private set; }
    // public int getCoinsType { get; private set; }
    // public long getCoinsCnt { get; private set; }
    // public event Action RefreshGetItemAct;
    // public void SetGetBoxItemInfo(HA810_tagMCNotifyUseItemGetItem boxItemInfo)
    // {
    //     getItems = JsonMapper.ToObject(boxItemInfo.GetItemData);
    //     getCoinsType = boxItemInfo.MoneyType;
    //     getCoinsCnt = boxItemInfo.MoneyCount;
    //     if (!NewBieCenter.Instance.inGuiding)
    //     {
    //         List-  items = new List
- ();
    //         for (int i = 0; i < getItems.Length; i++)
    //         {
    //             BoxGetItemInfo info = getItems[i];
    //             Dictionary> useDataDic = ConfigParse.Analysis(info.UserData);
    //             if (useDataDic != null && useDataDic.TryGetValue((int)ItemUseDataKey.itemCount, out List list) && list != null && list.Count > 0)
    //             {
    //                 int count = list[0];
    //                 items.Add(new Item(info.ItemID, count));
    //             }
    //             else
    //             {
    //                 items.Add(new Item(info.ItemID, info.Count));
    //             }
    //         }
    //         ItemLogicUtility.Instance.ShowGetItem(items, seconds: 0);
    //     }
    //     if (RefreshGetItemAct != null)
    //     {
    //         RefreshGetItemAct((int)boxItemInfo.UseItemID, (int)boxItemInfo.UseCount, getItems);
    //     }
    // }
    //获得奖励展示
    public void ReceiveAwardNotify(HA801_tagMCGiveAwardInfo netPack)
    {
        var eventName = UIHelper.ServerStringTrim(netPack.EventName);
        // 仙盟攻城战
        // if (eventName == "FamilyGCZSQGrid" || eventName == "FamilyGCZSQPass" || eventName == "FamilyGCZSQPassAll" ||
        //     eventName == "FamilyGCZContiribution" || eventName == "FamilyGCZAtk")
        // {
        //     ModelCenter.Instance.GetModel()?.OnUpdateAwardInfoAction(netPack);
        //     return;
        // }
        // if (!commonShowAwardEvents.Contains(eventName))
        //     return;
        if (string.IsNullOrEmpty(eventName))
        {
            Debug.Log("获得物品展示 无事件名");
            return;
        }
        List
-  showItems = new List
- ();
        if (netPack.Exp != 0 || netPack.ExpPoint != 0)
        {
            long expValue = netPack.Exp + netPack.ExpPoint * Constants.ExpPointValue;
            showItems.Add(new Item(GeneralDefine.expDisplayId, expValue));
        }
        if (netPack.MoneyList.Length != 0)
        {
            for (int i = 0; i < netPack.MoneyLen; i++)
            {
                var moneyType = netPack.MoneyList[i].MoneyType;
                if (GeneralDefine.MoneyDisplayModel.ContainsKey(moneyType) && netPack.MoneyList[i].MoneyValue != 0)
                {
                    showItems.Add(new Item(GeneralDefine.MoneyDisplayModel[moneyType], netPack.MoneyList[i].MoneyValue));
                }
            }
        }
        if (netPack.ItemList.Length != 0)
        {
            for (int i = 0; i < netPack.ItemLen; i++)
            {
                showItems.Add(new Item((int)netPack.ItemList[i].ItemID,
                netPack.ItemList[i].Count + netPack.ItemList[i].CountEx * Constants.ExpPointValue,
                netPack.ItemList[i].IsBind));
            }
        }
        string info = string.Empty;
        if (LanguageConfig.HasKey("commonShowAwardEvents_" + eventName))
            info = Language.Get("commonShowAwardEvents_" + eventName);
        if (showItems.Count == 0)
            return;
        ItemLogicUtility.Instance.ShowGetItem(showItems, eventName);
    }
    // public int GetUseCntByID(int itemId)
    // {
    //     return PackManager.Instance.GetItemUsedTimesToday(itemId);
    // }
    #endregion
    // #region 消耗材料货币开启的宝箱
    // public void SetModel(string guid, int itemId)
    // {
    //     ChestsConfig chestsConfig = ChestsConfig.Get(itemId);
    //     this.guid = guid;
    //     this.itemId = itemId;
    //     if (guid == "" || chestsConfig == null) return;
    //     ItemConfig boxConfig = ItemConfig.Get(itemId);
    //     if (PlayerDatas.Instance.baseData.LV < boxConfig.UseLV)
    //     {
    //         ServerTipDetails.DisplayNormalTip(Language.Get("MakeUseItem101", boxConfig.UseLV));
    //         return;
    //     }
    //     CheckOpenBoxCondi(guid, itemId);
    // }
    // public void CheckOpenBoxCondi(string guid, int itemId, int useCnt = 1)
    // {
    //     ChestsConfig chestsConfig = ChestsConfig.Get(itemId);
    //     if (chestsConfig == null) return;
    //     ItemConfig boxConfig = ItemConfig.Get(itemId);
    //     if (chestsConfig.ExpendItemID != 0)
    //     {
    //         ItemConfig itemConfig = ItemConfig.Get(chestsConfig.ExpendItemID);
    //         ConfirmCancel.ShowPopConfirm(Language.Get("Mail101"), Language.Get("OpenBoxTool", itemConfig.ItemName), (bool isOk) =>
    //         {
    //             if (isOk)
    //             {
    //                 if (!IsEnoughTools(chestsConfig.ExpendItemID, chestsConfig.ExpendCount * useCnt))
    //                 {
    //                     SysNotifyMgr.Instance.ShowTip("OpenBoxToolNoEnough", itemConfig.ItemName);
    //                     return;
    //                 }
    //                 else
    //                 {
    //                     CheckOpenMoney(chestsConfig, boxConfig, useCnt);
    //                 }
    //             }
    //         });
    //     }
    //     else
    //     {
    //         CheckOpenMoney(chestsConfig, boxConfig, useCnt);
    //     }
    // }
    // public void CheckOpenMoney(ChestsConfig chestsConfig, ItemConfig boxConfig, int useCnt)
    // {
    //     if (!IsEnoughMoney(chestsConfig.OpenMoney * useCnt))
    //     {
    //         SysNotifyMgr.Instance.ShowTip("BoxOpenCostMoney", 1);
    //         return;
    //     }
    //     else
    //     {
    //         if (chestsConfig.OpenMoney > 0)
    //         {
    //             ConfirmCancel.ShowPopConfirm(Language.Get("Mail101"), Language.Get("OpenBoxGold", chestsConfig.OpenMoney * useCnt), (bool isOk) =>
    //                 {
    //                     if (isOk)
    //                     {
    //                         CheckOtherCondi(chestsConfig, boxConfig, useCnt);
    //                     }
    //                 });
    //         }
    //         else
    //         {
    //             CheckOtherCondi(chestsConfig, boxConfig, useCnt);
    //         }
    //     }
    // }
    // public void CheckOtherCondi(ChestsConfig chestsConfig, ItemConfig boxConfig, int useCnt)
    // {
    //     if (boxConfig.MaxSkillCnt > 0 && GetUseCntByID(itemId) >= boxConfig.MaxSkillCnt)
    //     {
    //         SysNotifyMgr.Instance.ShowTip("UseCntLimit");
    //         return;
    //     }
    //     if (IsSelectItemByID(itemId))
    //     {
    //         UIManager.Instance.OpenWindow();
    //         return;
    //     }
    //     ItemLogicUtility.Instance.UseItem(guid, useCnt);
    // }
    // public bool CheckOpenBoxCondition(int itemId, out bool isBox)
    // {
    //     isBox = false;
    //     ChestsConfig chestsConfig = ChestsConfig.Get(itemId);
    //     if (chestsConfig == null) return false;
    //     isBox = true;
    //     bool isCanOpen = true;
    //     ItemConfig boxConfig = ItemConfig.Get(itemId);
    //     if (PlayerDatas.Instance.baseData.LV < boxConfig.UseLV)
    //     {
    //         isCanOpen = false;
    //         return isCanOpen;
    //     }
    //     if (chestsConfig.ExpendItemID != 0)
    //     {
    //         ItemConfig itemConfig = ItemConfig.Get(chestsConfig.ExpendItemID);
    //         if (!IsEnoughTools(chestsConfig.ExpendItemID, chestsConfig.ExpendCount))
    //         {
    //             isCanOpen = false;
    //             return isCanOpen;
    //         }
    //     }
    //     if (!IsEnoughMoney(chestsConfig.OpenMoney))
    //     {
    //         isCanOpen = false;
    //         return isCanOpen;
    //     }
    //     if (boxConfig.MaxSkillCnt > 0 && GetUseCntByID(itemId) >= boxConfig.MaxSkillCnt)
    //     {
    //         isCanOpen = false;
    //         return isCanOpen;
    //     }
    //     return isCanOpen;
    // }
    // private bool IsEnoughMoney(int moneyCnt)
    // {
    //     ulong haveMoney = UIHelper.GetMoneyCnt(1);
    //     if (haveMoney >= (ulong)moneyCnt)
    //     {
    //         return true;
    //     }
    //     else
    //     {
    //         return false;
    //     }
    // }
    // private bool IsEnoughTools(int itemId, int toolCnt)
    // {
    //     int count = PackManager.Instance.GetItemCountByID(PackType.Item, itemId);
    //     if (count >= toolCnt)
    //     {
    //         return true;
    //     }
    //     else
    //     {
    //         return false;
    //     }
    // }
    // #endregion
    //宝箱预览物品 (随机获得)
    public List
-  GetBoxItems(int boxID)
    {
        List
-  itemIDs = new List
- ();
        if (ChestsAwardConfig.GetBoxType(boxID) == 0)
        {
            return itemIDs;
        }
        var config = ChestsAwardConfig.GetChestsAwardByID(boxID);
        if (!string.IsNullOrEmpty(config.SelectList))
        {
            var selectlistDict = ConfigParse.GetDic(config.SelectList);
            foreach (var item in selectlistDict)
            {
                itemIDs.Add(new Item(item.Key, item.Value));
            }
        }
        if (!string.IsNullOrEmpty(config.FixedItem))
        {
            var itemListDict = ConfigParse.GetDic(config.FixedItem);
            foreach (var item in itemListDict)
            {
                itemIDs.Add(new Item(item.Key, item.Value));
            }
        }
        if (!string.IsNullOrEmpty(config.Probability1))
        {
            var arr = JsonMapper.ToObject(config.Probability1);
            for (int i = 0; i < arr.Count; i++)
            {
                itemIDs.Add(new Item(int.Parse(arr[i][1][0].ToString()), long.Parse(arr[i][1][1].ToString())));
            }
        }
        if (!string.IsNullOrEmpty(config.Probability2))
        {
            var arr = JsonMapper.ToObject(config.Probability2);
            for (int i = 0; i < arr.Count; i++)
            {
                itemIDs.Add(new Item(int.Parse(arr[i][1][0].ToString()), long.Parse(arr[i][1][1].ToString())));
            }
        }
        return itemIDs;
    }
    #region 自选物品宝箱
    //<物品ID,数量>  用户选中物品字典
    public Dictionary userChooseItemDict = new Dictionary();
    public Action countChangeAction;    //数量发生变化
    public bool IsSelectItemByID(int boxId)
    {
        ChestsAwardConfig awardConfig = ChestsAwardConfig.GetChestsAwardByID(boxId);
        if (string.IsNullOrEmpty(awardConfig.SelectList))
        {
            return false;
        }
        return true;
    }
    public int[][] GetSelectItemsByID(int boxId)
    {
        ChestsAwardConfig awardConfig = ChestsAwardConfig.GetChestsAwardByID(boxId);
        if (string.IsNullOrEmpty(awardConfig.SelectList))
        {
            return null;
        }
        var arr = ConfigParse.GetArray2(awardConfig.SelectList);
        Array.Sort(arr, SortShowItem);
        return arr;
    }
    int SortShowItem(int[] a, int[] b)
    {
        var itemConfig1 = ItemConfig.Get(a[0]);
        var itemConfig2 = ItemConfig.Get(b[0]);
        int quality1 = itemConfig1.ItemColor;
        int quality2 = itemConfig2.ItemColor;
        //品质高的排在前面
        if (quality1 != quality2)
            return quality2.CompareTo(quality1);
        return itemConfig1.ID - itemConfig2.ID;
    }
    /// 
    /// 选择自选物品数量
    /// 
    /// 被选择物品的ID
    /// 宝箱的GUID
    /// 
    /// 加减数量
    public void IncreaseUserChooseItemCount(int itemId, string guid, int extra, int changeCnt)
    {
        if (userChooseItemDict.ContainsKey(itemId))
        {
            userChooseItemDict[itemId].guid = guid;
            userChooseItemDict[itemId].useCnt = userChooseItemDict[itemId].useCnt + changeCnt;
            userChooseItemDict[itemId].extra = extra;
        }
        else
        {
            userChooseItemDict[itemId] = new ChooseItems() { guid = guid, useCnt = 1, extra = extra };
        }
        countChangeAction?.Invoke();
    }
    //当前选择材料总数量
    public int GetNowChooseItemCount()
    {
        int total = 0;
        if (userChooseItemDict == null && userChooseItemDict.Count == 0)
            return 0;
        List list = new List(userChooseItemDict.Keys);
        for (int i = 0; i < list.Count; i++)
            total += userChooseItemDict[list[i]].useCnt;
        return total;
    }
    public bool TrySendUse()
    {
        CA323_tagCMUseItems.tagCMUseItemsSelect[] chooseItemList = GetSendList(userChooseItemDict, out List resultChooseItemDict, out string guid, out int count);
        //一个材料也没选
        if (chooseItemList.Length < 1)
        {
            SysNotifyMgr.Instance.ShowTip("ChooseItems01");
            return false;
        }
        var itemModel = PackManager.Instance.GetItemByGuid(guid);
        if (itemModel == null)
            return false;
        for (int i = 0; i < resultChooseItemDict.Count; i++)
        {
            var item = PackManager.Instance.GetItemByGuid(resultChooseItemDict[i].guid);
            if (item == null)
                return false;
            var error = 0;
            if (!ItemLogicUtility.Instance.CanUseItem(resultChooseItemDict[i].guid, resultChooseItemDict[i].useCnt, out error))
            {
                switch (error)
                {
                    case 1:
                        SysNotifyMgr.Instance.ShowTip("EverydayUseLimit");
                        break;
                    case 2:
                        SysNotifyMgr.Instance.ShowTip("UseCntLimit");
                        break;
                    case 3:
                        SysNotifyMgr.Instance.ShowTip("GeRen_chenxin_749572");
                        break;
                    default:
                        break;
                }
                return false;
            }
        }
        var useItem = new CA323_tagCMUseItems();
        useItem.ItemIndex = (byte)itemModel.gridIndex;
        useItem.UseCnt = (ushort)count;
        useItem.ExData = (uint)0;
        useItem.SelectCount = (byte)chooseItemList.Length;
        useItem.SelectList = chooseItemList;
        GameNetSystem.Instance.SendInfo(useItem); 
        return true;
    }
  
    CA323_tagCMUseItems.tagCMUseItemsSelect[] GetSendList(Dictionary userChooseItemDict, out List resultChooseItemDict, out string guid, out int count)
    {
        guid = string.Empty;
        count = 0;
        resultChooseItemDict = new List { };
        List list = new List(userChooseItemDict.Keys);
        List result = new List();
        for (int i = 0; i < list.Count; i++)
        {
            int itemId = list[i];
            ChooseItems chooseItems = userChooseItemDict[itemId];
            if (!ItemConfig.HasKey(itemId))
                continue;
            if (chooseItems == null || chooseItems.useCnt <= 0)
                continue;
            count += chooseItems.useCnt;
            result.Add(chooseItems);
        }
        resultChooseItemDict = result;
        if (!result.IsNullOrEmpty())
            guid = result[0].guid;
        List tagCMUseItemsSelects = new List();
        for (int i = 0; i < result.Count; i++)
        {
            CA323_tagCMUseItems.tagCMUseItemsSelect temp = new CA323_tagCMUseItems.tagCMUseItemsSelect();
            temp.SelectID = (uint)result[i].extra;
            temp.SelectCnt = (ushort)result[i].useCnt;
            tagCMUseItemsSelects.Add(temp);
        }
        return tagCMUseItemsSelects.ToArray();
    }
    public void ClearAll()
    {
        userChooseItemDict.Clear();
    }
    #endregion
    
}
public class BoxGetItemInfo
{
    public int ItemID;
    public int Count;
    public int IsBind;
    public int IsSuite;
    public string UserData;
}
public class ChooseItems
{
    public string guid;
    public int useCnt;
    public int extra;
}