using System;
using System.Collections;
using System.Collections.Generic;
using GameFramework.Event;
using UnityEngine;
using GameFramework.DataTable;

namespace MetaClient
{
    public class CustomManager : MonoBehaviour
    {
        public static CustomManager Instance;

        public RoleCustomData bodyData;
        public const float valueFloating = 1f;
        public CustomRoleController testPlayer = null;
        public Dictionary<string, Transform> bones = new Dictionary<string, Transform>();

        private void Awake()
        {
            Instance = this;
        }

        public void Init()
        {
            GameEntry.Event.Subscribe(CustomRoleBodyEventArgs.EventId, UpdateBody);

            CreateCustomBodyData();
        }
        /// <summary>
        /// 生成玩家自定义数据信息
        /// </summary>
        public void CreateCustomBodyData()
        {
            testPlayer = GameObject.Find("5").GetComponent<CustomRoleController>();

            bodyData = new RoleCustomData();
            //初始化
            IDataTable<DRCustomBody> drCB = GameEntry.DataTable.GetDataTable<DRCustomBody>();
            DRCustomBody[] dtCB = drCB.GetAllDataRows();
            for (int i = 0; i < dtCB.Length; i++)
            {
                var partData = new PartData(
                    dtCB[i].Id,
                    dtCB[i].BoneName.Split(','),
                    dtCB[i].ScaleRangeMin,
                    dtCB[i].ScaleRangeMax,
                    dtCB[i].ScaleChange,
                    dtCB[i].PositionChange,
                    dtCB[i].RotationChange,
                    dtCB[i].IsBlend,
                    dtCB[i].BiggerBlendName,
                    dtCB[i].SmallerBlendName,
                    dtCB[i].DefaultBlendValue
                    );
                bodyData.bodyList.Add(dtCB[i].Id, partData);
            }

            bones.Clear();
            foreach (var item in bodyData.bodyList)
            {
                var key = item.Key;
                var value = item.Value;
                if(!value.useBlend)
                {
                    for (int i = 0; i < value.bones.Length; i++)
                    {
                        var transform = CustomRoleUtility.GetChild(testPlayer.transform, value.bones[i]);
                        if (!transform)
                        {
                            continue;
                        }
                        if (!bones.ContainsKey(value.bones[i]))
                        {
                            bones.Add(value.bones[i], transform);
                        }
                    }
                }
            }
            Debug.Log( "一共有"+ bones.Count + "部位的骨骼自定义修改");

            //获取自定义骨骼的初始数据
            foreach (var item in bones)
            {
                var key = item.Key;
                var value = item.Value;
                bodyData.orginLocalScaleList.Add(key, value.localScale);
            }

        }

        public void Clear()
        {
            GameEntry.Event.Unsubscribe(CustomRoleBodyEventArgs.EventId, UpdateBody);
        }

        private void UpdateBody(object sender, GameEventArgs e)
        {
            CustomRoleBodyEventArgs crf = (CustomRoleBodyEventArgs)e;
            if (crf != null)
            {
                
                //更新数据
                var partData = bodyData.bodyList[crf.Part];
                if(partData == null)
                {
                    Debug.LogError("ID :" + crf.Part + "   无数据");
                    return;
                }
                if(partData.useBlend)
                {
                    ChangeBlendShape(partData, crf.ChangeValue);
                }
                else
                {
                    ChangeBone(partData, crf.ChangeValue);
                }
                
            }
        }
        /// <summary>
        /// 变形器改变
        /// </summary>
        /// <param name="partData"></param>
        /// <param name="changeValue"></param>
        private void ChangeBlendShape(PartData partData, Vector3 changeValue)
        {
            partData.floatValue = changeValue.x;
            if(partData.floatValue == 0.5f)
            {
                RefreshRoleBlendShape(partData.biggerBlendName, 0);
                RefreshRoleBlendShape(partData.smallerBlendName, 0);
            }
            if(partData.floatValue > 0.5f)
            {
                RefreshRoleBlendShape(partData.biggerBlendName, (partData.floatValue - 0.5f) * 2 * 100);
                RefreshRoleBlendShape(partData.smallerBlendName, 0);
            }
            if(partData.floatValue < 0.5f)
            {
                RefreshRoleBlendShape(partData.biggerBlendName, 0);
                RefreshRoleBlendShape(partData.smallerBlendName, (0.5f - partData.floatValue) * 2 * 100);
            }
        }
        /// <summary>
        /// 骨骼改变
        /// </summary>
        /// <param name="partData"></param>
        /// <param name="changeValue"></param>
        private void ChangeBone(PartData partData,Vector3 changeValue)
        {
            if (changeValue.x == 0.5f)
            {
                partData.floatValue = 1;
            }
            if (changeValue.x < 0.5f)
            {
                partData.floatValue = partData.minChangeValue + (1 - partData.minChangeValue) * (changeValue.x / 0.5f);
            }
            if (changeValue.x > 0.5f)
            {
                partData.floatValue = 1 + (partData.maxChangeValue - 1) * ((changeValue.x - 0.5f) / 0.5f);
            }
            Debug.Log(partData.id + " : " + changeValue + " 转换后 :" + partData.floatValue);
            if (partData.scaleChange != Vector3.zero)
            {
                for (int i = 0; i < partData.bones.Length; i++)
                {
                    var orginBoneScale = bodyData.orginLocalScaleList[partData.bones[i]];
                    var bone = bones[partData.bones[i]];

                    var nowBone = bones[partData.bones[i]];
                    var nowScale = new Vector3(nowBone.localScale.x / orginBoneScale.x, nowBone.localScale.y / orginBoneScale.y, nowBone.localScale.z / orginBoneScale.z);
                    //var newBoneScale = new Vector3(orginBoneScale.x * (partData.scaleChange.x == 1 ? partData.floatValue : 1) * nowScale.x, orginBoneScale.y * (partData.scaleChange.y == 1 ? partData.floatValue : 1) * nowScale.y, orginBoneScale.z * (partData.scaleChange.z == 1 ? partData.floatValue : 1) * nowScale.y);

                    var newBoneScale = new Vector3(
                        partData.scaleChange.x == 1 ? partData.floatValue * orginBoneScale.x : nowBone.localScale.x,
                        partData.scaleChange.y == 1 ? partData.floatValue * orginBoneScale.y : nowBone.localScale.y,
                        partData.scaleChange.z == 1 ? partData.floatValue * orginBoneScale.z : nowBone.localScale.z
                        );

                    Debug.Log("newBoneScale : " + newBoneScale);
                    bodyData.changedScaleList[partData.bones[i]] = newBoneScale;
                }
            }

            RefreshRoleBone();
        }

        public float GetBodyBoneValue(int id)
        {
            var partData = bodyData.bodyList[id];
            if(partData.useBlend)
            {
                return partData.floatValue;
            }

            Debug.Log(id +":  GetBodyBoneValue + " + partData.scaleChange + "   " + partData.floatValue);
            if (partData.scaleChange.x == 1 || partData.scaleChange.y == 1 || partData.scaleChange.z == 1)
            {
                if (partData.floatValue == 1)
                {
                    return 0.5f;
                }
                if (partData.floatValue < 1)
                {
                    return (partData.floatValue - partData.minChangeValue) / (1 - partData.minChangeValue)/2;
                }
                if (partData.floatValue > 1)
                {
                    return 0.5f + (partData.floatValue - 1) / (partData.maxChangeValue - 1)/2;
                }
            }
            
            return 0.5f;
        }
        /// <summary>
        /// 重置角色数据
        /// </summary>
        public void ResetRole()
        {
            if(testPlayer == null)
            {
                Debug.LogError("没有模型存在");
                return;
            }
            Debug.Log("重置模型");

            foreach (var item in bodyData.bodyList)
            {
                var key = item.Key;
                var value = item.Value;
                if(value.useBlend)
                {
                    value.floatValue = 0;
                }
                else
                {
                    value.floatValue = 1;
                }
            }

            //重置缩放
            foreach (var item in bodyData.orginLocalScaleList)
            {
                var key = item.Key;
                var value = item.Value;
                //testPlayer.SetBoneScale(key, value);
                testPlayer.SetBoneWorldScale(key, value);
                if(bodyData.changedScaleList.ContainsKey(key))
                {
                    bodyData.changedScaleList[key] = bodyData.orginLocalScaleList[key];
                }
            }

            //重置旋转
            foreach (var item in bodyData.orginLocalRotationList)
            {
                var key = item.Key;
                var value = item.Value;
                testPlayer.SetBoneRot(key, value);
            }

            //重置位置
            foreach (var item in bodyData.orginLocalPositionList)
            {
                var key = item.Key;
                var value = item.Value;
                testPlayer.SetBonePos(key, value);
            }

            testPlayer.ResetAllBlendShape();
        }

        public void RefreshRoleBlendShape(string name,float value)
        {
            if (testPlayer == null)
            {
                Debug.LogError("没有模型存在");
                return;
            }

            testPlayer.SetBlendShape(name, value);
        }

        public void RefreshRoleBone()
        {
            if (testPlayer == null)
            {
                Debug.LogError("没有模型存在");
                return;
            }
            Debug.Log("刷新模型");

            //刷新缩放
            //foreach (var item in bodyData.orginLocalScaleList)
            //{
            //    var key = item.Key;
            //    var value = item.Value;

            //    if(bodyData.changedScaleList.ContainsKey(key))
            //    {
            //        testPlayer.SetBoneScale(key, bodyData.changedScaleList[key]);
            //    }
            //    else
            //    {
            //        testPlayer.SetBoneScale(key, value);
            //    }
            //}

            foreach (var item in bodyData.changedScaleList)
            {
                var key = item.Key;
                var value = item.Value;

                testPlayer.SetBoneScale(key, value);
            }
        }
        /// <summary>
        /// 旋转模特
        /// </summary>
        public void RotateModel(float offset)
        {

        }
    }
}