using XGame.Editor.Asset;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace XGame.Editor.Build
{
    public class BuildAppWindow : EditorWindow
    {
        //[MenuItem("Tools/AssetBundle/一键打包", priority = 2)]
        public static void CreateWindow()
        {
            var window = EditorWindow.GetWindow<BuildAppWindow>(true, "BuildAppWindow");
            window.Show();
        }

        private BuildTarget buildTarget;
        private string outputPath;

        private string productName;
        private string bundleIdentifier;
        private string version;
        private string versionCode;
        private string assetVersion;
        private int assetVersionCode;

        //private bool isForceRebuildAB = true;
        private bool isClearSpriteAtlas;
        private GUIContent clearAtlasContent;
        /// <summary>
        /// 是否导出Android工程
        /// </summary>
        private bool exportProject = false;
        ///// <summary>
        ///// 是否分离二进制资源
        ///// Unity国际版才能使用
        ///// </summary>
        //private bool splitApplicationBinary = false;

        private ScriptingImplementation scriptImpl;
        private AndroidArchitecture androidArchitecture;

        private PublishType publishType = PublishType.Release;

        private Vector2 scrollPosition;
        private void OnEnable()
        {
            buildTarget = EditorUserBuildSettings.activeBuildTarget;

            outputPath = PathDefine.DefaultOutputPath;
            if (!Directory.Exists(outputPath))
            {
                Directory.CreateDirectory(outputPath);
            }
            version = PlayerSettings.bundleVersion;
            versionCode = GetVersionCode(buildTarget);
            productName = PlayerSettings.productName;// BuildHelper.GetProductName();
            assetVersion = "0.0.1";
            assetVersionCode = 1000;
            bundleIdentifier = PlayerSettings.applicationIdentifier;// BuildHelper.GetDefaultBundleIdentifier(productName);

            scriptImpl = ScriptingImplementation.Mono2x;
            androidArchitecture = AndroidArchitecture.ARMv7;
            publishType = PublishType.Release;

            clearAtlasContent = new GUIContent("打包完删除图集配置(*.SpriteAtlas)", "打包完删除图集配置(*.SpriteAtlas)");
            //Debug.Log($"platform:{Application.platform}");
        }

        //private void OnDisable()
        //{

        //}

        private void OnGUI()
        {
            scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition, false, true);
            //不可操作区域
            EditorGUI.BeginDisabledGroup(true);
            buildTarget = (BuildTarget)EditorGUILayout.EnumFlagsField("Build Target", buildTarget);
            outputPath = EditorGUILayout.TextField("Output Path", outputPath);
            EditorGUI.EndDisabledGroup();
            //Browse按钮
            EditorGUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Browse", GUILayout.MaxWidth(75f)))
                BrowseForFolder();
            EditorGUILayout.EndHorizontal();
            //
            EditorGUILayout.Space();
            productName = EditorGUILayout.TextField("Product Name", productName);
            bundleIdentifier = EditorGUILayout.TextField("Bundle Identifier", bundleIdentifier);
            version = EditorGUILayout.TextField("Version", version);

            if (buildTarget == BuildTarget.Android)
            {
                int.TryParse(versionCode, out var code);
                code = EditorGUILayout.IntField("Version Code", code);
                versionCode = code.ToString();
                scriptImpl = (ScriptingImplementation)EditorGUILayout.EnumPopup("Scripting Backend", scriptImpl);
                if (scriptImpl == ScriptingImplementation.Mono2x)
                {
                    androidArchitecture = AndroidArchitecture.ARMv7;
                }
                else
                {
                    androidArchitecture = (AndroidArchitecture)EditorGUILayout.EnumPopup("Target Architectures", androidArchitecture);
                }
                exportProject = EditorGUILayout.Toggle("导出Android工程", exportProject);
                //splitApplicationBinary = EditorGUILayout.Toggle("分离obb资源", splitApplicationBinary);
                //EditorGUILayout.HelpBox("Unity国际版才能使用obb，否则启动会闪退！！！！", MessageType.Warning);
            }
            else if (buildTarget == BuildTarget.iOS)
            {
                versionCode = EditorGUILayout.TextField("Build", versionCode);
            }
            else
            {
                scriptImpl = (ScriptingImplementation)EditorGUILayout.EnumPopup("Scripting Backend", scriptImpl);
            }
            assetVersion = EditorGUILayout.TextField("Assets Version", assetVersion);
            assetVersionCode = EditorGUILayout.IntField("Assets Version Code", assetVersionCode);
            //
            //isForceRebuildAB = EditorGUILayout.Toggle("重新构建AssetBundle", isForceRebuildAB);
            isClearSpriteAtlas = EditorGUILayout.Toggle(clearAtlasContent, isClearSpriteAtlas);
            publishType = (PublishType)EditorGUILayout.EnumPopup("发布类型", publishType);
            var isBuildApp = GUILayout.Button("打包");
            EditorGUILayout.EndScrollView();
            if (isBuildApp)
            {
                BuildApp();
                Close();
            }
        }
        private string GetVersionCode(BuildTarget target)
        {
            string versionCode;
            switch (target)
            {
                case BuildTarget.Android:
                    versionCode = PlayerSettings.Android.bundleVersionCode.ToString();
                    break;
                case BuildTarget.iOS:
                    versionCode = PlayerSettings.iOS.buildNumber;
                    break;
                //case BuildTarget.StandaloneWindows:
                //case BuildTarget.StandaloneWindows64:
                //    bundleVersion = PlayerSettings.bundleVersion;
                //    break;
                default:
                    versionCode = "0";
                    break;
            }
            return versionCode;
        }
        private void BrowseForFolder()
        {
            var newPath = EditorUtility.OpenFolderPanel("Output Folder", outputPath, string.Empty);
            if (!string.IsNullOrEmpty(newPath))
            {
                outputPath = newPath;
            }
        }

        private void BuildApp()
        {
            var config = new BuildConfig()
            {
                target = buildTarget,
                compatibilityLevel = ApiCompatibilityLevel.NET_Standard_2_0,
                scriptImpl = scriptImpl,
                isSetScriptDefine = true,
                androidCreateSymbols = 0,
                //splitApplicationBinary = splitApplicationBinary,
                publishType = publishType,
                callback = BuildUtils.CallbackToString(BuildCallback),
            };
            config.project = new BuildConfig.ProjectSettings()
            {
                productName = productName,
                applicationIdentifier = bundleIdentifier,
                bundleVersion = version,
                versionCode = versionCode,
                assetVersionName = assetVersion,
                assetVersionCode = assetVersionCode,
                isIgnoreGenIlrt = false,//publishType == PublishType.Profiler,
                outputPath = outputPath,
                //isForceRebuildAB = isForceRebuildAB,
                isSaveSpriteAtlas = !isClearSpriteAtlas,
            };
            config.android = new BuildConfig.AndroidSettings()
            {
                architecture = androidArchitecture,
                exportAsGoogleAndroidProject = exportProject,
            };
            config.editor = new BuildConfig.EditorSettings()
            {
                autoExplorer = buildTarget != BuildTarget.iOS,
                isNative = true,
            };
            //var text = Framework.Json.XJson.ToJson(config);
            //var configPath = PathDefine.ExtAssetsPath + "/Editor/BuildConfig.json";
            //File.WriteAllBytes(configPath, System.Text.Encoding.UTF8.GetBytes(text));
            BuildEventHelper.InvokeBeforeBuild();
            CommandLineBuild.BuildApp(config);
        }
        //[MenuItem("Build/Test/TestCallback")]
        //public static void TestCallback()
        //{
        //    var callback = BuildUtils.CallbackToString(BuildCallback);
        //    BuildUtils.BuildCompleted(callback, BuildErrorCode.CmdCompleted);
        //    var configPath = PathDefine.ExtAssetsPath + "/Editor/BuildConfig.json";
        //    var dirPath = Path.GetDirectoryName(configPath);
        //    Debug.Log($"file:{configPath} dir:{dirPath}");
        //}
        private static void BuildCallback(int code)
        {
            BuildEventHelper.InvokeAfterBuild(code);
            BuildLog.Log($"BuildAppWindow BuildCallback code:{code}");
        }
    }

}


