﻿using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using SpacePlayer;
using Wormhole;

public class SPEditor_GeneralTools : MonoBehaviour
{
    static AssetBundle spaceObjBundle;

    /// <summary>
    /// 提供编辑器版本
    /// </summary>
    /// <returns></returns>
    public static string GetEditorVersion()
    {
        return "2.1.260720";
    }


    ///// <summary>
    ///// 加载BaseSpace中的指定序号的背景空间
    ///// </summary>
    ///// <param name="space"></param>
    ///// <param name="player"></param>
    ///// <param name="spaceObjNum">空间体在许可证里面的编号</param>
    ///// <param name="beRef">是否就是作为参考，不是作为参考的时候则直接作为资源的内置背景空间进行创建</param>
    //public static void LoadBundleInBaseSpaceAndInstantiate(BaseSpace space, SpacePlayerManager player, Transform parentTran, int spaceObjNum = 0, bool beRef = true) //ImageSpacePlayer.ImageSpacePlayer player)
    //{
    //    if (space.spaceObjs.Count == 0)
    //        return;
    //    if (spaceObjNum >= space.spaceObjs.Count)
    //        return;

    //    string url = Path.Combine(Application.streamingAssetsPath, space.spaceObjs[spaceObjNum].url);
    //    if (spaceObjBundle == null)
    //    {
    //        AssetBundle.UnloadAllAssetBundles(true);
    //        spaceObjBundle = AssetBundle.LoadFromFile(url);
    //    }
    //    if (spaceObjBundle == null)
    //    {
    //        Debug.Log("Failed to load AssetBundle!");
    //        return;
    //    }

    //    GameObject prefab = spaceObjBundle.LoadAsset<GameObject>(spaceObjBundle.GetAllAssetNames()[0]);
    //    if (prefab != null)
    //    {
    //        GameObject go = Instantiate(prefab);
    //        if (beRef)
    //        {
    //            go.name = "SpaceFrameTemp";
    //            go.transform.SetParent(GameObject.Find("SpacePivotRoot").transform);
    //            go.transform.localPosition = Vector3.zero;
    //            go.transform.localEulerAngles = Vector3.zero;

    //            // 确保材质正确应用（如果需要）
    //            Renderer[] renderers = go.GetComponentsInChildren<Renderer>();
    //            Debug.Log("renderers:" + renderers.Length);
    //            if (renderers != null)
    //            {
    //                foreach (Renderer item in renderers)
    //                {
    //                    item.sharedMaterial = player.framewireMat;    //替换为线框材质，以作为参考
    //                }
    //            }
    //        }
    //        else
    //        {
    //            go.name = "SpaceFrame";
    //            go.transform.SetParent(parentTran);
    //            go.transform.localPosition = Vector3.zero;
    //            go.transform.localEulerAngles = Vector3.zero;
    //        }
    //    }
    //    else
    //    {
    //        Debug.Log("Failed to load Asset from AssetBundle!");
    //    }

    //    spaceObjBundle.Unload(false);
    //}


    ///// <summary>
    ///// 加载BaseSpace中的指定序号的背景空间
    ///// </summary>
    ///// <param name="bundleUrl"></param>
    ///// <param name="player"></param>
    ///// <param name="beRef">是否就是作为参考，不是作为参考的时候则直接作为资源的内置背景空间进行创建</param>
    //public static GameObject  LoadBundleAndInstantiate(string bundleUrl, SpacePlayerManager player, Transform parentTran, bool beRef = true) //ImageSpacePlayer.ImageSpacePlayer player)
    //{
    //    if (!File.Exists(bundleUrl))
    //    {
    //        Debug.Log("Bundle文件不存在");
    //        return null;
    //    }

    //    if (spaceObjBundle == null)
    //    {
    //        AssetBundle.UnloadAllAssetBundles(true);
    //        spaceObjBundle = AssetBundle.LoadFromFile(bundleUrl);
    //    }
    //    if (spaceObjBundle == null)
    //    {
    //        Debug.Log("Failed to load AssetBundle!");
    //        return null;
    //    }

    //    GameObject prefab = spaceObjBundle.LoadAsset<GameObject>(spaceObjBundle.GetAllAssetNames()[0]);
    //    if (prefab != null)
    //    {
    //        GameObject go = Instantiate(prefab);
    //        if (beRef)
    //        {
    //            go.name = "SpaceFrameTemp";
    //            go.transform.SetParent(GameObject.Find("SpacePivotRoot").transform);
    //            go.transform.localPosition = Vector3.zero;
    //            go.transform.localEulerAngles = Vector3.zero;

    //            // 确保材质正确应用（如果需要）
    //            Renderer[] renderers = go.GetComponentsInChildren<Renderer>();
    //            Debug.Log("renderers:" + renderers.Length);
    //            if (renderers != null)
    //            {
    //                foreach (Renderer item in renderers)
    //                {
    //                    item.sharedMaterial = player.framewireMat;    //替换为线框材质，以作为参考
    //                }
    //            }
    //        }
    //        else
    //        {
    //            go.name = "SpaceFrame";
    //            go.transform.SetParent(parentTran);
    //            go.transform.localPosition = Vector3.zero;
    //            go.transform.localEulerAngles = Vector3.zero;
    //        }
    //        spaceObjBundle.Unload(false);
    //        return go;
    //    }
    //    else
    //    {
    //        Debug.Log("Failed to load Asset from AssetBundle!");
    //        return null;
    //    }        
    //}


    /// <summary>
    /// 获得从rootTran到curTransform的索引路径
    /// </summary>
    /// <param name="rootTran"></param>
    /// <param name="curTransform"></param>
    public static string GetTranPath(Transform rootTran,Transform curTransform)
    {
        if (curTransform == null) return "";

        string rtnStr;

        if (curTransform.parent == null)
            rtnStr = "";
        else if (curTransform.parent.gameObject  == rootTran.gameObject )    //根物体下一级
            rtnStr = curTransform .name ;
        else    //根物体下一级再以下的递归
            rtnStr = GetTranPath(rootTran, curTransform.parent) + "/" + curTransform .name ;

        return rtnStr;
    }

    /// <summary>
    /// 获得从rootTran到curTransform的索引路径
    /// </summary>
    /// <param name="rootTran"></param>
    /// <param name="curTransform"></param>
    static string CheckRepeatAboutTranPath(Transform rootTran, Transform curTran , string tranPath)
    {
        Transform tran = rootTran.Find(tranPath);
        if (curTran != tran)
            return rootTran.name + "的子物体路径（"+tranPath+"）所对应的物体可能不止一个,请检查并确保该层级路径（Hierarchy窗口）对应的物体的唯一性。";
        else
            return "";
    }

    /// <summary>
    /// 判断某物体是否有相同路径的其它物体
    /// </summary>
    /// <returns></returns>
    public static string ExistOtherSameTranPath(Transform rootTran, Transform curTran)
    {
        string str = GetTranPath(rootTran, curTran);
        return  CheckRepeatAboutTranPath(rootTran, curTran, str);
    }


    /// <summary>
    /// 
    /// </summary>
    /// <param name="formworkPath"></param>
    /// <returns></returns>
    public static string CreateFormwork(string formworkPath)
    {
        string formworkPathFull = Path.Combine(Application.dataPath, formworkPath);
        if (!File.Exists(formworkPathFull))
        {
            if (EditorUtility.DisplayDialog("模板场景丢失", "模板场景丢失，请重新导入插件包进行修复。插件包中的原始文件请不要自行删除或修改。", "确定"))
                return "" ;
        }

        string newSourcePath = EditorUtility.SaveFilePanel("选择场景存放路径", Application.dataPath + "/Custom", "NewSource", "");
        string newScenePath = newSourcePath + "scene.unity";
        if (!newScenePath.StartsWith(Application.dataPath + "/Custom"))
        {
            if (EditorUtility.DisplayDialog("路径错误", "需要指定工程内的Custom文件夹路径。", "确定"))
                return "" ;
        }

        File.Copy(formworkPathFull, newScenePath, true);
        AssetDatabase.Refresh();

        //打开场景       
        UnityEngine .SceneManagement .Scene scene = UnityEditor.SceneManagement.EditorSceneManager.OpenScene(newScenePath.Remove(0, Application.dataPath.Length - 6),UnityEditor.SceneManagement.OpenSceneMode.Single);    // "Assets/Scenes/Test.unity");
        
        AssetDatabase.Refresh();

        return newSourcePath;
    }

    public static void CreatePrefabAndAssetBundle(GameObject  curMainSrcGObj, string newSourcePath,string extName)
    {
        //创建Prefab
        string prefabPath = newSourcePath + ".prefab";    //.Replace(".unity", ".prefab");
        PrefabUtility.SaveAsPrefabAssetAndConnect(curMainSrcGObj, prefabPath, InteractionMode.AutomatedAction);

        AssetImporter importer = AssetImporter.GetAtPath(prefabPath.Remove(0, Application.dataPath.Length - 6));
        importer.assetBundleName = curMainSrcGObj.name;
        importer.assetBundleVariant = extName;
    }



    public static bool Create3DSourceFolder(DirectoryInfo di, string fileName)  // UnityEngine.Object obj)
    {
        //先刷一遍AB资源输出
        string pathT = Application.dataPath;
        pathT = pathT.Remove(pathT.Length - 7);    // "/Assets"的长度
        
        DirectoryInfo diT = new DirectoryInfo(pathT + "/AssetBundles/StandaloneWindows");
        if (!diT.Exists)
            diT.Create();
        BuildPipeline.BuildAssetBundles(diT.FullName , BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);

        AssetDatabase.Refresh();
        Debug.Log("AssetBundle输出完毕");

        string sourcePath = pathT + "/AssetBundles/StandaloneWindows/" + fileName;
        if (!File.Exists(sourcePath))    //StandaloneWindows一定要
        {
            Debug.Log("找不到：" + sourcePath);
            EditorUtility.DisplayDialog("打包失败", "打包中转路径为空,请确认是否已经安装了Windows的IL2CPP包（一般安装好重新打包即可）；若确认已安装还存在该问题，请先将" + fileName  + "预制体添加到AssetBundle Browser(Windows/AssetBundle Browser菜单打开)窗口中，并设置扩展名为sps，重新执行本步操作。", "确定");
            return false ;
        }
        string targetPath = di.FullName + "/" + fileName;
        File.Copy(sourcePath, targetPath,true );

        //sourcePath = pathT + "/AssetBundles/Android/" + fileName;
        //if (File.Exists(sourcePath))     //Android有就要
        //{
        //    targetPath = di.FullName + "/" + fileName;
        //    File.Copy(sourcePath, targetPath, true);
        //    return false;
        //}

        //sourcePath = pathT + "/AssetBundles/WebGL/" + fileName;
        //if (File.Exists(sourcePath))           //WebGL有就要
        //{
        //    targetPath = di.FullName + "/" + fileName;
        //    File.Copy(sourcePath, targetPath, true);
        //    return false;
        //}

        return true;
    }


    



    public static void CopyRefVideo(string videoAbsoluteUrl, string _targetPath)    // string _targetPath)
    {
        string targetUrl = Path.Combine(_targetPath, Path.GetFileName(videoAbsoluteUrl));
        if (File.Exists(videoAbsoluteUrl))
        {
            if (!File.Exists(targetUrl))    //存在不重复拷贝
                File.Copy(videoAbsoluteUrl, targetUrl);
        }
        else
        {
            EditorUtility.DisplayDialog("找不到文件", "场景引用的视频【" + videoAbsoluteUrl + "】不存在。请在打包完毕后自行拷贝到XXXX[cuss（或其它）]文件夹下", "确定");
        }
    }



    /// <summary>
    /// 获取所选资源的路径
    /// </summary>
    /// <returns></returns>
    public static string GetSelectedAssetsPath()
    {
        string path = "";

        foreach (UnityEngine.Object obj in Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets))
        {
            path = AssetDatabase.GetAssetPath(obj);
            if (!string.IsNullOrEmpty(path) && File.Exists(path))
            {
                break;
            }
        }

        return path;
    }


    ///////////////////////////////////////////////////////////////////////////////////////
    [MenuItem("SpacePlayer/辅助工具/遍历子物体添加MeshCollider", true, 9000)]
    static bool AddSubMeshColliderValidateFunc()
    {
        //return Selection.activeGameObject != null;

        if (Selection.transforms == null)
            return false;

        return true;
    }
    [MenuItem("SpacePlayer/辅助工具/遍历子物体添加MeshCollider", false, 9000)]
    static void AddSubMeshCollider()
    {
        //Transform[] transforms = Selection.GetTransforms(SelectionMode.TopLevel | SelectionMode.ExcludePrefab);
        for (int i = 0 ,length = Selection.transforms.Length ; i < length; i++)
        {
            MeshRenderer[] mrs = Selection.transforms[i].GetComponentsInChildren<MeshRenderer>();
            if (mrs != null)
            {
                for (int j = 0, jLength = mrs.Length; j < jLength; j++)
                {
                    if (mrs[j].GetComponent<MeshCollider>() == null)
                        mrs[j].gameObject.AddComponent<MeshCollider>();
                    else
                        Debug.Log(mrs[j].gameObject.name + "已经有MeshCollider组件");
                }
            }
            else
                Debug.Log("所选物体及子物体中没有可以添加MeshCollider的物体");
        }

        EditorUtility.DisplayDialog("提示", "碰撞体批量添加完毕。", "确定");
    }



    [MenuItem("SpacePlayer/辅助工具/批量添加MeshCollider", true, 9001)]
    static bool AddMeshColliderValidateFunc()
    {
        //return Selection.activeGameObject != null;

        if (Selection.transforms == null)
            return false;

        return true;
    }
    [MenuItem("SpacePlayer/辅助工具/批量添加MeshCollider", false, 9001)]
    static void AddMeshCollider()
    {
        //Transform[] transforms = Selection.GetTransforms(SelectionMode.TopLevel | SelectionMode.ExcludePrefab);
        for (int i = 0, length = Selection.transforms.Length; i < length; i++)
        {
            MeshRenderer mr = Selection.transforms[i].GetComponent<MeshRenderer>();
            if (mr != null)
            {
                if (mr.GetComponent<MeshCollider>() == null)
                    mr.gameObject.AddComponent<MeshCollider>();
                else
                    Debug.Log(mr.gameObject.name + "已经有MeshCollider组件");
            }
            else
                Debug.Log("所选物体中没有可以添加MeshCollider的物体");

        }

        EditorUtility.DisplayDialog("提示", "碰撞体批量添加完毕。", "确定");
    }


    [MenuItem("SpacePlayer/辅助工具/清除丢失引用的组件",false,9002)]
    static void ClearMissingComponent()
    {
        for (int i = 0, length = Selection.gameObjects.Length; i < length; i++)
        {
            RemoveMissingRec(Selection.gameObjects[i]);
        }

        Debug.Log("清除丢失引用的组件完毕");
    }

    static void RemoveMissingRec(GameObject go)
    {
        if (!go)
            return;

        GameObjectUtility.RemoveMonoBehavioursWithMissingScript(go);
        foreach (Transform c in go.transform)
            RemoveMissingRec(c.gameObject);
    }


    ///////////////资源辅助工具////////////
    [MenuItem("SpacePlayer/拓展资源工具/打包所选Prefab为自定义AssetBundle", true, 7101)]
    static bool ExportPrefabAsAssetbundleValidateFunc()
    {
        if (Selection.activeObject == null)
        {
            return false;
        }
        if (!PrefabUtility.IsPartOfAnyPrefab(Selection.activeObject))
        {
            //Debug.LogError("选中的对象不是一个Prefab！");
            return false;
        }

        return true;
    }
    [MenuItem("SpacePlayer/拓展资源工具/打包所选Prefab为自定义AssetBundle", false, 7101)]
    static void ExportPrefabAsAssetbundle()
    {
        // 获取当前选中的对象
        UnityEngine.Object selectedObject = Selection.activeObject;

        // 判断是否为Prefab
        if (selectedObject == null || !PrefabUtility.IsPartOfAnyPrefab(selectedObject))
        {
            Debug.LogError("选中的对象不是一个Prefab！");
            return;
        }

        string packagePath = UnityEditor.EditorUtility.OpenFolderPanel("选择打包输出的目标文件夹",
            Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
            , "");
        DirectoryInfo di;
        if (string.IsNullOrEmpty(packagePath))
            return;
        else 
            di = new DirectoryInfo(packagePath);

        if (!di.Exists)
        {
            Debug.Log("未选择输出路径，中断打包");
            return;
        }

        //检查AssetBundle
        // 获取Prefab的路径
        string prefabPath = AssetDatabase.GetAssetPath(Selection.activeObject);

        // 获取AssetImporter
        AssetImporter importer = AssetImporter.GetAtPath(prefabPath);

        // 检查是否设置了AssetBundle名称和扩展名
        if (string.IsNullOrEmpty(importer.assetBundleName) || string.IsNullOrEmpty(importer.assetBundleVariant))
        {
            // 弹窗提示设置AssetBundle名称和扩展名
            if (EditorUtility.DisplayDialog("AssetBundle设置提示", "当前Prefab未设置AssetBundle名称和扩展名，是否自动设置！", "确定", "取消"))
            {
                // 设置AssetBundle名称为Prefab的名字，变体为.cab
                importer.assetBundleName = Selection.activeObject.name.ToLower();
                importer.assetBundleVariant = "cab";

                // 保存设置
                AssetDatabase.ImportAsset(prefabPath);
            }
            else
            {
                return;
            }
        }

        string fileName = importer.assetBundleName  +"."+ importer.assetBundleVariant;
        FileInfo fit = new FileInfo(Path.Combine (di.FullName , fileName));
        if(fit.Exists )
        {
            if (!EditorUtility.DisplayDialog("提示", "目标文件夹存在同名文件，是否覆盖" , "确定","取消"))
            {
                return;
            }
        }

        if (!Create3DSourceFolder(di, fileName))
        {
            Debug.Log("创建Custom AssetBundle失败"); 
            return;
        }

       if(  EditorUtility.DisplayDialog("提示", "创建自定义模型（Custom AssetBundle）文件成功:" + fileName + "。", "确定"))
        {
            Application.OpenURL(di.FullName  );
        }

    }



}
