using UnityEditor;
using UnityEngine;

namespace FL.Editor
{
    /// <summary>
    /// 模型资源属性预设
    /// </summary>
    public partial class FLAssetPostprocessor : AssetPostprocessor
    {
        private void OnPreprocessModel()
        {
            if (!assetPath.StartsWith(ResRelative))
                return;
	        
            var modelImporter = (ModelImporter)assetImporter;
            modelImporter.isReadable = assetPath.ToLower().Contains(Readable);
            
            //顶点优化选项,开启后顶点将被重新排序,GPU性能可以得到提升
            modelImporter.optimizeMeshVertices = true;
            
            //合并相同位置的顶点
            modelImporter.weldVertices = true;
            
            //优化骨骼节点
            modelImporter.optimizeGameObjects = true;
        
            // 混合形状，人物模型看情况开启，开启的话使用SkinnedMeshRenderer代替MeshRenderer
            modelImporter.importBlendShapes = false;
            
            // 可见性
            //modelImporter.importVisibility = false;
            
            // 导入相机
            modelImporter.importCameras = false;
            
            // 光照
            modelImporter.importLights = false;
            
            //材质球
            //临时注释
            //modelImporter.materialImportMode = ModelImporterMaterialImportMode.None;
            
            modelImporter.keepQuads = false;
            modelImporter.meshCompression = ModelImporterMeshCompression.Medium;
            modelImporter.meshOptimizationFlags = MeshOptimizationFlags.Everything;
            
            modelImporter.importAnimation = assetPath.Contains("@");
            modelImporter.animationCompression = ModelImporterAnimationCompression.Optimal;
            modelImporter.animationType = ModelImporterAnimationType.Generic;
            modelImporter.skinWeights = ModelImporterSkinWeights.Custom;
            modelImporter.maxBonesPerVertex = 2;
            
            //网格缓冲区大小，默认为Auto，根据Mesh Size自动选择16或者32位Buff
            //modelImporter.indexFormat = ModelImporterIndexFormat.Auto;
            //法线，先全部关闭，后期看美术是否需要使用Mesh 的法线再开启
            //modelImporter.importNormals = ModelImporterNormals.None;
            //切线
            modelImporter.importTangents = ModelImporterTangents.None;
            //uv交换，使用lightmap时需要开启
            modelImporter.swapUVChannels = false;
            modelImporter.generateSecondaryUV = false;
        }

        private void OnPostprocessModel(GameObject model)
        {
            var modelImporter = (ModelImporter)assetImporter;
            var isAnimation = assetPath.Contains("@");

            //动画后处理部分
			if (isAnimation)
			{
				//var animationClipList = new List<AnimationClip>(AnimationUtility.GetAnimationClips(model));
				//if (animationClipList.Count == 0) 
				//{
				//	var objectList = UnityEngine.Object.FindObjectsOfType (typeof(AnimationClip)) as AnimationClip[];
				//	animationClipList.AddRange(objectList);
				//}
				
				//foreach (var clip in animationClipList)
				//{
				//	try
				//	{
    //                    //AnimationUtils.CompressAnimationClip(clip);
				//		//var curves = AnimationUtility.GetAllCurves(clip);

				//		////浮点数精度压缩为f4
				//		//foreach (var curveDate in curves)
				//		//{
				//		//	if (curveDate.curve?.keys == null)
				//		//		continue;

				//		//	var keyFrames = curveDate.curve.keys;
				//		//	for (var i = 0; i < keyFrames.Length; i++)
				//		//	{
				//		//		var key = keyFrames[i];
				//		//		key.value = float.Parse(key.value.ToString("f4"));
				//		//		key.inTangent = float.Parse(key.inTangent.ToString("f4"));
				//		//		key.outTangent = float.Parse(key.outTangent.ToString("f4"));
				//		//		keyFrames[i] = key;
				//		//	}
				//		//	curveDate.curve.keys = keyFrames;
				//		//	clip.SetCurve(curveDate.path, curveDate.type, curveDate.propertyName, curveDate.curve);
				//		//}
				//	}
				//	catch (System.Exception e)
				//	{
				//		Debug.LogError($"CompressAnimationClip Failed !!! animationPath : {assetPath} error: {e}");
				//	}
				//}
			}
			else
			{
				var renderers = model.transform.GetComponentsInChildren<Renderer>();
				foreach (var renderer in renderers)
				{
                    if (renderer == null || renderer.sharedMaterial == null)
						continue;
                    
					if (renderer.sharedMaterial.name != model.name)
					{
						Debug.LogWarning("材质名和模型名不匹配！" + model.name);
					}
				}
			}
        }
        
    }

}

