using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
using SpacePlayer;
using System.IO;
using System.Xml;
using System;
using System.Text;
using Ionic.Zip;
using System.Collections;
using UnityEngine.Networking;
using System.Collections.Generic;

public class SPEditor_SpaceObj : MonoBehaviour
{
    static string formworkPath = "ISPlayer/Sample/Scenes/Formwork.unity";
    static SPSpaceObj  curMainSrc;

    static  Transform srcTran;


    ///////////////////////////////////////////////////////////////////////////////////////
    [MenuItem("SpacePlayer/背景空间/新建背景空间", true, 6000)]
    private static bool NewSpaceObjValidateFunc()
    {
        //检查是否有配置文件
        FileInfo fi = new FileInfo(Path.Combine(Application.streamingAssetsPath, "Config.json"));
        if (!fi.Exists)
        {
            return false;
        }

        if (SPEditor_SpaceSource.space == null)
            return false;
        else  
            return true;
    }

    [MenuItem("SpacePlayer/背景空间/新建背景空间", false , 6000)]
    static void NewSpaceObj()
    {
        string newSourcePath = SPEditor_GeneralTools.CreateFormwork(formworkPath);
        if (string.IsNullOrEmpty(newSourcePath))
        {
            Debug.Log("资源创建失败");
            return;             //创建失败则停止创建
        }

        GameObject spacePivotRoot = GameObject.Find("SpacePivotRoot");
        if (spacePivotRoot == null)
        {
            spacePivotRoot = new GameObject();
            spacePivotRoot.name = "SpacePivotRoot";
        }

        ////生成屏幕角点作为参考
        //SPEditor_SpaceSource.space.screenEdgesInWorld = new List<EdgeVector3>();
        //for (int i = 0, length = SPEditor_SpaceSource.space.screenlocalEdgesList.Length; i < length; i++)
        //{
        //    SPEditor_SpaceSource.space.screenEdgesInWorld.Add(
        //        new EdgeVector3()
        //        {
        //            point1 = spacePivotTran.TransformPoint(this.space.screenlocalEdgesList[i].point1),
        //            point2 = spacePivotTran.TransformPoint(this.space.screenlocalEdgesList[i].point2)
        //        }
        //        );
        //}

        //往场景中添加初始内容
        GameObject spaceFrame = new GameObject();
        srcTran = spaceFrame.transform;
        spaceFrame.name = Path.GetFileNameWithoutExtension(newSourcePath);
        spaceFrame.transform.SetParent(spacePivotRoot.transform );
        spaceFrame.transform.localPosition = Vector3.zero;
        spaceFrame.transform.localEulerAngles = Vector3.zero;
        spaceFrame.transform.localScale = Vector3.one;

        GameObject wallRoot = new GameObject();
        wallRoot.name = "BGWallRoot";
        wallRoot.transform.SetParent(spaceFrame.transform);
        wallRoot.transform.localPosition = Vector3.zero;
        wallRoot.transform.localEulerAngles = Vector3.zero;
        wallRoot.transform.localScale = Vector3.one;

        GameObject edgeRoot = new GameObject();
        edgeRoot.name = "EdgeRoot";
        edgeRoot.transform.SetParent(spaceFrame.transform);
        wallRoot.transform.localPosition = Vector3.zero;
        wallRoot.transform.localEulerAngles = Vector3.zero;
        wallRoot.transform.localScale = Vector3.one;

        curMainSrc = spaceFrame.gameObject.AddComponent<SimpleSpaceObj>();

        if (SPEditor_SpaceSource.space != null)
        {
            spacePivotRoot.transform.position = SPEditor_SpaceSource.space.position;
            spacePivotRoot.transform.localEulerAngles = SPEditor_SpaceSource.space.localEulur;
        }

        //创建Prefab
        SPEditor_GeneralTools.CreatePrefabAndAssetBundle(curMainSrc.gameObject, newSourcePath, "space");

        // 注册撤销操作
        Undo.RegisterCreatedObjectUndo(spacePivotRoot, "Create Base GameObject");

        UnityEditor.SceneManagement.EditorSceneManager.SaveOpenScenes();

        Selection.activeGameObject = curMainSrc.gameObject;
    }



    [MenuItem("SpacePlayer/背景空间/导入许可自带背景空间包", true, 6001)]
    private static bool ImportSpaceObjPackageValidateFunc()
    {
        //检查是否有配置文件
        FileInfo fi = new FileInfo(Path.Combine(Application.streamingAssetsPath, "Config.json"));
        if (!fi.Exists)
        {
            return false;
        }

        if (SPEditor_SpaceSource.space == null)
            SPEditor_SpaceSource.space = SpacePlayerLicUtility.ParseSpace(false);

        if (SPEditor_SpaceSource.space == null)
            return false;
        else
            return true;
    }

    [MenuItem("SpacePlayer/背景空间/导入许可自带背景空间包", false, 6001)]
    static void ImportSpaceObjPackage()
    {
        //选择背景空间
        string spaceObjUrl = EditorUtility.OpenFilePanel("选择母版背景空间UnityPackage文件", Path.Combine(Application.streamingAssetsPath, "System/space"), "unitypackage");
        if (string.IsNullOrEmpty(spaceObjUrl))
        {
            Debug.LogWarning ("未正确选择UnityPackage文件，中止创建");
            return;   //创建失败则停止创建
        }
        else if (!File.Exists(spaceObjUrl))
        {
            Debug.LogWarning ("未正确选择UnityPackage文件，中止创建");
            return;   //创建失败则停止创建
        }

        AssetDatabase.ImportPackage(spaceObjUrl, true);
    }



    [MenuItem("SpacePlayer/背景空间/根据所选母版Prefab新建背景空间", true, 6002)]
    private static bool CopySpaceObjValidateFunc()
    {
        if (Selection.activeObject == null)
            return false;

        if (!(Selection.activeObject is GameObject))
            return false;

        if ((Selection.activeObject as GameObject).GetComponent<SPSpaceObj>() == null)
            return false;

        return true;
    }

    [MenuItem("SpacePlayer/背景空间/根据所选母版Prefab新建背景空间", false, 6002)]
    static void CopySpaceObj()
    {
        string newSourcePath = SPEditor_GeneralTools.CreateFormwork(formworkPath);
        if (string.IsNullOrEmpty(newSourcePath))
        {
            Debug.Log("资源创建失败");
            return;   //创建失败则停止创建
        }

        ////解析基础Space空间
        //space = ImageSpacePlayer.SpacePlayerLicUtility.ParseSpace(false);

        //往场景中添加空间基座
        GameObject spacePivotRoot = GameObject.Find("SpacePivotRoot");
        if (spacePivotRoot == null)
        {
            spacePivotRoot = new GameObject();
            spacePivotRoot.name = "SpacePivotRoot";
        }
        
        //Prefab加载
        GameObject prefab = Selection.activeObject as GameObject;
        if (prefab == null || PrefabUtility.GetPrefabAssetType(prefab) != PrefabAssetType.Regular)
        {
            Debug.LogError("Please select a valid prefab to instantiate and break connection.");
            return;
        }

        // 在场景中实例化Prefab
        GameObject spaceFrame = PrefabUtility.InstantiatePrefab(prefab,spacePivotRoot .transform ) as GameObject;
        spaceFrame.name = Path.GetFileNameWithoutExtension(newSourcePath);
        srcTran = spaceFrame.transform;
        curMainSrc = spaceFrame.GetComponent<SPSpaceObj >();
        if (curMainSrc == null)
        {
            curMainSrc = spaceFrame.AddComponent<SimpleSpaceObj>();
        }

        // 打断Prefab连接
        PrefabUtility.UnpackPrefabInstance(spaceFrame, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction);

        //// 将实例化后的物体设置为新的Prefab
        //PrefabUtility.SaveAsPrefabAsset(instantiatedPrefab, "Assets/NewPrefab.prefab");
        //创建Prefab
        SPEditor_GeneralTools.CreatePrefabAndAssetBundle(curMainSrc.gameObject, newSourcePath, "space");

        //Debug.Log("Prefab instantiated and connection broken successfully.");

        if (SPEditor_SpaceSource.space != null)
        {
            spacePivotRoot.transform.position = SPEditor_SpaceSource.space.position;
            spacePivotRoot.transform.localEulerAngles = SPEditor_SpaceSource.space.localEulur;

            //生成参考体
        }


        // 注册撤销操作
        Undo.RegisterCreatedObjectUndo(spaceFrame, "Create Base GameObject");

        UnityEditor.SceneManagement.EditorSceneManager.SaveOpenScenes();

        Selection.activeGameObject = curMainSrc.gameObject;
    }


    BaseSpace spaceInEditor;
    List<SpacePlayer.EdgeVector3> screenEdgesInWorld;
    void ParseSpaceDataInEditor()
    {
        spaceInEditor =  SpacePlayerLicUtility.ParseSpace(false );
        if (spaceInEditor != null)
        {
            Transform spacePivotTran = GameObject.Find("SpacePivotTran").transform;
            //生成屏幕角点
            screenEdgesInWorld = new List<EdgeVector3>();
            for (int i = 0, length = spaceInEditor.screenlocalEdgesList.Length; i < length; i++)
            {
                screenEdgesInWorld.Add(
                    new EdgeVector3()
                    {
                        point1 = spacePivotTran.TransformPoint(spaceInEditor.screenlocalEdgesList[i].point1),
                        point2 = spacePivotTran.TransformPoint(spaceInEditor.screenlocalEdgesList[i].point2)
                    }
                    );
            }

            if (EditorUtility.DisplayDialog("成功", "许可已导入，请将Game面板分辨率调为：" + spaceInEditor.pixelWidth + "X" + spaceInEditor.pixelsHeight, "确定"))
            {

            }
        }
    }

    void OnSceneGUI()
    {
        //SpacePlayerManager.Instance .space .screenlocalEdgesList 
        if (screenEdgesInWorld != null && screenEdgesInWorld.Count > 0)
        {
            Handles.color = Color.green;

            for (int i = 0; i < screenEdgesInWorld.Count; i++)
            {
                EdgeVector3 edge = screenEdgesInWorld[i];
                Handles.DrawLine(edge.point1, edge.point2);
            }

            // 绘制参考曲面
            Vector3[] points = new Vector3[screenEdgesInWorld.Count * 2];
            for (int i = 0; i < screenEdgesInWorld.Count; i++)
            {
                points[i * 2] = screenEdgesInWorld[i].point1;
                points[i * 2 + 1] = screenEdgesInWorld[i].point2;
            }
            Handles.DrawSolidRectangleWithOutline(points, new Color(0, 1, 0, 0.1f), Color.green);
        }
        else
            ParseSpaceDataInEditor();
    }

    //static void CopySpaceObjFromBundle()
    //{
    //    string newSourcePath = SPEditor_GeneralTools.CreateFormwork(formworkPath);
    //    if (string.IsNullOrEmpty(newSourcePath))
    //    {
    //        Debug.Log("资源创建失败");
    //        return;   //创建失败则停止创建
    //    }

    //    //选择背景空间
    //    string spaceObjUrl = EditorUtility.OpenFilePanel("选择母版背景空间", Path.Combine(Application.streamingAssetsPath, "System/space"), "space");
    //    if (string.IsNullOrEmpty(spaceObjUrl))
    //    {
    //        Debug.Log("未正确选择模板文件，中止创建");
    //        return;   //创建失败则停止创建
    //    }
    //    else if (!File.Exists(spaceObjUrl))
    //    {
    //        Debug.Log("未正确选择模板文件，中止创建");
    //        return;   //创建失败则停止创建
    //    }


    //    //往场景中添加空间基座
    //    GameObject spacePivotRoot = new GameObject();
    //    spacePivotRoot.name = "SpacePivotRoot";
    //    // 注册撤销操作
    //    Undo.RegisterCreatedObjectUndo(spacePivotRoot, "Create Base GameObject");

    //    SpacePlayerManager player = FindObjectOfType<SpacePlayerManager>();

    //    if (SPEditor_SpaceSource.space != null)
    //    {
    //        spacePivotRoot.transform.position = SPEditor_SpaceSource.space.position;
    //        spacePivotRoot.transform.localEulerAngles = SPEditor_SpaceSource.space.localEulur;

    //        GameObject objBody = SPEditor_GeneralTools.LoadBundleAndInstantiate(spaceObjUrl, player, spacePivotRoot.transform, false);
    //        srcTran = objBody.transform;
    //        srcTran.name = Path.GetFileNameWithoutExtension(newSourcePath);

    //        curMainSrc = srcTran.gameObject.AddComponent<SimpleSpaceObj>();

    //        // 注册撤销操作
    //        Undo.RegisterCreatedObjectUndo(objBody, "Create Base GameObject");
    //    }
    //    else
    //    {
    //        Debug.Log("没有可用的基础空间许可");
    //        return;
    //    }

    //    //创建Prefab
    //    SPEditor_GeneralTools.CreatePrefabAndAssetBundle(curMainSrc.gameObject, newSourcePath, "space");

    //    UnityEditor.SceneManagement.EditorSceneManager.SaveOpenScenes();

    //    Selection.activeGameObject = curMainSrc.gameObject;

    //    EditorUtility.DisplayDialog("提示", "从模板为资源创建内置背景空间完成，需要你自行为背景空间另附材质", "确定");
    //}



    ///////////////////////////////////////////////////////////////////////////////////////////////////////
    [MenuItem("SpacePlayer/背景空间/检查在编背景空间是否存在常见问题", true, 6011)]
    private static bool PreCheckProblemInValidateFunc()
    {
        if (null == curMainSrc)
        {
            curMainSrc = FindObjectOfType<SimpleSpaceObj>();
            if (curMainSrc == null)
                return false;
        }

        return true;
    }

    [MenuItem("SpacePlayer/背景空间/检查在编背景空间是否存在常见问题", false, 6011)]
    static void PreCheckProblemInSrc()
    {
        //检查确保所有东西都要在Src之下 // 获取当前场景的根物体列表
        GameObject[] rootObjects = UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects();
        if (rootObjects.Length != 2)
        {
            if (EditorUtility.DisplayDialog("【警告】", "标准的编辑场景的根级物体有且只有两个，请检查下要编辑的所有物体是否都在CustomObjSrc脚本物体之下。", "确定", "忽略"))
            {
                Selection.activeGameObject = curMainSrc.gameObject;
                return;
            }
        }

        EditorUtility.DisplayDialog("预检完成", "未发现常见的错误，可以选中资源Prefab，通过菜单开始打包。", "确定");
    }


    #region 打包输出
    [MenuItem("SpacePlayer/背景空间/选择背景空间预制体导出", true, 6012)]
    private static bool ExportSpacePlayerSrcValidateFunc()
    {
        if (Selection.activeObject == null)
            return false;

        if (!(Selection.activeObject is GameObject))
            return false;

        if(curMainSrc==null )
        {
            curMainSrc = FindObjectOfType <SimpleSpaceObj>();
            if (curMainSrc == null)
                return false;
        } 

        return true;
    }

    [MenuItem("SpacePlayer/背景空间/选择背景空间预制体导出", false, 6012)]
    private static void ExportSpacePlayerSrc()
    {
        string packagePath = UnityEditor.EditorUtility.OpenFolderPanel("选择打包输出的目标文件夹",
            Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
            , "");
        if (string.IsNullOrEmpty(packagePath))
        {
            Debug.Log("未选择打包输出的目标文件夹路径");
            return;
        }

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

        //先输出UnityPackage
        string fileName = Selection.activeObject.name.ToLower() + ".unitypackage";
        FileInfo fi = new FileInfo(Path.Combine(packagePath, fileName));
        if (fi.Exists)
        {
            if (EditorUtility.DisplayDialog("警告", "目标文件夹已经存在同名文件:" + fileName + "，是否继续，继续将覆盖已存在的文件。", "确定", "取消"))
            {
                ExportSimplePackage(di, Selection.activeObject);
            }
            else
                return;
        }
        else
        {
            ExportSimplePackage(di, Selection.activeObject);
        }

        fileName = Selection.activeObject.name.ToLower() + ".space";
        fi = new FileInfo (Path.Combine(packagePath, fileName));
        if (fi.Exists)
        {
            if (EditorUtility.DisplayDialog("警告", "目标文件夹已经存在同名文件:" + fileName + "，是否继续，继续将覆盖已存在的文件。", "确定", "取消"))
            {
                Export(di, Selection.activeObject);
            }
            else
                return;
        }
        else
        {
            Export(di, Selection.activeObject);
        }

    }

    static void Export(DirectoryInfo di, UnityEngine.Object obj)
    {
        GameObject go = obj as GameObject;
        if (null == curMainSrc)
            Debug.LogWarning("没有在当前场景中找到对应的结构根物体，未能检查场景中的预制体实例更改是否已经全部更新到预制体上了，但并没影响打包。");
        else
        {
            if (curMainSrc.name == obj.name)
            {
                PrefabUtility.ApplyPrefabInstance(curMainSrc.gameObject, InteractionMode.UserAction);
                AssetDatabase.Refresh();
                Debug.Log("预制体已经跟场景中实例刷新一致");
            }
            else
                Debug.LogWarning("对应场景未打开，未能检查场景中的预制体实例更改是否已经全部更新到预制体上了，但并没影响打包。");
        }

        /////开始输出
        string fileName = go.name.ToLower() + ".space";
        if (!SPEditor_GeneralTools.Create3DSourceFolder(di, fileName)) return;

        if (EditorUtility.DisplayDialog("成功", go.name.ToLower() + "资源导出完毕。", "确定"))
        {
            Application.OpenURL(di.FullName);
        }
    }


    static void ExportSimplePackage(DirectoryInfo di, UnityEngine.Object obj)
    {
        // 创建一个临时目录用于存放打包的资源
        string _name = obj.name.ToLower();
        string _upkName = _name + ".unitypackage";

        AssetDatabase.ExportPackage(AssetDatabase.GetAssetPath(obj), _upkName, ExportPackageOptions.IncludeDependencies);

        //拷贝到目标位置
        string upkTempPath = Application.dataPath.Remove(Application.dataPath.Length - 7) + "/" + _upkName;
        if (File.Exists(upkTempPath))
        {
            string targetPath = di.FullName + "/" + _upkName;
            File.Copy(upkTempPath, targetPath, true);

            File.Delete(upkTempPath);
        }

        AssetDatabase.Refresh();
    }



    static void ExportPackage(DirectoryInfo di, UnityEngine.Object obj)
    {
        string assetsPath = SPEditor_GeneralTools.GetSelectedAssetsPath();

        // 创建一个临时目录用于存放打包的资源
        string _name = obj.name.ToLower();
        string _upkName = _name + ".unitypackage";
        string tempPath = "Custom/" + _name + "UPK";
        string tempPathwithAsset = "Assets/" + tempPath;
        //Debug.Log("Path:" + Path.Combine(Application.dataPath, tempPath));
        if(!Directory .Exists (Path.Combine (Application.dataPath ,tempPath )))
            AssetDatabase.CreateFolder("Assets/Custom", _name+"UPK");

        // 获取需要打包的 Prefab 及其依赖资源
        //GameObject prefab = obj as GameObject;   // AssetDatabase.LoadAssetAtPath<GameObject>("Assets/YourPrefab.prefab");
        string[] dependencies = AssetDatabase.GetDependencies(assetsPath);

        // 将 Prefab 及其依赖资源复制到临时目录
        AssetDatabase.CopyAsset(AssetDatabase.GetAssetPath(obj), tempPathwithAsset + "/"+_name  +".prefab");
        AssetDatabase.Refresh();

        foreach (string dependency in dependencies)
        {
            Debug.Log("dependency:" + dependency);
            if (Path.GetExtension(dependency) != ".dll")
            {
                AssetDatabase.CopyAsset(dependency, tempPathwithAsset + "/" + System.IO.Path.GetFileName(dependency));
            }
            else
                Debug.Log("dll依赖项不必打包-" + dependency);
        }
        AssetDatabase.Refresh();

        //导出.unitypackage 文件
        AssetDatabase.ExportPackage(tempPathwithAsset, _upkName, ExportPackageOptions.Recurse);

        //拷贝到目标位置
        string upkTempPath = Application.dataPath.Remove(Application.dataPath.Length - 7) + "/" + _upkName;
        if(File.Exists(upkTempPath ))
        {
            string targetPath = di.FullName + "/" + _upkName;
            File.Copy(upkTempPath, targetPath, true);

            File.Delete(upkTempPath);
        }

        // 删除临时目录
        AssetDatabase.DeleteAsset(tempPathwithAsset);
        AssetDatabase.Refresh();
    }


    #endregion 


}

