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

[RequireComponent(typeof(CircleCollider2D))]
[RequireComponent(typeof(Rigidbody2D))]
public class Fruit : MonoBehaviour
{
    private Rigidbody2D rig2D;

    //碰撞底部播放声音的CD
    private float BottomColiderCD = 1f;
    //CD计时器
    private float BottomColiderCDTimer;
    //底部播放声音是否正在CD  
    private bool BottomColiderIsCD;

    //两侧是否正在CD
    private float SidesColiderCD = 1f;
    private float SidesColiderCDTimer;
    private bool SidesColiderIsCD;


    public void OnInit() 
    {
        rig2D = GetComponent<Rigidbody2D>();
        rig2D.bodyType = RigidbodyType2D.Kinematic;
    }

    public void OnDrag() 
    {
        rig2D.bodyType = RigidbodyType2D.Dynamic;
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Bottom"))
        {
            if (!BottomColiderIsCD)
            {
                BottomColiderIsCD = true;

                //计算碰撞点
                Bounds bound = transform.GetComponent<SpriteRenderer>().bounds;
                float FruitRadius = bound.size.x / 2;
                //世界坐标
                Vector3 CollisionPos = new Vector3(transform.position.x, transform.position.y - FruitRadius, 0);
                FlyNotes(CollisionPos);
            }
            return;
        }

        if (collision.gameObject.CompareTag("Sides"))
        {
            //加上角度限制 防止玩家从最左右边落下水果 直接触发音乐符号
            if (!SidesColiderIsCD && Vector3.Angle(gameObject.GetComponent<Rigidbody2D>().velocity, Vector2.down) > 5)
            {
                SidesColiderIsCD = true;

                //计算碰撞点
                Bounds bound = transform.GetComponent<SpriteRenderer>().bounds;
                float FruitRadius = bound.size.x / 2;

                //判断是左边碰到还是右边碰到
                int factor = collision.transform.position.x > transform.position.x ? 1 : -1;
                //世界坐标
                Vector3 CollisionPos = new Vector3(transform.position.x + (FruitRadius * factor), transform.position.y, 0);
                FlyNotes(CollisionPos);
            }
            return;
        }

        //如果两个水果名字一样
        if (gameObject.name == collision.gameObject.name) 
        {
            //如果已经是最大的
            if (int.Parse(gameObject.name) >= 11)
            {
                return;
            }

            //如果另一边的水果已经触发 碰撞函数 则直接返回
            if (GameController.GetInstance().TempList.Contains(gameObject))
            {
                GameController.GetInstance().TempList.Remove(gameObject);
                return;
            }

            //把被碰撞的水果 放入集合中 防止重复碰撞检测
            GameController.GetInstance().TempList.AddLast(collision.gameObject);

            //两个水果的中间位置
            Vector3 MidPos = (transform.position + collision.transform.position) / 2;
            //生成一个新的
            int fruitNum = int.Parse(gameObject.name) + 1;
            string NewObjName = fruitNum.ToString();

            GameObject Obj = Instantiate(Resources.Load<GameObject>("Fruits/" + NewObjName), MidPos, Quaternion.identity);
            Obj.transform.localScale = new Vector3(0.3f, 0.3f, 1);
            Obj.name = NewObjName;

            //取两个水果中 速度大的一个 赋值给新生成的水果
            Vector2 Velocity = 
                gameObject.GetComponent<Rigidbody2D>().velocity.magnitude > collision.gameObject.GetComponent<Rigidbody2D>().velocity.magnitude?
                gameObject.GetComponent<Rigidbody2D>().velocity : collision.gameObject.GetComponent<Rigidbody2D>().velocity;

            Obj.GetComponent<Rigidbody2D>().velocity = Velocity;

            #region 上报水果合成

            Dictionary<string, object> paras = new Dictionary<string, object>();
            paras.Add("type", fruitNum);
            HttpTool.Instance._Get("app/v1/watermelon/synthetic", paras, new Action<List<int>>((result) =>
            {
                if (fruitNum==11)
                {
                    UIMgr.Getinstance().GetPanel<MainPanel>().GetHomeInfo();
                }

            }), new Action<string, string>((code, msg) =>
            {
                Debug.unityLogger.Log("合成水果上报 " + code + " msg " + msg);
            }));

            #endregion

            //生成爆炸效果
            Instantiate(Resources.Load<GameObject>("Prefabs/BoomEffect"), MidPos, Quaternion.identity);

            //生成音符特效 并发送事件
            FlyNotes(MidPos);

            Destroy(collision.gameObject);
            Destroy(this.gameObject);
        }
    }

    private void FixedUpdate()
    {
        UpdateBottomColiderInCD();
        UpdateSidesColiderInCD();
    }

    //生成音符特效 并发送事件
    private void FlyNotes(Vector2 StartPos) 
    {
        GameObject obj = ResMgr.Getinstance().Load<GameObject>("Prefabs/Note");
        obj.transform.ResetToCanvas(E_Layer.system, UIMgr.Getinstance().canvas.InverseTransformPoint(StartPos));
        obj.GetComponent<Image>().sprite =
            ResMgr.Getinstance().Load<SpriteAtlas>("Atlas/Notes").GetSprite("note" + UnityEngine.Random.Range(1, 4).ToString());
        (obj.transform as RectTransform).DoMove(0.5f, new Vector2(0, 580), trans => { Destroy(trans.gameObject); });

        //发送事件
        EventCenter.Getinstance().EventTrigger("FlyNote");
    }

    //刷新底部CD
    private void UpdateBottomColiderInCD()
    {
        if (BottomColiderIsCD)
        {
            BottomColiderCDTimer += Time.fixedDeltaTime;

            if (BottomColiderCDTimer >= BottomColiderCD)
            {
                BottomColiderIsCD = false;
                BottomColiderCDTimer = 0;
            }
        }
    }

    //刷新两侧CD
    private void UpdateSidesColiderInCD()
    {
        if (SidesColiderIsCD)
        {
            SidesColiderCDTimer += Time.fixedDeltaTime;

            if (SidesColiderCDTimer >= SidesColiderCD)
            {
                SidesColiderIsCD = false;
                SidesColiderCDTimer = 0;
            }
        }
    }
}
