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

public class AnalyzeGame : MonoBehaviour
{
    public const int AnalyzeContainerMax = 18;
    public UIContainerBase AnalyzeContainer;
    public UIContainerBase BackContainer;
    public GridLayoutGroup BackgridLayoutGroup;
    public Text IndexText;
    public GameObject ToggleObj;
    public Toggle[] toggles;
    public Text ToggleText;
    public Text Tip;
    public Transform EndPoint;


    private List<GameItem> AnalyzeList = new List<GameItem>(); //需要分解的物品列表
    private List<AnalyzeGameItem.BackItemInfo> BackList = new List<AnalyzeGameItem.BackItemInfo>();  //当前分解物品后可以获得的物品列表

    int IsDuty = 0;
    private void Update()
    {
        UpdateAnima();

        if (IsDuty>0)
        {
            IsDuty--;
            if(IsDuty<=0)
            {
                InitAnalyzeContainer();
                InitBackList();
            }
        }
    }

    private void InitBackList()
    {
        while (BackList.Count < 4)
        {
            AnalyzeGameItem.BackItemInfo backItemInfo = new AnalyzeGameItem.BackItemInfo();
            BackList.Add(backItemInfo);
        }
        if (BackList.Count == 4)
            BackContainer.transform.localPosition = new Vector3(-775,-292,0);
        else
            BackContainer.transform.localPosition = new Vector3(-790, -292, 0);
        BackgridLayoutGroup.constraintCount = BackList.Count;
        BackContainer.InitContentItem(BackList);
    }

    private void Start()
    {
        Tip.text = StrDictionary.GetClientDictionaryString("#{8904}");
    }

    public bool IsInAnalyze(GameItem gameItem)
    {
        return AnalyzeList.Contains(gameItem);
    }

    public void ClearList()
    {
        AnalyzeList.Clear();
        BackList.Clear();
    }

    private void OnEnable()
    {
        AnalyzeList.Clear();
        BackList.Clear();
        int index = 0;

        if (GameManager.gameManager.PlayerDataPool.MainPlayerBaseAttr.Level >= 70)
            index = 1;

        for (int i = 0; i < toggles.Length; i++)
        {
            if(index == i)
            {
                if(toggles[i].isOn)
                {
                    Toggle_Click(true);
                }
                else
                {
                    toggles[i].isOn = true;
                }
            }
            else
                toggles[i].isOn = false;
        }
        int Count = (AnalyzeList.Count / AnalyzeContainerMax) + 1;
        if (Count <= 0)
        {
            IndexText.text = "1/1";
            return;
        }
        _ShowIndex = 0;
        IsDuty = 4;
        IndexText.text = string.Format("{0}/{1}", _ShowIndex + 1, Count);
    }

    private void AddQualityItem(int quality)
    {
        AnalyzeList.Clear();
        BackList.Clear();
        for (int i = 0; i < GameManager.gameManager.PlayerDataPool.BackPack.Items.Count; i++)
        {
            GameItem gameItem = GameManager.gameManager.PlayerDataPool.BackPack.Items[i];
            if (gameItem.IsValid() && (int)gameItem.GetQuality() <= quality && gameItem.SellPrice() > 0 && gameItem.IsEquipMent())
            {
                AddAnalyzeGameItem(gameItem);
            }
        }

        int Count = (AnalyzeList.Count / AnalyzeContainerMax);
        if ((AnalyzeList.Count % AnalyzeContainerMax) > 0)
            Count++;
        if (Count <= 0)
            IndexText.text = "1/1";
        else
            IndexText.text = string.Format("{0}/{1}", _ShowIndex + 1, Count);
        IsDuty = 4;
        if (BackPackLogic.Instance() != null)
            BackPackLogic.Instance().OnToggleClick();
    }

    public void ShowToggle_Click()
    {
        if (ToggleObj.activeSelf)
            ToggleObj.SetActive(false);
        else
            ToggleObj.SetActive(true);
    }

    public void Toggle_Click(bool isOn)
    {
        if (isOn == false)
            return;
        int index = 0;
        for(;index<toggles.Length;index++)
        {
            if (toggles[index].isOn)
            {
                Text title = toggles[index].GetComponentInChildren<Text>();
                if (title != null)
                    ToggleText.text = title.text;
                break;
            }
        }
        if (index == 0)
            AddQualityItem((int)ItemQuality.QUALITY_BLUE);
        if (index == 1)
            AddQualityItem((int)ItemQuality.QUALITY_PURPLE);
        ToggleObj.SetActive(false);
    }

    private int _ShowIndex;
    public void ShowLast_Click()
    {
        int Count = (AnalyzeList.Count / AnalyzeContainerMax);
        if ((AnalyzeList.Count % AnalyzeContainerMax) > 0)
            Count++;
        if (_ShowIndex <= 0 || Count<=1)
            return;
        _ShowIndex--;
        InitAnalyzeContainer();
    }

    public void ShowNext_Click()
    {
        int Count = (AnalyzeList.Count / AnalyzeContainerMax);
        if ((AnalyzeList.Count % AnalyzeContainerMax) > 0)
            Count++;
        if (Count <= 1 || _ShowIndex+1>=Count)
            return;
        _ShowIndex++;
        InitAnalyzeContainer();
    }

    private void InitAnalyzeContainer()
    {
        List<AnalyzeGameItem.BackItemInfo> showLists = new List<AnalyzeGameItem.BackItemInfo>();
        int Index = _ShowIndex * AnalyzeContainerMax;
        if(Index >= AnalyzeList.Count)
        {
            _ShowIndex = 0;
            Index = 0;
        }
        int Count = Index + AnalyzeContainerMax;
        for (;Index< Count; Index++)
        {
            if (AnalyzeList.Count <= Index)
                break;
            AnalyzeGameItem.BackItemInfo backItemInfo = new AnalyzeGameItem.BackItemInfo();
            GameItem gameItem = AnalyzeList[Index];
            if(gameItem != null && gameItem.IsValid())
            {
                backItemInfo.ItemType = 3;
                backItemInfo.ItemSubType = gameItem.DataID;
                backItemInfo.ItemNum = gameItem.StackCount;
                backItemInfo.gameItem = gameItem;
                backItemInfo.IsFrenzy = gameItem.IsFrenzy;
            }
            showLists.Add(backItemInfo);
        }

        AnalyzeContainer.InitContentItem(showLists, AnalyzeItemClick);

        int Length = (AnalyzeList.Count / AnalyzeContainerMax);
        if ((AnalyzeList.Count % AnalyzeContainerMax) > 0)
            Length += 1;
        if (Length <= 0)
            IndexText.text = "1/1";
        else
            IndexText.text = string.Format("{0}/{1}", _ShowIndex + 1, Length);
    }

    public void AnalyzeItemClick(object Obj)
    {
        AnalyzeGameItem.BackItemInfo gameItem = Obj as AnalyzeGameItem.BackItemInfo;
        if (gameItem == null || gameItem.IsVaild()==false || gameItem.gameItem == null)
            return;
        DelAnalyzeGameItem(gameItem.gameItem);
        if (BackPackLogic.Instance() != null && BackPackLogic.Instance().gameObject.activeInHierarchy)
            BackPackLogic.Instance().UnSelectAnalyGameItem(gameItem.gameItem);
    }

    //删除一个分解列表中的物品
    public void DelAnalyzeGameItem(GameItem gameItem)
    {
        if (gameItem == null || gameItem.IsValid() == false)
            return;
        Tab_CommonItem commonItem = TableManager.GetCommonItemByID(gameItem.DataID, 0);
        if (commonItem == null)
            return;
        if (AnalyzeList.Contains(gameItem) == false)
            return;
        AnalyzeList.Remove(gameItem);
        if (gameItem.IsGem())
        {
            GemAnalyze(gameItem, true);
        }
        if (gameItem.IsEquipMent() || gameItem.IsAdvanceMent())
        {
            EquipItem(commonItem, gameItem,true);
        }
        if (commonItem.CanSell == 1 && commonItem.SellPrice > 0)
        {
            BackItem(commonItem.SellMoneyType, -1 * commonItem.SellPrice * (gameItem != null ? gameItem.StackCount : 1), 4);
        }

        Tab_ItemDecomposition tab_ItemDecomposition = TableManager.GetItemDecompositionByID(gameItem.DataID, 0);
        if (tab_ItemDecomposition != null)
        {
            for (int i = 0; i < tab_ItemDecomposition.getTypeCount(); i++)
            {
                int Type = tab_ItemDecomposition.GetTypebyIndex(i);
                int SubType = tab_ItemDecomposition.GetSubTypebyIndex(i);
                int Count = tab_ItemDecomposition.GetNumbyIndex(i);
                BackItem(SubType,-1 * Count * (gameItem != null ? gameItem.StackCount : 1), Type);
            }
        }

        IsDuty = 4;
    }

    public bool IsGameItemInAnalyList(GameItem gameItem)
    {
        return AnalyzeList.Count > 0 && AnalyzeList.Contains(gameItem);
    }

    //添加一个物品到分解列表
    public void AddAnalyzeGameItem(GameItem gameItem)
    {
        if (gameItem == null || gameItem.IsValid() == false)
            return;
        Tab_CommonItem commonItem = TableManager.GetCommonItemByID(gameItem.DataID, 0);
        if (commonItem == null || commonItem.CanSell != 1)
            return;
        if (AnalyzeList.Contains(gameItem))
            return;
        AnalyzeList.Add(gameItem);
        if(gameItem.IsGem())
        {
            GemAnalyze(gameItem,false);
        }
        if (gameItem.IsEquipMent() || gameItem.IsAdvanceMent())
        {
            EquipItem(commonItem, gameItem);
        }
        if (commonItem.CanSell == 1 && commonItem.SellPrice > 0)
        {
            BackItem(commonItem.SellMoneyType, commonItem.SellPrice * (gameItem != null ? gameItem.StackCount : 1), 4);
        }
        Tab_ItemDecomposition tab_ItemDecomposition = TableManager.GetItemDecompositionByID(gameItem.DataID, 0);
        if(tab_ItemDecomposition!=null)
        {
            for(int i=0;i<tab_ItemDecomposition.getTypeCount();i++)
            {
                int Type = tab_ItemDecomposition.GetTypebyIndex(i);
                int SubType = tab_ItemDecomposition.GetSubTypebyIndex(i);
                int Count = tab_ItemDecomposition.GetNumbyIndex(i);
                BackItem(SubType, Count * (gameItem != null ? gameItem.StackCount : 1), Type);
            }
        }

        IsDuty = 4;
    }

    //宝石特殊处理一下
    private void GemAnalyze(GameItem gameItem,bool IsRemove)
    {
        Tab_GemLvlUpConsume tab_GemLvlUpConsume = TableManager.GetGemLvlUpConsumeByID(gameItem.DataID, 0);
        if (tab_GemLvlUpConsume == null)
            return;
        if (gameItem.DataID == tab_GemLvlUpConsume.ConsumeSubType)
            return;
        BackItem(tab_GemLvlUpConsume.ConsumeSubType, (IsRemove ? -1 : 1) * tab_GemLvlUpConsume.GemMaterialCnt * (gameItem != null ? gameItem.StackCount : 1), 3);
    }

    private void BackItem(int Id, int Num,int Type)
    {
        if (Num == 0)
            return;
        AnalyzeGameItem.BackItemInfo UnVaildItem = null;
        for (int i = 0; i < BackList.Count; i++)
        {
            if (BackList[i].ItemType == Type && BackList[i].ItemSubType == Id)
            {
                BackList[i].ItemNum += Num;
                if (BackList[i].ItemNum <= 0)
                    BackList.Remove(BackList[i]);
                return;
            }
            if (UnVaildItem == null && BackList[i].IsVaild() == false)
                UnVaildItem = BackList[i];
        }
        if (Num < 0 && UnVaildItem == null)
            return;
        AnalyzeGameItem.BackItemInfo backItemInfo = (UnVaildItem != null ? UnVaildItem : new AnalyzeGameItem.BackItemInfo());
        if(UnVaildItem==null)
            BackList.Add(backItemInfo);
        backItemInfo.ItemType = Type;
        backItemInfo.ItemSubType = Id;
        backItemInfo.ItemNum = Num;
    }

    private void EquipItem(Tab_CommonItem commonItem,GameItem gameItem,bool IsRemove = false)
    {
        //是否可拆解
        Dictionary<int, Tab_EquipDecomposition> tab_EquipDecompositions = TableManager.GetEquipDecomposition();
        foreach (var tab in tab_EquipDecompositions)
        {
            int EquipType = 1;
            if (gameItem.IsAdvanceMent())
            {
                EquipType = 2;
                if (commonItem.MinLevelRequire == tab.Value.EquipLevel && commonItem.Quality == tab.Value.Quality && EquipType == tab.Value.EquipType)
                {
                    BackItem(tab.Value.ItemID, (IsRemove ? -1 : 1) * tab.Value.ItemNum * (gameItem != null ? gameItem.StackCount : 1), 3);
                    break;
                }
            }
            else if (gameItem.EquipUseLevel <= tab.Value.EquipLevel && commonItem.Quality == tab.Value.Quality && EquipType == tab.Value.EquipType)
            {
                BackItem(tab.Value.ItemID, (IsRemove ? -1 : 1) * tab.Value.ItemNum * (gameItem != null ? gameItem.StackCount : 1), 3);
                break;
            }
        }
        if(gameItem.IsEquipMent())
        {
            Dictionary<int, Tab_EquipPropBarBaptizeConsume> equipPropBarBaptizeConsumes = TableManager.GetEquipPropBarBaptizeConsume();
            foreach (var tab in equipPropBarBaptizeConsumes)
            {
                if(gameItem.EquipUseLevel <= tab.Value.MaxLevel && commonItem.Quality == tab.Value.Quality)
                {
                    if (tab.Value.ConsumeNum <= 0)
                        continue;
                    if(tab.Value.ConsumeType == 3)
                    {
                        BackItem(tab.Value.ConsumeSubType, (IsRemove ? -1 : 1) * (int)(gameItem.XilianPoint * 0.8f * tab.Value.ConsumeNum * (gameItem != null ? gameItem.StackCount : 1)), 3);
                    }
                    if(tab.Value.ConsumeType == 4)
                    {
                        BackItem(tab.Value.ConsumeSubType, (IsRemove ? -1 : 1) * tab.Value.ConsumeNum * (gameItem != null ? gameItem.StackCount : 1), 4);
                    }
                    break;
                }
            }
        }
        if(gameItem.IsFrenzy)
        {
            Dictionary<int, Tab_EquipFrenzy> equipFrenzy = TableManager.GetEquipFrenzy();
            foreach (var tab in equipFrenzy)
            {
                if (gameItem.EquipUseLevel >= tab.Value.EquipLevelMin && gameItem.EquipUseLevel <= tab.Value.EquipLevelMax && commonItem.Quality == tab.Value.Quality)
                {
                    if (tab.Value.ReturnNum <= 0)
                        continue;
                    if (tab.Value.ReturnType == 3)
                    {
                        BackItem(tab.Value.ReturnSubType, tab.Value.ReturnNum * (gameItem != null ? gameItem.StackCount : 1), 3);
                    }
                    if (tab.Value.ReturnType == 4)
                    {
                        BackItem(tab.Value.ReturnSubType, (IsRemove ? -1 : 1) * tab.Value.ReturnNum * (gameItem != null ? gameItem.StackCount : 1), 4);
                    }
                    break;
                }
            }
        }
    }

    public void AnalyzeSuccess()
    {
        Hashtable table = new Hashtable();
        table["Move"] = 1;
        AnalyzeContainer.RefreshItems(table);
        IndexText.text = "1/1";

        BackList.Clear();
        InitBackList();
        AnalyzeList.Clear();
        InitAnalyzeContainer();
    }

    // 回收中的珍贵物品名字排序规则
    // 优先排序装备,再到品质
    // 如果是同部位同品质的装备,战斗力高的排前面
    private int PreciousItemSort(GameItem l, GameItem r)
    {
        if (l.IsEquipMent() && !r.IsEquipMent())
        {
            return -1;
        }
        else if (!l.IsEquipMent() && r.IsEquipMent())
        {
            return 1;
        }

        int tempResult = ((int)l.GetQuality()).CompareTo((int)r.GetQuality());
        if (l.IsEquipMent())
        {
            if (tempResult == 0 && l.GetEquipSlotIndex() == r.GetEquipSlotIndex())
            {
                return r.CombatValue.CompareTo(l.CombatValue);
            }
        }

        return tempResult;
    }

    public void AnalyzeOK_Click()
    {
        int index = 0;
        for (; index < toggles.Length; index++)
        {
            if (toggles[index].isOn)
            {
                break;
            }
        }
        int Quality = (int)ItemQuality.QUALITY_BLUE;
        if (index == 0)
            Quality = (int)ItemQuality.QUALITY_BLUE;
        if (index == 1)
            Quality = (int)ItemQuality.QUALITY_PURPLE;


        List<GameItem> preciousItem = new List<GameItem>();     // 贵重物品
        foreach (var sellItem in AnalyzeList)
        {
            if (((int)sellItem.GetQuality() > Quality || sellItem.EnchanceLevel > 0 || sellItem.IsEquipGem()))
            {
                preciousItem.Add(sellItem);
            }
        }
        SysShopController.m_TipSelDataID = -1;
        // 将品质大于 3 或者 经过强化的任何装备 或者 镶嵌宝石的装备,最多显示 5 个贵重物品
        if (preciousItem.Count > 0)
        {
            preciousItem.Sort(PreciousItemSort);

            // 可取消框
            string itemDesc = "";
            string tempStr = "";
            for (int i = 0; i < preciousItem.Count && i < 5; ++i)
            {
                if (preciousItem[i].IsEquipGem())
                {
                    tempStr = preciousItem[i].GetEquipName(false, StrDictionary.GetClientDictionaryString("#{6755}"));
                }
                else
                {
                    tempStr = preciousItem[i].GetEquipName();
                }

                if (i == 0)
                {
                    itemDesc += tempStr;
                }
                else
                {
                    itemDesc += "、" + tempStr;
                }
            }

            string tip = StrDictionary.GetClientDictionaryString("#{6713}", itemDesc, preciousItem.Count);
            MessageBoxLogic.OpenOKCancelBox(tip, null, delegate ()
            {
                SysShopController.m_TipSelDataID = -1;
                SysShopController.SellItem((int)GameItemContainer.Type.TYPE_BACKPACK, AnalyzeList);
            });
        }
        else
        {
            SysShopController.SellItem((int)GameItemContainer.Type.TYPE_BACKPACK, AnalyzeList);
        }
    }


    private const float MOVETIME = 0.6f;
    Dictionary<Image, KeyValuePair<float,Vector3>> _RunningImages = new Dictionary<Image, KeyValuePair<float, Vector3>>();
    List<Image> AnimationImages = new List<Image>();
    //分解动画处理
    public void AddAnimationItem(Image image)
    {
        Image imageRun = null;
        if (AnimationImages.Count>0)
        {
            imageRun = AnimationImages[0];
            imageRun.transform.position = image.transform.position;
            AnimationImages.Remove(imageRun);
        }
        else
        {
            imageRun = GameObject.Instantiate<Image>(image, EndPoint, true);
        }
        if (imageRun == null)
            return;
        imageRun.gameObject.SetActive(true);
        imageRun.transform.localScale = new Vector3(1.3f, 1.3f, 1.3f);
        _RunningImages[imageRun] = new KeyValuePair<float, Vector3>(Time.realtimeSinceStartup, imageRun.transform.localPosition);
    }

    private void UpdateAnima()
    {
        bool DicNeedDel = false;
        foreach(var Run in _RunningImages)
        {
            if (Run.Key == null)
                continue;
            if((Time.realtimeSinceStartup - Run.Value.Key) >= MOVETIME)
            {
                Run.Key.gameObject.SetActive(false);
                AnimationImages.Add(Run.Key);
                DicNeedDel = true;
            }
            else
            {
                Vector3 newPos = Vector3.Lerp(Run.Value.Value, Vector3.zero, (Time.realtimeSinceStartup - Run.Value.Key) / MOVETIME);
                newPos.z = 0;
                Run.Key.gameObject.transform.localPosition = newPos;
                float scale = Mathf.Lerp(1.3f, 0.1f, (Time.realtimeSinceStartup - Run.Value.Key) / MOVETIME);
                Run.Key.gameObject.transform.localScale = Vector3.one * scale;
            }
        }
        if(DicNeedDel)
        {
            for (int i = 0; i < AnimationImages.Count; i++)
            {
                if(_RunningImages.ContainsKey(AnimationImages[i]))
                    _RunningImages.Remove(AnimationImages[i]);
            }
        }
    }

}