using System;
using System.Collections;
using System.Collections.Generic;
using Cute;
using UnityEngine;
using Wizard.Scripts.Network.Data.TaskData.SpotCardExchange;
using Wizard.UI.Common;

namespace Wizard;

public class GachaPointExchange : MonoBehaviour
{
	private const string SPRITE_CLASS_TAB_NEUTRAL = "class_tab_neutral";

	private const int CONFIRM_DIALOG_DEPTH = 600;

	private const int CONFIRM_DIALOG_INNER_DEPTH = 610;

	private const int SORTING_ORDER_REWARD_DIALOG = 2;

	private const int CARD_OBJECT_DEPTH = 20;

	private const float CARD_OBJECT_SCALE = 0.36f;

	private const float CARD_OBJECT_COLLIDER_SCALE = 0.9f;

	[SerializeField]
	private SimpleScrollViewUI _gachaPointScrollView;

	[SerializeField]
	private TabList _tabListClass;

	[SerializeField]
	private UISprite _spriteClassTab;

	private List<string> _loadedResourceList = new List<string>();

	private UIAtlas _atlasProfile;

	private List<UIBase_CardManager.CardObjData> _cardObjectList;

	[SerializeField]
	private GameObject _cardObjectRoot;

	[SerializeField]
	private GameObject _cardDetailRoot;

	private CardDetailUI _cardDetail;

	private List<string> _loadedCardResourceList = new List<string>();

	private int _cardDetailIndex;

	private CardBasePrm.ClanType _displayClassType = CardBasePrm.ClanType.NONE;

	[SerializeField]
	private GameObject _prefabRewardConfirmDialog;

	[SerializeField]
	private GameObject _prefabExchangeConfirmDialog;

	private PackConfig _packConfig;

	private Dictionary<CardBasePrm.ClanType, List<GachaPointExchangeInfo>> _exchangableRewardListInClassDict = new Dictionary<CardBasePrm.ClanType, List<GachaPointExchangeInfo>>();

	private Action _closeDialogCallBack;

	private Action _packInfoCallBack;

	private int _gachaPointPackId => _packConfig.GachaPointData.GachaPointPackId;

	public void SetCallBack(Action closeDialogCallBack, Action packInfoCallBack)
	{
		_closeDialogCallBack = closeDialogCallBack;
		_packInfoCallBack = packInfoCallBack;
	}

	public void CreateCardList(PackConfig packConfig)
	{
		_packConfig = packConfig;
		InitCardDetail();
		StartCoroutine(LoadInitialResources(delegate
		{
			InitClassTab();
			UpdateExchangeableCardList(CardBasePrm.ClanType.ALL);
		}));
	}

	private IEnumerator LoadInitialResources(Action onFinish)
	{
		UIManager.GetInstance().createInSceneCenterLoading();
		yield return StartCoroutine(LoadProfileAtlas());
		UIManager.GetInstance().closeInSceneCenterLoading();
		onFinish.Call();
	}

	private IEnumerator LoadProfileAtlas()
	{
		string profileAtlasName = UIManager.GetInstance().GetSceneAssetPath(UIAtlasManager.AssetBundleNames.Profile, null);
		yield return StartCoroutine(Toolbox.ResourcesManager.LoadAssetAsync(profileAtlasName, null));
		_loadedResourceList.Add(profileAtlasName);
		profileAtlasName = UIManager.GetInstance().GetSceneAssetPath(UIAtlasManager.AssetBundleNames.Profile, null, isload: true);
		_atlasProfile = Toolbox.ResourcesManager.LoadObject<GameObject>(profileAtlasName).GetComponent<UIAtlas>();
	}

	private void UnloadResources()
	{
		Toolbox.ResourcesManager.RemoveAssetGroup(_loadedResourceList);
		_loadedResourceList.Clear();
	}

	private void OnDestroy()
	{
		UnloadResources();
		UnloadCardObject();
	}

	private void InitCardDetail()
	{
		_cardDetail = DialogCreator.CreateCardDetailDialog(_cardDetailRoot, "Detail");
		_cardDetail.OnDragCard = CardDetailDragCallback;
		_cardDetail.OnDetailCardUpdate = UpdateCardDetailArrowButtonVisible;
		_cardDetail.gameObject.SetActive(value: false);
	}

	private IEnumerator LoadCardObject(List<int> cardIdList, Action onFinish)
	{
		if (cardIdList.Count == 0)
		{
			onFinish.Call();
			yield break;
		}
		UnloadCardObject();
		UIManager uiMgr = UIManager.GetInstance();
		uiMgr.createInSceneCenterLoading();
		bool isLoaded = false;
		uiMgr.CardLoadSelect(null, cardIdList, base.gameObject.layer, is2D: true, delegate
		{
			isLoaded = true;
		});
		while (!isLoaded)
		{
			yield return null;
		}
		InitCardObject();
		uiMgr.closeInSceneCenterLoading();
		onFinish.Call();
	}

	private void InitCardObject()
	{
		List<UIBase_CardManager.CardObjData> cardList2DObjs = UIManager.GetInstance().getCardList2DObjs();
		_cardObjectList = new List<UIBase_CardManager.CardObjData>(cardList2DObjs);
		cardList2DObjs.Clear();
		List<string> cardListAssetPathList = Toolbox.ResourcesManager.CardListAssetPathList;
		_loadedCardResourceList.AddRange(new List<string>(cardListAssetPathList));
		cardListAssetPathList.Clear();
		if (_cardObjectList == null)
		{
			return;
		}
		for (int i = 0; i < _cardObjectList.Count; i++)
		{
			GameObject cardObject = _cardObjectList[i].CardObj;
			cardObject.SetActive(value: false);
			UITexture[] componentsInChildren = cardObject.GetComponentsInChildren<UITexture>();
			foreach (UITexture uITexture in componentsInChildren)
			{
				if (uITexture.name.Contains("CardTexture"))
				{
					UITexture component = uITexture.GetComponent<UITexture>();
					Material material = component.material;
					component.mainTexture = material.mainTexture;
					component.material = null;
				}
			}
			cardObject.transform.parent = _cardObjectRoot.transform;
			CardListTemplate component2 = cardObject.GetComponent<CardListTemplate>();
			component2.HideNum();
			component2._newLabel.gameObject.SetActive(value: false);
			component2.SetId(_cardObjectList[i].ids);
			component2.SetScale(0.36f);
			component2.AddDepth(20);
			int tempIndex = i;
			component2.AddColliderToFrame(0.9f).onClick = delegate
			{
				_cardDetailIndex = tempIndex;
				_cardDetail.OnPushCardDetailOn(cardObject);
			};
		}
	}

	private void CardDetailDragCallback(Vector2 vec)
	{
		if (!_cardDetail.IsEnableShowDetail)
		{
			return;
		}
		float x = vec.x;
		if (!(Mathf.Abs(x) < 70f))
		{
			int num = _cardDetailIndex + ((!(x > 0f)) ? 1 : (-1));
			if (num >= 0 && _cardObjectList.Count > num)
			{
				GameMgr.GetIns().GetSoundMgr().PlaySe(Se.TYPE.SYS_SLIDE_BTN);
				_cardDetail.CloseDefault(playSe: false);
				_cardDetail.ShowCardDetail(_cardObjectList[num].CardObj);
				_cardDetailIndex = num;
				UpdateCardDetailArrowButtonVisible();
			}
		}
	}

	private void UpdateCardDetailArrowButtonVisible()
	{
		_cardDetail.LeftButtonVisible = _cardDetailIndex > 0;
		_cardDetail.RightButtonVisible = _cardDetailIndex < _cardObjectList.Count - 1;
	}

	private void UnloadCardObject()
	{
		Toolbox.ResourcesManager.RemoveAssetGroup(_loadedCardResourceList);
		_loadedCardResourceList.Clear();
		if (_cardObjectList != null)
		{
			for (int i = 0; i < _cardObjectList.Count; i++)
			{
				UnityEngine.Object.Destroy(_cardObjectList[i].CardObj.gameObject);
			}
			_cardObjectList.Clear();
		}
	}

	private void InitClassTab()
	{
		_spriteClassTab.atlas = _atlasProfile;
		for (int i = 0; i < 9; i++)
		{
			CardBasePrm.ClanType classType = (CardBasePrm.ClanType)i;
			string spriteBaseName = ((classType != CardBasePrm.ClanType.ALL) ? ("class_tab_" + i.ToString("00")) : "class_tab_neutral");
			_tabListClass.AddTab(delegate
			{
				if (classType != _displayClassType)
				{
					ShowExchangeableCardList(classType);
				}
			}, spriteBaseName).name = "Class_" + i + "(Clone)";
		}
		_tabListClass.Reset(notSelectTab: true);
	}

	private void GrayOutUnnecessaryTab(ref CardBasePrm.ClanType displayClassType)
	{
		bool flag = false;
		for (CardBasePrm.ClanType clanType = CardBasePrm.ClanType.ALL; clanType < CardBasePrm.ClanType.MAX; clanType++)
		{
			if (_exchangableRewardListInClassDict[clanType].Count == 0)
			{
				_tabListClass.SetTabToGrayByIndex((int)clanType, disable: true);
			}
			else if (!flag)
			{
				flag = true;
				displayClassType = clanType;
			}
		}
	}

	private void UpdateExchangeableCardList(CardBasePrm.ClanType displayClassType)
	{
		GachaPointExchangeInfoTask task = new GachaPointExchangeInfoTask();
		task.SetParameter(_packConfig.PackId, _gachaPointPackId);
		StartCoroutine(Toolbox.NetworkManager.Connect(task, delegate
		{
			_exchangableRewardListInClassDict = task.ExchangeableRewardListInClassDict;
			GrayOutUnnecessaryTab(ref displayClassType);
			_tabListClass.SelectTabByIndex((int)displayClassType, isForceSet: true);
		}));
	}

	private void ShowExchangeableCardList(CardBasePrm.ClanType classType)
	{
		_displayClassType = classType;
		List<GachaPointExchangeInfo> cardList = _exchangableRewardListInClassDict[_displayClassType];
		_gachaPointScrollView.SetVisiable(isVisiable: false);
		List<int> list = new List<int>(cardList.Count);
		for (int i = 0; i < cardList.Count; i++)
		{
			list.Add(cardList[i].CardId);
		}
		StartCoroutine(LoadCardObject(list, delegate
		{
			_gachaPointScrollView.SetVisiable(isVisiable: true);
			_gachaPointScrollView.CreateScrollView(cardList.Count, InitializePlate);
		}));
	}

	private void InitializePlate(int index, GameObject plate)
	{
		List<GachaPointExchangeInfo> list = _exchangableRewardListInClassDict[_displayClassType];
		if (index >= list.Count)
		{
			plate.SetActive(value: false);
			return;
		}
		GachaPointExchangePlate component = plate.GetComponent<GachaPointExchangePlate>();
		component.SetData(list[index], OnClickConfirmExchangeButton, _packConfig.GachaPointData.IsExchangeableGachaPoint);
		component.SetCardObject(_cardObjectList[index].CardObj, _cardObjectRoot);
	}

	private void OnClickConfirmExchangeButton(GachaPointExchangeInfo gachaPointExchangeInfo)
	{
		GameMgr.GetIns().GetSoundMgr().PlaySe(Se.TYPE.SYS_BTN_DECIDE);
		ShowConfirmExchangeDialog(gachaPointExchangeInfo);
	}

	private void ShowConfirmExchangeDialog(GachaPointExchangeInfo gachaPointExchangeInfo)
	{
		SystemText systemText = Data.SystemText;
		DialogBase dialogBase = UIManager.GetInstance().CreateDialogClose();
		dialogBase.SetTitleLabel(Data.SystemText.Get("Shop_0173"));
		dialogBase.SetButtonLayout(DialogBase.ButtonLayout.BlueBtn_CancelBtn);
		dialogBase.SetButtonText(systemText.Get("Shop_0154"));
		dialogBase.SetPanelSortingOrder(2);
		dialogBase.SetPanelDepth(600);
		dialogBase.onPushButton1 = (Action)Delegate.Combine(dialogBase.onPushButton1, (Action)delegate
		{
			OnClickExchangeButton(gachaPointExchangeInfo);
		});
		string mainTextFirst = systemText.Get("Shop_0164", _packConfig.GachaPointData.ExchangeableGachaPoint.ToString());
		string mainTextSecond = systemText.Get("Shop_0174", gachaPointExchangeInfo.GetExchangeCardText());
		if (gachaPointExchangeInfo.RewardList.Count == 0)
		{
			dialogBase.SetSize(DialogBase.Size.S);
			ExchangeConfirmDialog component = NGUITools.AddChild(dialogBase.gameObject, _prefabExchangeConfirmDialog).GetComponent<ExchangeConfirmDialog>();
			string empty = string.Empty;
			component.SetText(mainTextFirst, mainTextSecond, empty);
		}
		else if (gachaPointExchangeInfo.IsReceived)
		{
			dialogBase.SetSize(DialogBase.Size.S);
			ExchangeConfirmDialog component2 = NGUITools.AddChild(dialogBase.gameObject, _prefabExchangeConfirmDialog).GetComponent<ExchangeConfirmDialog>();
			string subText = systemText.Get("Shop_0166");
			component2.SetText(mainTextFirst, mainTextSecond, subText);
		}
		else
		{
			dialogBase.SetSize(DialogBase.Size.M);
			RewardConfirmDialog component3 = NGUITools.AddChild(dialogBase.gameObject, _prefabRewardConfirmDialog).GetComponent<RewardConfirmDialog>();
			string subText2 = systemText.Get("Shop_0165");
			component3.CreateRewardConfirmDialog(gachaPointExchangeInfo, 610, 2);
			component3.SetText(mainTextFirst, mainTextSecond, subText2);
			component3.transform.localPosition = Vector3.forward * 10f;
		}
	}

	private void OnClickExchangeButton(GachaPointExchangeInfo gachaPointExchangeInfo)
	{
		GachaPointExchangeTask gachaPointExchangeTask = new GachaPointExchangeTask();
		gachaPointExchangeTask.SetParameter(gachaPointExchangeInfo.CardId, _gachaPointPackId, _packConfig.PackId);
		StartCoroutine(Toolbox.NetworkManager.Connect(gachaPointExchangeTask, delegate
		{
			PlayerPrefsWrapper.SetValue(PlayerPrefsWrapper.LAST_PURCHASE_PACK_ID, _packConfig.PackId);
			_packInfoCallBack.Call();
			ShowSuccessExchangeDialog(gachaPointExchangeInfo.GetExchangeCardText());
		}));
	}

	private void ShowSuccessExchangeDialog(string exchangedCardName)
	{
		SystemText systemText = Data.SystemText;
		DialogBase dialogBase = UIManager.GetInstance().CreateDialogClose();
		dialogBase.SetTitleLabel(systemText.Get("Common_0021"));
		dialogBase.SetButtonLayout(DialogBase.ButtonLayout.OkBtn);
		dialogBase.SetText(systemText.Get("Shop_0155", exchangedCardName), isWrapText: true);
		dialogBase.SetPanelDepth(600);
		dialogBase.OnClose = delegate
		{
			_closeDialogCallBack.Call();
		};
	}
}
