using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;

public class Red_pack_item : MonoBehaviour
{
    public Text red_pack_timeTv;
    private LandEntity[] redPackItem;
    private int index = 0;
    private void OnEnable()
    {
        redPackItem = GameObject.Find("RedPackList").GetComponent<RedPackControl>().getRedPackItem;
        if (redPackItem != null && redPackItem.Length >= 10)
        {
            try
            {
                int.TryParse(tag, out index);
            }
            catch (Exception e)
            {
                Debug.Log("红包Item"+e.Message);
                index = 0;
            }
            coinTime = 0;
            setRedPackTime(redPackItem[index].countDownSecond);
        }
    }
    private void OnDisable()
    {
        //关闭上一次倒计时
        if (fruitTimeControl != null)
        {
            StopCoroutine(fruitTimeControl);
        }
    }


    public void onClickRedPackItem()
    {
        if (coinTime <= 0 && redPackItem != null)
        {
            GameObject.Find("RedPackList").GetComponent<RedPackControl>().onClickRedPackReceive(redPackItem[index].id, redPackItem[index].coinsStr);
        }
        else
        {
            Debug.Log("红包还在倒计时");
        }
    }


    public void setRedPackTime(int second)
    {
        //关闭上一次倒计时
        if (fruitTimeControl != null)
        {
            StopCoroutine(fruitTimeControl);
        }
        if (second <= 0)
        {
            //倒计时完成
            red_pack_timeTv.text = "拆开";
        }
        else
        {
            red_pack_timeTv.text = UnityUtil.getCountdown(second);
            fruitTimeControl = StartCoroutine(fruitCountDown(second));
        }
    }

    private int coinTime=0;
    //time
    private Coroutine fruitTimeControl;
    //农作物成熟倒计时
    private IEnumerator fruitCountDown(int second)
    {
        coinTime = second;//倒计时
        while (coinTime >= 0)
        {
            yield return new WaitForSecondsRealtime(1f);
            if (coinTime <= 0)
            {//倒计时完成
                coinTime = 0;
                red_pack_timeTv.text = "拆开";
                //关闭上一次倒计时
                StopCoroutine(fruitTimeControl);
                if (fruitTimeControl != null)
                {
                    fruitTimeControl = null;
                }
            }
            else
            {
                coinTime--;
                red_pack_timeTv.text = UnityUtil.getCountdown(coinTime);
            }
        }
    }






}
