using FairyGUI;
using System;
using System.Collections;
using System.Collections.Generic;
using UI.CommonGame;
using UI.FieldGuide;
using UnityEngine;
namespace GFGGame
{
    /// 
    /// 服装图鉴界面
    /// 
    public class DressUpGuideView : BaseWindow
    {
        private UI_DressUpGuideUI _ui;
        private List _itemIdList;
        private bool _startInAnim;
        private string _filterStr;
        // 上次点击单选按钮的index
        private struct LastClickIndex
        {
            public int typeIndex;   // 菜单类型:一级/二级
            public int index;
        }
        private LastClickIndex _lastClickIndex;
        private int[] _currentList2;
        public override void Dispose()
        {
            if (_ui != null)
            {
                _ui.Dispose();
                _ui = null;
            }
            base.Dispose();
        }
        protected override void OnInit()
        {
            base.OnInit();
            packageName = UI_DressUpGuideUI.PACKAGE_NAME;
            _ui = UI_DressUpGuideUI.Create();
            this.viewCom = _ui.target;
            isfullScreen = true;
            isReturnView = true;
            _ui.m_loaBg.url = ResPathUtil.GetBgImgPath("quanping_moren_bg");
            _itemIdList = new List();
            _startInAnim = true;
            _ui.m_btnSearch.onClick.Add(OnClickBtnSearch);
            _ui.m_btnBack.onClick.Add(OnClickBtnBack);
            _ui.m_listType1.onClickItem.Add(OnClickListType1Item);
            _ui.m_listType2.onClickItem.Add(OnClickListType2Item);
            _ui.m_listDressUp.itemRenderer = RenderListDressUpItem;
            _ui.m_listDressUp.onClickItem.Add(OnClickListDressUpItem);
            _ui.m_listDressUp.SetVirtual();
            _ui.m_btnAccessories.onClick.Add(OnClickBtnAllAccessories);
            DressUpMenuItemDataManager.isLoading = true;
        }
        protected override void AddEventListener()
        {
            base.AddEventListener();
            EventAgent.AddEventListener(ConstMessage.DRESS_SEARCH, FilterItems);
            EventAgent.AddEventListener(ConstMessage.DRESS_FILTER, FilterItems);
            EventAgent.AddEventListener(ConstMessage.DRESS_FILTER_RESET, ResetFilterStr);
            EventAgent.AddEventListener(ConstMessage.DRESS_PART_LOAD_FINISHED, LoadFinished);
        }
        protected override void RemoveEventListener()
        {
            base.RemoveEventListener();
            EventAgent.RemoveEventListener(ConstMessage.DRESS_SEARCH, FilterItems);
            EventAgent.RemoveEventListener(ConstMessage.DRESS_FILTER, FilterItems);
            EventAgent.RemoveEventListener(ConstMessage.DRESS_FILTER_RESET, ResetFilterStr);
            EventAgent.RemoveEventListener(ConstMessage.DRESS_PART_LOAD_FINISHED, LoadFinished);
        }
        protected override void OnShown()
        {
            base.OnShown();
            _ui.m_listType1.selectedIndex = 0;
            _ui.m_c1.selectedIndex = 0;
            _ui.m_listType1.scrollPane.SetPercX(0, false);
            if (DressUpMenuItemDataManager.isLoading)
            {
                ViewManager.Show();
                LoadingView.Instance.SetDesc("正在加载服装数据...");
                DressUpConfigUtil.LoadCount = 0;
                Timers.inst.StartCoroutine(UpdateLoadProgress());
                DressUpMenuItemDataManager.GetAllDressUpGuideIdListBySubTypeAsync();
            }
            else
            {
                UpdateItemIdListByType1(0);
                UpdateItemListUI();
            }
            if (_startInAnim)
            {
                _startInAnim = false;
                _ui.m_In.Play();
            }
        }
        protected override void OnHide()
        {
            base.OnHide();
            _itemIdList.Clear();
            _currentList2 = null;
            _filterStr = "";
            DressUpMenuItemDataManager.Clear();
            // 清空服装过滤界面选择
            EventAgent.DispatchEvent(ConstMessage.DRESS_FILTER_RESET_ALL);
        }
        /// 
        /// 一级菜单的点击
        /// 
        /// 
        /// 
        private void OnClickListType1Item(EventContext context)
        {
            GObject gObject = context.data as GObject;
            int index = _ui.m_listType1.GetChildIndex(gObject);
            if (_lastClickIndex.typeIndex == 1 && _lastClickIndex.index == index)
            {
                return;
            }
            UpdateItemIdListByType1(index);
            UpdateItemListUI();
            _ui.m_Refresh.Play();
            UI_Button21 button = UI_Button21.Proxy(gObject);
            button.m_fadeIn.Play();
            UI_Button21.ProxyEnd();
        }
        private IEnumerator UpdateLoadProgress()
        {
            while (DressUpMenuItemDataManager.isLoading)
            {
                int sum = GlobalCfgArray.globalCfg.ClothingPartsCount;
                LoadingView.Instance.SetProgress(FieldGuideView.ProgressCalculate(DressUpConfigUtil.LoadCount, sum));
                yield return new WaitForEndOfFrame();
            }
            LoadingView.Instance.SetProgress(100, () =>
            {
                ViewManager.Hide();
            }
            );
            
        }
        private void RenderListDressUpItem(int index, GObject item)
        {
            if(index >= _itemIdList.Count)
            {
                return;
            }
            UI_ListDressUpPartsItem listItem = UI_ListDressUpPartsItem.Proxy(item);
            ItemCfg itemCfg = ItemCfgArray.Instance.GetCfg(_itemIdList[index]);
            listItem.m_icon.url = ResPathUtil.GetIconPath(itemCfg.res, "png");
            listItem.m_txtTitle.text = itemCfg.name;
            listItem.m_ScoreType.url = ResPathUtil.GetCommonGameResPath("kp_sx_" + itemCfg.mainScore);
            listItem.m_unlockMask.visible = !DressUpMenuItemDataManager.CheckHasItem(itemCfg.id);
            RarityIconController.UpdateRarityIcon(listItem.m_rarity, _itemIdList[index], false);
            listItem.target.data = _itemIdList[index];
            UI_ListDressUpPartsItem.ProxyEnd();
        }
        private void OnClickListDressUpItem(EventContext eventContext)
        {
            int id = (int)(eventContext.data as GObject).data;
            object[] goBackDatas = ViewManager.GetGoBackDatas(typeof(DressUpGuideView).Name);
            object[] sourceDatas = new object[] { id, goBackDatas, 1 };
            GoodsItemTipsController.ShowItemTips(id, sourceDatas, DressUpMenuItemDataManager.CheckHasItem(id));
        }
        /// 
        /// 二级菜单的点击
        /// 
        /// 
        /// 
        private void OnClickListType2Item(EventContext eventContext)
        {
            GObject gObject = eventContext.data as GObject;
            int index = _ui.m_listType2.GetChildIndex(gObject);
            if (_lastClickIndex.typeIndex == 2 && _lastClickIndex.index == index)
            {
                return;
            }
            UpdateItemIdListByType2(index);
            UpdateItemListUI();
            _ui.m_Refresh.Play();
        }
        private void OnClickBtnAllAccessories()
        {
            // 点击饰品按钮回到一级菜单时,需要更新为 全部饰品 选项
            UpdateItemIdListByType2(0);
            UpdateItemListUI();
            ShowListType1();
            // 饰品
            _lastClickIndex.index = 9;
        }
        /// 
        /// 根据一级菜单的按钮点击,更新itemIDList
        /// 
        /// 点击按钮的index
        private void UpdateItemIdListByType1(int index)
        {
            _lastClickIndex.typeIndex = 1;
            _lastClickIndex.index = index;
            // 点击了“全部服装”
            if (index == 0)
            {
                _itemIdList = DressUpMenuItemDataManager.GetAllDressUpGuideIdListBySubType(0);
            }
            else
            {
                DressUpMenuItemCfg1 item1 = DressUpMenuItemCfg1Array.Instance.dataArray[index - 1];
                // 存在二级菜单
                if (item1.subMenusArr.Length > 0)
                {
                    _currentList2 = item1.subMenusArr.Clone() as int[];
                    List types = new List();
                    for (int i = 0; i < _currentList2.Length; i++)
                    {
                        DressUpMenuItemCfg2 item2 = DressUpMenuItemCfg2Array.Instance.dataArray[_currentList2[i] - 1];
                        types.Add(item2.type);
                    }
                    _itemIdList = DressUpMenuItemDataManager.GetAllDressUpGuideIdListBySubTypes(types);
                    ShowListType2();
                }
                else
                {
                    _itemIdList = DressUpMenuItemDataManager.GetAllDressUpGuideIdListBySubType(item1.type);
                }
            }
            _itemIdList = GetFilterList(_itemIdList, _filterStr);
        }
        /// 
        /// 根据二级菜单的按钮点击,更新itemIDList
        /// 
        /// 点击按钮的index
        private void UpdateItemIdListByType2(int index)
        {
            _lastClickIndex.typeIndex = 2;
            _lastClickIndex.index = index;
            if (index == 0)
            {
                List types = new List();
                for (int i = 0; i < _currentList2.Length; i++)
                {
                    DressUpMenuItemCfg2 item2 = DressUpMenuItemCfg2Array.Instance.dataArray[_currentList2[i] - 1];
                    types.Add(item2.type);
                }
                _itemIdList = DressUpMenuItemDataManager.GetAllDressUpGuideIdListBySubTypes(types);
            }
            else
            {
                DressUpMenuItemCfg2 item2 = DressUpMenuItemCfg2Array.Instance.dataArray[_currentList2[index - 1] - 1];
                _itemIdList = DressUpMenuItemDataManager.GetAllDressUpGuideIdListBySubType(item2.type);
            }
            _itemIdList = GetFilterList(_itemIdList, _filterStr);
        }
        /// 
        /// 更新散件列表UI,及收集度
        /// 
        private void UpdateItemListUI(bool refreshProgress = true)
        {
            int haveCount = 0;
            int totalCount = 0;
            _ui.m_listDressUp.numItems = _itemIdList.Count;
            _ui.m_listDressUp.scrollPane.ScrollTop();
            if (refreshProgress)
            {
                for (int i = 0; i < _itemIdList.Count; i++)
                {
                    if (DressUpMenuItemDataManager.CheckHasItem(_itemIdList[i]))
                    {
                        ++haveCount;
                    }
                    ++totalCount;
                }
                UpdateProgress(haveCount, totalCount);
            }
        }
        private void ShowListType2()
        {
            _ui.m_c1.selectedIndex = 1;
            _ui.m_listType2.selectedIndex = 0;
            _ui.m_listType2.scrollPane.SetPercX(0, false);
            _lastClickIndex.typeIndex = 2;
            _lastClickIndex.index = 0;
        }
        private void ShowListType1()
        {
            _ui.m_c1.selectedIndex = 0;
            _lastClickIndex.typeIndex = 1;
            _currentList2 = null;
        }
        /// 
        /// 更新收集进度
        /// 
        private void UpdateProgress(int haveCount, int totalCount)
        {
            _ui.m_progressBar.target.max = totalCount;
            _ui.m_progressBar.target.value = haveCount;
            _ui.m_progressBar.m_title1.SetVar("value", haveCount.ToString()).SetVar("max", totalCount.ToString()).FlushVars();
            if(totalCount > 0)
            {
                _ui.m_progressBar.m_rate.SetVar("rate", FieldGuideView.ProgressCalculate(haveCount, totalCount).ToString()).FlushVars();
            }
            else
            {
                _ui.m_progressBar.m_rate.SetVar("rate", "0").FlushVars();
            }
        }
        private void OnClickBtnBack()
        {
            _startInAnim = true;
            ViewManager.GoBackFrom(typeof(DressUpGuideView).FullName);
        }
        private void OnClickBtnSearch()
        {
            ViewManager.Show(false);
        }
        private void FilterItems(EventContext context)
        {
            _filterStr = "";
            // 过滤之前,需要更新_itemIdList为全部物品
            if (_lastClickIndex.typeIndex == 1)
            {
                UpdateItemIdListByType1(_lastClickIndex.index);
            }
            else if (_lastClickIndex.typeIndex == 2)
            {
                UpdateItemIdListByType2(_lastClickIndex.index);
            }
            _filterStr = context.data.ToString();
            _itemIdList = GetFilterList(_itemIdList, _filterStr);
            UpdateItemListUI();
            ViewManager.Hide();
            _ui.m_Refresh.Play();
        }
        private void LoadFinished()
        {
            UpdateItemIdListByType1(0);
            UpdateItemListUI();
        }
        private List GetFilterList(List list, string filterStr)
        {
            if (filterStr == ConstMessage.DRESS_SEARCH)
            {
                list = DressUpMenuItemDataManager.DressSearch(list, DressFilterItemType.DressUpItem);
            }
            else if (filterStr == ConstMessage.DRESS_FILTER)
            {
                list = DressUpMenuItemDataManager.DressFilter(list, DressFilterItemType.DressUpItem);
            }
            return list;
        }
        private void ResetFilterStr()
        {
            _filterStr = "";
            if (_lastClickIndex.typeIndex == 1)
            {
                UpdateItemIdListByType1(_lastClickIndex.index);
            }
            else if(_lastClickIndex.typeIndex == 2)
            {
                UpdateItemIdListByType2(_lastClickIndex.index);
            }
            UpdateItemListUI();
        }
    }
}