// 本脚本只在不存在时会生成一次。组件逻辑写在当前脚本内。已存在不会再次生成覆盖 

using System.Collections.Generic;
using UnityEngine;
using FairyGUI;
using Fantasy;
using Fantasy.Async;
using NBC;
using NBF.Fishing2;
using NBF.Utils;
using Log = NBC.Log;

namespace NBF
{
    public partial class ItemGearInfoTag : GComponent
    {
        public ItemInfo Info { get; private set; }
        // private RoleBag _bag;
        private List<ItemInfo> _bindItems;

        private void OnInited()
        {
            List.onClickItem.Add(OnClickItem);
        }

        #region 设置配件

        private HashSet<long> _usedItems = new HashSet<long>();

        public void SetInfo(ItemInfo itemInfo)
        {
            _usedItems.Clear();

            Info = itemInfo;
            _bindItems = RoleModel.Instance.GetBindItems(Info.Id);
            var types = itemInfo.GetBindConfig();
            List.RemoveChildrenToPool();
            if (types != null)
            {
                foreach (var bindData in types.Binds)
                {
                    var item = List.AddItemFromPool() as BagGearItem;
                    SetItemData(item, bindData);
                }

                List.AutoHeight();
                this.height = List.height + List.y + 10;
                parent.scrollPane.touchEffect = height + y > parent.height;
                parent.scrollPane.ScrollTop();
            }

            if (types == null || types.Binds.Count < 1)
            {
                visible = false;
            }
        }

        private void SetItemData(BagGearItem item, ItemBindData bindData)
        {
            ItemInfo bind = null;
            if (_bindItems != null && _bindItems.Count > 0)
            {
                bind = _bindItems.Find(t => t.ItemType == bindData.Type && !_usedItems.Contains(t.Id));
            }

            if (bind != null)
            {
                _usedItems.Add(bind.Id);
            }

            if (item != null)
            {
                item.OnCloseAction = CloseCallback;
                item.SetData(Info, bindData, bind);
            }
        }

        #endregion

        #region 配件选择

        private BagGearItem _lastSelectedItem;

        private void SelectCallback(long selectId)
        {
            if (_lastSelectedItem == null) return;
            Log.Info($"选中id={selectId}");
            RoleModel.Instance.AddRig(Info.Id, selectId, _lastSelectedItem.RigId).OnCompleted(ChangeInfo);
        }

        private void CloseCallback(long id, long removeId)
        {
            RoleModel.Instance.RemoveRig(Info.Id, removeId).OnCompleted(ChangeInfo);
        }

        private void ChangeInfo()
        {
            Log.Info("刷新安装的配件");
            SetInfo(Info);
        }

        private void OnClickItem(EventContext context)
        {
            if (context.data is not BagGearItem item) return;
            _lastSelectedItem = item;
            BagSelectPanel.Show(SelectCallback, item.BindData.Type);
        }

        #endregion
    }
}