#if UNITY_EDITOR
using System;
using System.IO;
using UnityEditor;
using UnityEditor.AI;
using UnityEngine;
using UnityEngine.AI;

public partial class Battle3DScene
{
    private Action m_OnSaveEnd;
    public void Save(Action onEnd)
    {
        m_OnSaveEnd = onEnd;
        
        SaveData();
        
        SaveRuntimePrefab();

        UnityEditor.AssetDatabase.Refresh();
        
        m_OnSaveEnd?.Invoke();
    }

    void SaveData()
    {
        Battle3DScene _this = this;
        //保存数据
        BattleMapData mapData = _this.GetData();

        var bytes = Newtonsoft.Json.JsonConvert.SerializeObject(mapData);// mapData.ObjectToProtobuf();

        string path = Battle3DScene.testMapEditDataSavePath(_this.mapId);

        string dir = Path.GetDirectoryName(path);

        GameDebug.Log($"dir：{dir}");

        if (!Directory.Exists(dir))
            Directory.CreateDirectory(dir);

        //File.WriteAllBytes(path, bytes);
        File.WriteAllText(path, bytes);
        GameDebug.Log($"保存数据路径：{Battle3DScene.testMapEditDataSavePath(_this.mapId)}");
    }

    string mapPrefabPath
    {
        get
        {
            Battle3DScene _this = this;

            return "Assets/Resources/" + Battle3DScene.GetMapPrefabPath(_this.mapId);
        }
    }

    
    void SaveRuntimePrefab()
    {
        Battle3DScene _this = Instantiate(this);

        var listener = _this.GetComponentInChildren<AudioListener>();
        if(listener)
            listener.enabled = false;
        
        _this.name = Path.GetFileNameWithoutExtension(mapPrefabPath);

        GameObject go = AssetDatabase.LoadAssetAtPath<GameObject>(mapPrefabPath);
        
        DestroyImmediate(_this.GetComponent<BattleSceneEditorTest>());
        
        OnPostProcessGenPrefab(_this);
        
        if (go == null)
        {
            PrefabUtility.SaveAsPrefabAsset(_this.gameObject, mapPrefabPath);//
            //,InteractionMode.UserAction);
        }
        else
        {
            PrefabUtility.SaveAsPrefabAsset(_this.gameObject, mapPrefabPath);//
            //UnityEditor.PrefabUtility.ApplyPrefabInstance(_this.gameObject, InteractionMode.UserAction);
        }

        //DestroyImmediate(gen);

        this.name = $"场景{_this.mapId}编辑";
        
        DestroyImmediate(_this.gameObject);
    }
    
    protected virtual void OnPostProcessGenPrefab(Battle3DScene prefToSave)
    {
        
    }
    
    void DeleteFilesInDir(string dir, string filter)
    {
        if (!Directory.Exists(dir))
            return;
        DirectoryInfo dirInfo = new DirectoryInfo(dir);

        var files = dirInfo.GetFiles();
        for (int i = 0; i < files.Length; i++)
        {
            if (files[i].Name.Contains(filter))
            {
                string path = Path.Combine(dir, files[i].Name);
                GameDebug.Log($"删除：{path}");
                if (File.Exists(path))
                    File.Delete(path);
            }
        }
    }

}

#endif