using System;
using System.Collections.Generic;
using ChillConnect;
using Spine.Unity;
using UnityEngine;
using Random = UnityEngine.Random;

public class CreatAnimalCard : MonoBehaviour
{
    private GameObject card_item;

    public static CreatAnimalCard instance;
    private List<Sprite> img_list;

    public Camera orthoCamera; // 这个变量应该被设置为您想要调整大小的正交相机


    private void Awake()
    {
        instance = this;
        card_item = Resources.Load<GameObject>("card/card_item/card_");
        img_list = new List<Sprite>();
        // img_list = Resources.LoadAll<Sprite>("card/card_sprite").ToList();
        // img_list.Sort((x, y) => String.Compare(x.name, y.name));
        for (int i = 0; i < 16; i++)
        {
            img_list.Add(Resources.Load<Sprite>("card/card_sprite/" + i));

        }
        orthoCamera = GameObject.Find("GameCamera").GetComponent<Camera>();

        float size = 52.4f;
        string type = SystemInfo.deviceModel.ToLower().Trim();
        // Debug.Log($"barry device type========={type} == {type.Substring(0, 3)}");
        if (type.Substring(0, 3) == "iph")
        {//iPad机型
            size = (float)Math.Round(28.125f / ((float)Screen.width / Screen.height), 4);
        }
#if UNITY_EDITOR
        size = (float)Math.Round(28.125f / ((float)Screen.width / Screen.height), 4);
#endif        

        orthoCamera.orthographicSize = size;

    }

    public void SetCameraVisible(bool visible)
    {
        orthoCamera.SetActive(visible);
        GameHelper.ShowSheepPlayUI(visible);
    }

    // Start is called before the first frame update

    public List<List<Card_item>> card_item_list = new List<List<Card_item>>();
    public List<List<Card_item>> CreatCardNew(int all_card_numbers, int card_type_max, int card_layer, int extra_max, List<List<Vector2>> map_list, List<Vector2> left_extra_list,
    List<Vector2> right_extra_list)

    {

        //all_card_numbers *= 3;
        int money_rate = ConfigSystem.GetConfig<CommonModel>().rewardrate;
        List<int> type_list = new List<int>();
        List<int> this_timetype_list = new List<int>();
        // Debug.Log(card_layer);
        card_item_list.Clear();
        // if (card_layer < extra_max)
        // {
        //     card_layer = extra_max;
        // }

        for (int i = 0; i < all_card_numbers; i++)
        {
            int type = 0;
            if (GameHelper.IsGiftSwitch() && Random.Range(0, 100) < money_rate) type = 15;
            else type = Random.Range(0, card_type_max);
            if (!GameHelper.IsGiftSwitch() && type == 15)
            {
                type = Random.Range(0, card_type_max - 1);
            }

            type_list.Add(type);
            type_list.Add(type);
            type_list.Add(type);
            if (!this_timetype_list.Contains(type)) this_timetype_list.Add(type);
        }
        SaveData.GetSaveObject().this_time_cardtype = this_timetype_list.Count;

        for (int i = 0; i < card_layer; i++)
        {
            card_item_list.Add(new List<Card_item>());
        }
        if (left_extra_list.Count > 0 || right_extra_list.Count > 0)
        {
            for (int i = 0; i < left_extra_list.Count; i++)
            {

                Card_item _tempObject = new()
                {
                    pos_x = left_extra_list[i].x,
                    pos_y = left_extra_list[i].y,
                    _layer = i
                };
                card_item_list[i].Add(_tempObject);

            }
            for (int i = 0; i < right_extra_list.Count; i++)
            {
                Card_item _tempObject1 = new()
                {
                    pos_x = right_extra_list[i].x,
                    pos_y = right_extra_list[i].y,
                    _layer = i
                };
                card_item_list[i].Add(_tempObject1);
            }
        }

        var nums = 0;
        for (int i = 0; i < map_list.Count; i++)
        {
            nums += map_list[i].Count;
        }

        for (int i = 0; i < nums; i++)
        {
            Card_item _tempObject = new();

            int layer = getMaplayer(map_list);//确定层数
            int pos = Random.Range(0, map_list[layer].Count);
            _tempObject.pos_x = map_list[layer][pos].x;
            _tempObject.pos_y = map_list[layer][pos].y;
            _tempObject._layer = layer;

            card_item_list[layer].Add(_tempObject);
            map_list[layer].RemoveAt(pos);

        }
        for (int i = 0; i < card_item_list.Count; i++)
        {
            card_item_list[i].Sort((x, y) => y.pos_y.CompareTo(x.pos_y));
        }

        int index = 0;
        for (int i = 0; i < card_item_list.Count; i++)
        {
            float z_offset = 0;//用来微调每层之间的z值，让下层盖住上层
            float last_posy = 0;
            for (int j = 0; j < card_item_list[i].Count; j++)
            {
                if (last_posy != card_item_list[i][j].pos_y)
                {
                    z_offset += 0.05f;
                    last_posy = card_item_list[i][j].pos_y;
                }
                GameObject temp = Instantiate(card_item, new Vector3(card_item_list[i][j].pos_x, card_item_list[i][j].pos_y, 400 - card_item_list[i][j]._layer - z_offset), Quaternion.identity, gameObject.transform);
                index = Random.Range(0, type_list.Count);
                temp.GetComponent<SpriteRenderer>().sprite = img_list[type_list[index]];
                card_item_list[i][j].sheep_card = temp;
                card_item_list[i][j].card_type = type_list[index];
                temp.gameObject.name = i + "-" + j;
                type_list.RemoveAt(index);
            }
        }
        return card_item_list;


    }
    public void creatSaveCard(List<List<Card_item>> card_item_list)
    {
        this.card_item_list = card_item_list;
        for (int i = 0; i < card_item_list.Count; i++)
        {
            for (int j = 0; j < card_item_list[i].Count; j++)
            {
                GameObject temp;
                // if (card_item_list[i][j].is_out)
                // {
                //     temp = Instantiate(card_item, new Vector3(card_item_list[i][j].pos_x, card_item_list[i][j].pos_y, 400 - card_item_list[i][j].out_layer), Quaternion.identity, gameObject.transform);
                // }
                // else
                temp = Instantiate(card_item, new Vector3(card_item_list[i][j].pos_x, card_item_list[i][j].pos_y, 400 - card_item_list[i][j]._layer), Quaternion.identity, gameObject.transform);
                temp.GetComponent<SpriteRenderer>().sprite = img_list[card_item_list[i][j].card_type];
                card_item_list[i][j].sheep_card = temp;
                if (card_item_list[i][j].in_slot || card_item_list[i][j].is_out) temp.transform.localScale = new Vector3(4.68f, 4.68f, 1);
                temp.gameObject.name = i + "-" + j;
            }
        }

    }
    private GameObject Popup;

#if UNITY_EDITOR || UNITY_IOS
    void Update()
    {

        if (Input.GetMouseButtonDown(0))
        {

            if (Popup == null) Popup = GameObject.Find("Popup");
            if (Popup.transform.childCount != 0) return;

            Ray ray = orthoCamera.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            int layerMask = 1 << 6; // 只与第8层的碰撞器碰撞
            // 如果射线与layerMask指定层的碰撞器发生碰撞
            if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask))
            {
                // Debug.Log("Hit " + hit.collider.gameObject.name);

                GameDispatcher.Instance.Dispatch(GameMsg.card_click, hit.collider.gameObject.name);
                // 在此处添加点击物体后的逻辑
            }
            // Debug.Log("No hit");
        }
    }
#endif
    private GameObject disappear01;
    private GameObject disappear02;
    public void creatSpine(int type, Vector3 vec3)
    {
        if (disappear01 == null) disappear01 = Resources.Load<GameObject>("card/bg_img/fx_disaappear_1");
        if (disappear02 == null) disappear02 = Resources.Load<GameObject>("card/bg_img/fx_disaappear_2");
        if (type == 1)
        {
            SkeletonAnimation temp = Instantiate(disappear01, new Vector3(vec3.x, vec3.y, 110), Quaternion.identity, gameObject.transform).GetComponent<SkeletonAnimation>();
            temp.AnimationState.SetAnimation(0, "disappear01", true);
            temp.AnimationState.Complete += trackEntry =>
            {
                Destroy(temp.gameObject);
            };
        }
        if (type == 2)
        {
            SkeletonAnimation temp = Instantiate(disappear02, new Vector3(vec3.x, vec3.y, 110), Quaternion.identity, gameObject.transform).GetComponent<SkeletonAnimation>();
            temp.AnimationState.SetAnimation(0, "disappear02", true);
            temp.AnimationState.Complete += trackEntry =>
            {
                Destroy(temp.gameObject);
            };
        }
        //   temp.GetComponent<SpriteRenderer>().sprite = img_list[card_item_list[i][j].card_type];

    }

    int getMaplayer(List<List<Vector2>> map_list)
    {
        int layer = Random.Range(0, map_list.Count);//确定层数
        if (map_list[layer].Count == 0)
        {
            layer = getMaplayer(map_list);
        }
        return layer;
    }
}
