using LitJson;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEditor;
using UnityEngine;
using UnityEngine.U2D;
using UnityEngine.UI;
using YooAsset;
using static UnityEngine.EventSystems.EventTrigger;

public class FaceBuildSystem : MonoBehaviour
{
    private ReferenceCollector re;
    private Button EFinish;
    private RectTransform EModel;
    private RectTransform EGShowClothName;
    private RectTransform ESNickName;
    private GameObject EColorText;
    private ScrollRect EColor;
    private ScrollRect EG_TypeFilter;
    private ScrollRect EBagContent;
    private Toggle Edress;
    private Toggle Ebody;
    private GameObject EItem_TypeFilter;
    private RectTransform EGTypeContent;
    private RectTransform EGColorItem;
    private RectTransform EGColorFilter;
    private TextMeshProUGUI EClothName;


    private SpriteAtlas ColorStyle;
    private SpriteAtlas ItemIcon;


    /// <summary>���е���Ʒ</summary>
    public Dictionary<int, ItemPackage_View> itemPackage = new Dictionary<int, ItemPackage_View>();
    /// <summary>���е���Ʒ��Ϣ</summary>
     public Dictionary<int, Good> standardPackageItems  =new Dictionary<int, Good>();

    /// <summary>��Ʒ����</summary>
    public Dictionary<int, List<GameObject>> TypeItemClassGroup = new Dictionary<int, List<GameObject>>();
    /// <summary>�ո���</summary>
    public List<GameObject> Cells = new List<GameObject>();
    /// <summary>ȡ��������װ��</summary>
    public List<int> Unworn = new List<int>();

    public List<string> ColorList = new List<string>();
    public List<GameObject> ColorObjList = new List<GameObject>();
    public int ColorType;
    public int BodyType;
    public int ClothType;
    public Dictionary<int, List<Good>> ItemTypeData = new Dictionary<int, List<Good>>();
    public List<Good> ImageGoods = new List<Good>();
    public Dictionary<int, GameObject> ClassType = new Dictionary<int, GameObject>();

    private GameObject itempackage;
    private async void Start()
    {
        re = GetComponent<ReferenceCollector>();
        EFinish = re.Get<GameObject>("EFinish").GetComponent<Button>();
        EModel = re.Get<GameObject>("EModel").GetComponent<RectTransform>();
        EGShowClothName = re.Get<GameObject>("EGShowClothName").GetComponent<RectTransform>();
        ESNickName = re.Get<GameObject>("ESNickName").GetComponent<RectTransform>();
        EColorText = re.Get<GameObject>("EColorText");
        EColor = re.Get<GameObject>("EColor").GetComponent<ScrollRect>();
        EG_TypeFilter = re.Get<GameObject>("EG_TypeFilter").GetComponent<ScrollRect>();
        EBagContent = re.Get<GameObject>("EBagContent").GetComponent<ScrollRect>();
        Edress = re.Get<GameObject>("Edress").GetComponent<Toggle>();
        Ebody = re.Get<GameObject>("Ebody").GetComponent<Toggle>();
        EItem_TypeFilter = re.Get<GameObject>("EItem_TypeFilter");
        EGTypeContent = re.Get<GameObject>("EGTypeContent").GetComponent<RectTransform>();
        EGColorItem = re.Get<GameObject>("EGColorItem").GetComponent<RectTransform>();
        EGColorFilter = re.Get<GameObject>("EGColorFilter").GetComponent<RectTransform>();
        EClothName = re.Get<GameObject>("EClothName").GetComponent<TextMeshProUGUI>();
        EModel.GetComponent<RawImage>().texture = GameObject.Find("UICamera").GetComponent<Camera>().targetTexture;


        ColorStyle =await YooAssetManager.Instance.LoadAsset<SpriteAtlas>("colorItems");
        ItemIcon = await YooAssetManager.Instance.LoadAsset<SpriteAtlas>("ItemIcon");
        itempackage = await YooAssetManager.Instance.LoadAsset<GameObject>("Item_Package");


     
        List<Good> goods = JsonMapper.ToObject<List<Good>>(Resources.Load<TextAsset>("goodsData").text);
        for (int i = 0; i < goods.Count; i++)
        {
            goods[i].assetsType = goods[i].dressType;
            goods[i].dressType = (goods[i].id / 10000).ToString();
        }




        for (int i = 0; i < goods.Count; i++)
        {
            //if (goods[i].type == 1)
            //{
               
            //}
            ImageGoods.Add(goods[i]);
        }
        ItemTypeData = new Dictionary<int, List<Good>>();
        for (int i = 0; i < 17; i++)
        {
           TypeItemClassGroup.Add(i + 1, new List<GameObject>());
        }
        for (int i = 0; i < ImageGoods.Count; i++)
        {
            int type = ImageGoods[i].id / 10000;
            if (!ItemTypeData.ContainsKey(type))
            {
                ItemTypeData.Add(type, new List<Good>());
            }
            ItemTypeData[type].Add(ImageGoods[i]);
            if (!TypeItemClassGroup.ContainsKey(type))
            {
               TypeItemClassGroup.Add(type, new List<GameObject>());
            }
        }
  //foreach (var item in ItemTypeData)
  //      {
  //          Debug.Log(item.Key + "************" + item.Value.Count);
  //      }
        AddCreatCell();
        CreatTypeItem();
        CreatColorItem();
        Init();
        Ebody.isOn = true;

        //Good config = ItemTypeData[10][6];
        //Good config2= ItemTypeData[11][2];
        //await CharacterManager.Inst.ChangePlayerTex(CharacterManager.Inst.selfRender, config);
        //await CharacterManager.Inst.ChangePlayerTex(CharacterManager.Inst.selfRender, config2);
        //ShowEquipName();

    }

    private void Init()
    {
        //����
        Ebody.onValueChanged.AddListener((x) =>
        {
            foreach (var item in ClassType)
            {
                if (item.Key < 10)
                {
                    item.Value.SetActive(x);
                }
            }
            if (x)
            {
                Ebody.transform.Find("lan_Ebody").GetComponent<TextMeshProUGUI>().color = Color.black;
                Filter(true);
                ClassType[1].GetComponent<Toggle>().isOn = true;
            }
            else
            {
                Ebody.transform.Find("lan_Ebody").GetComponent<TextMeshProUGUI>().color = new Color(1, 1, 1, 0.4f);
            }
        });
        //����
        Edress.onValueChanged.AddListener((x) =>
        {
            foreach (var item in ClassType)
            {
                if (item.Key > 9)
                {
                    item.Value.SetActive(x);
                }
            }
            if (x)
            {
                Edress.transform.Find("lan_Edress").GetComponent<TextMeshProUGUI>().color = Color.black;
                Filter(true);
                ClassType[10].GetComponent<Toggle>().isOn = true;
            }
            else
            {
                Edress.transform.Find("lan_Edress").GetComponent<TextMeshProUGUI>().color = new Color(1, 1, 1, 0.4f);
            }
        });
    }
    private   void AddCreatCell()
    {
        int count = 15;

        GameObject obj = itempackage;
        for (int i = 0; i < count; i++)
        {
            GameObject go = GameObject.Instantiate(obj);
            Cells.Add(go);
            go.transform.SetParent(EBagContent.content, false);
            go.transform.SetAsLastSibling();
            go.GetComponent<Toggle>().enabled = false;
            go.SetActive(false);
            for (int j = 0; j < go.transform.childCount; j++)
            {
                go.transform.GetChild(j).gameObject.SetActive(false);
            }
        }
    }
    /// <summary>
    /// �������岿λ���
    /// </summary>
    /// <param name="self"></param>
    private  void CreatTypeItem()
    {
        var classdir = JsonMapper.ToObject<Dictionary<string,ItemClassConfig>>(Resources.Load<TextAsset>("ItemClass").text);
        EItem_TypeFilter.gameObject.SetActive(false);
        Toggle toggle = null;
        foreach (var item in classdir)
        {

            GameObject go = GameObject.Instantiate(EItem_TypeFilter.gameObject);
            go.SetActive(true);
            go.GetComponent<Toggle>().group = EGTypeContent.GetComponent<ToggleGroup>();
            go.transform.SetParent(EGTypeContent.transform);
            go.transform.localPosition = Vector3.zero;
            go.transform.localScale = Vector3.one;
            var text = go.transform.Find("Image/Text").GetComponent<TextMeshProUGUI>();
            text.text = LanguageMatchManager.Instance.GetLanByKey(item.Value.Id.ToString());
            LanguageMatchManager.Instance.changeLanguage += () =>
            {
                text.text = LanguageMatchManager.Instance.GetLanByKey(item.Value.Id.ToString());
            };
            go.GetComponent<Toggle>().onValueChanged.AddListener((x) =>
            {
                if (x)
                {
                    text.color = Color.black;
                    if (item.Value.type == 1)
                    {
                        ClothType = item.Value.Id;
                    }
                    else
                    {
                        BodyType = item.Value.Id;
                    }
                    Filter(true, item.Value.Id);
                }
                else
                {
                    text.color = new Color(1, 1, 1, 0.4f);

                }
            });

            if (item.Value.Id == 1)
            {
                go.GetComponent<Toggle>().isOn = true;
            }
            ClassType.Add(item.Value.Id, go);
        }
    }
    /// <summary>
    /// ������ɫ����
    /// </summary>
    /// <param name="self"></param>
    private  void CreatColorItem()
    {
        for (int i = 0; i <ColorObjList.Count; i++)
        {
            GameObject.Destroy(ColorObjList[i]);
        }
        ColorObjList.Clear();
        ColorList = ColorList.Distinct().ToList();
        if (ColorList.Count != 0)
        {
            ColorType = int.Parse(ColorList[0]);
        }
        var colordir = JsonMapper.ToObject<Dictionary<string, ItemColorConfig>>(Resources.Load<TextAsset>("ItemColor").text);

        EGColorItem.gameObject.SetActive(false);
        foreach (var item in colordir)
        {
            string color =ColorList.Find(x => x == item.Value.Id.ToString());
            if (string.IsNullOrEmpty(color)) continue;
            GameObject go = GameObject.Instantiate(EGColorItem.gameObject);
            go.SetActive(true);
            go.GetComponent<Toggle>().group =EGColorFilter.GetComponent<ToggleGroup>();
            go.transform.SetParent(EGColorFilter.transform);
            go.transform.localPosition = Vector3.zero;
            go.transform.localScale = Vector3.one;
            go.transform.GetChild(0).GetComponent<Image>().sprite =ColorStyle.GetSprite(item.Value.assetsName);
            go.GetComponent<Toggle>().onValueChanged.AddListener((x) =>
            {
                if (x)
                {
                    ColorType = item.Value.Id;
                    Filter();
                }
                else
                {

                }
            });
           ColorObjList.Add(go);
        }
    }
    private   void Filter(bool isTypeSelect = false, int type = -1)
    {
        int count = 0;
        ColorList.Clear();
        Dictionary<GameObject, Good> showObj = new Dictionary<GameObject, Good>();
    
        if (type != -1)
        {
            if (TypeItemClassGroup[type].Count == 0 &&ItemTypeData.ContainsKey(type))
            {
                AddUIScrollItems(itemPackage, ItemTypeData[type].Count);
                GameObject obj = itempackage;
                for (int i = 0; i < ItemTypeData[type].Count; i++)
                {
                    GameObject go = GameObject.Instantiate(obj);
                    RefreshBagItem(go.transform, type, i);
                    go.transform.SetParent(EBagContent.content);
                    go.transform.localScale = Vector3.one;
                    go.transform.localPosition = Vector3.zero;
                    go.transform.SetAsFirstSibling();
                    go.name = ItemTypeData[type][i].id.ToString();
                }
               
            }
        }
        int typeUsed = 0;
        if (Ebody.isOn)
        {
            typeUsed =BodyType;
        }
        else
        {
            typeUsed = ClothType;
        }
        Good dressItem = null;
        foreach (var item in TypeItemClassGroup)
        {
            var list = item.Value;
            for (int i = 0; i < list.Count; i++)
            {
                Good data = ItemTypeData[item.Key][i];
                ColorList.Add(data.color);
                showObj.Add(list[i], data);
                if (item.Key == typeUsed)
                {
                    list[i].SetActive(true);
                    count++;
                    //todo ����
                    //if (UserData.Instance.TempWornPackageItems != null && UserData.Instance.TempWornPackageItems.Count != 0)
                    //{
                    //    dressItem = UserData.Instance.TempWornPackageItems.Find(x => x.id == data.id);
                    //}
                    //else
                    //{
                    //    dressItem = UserData.Instance.WornPackageItems.Find(x => x.id == data.id);
                    //}
                }
                else
                {
                    list[i].SetActive(false);
                    ColorList.Remove(data.color);
                    showObj.Remove(list[i]);
                }
                list[i].GetComponent<Toggle>().SetIsOnWithoutNotify(false);
                list[i].GetComponent<Toggle>().interactable = true;
            }
        }

        if (isTypeSelect)
        {
            if (typeUsed == 2)
            {
               CreatColorItem();
            }
            else
            {
               ColorType = 0;
            }
           EColor.gameObject.SetActive(typeUsed == 2);
           EColorText.gameObject.SetActive(typeUsed == 2);
        }
        foreach (var item in showObj)
        {

            if (int.Parse(item.Value.color) !=ColorType && ColorType != 0)
            {
                item.Key.SetActive(false);
                count--;
            }
        }
        SetCellShow(count, Cells);
    }
    /// <summary>
    /// ��ʾ���ٸ�����
    /// </summary>
    /// <param name="self"></param>
    /// <param name="count">���ص�����</param>
    private  void SetCellShow(int count, List<GameObject> cells)
    {
        int show = count;
        if (show > cells.Count)
        {
            show = show % 5;
            show = 5 - show;
            show = cells.Count - show;
        }
        for (int i = 0; i < cells.Count; i++)
        {
            if (i < show)
            {
                cells[i].gameObject.SetActive(false);
            }
            else
            {
                cells[i].gameObject.SetActive(true);
            }
        }
    }


    private  void RefreshBagItem(Transform t, int type, int id)
    {
       itemPackage[id].BindTrans(t);
        Good config = ItemTypeData[type][id];
        //TODO:��Ʒ������;
        //itemPackage[id].ENameTextMeshProUGUI.text = LanguageMatchManager.Instance.GetLanByKey(config.name);
        //LanguageMatchManager.Instance.changeLanguage += () =>
        //{
        //    itemPackage[id].ENameTextMeshProUGUI.text = LanguageMatchManager.Instance.GetLanByKey(config.name);
        //};
        //itemPackage[id].ENameTextMeshProUGUI.text = config.name;
       itemPackage[id].EIconImage.sprite =ItemIcon.GetSprite(config.id.ToString());
       itemPackage[id].uiTransform.SetAsFirstSibling();
        //�������� CharacterRender.addDress();
        t.GetComponent<Toggle>().group =EBagContent.content.GetComponent<ToggleGroup>();
        t.GetComponent<Toggle>().onValueChanged.AddListener(async (b) =>
        {
            //todo  װ��
            if (b)
            {
                await CharacterManager.Inst.ChangePlayerTex(CharacterManager.Inst.selfRender, config);
                //ShowEquipName();
            }
            else
            {
                //if (!self.Unworn.Contains(config.id))
                //{
                //    self.Unworn.Add(config.id);
                //}
                //CharacterManager.Inst.UnEquip(CharacterManager.Inst.selfRender, config, UserData.Instance.WornPackageItems);
            }
        });

        if (config.level == 1)
        {
            itemPackage[id].ENameColorImage.color = new Color(0.8f, 0.8f, 0.8f, 1);
        }
        if (config.level == 2)
        {
           itemPackage[id].ENameColorImage.color = new Color(0.82f, 0.98f, 0, 1);
        }
        if (config.level == 3)
        {
           itemPackage[id].ENameColorImage.color = new Color(0.63f, 0.82f, 1, 1);
        }
        if (config.level == 4)
        {
            itemPackage[id].ENameColorImage.color = new Color(0.392f, 0, 1, 1);
            itemPackage[id].ENameTextMeshProUGUI.color = new Color(0.82f, 0.98f, 0, 1);
            itemPackage[id].ELinkIconImage.gameObject.SetActive(true);
        }
       TypeItemClassGroup[type].Add(t.gameObject);
    }
    public  void AddUIScrollItems(Dictionary<int , ItemPackage_View> dictionary, int count)
    {
        if (dictionary == null)
        {
            dictionary = new Dictionary<int, ItemPackage_View>();
        }
        if (count <= 0)
        {
            return;
        }
        if (count > dictionary.Count)
        {

            for (int i = dictionary.Count; i < count; i++)
            {
                ItemPackage_View itemServer = new ItemPackage_View();
                dictionary.Add(i, itemServer);
            }

        }
        else if (count < dictionary.Count)
        {
            for (int i = (dictionary.Count - 1); i >= count; i--)
            {
                dictionary[i].Dispose();
                dictionary.Remove(i);

            }


        }
    }

    /// <summary>��ʾװ����</summary>
    public  void ShowEquipName()
    {

        List<Good> goods =new List<Good>();
        foreach (var item in CharacterManager.Inst.selfRender.dressRenders)
        {
            goods.Add(item.Value.good);
        }

        string text = null;
        for (int i = 0; i < goods.Count; i++)
        {
            if (i < 5)
            {
                text += $"-{goods[i].name}\r\n";
            }
        }
        if (goods.Count > 5)
        {
            text += "-and_more";
        }
       EClothName.text = text;

    }
}