using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace Unity.Func.Sample.UI
{
    public class RewardUIController : MonoBehaviour
    {
        public Transform listContent;
        public GameObject itemPrefab;

        [Header("SSR 展示")]
        public GameObject ssrPopup;
        public GameObject heroItem;
        private CardItem _hero;
        private Coroutine _ssrCoroutine;

        public void Init(List<CardConfig.Card> cards)
        {
            // 恢复初始状态
            DestroyAllChildren(listContent);
            _hero = heroItem.GetComponent<CardItem>();
            ssrPopup.SetActive(false);
            gameObject.SetActive(true);

            foreach (var card in cards)
            {
                var gameObj = Instantiate(itemPrefab, listContent);
                gameObj.GetComponent<CardItem>().Init(card);
            }

            // 获取英雄卡牌
            var heroes = cards.Where(card => card.type == CardConfig.Type.Heroes).ToList();

            if (heroes.Any())
            {
                _ssrCoroutine = StartCoroutine(SsrDisplay(cards, heroes));
            }
        }

        private IEnumerator SsrDisplay(List<CardConfig.Card> cards, List<CardConfig.Card> heroes)
        {
            ssrPopup.SetActive(true);
            foreach (var hero in heroes)
            {
                _hero.Init(hero);
                yield return new WaitForSeconds(2);
            }
            ssrPopup.SetActive(false);
        }

        public void Skip()
        {
            StopCoroutine(_ssrCoroutine);
            ssrPopup.SetActive(false);
        }


        public void Hide()
        {
            gameObject.SetActive(false);
        }

        private static void DestroyAllChildren(Transform parent)
        {
            for (var i = 0; i < parent.childCount; i += 1)
            {
                Destroy(parent.GetChild(i).gameObject);
            }
        }

    }
}