/****************************************************
 文件：BuildAssetWindow.cs
 作者：xosmo_
 邮箱：
 日期：2025/3/10 10:43:20
 功能：
*****************************************************/

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using EditorFramework;
using HybridCLR.Editor;
using HybridCLR.Editor.Commands;
using Sirenix.OdinInspector;
using Sirenix.OdinInspector.Editor;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.Serialization;
using YooAsset;
using YooAsset.Editor;

namespace Stary.Evo.Editor
{
    public class BuildAssetWindow : OdinEditorWindow
    {

        private static BuildAssetWindow window;
        [MenuItem("Evo/资源打包工具")]
        static void ShowWindows()
        {
            if (CreatAssetWindow.GetCreatDomainAll().Count <= 0)
            {
                EditorUtility.DisplayDialog("提示", "不存在Domain元素，无法打开此面板，请先创建Domain元素", "确定" );
                return;
            }
            window = (BuildAssetWindow)EditorWindow.GetWindow(typeof(BuildAssetWindow));
            window.Show();
        }

    

        protected override void Initialize()
        {
            base.Initialize();
            GetBuildPackageNames();
        }

        public static void RemoveBuildAssetWindow()
        {
            if(window != null)
            window.Close();
        }
        protected void OnSelectionChange()
        {
            EditorUtility.SetDirty(BuildAssetDataSetting);
            AssetDatabase.SaveAssets();
            //AssetDatabase.Refresh();
        }

        [Title("包裹列表", titleAlignment: TitleAlignments.Centered)]
        [HorizontalGroup("BuildPipeline"), HideLabel]
        [ValueDropdown("GetBuildPackageNames")]
        [OnValueChanged("SetBuildPackageNames")]
        public string selectedPackageNames;
        
        public static string packageName;
        #region HyBridCLRBuild

        [Title("HyBridCLRBuild", titleAlignment: TitleAlignments.Centered)] [HideLabel]
        public BuildAssetEntity hyBridClrBuildEntity =
                new BuildAssetEntity("HyBridCLRBuild", "DllBuildTarget", () =>
                {
                    //PrebuildCommand.GenerateAll();
                    CompileDllCommand.CompileDllActiveBuildTarget();
                });
        #endregion


        #region MarkAsset

        [Title("MarkAsset", titleAlignment: TitleAlignments.Centered)] [HideLabel]
        public BuildAssetEntity markAssetEntity =
            new BuildAssetEntity("MarkAsset", "MarkAsset", MarkAdressable.AddMark);

        #endregion

        #region BuildAsset



        [InlineEditor(InlineEditorObjectFieldModes.CompletelyHidden)]
        [HideLabel] public BuildAssetDataSetting BuildAssetDataSetting;

        /// <summary>
        /// 检测当前所有包裹
        /// </summary>
        /// <returns></returns>
        private List<string> GetBuildPackageNames()
        {
            List<string> result = new List<string>();
            foreach (var name in CreatAssetWindow.GetCreatDomainAllName()) 
            {
                result.Add(name);
            }

            if (selectedPackageNames.IsNullOrEmpty())
            {
                // string buildPackageName = DataSetting.packageName;
                // if (result.Exists(p => p == buildPackageName))
                // {
                //     selectedPackageNames = buildPackageName;
                // }
                // else
                // {
                selectedPackageNames = result[0];
                //}

            
            }
            SetBuildPackageNames();
            return result;
        }

        /// <summary>
        /// 设置当前包裹
        /// </summary>
        /// <returns></returns>
        private void SetBuildPackageNames()
        {
            //PlayerPrefs.SetString("BuildPackageNames", selectedPackageNames);
            // DataSetting.packageName = selectedPackageNames;
            packageName = selectedPackageNames;
            // DataSetting = Resources.Load<BuildAssetDataSetting>("BuildAssetDataSetting");
            string buildAssetDataSettingPath = $"Assets/Domain/{selectedPackageNames}/Conf/BuildAssetDataSetting.asset";
            BuildAssetDataSetting buildAssetDataSetting =
                AssetDatabase.LoadAssetAtPath<BuildAssetDataSetting>(buildAssetDataSettingPath);
            if (buildAssetDataSetting != null)
            {
                BuildAssetDataSetting = buildAssetDataSetting;
                Init();
            }
            else
            {
                Debug.LogError($"UnityEvo:BuildAssetDataSetting 不存在，请检查路径{buildAssetDataSettingPath}");
            }
        }
        /// <summary>
        /// 获取当前包裹
        /// </summary>
        /// <returns></returns>
        public static string GetBuildPackageName()
        {
            return packageName;
        }
        #endregion

        #region Update

        [Title("BuildAssetButton", titleAlignment: TitleAlignments.Centered)] [HideLabel]
        public BuildAssetEntity onBuildPipelineEntity;

        [FormerlySerializedAs("UpdateServerPath")]
        [TitleGroup("UpdateAssetButton", alignment: TitleAlignments.Centered)][ShowIf("@ BuildAssetDataSetting.environmentType== EnvironmentType.Release",true)]
        [ReadOnly]
        [InfoBox("服务器资源盘位未存在", InfoMessageType.Error, "@ _isCheckDriveExist==false")]
        [InfoBox("1、映射网络驱动器\n2、添加http://192.168.31.100:5005/alist/HotRefresh地址\n3、设置盘符为Z盘", InfoMessageType.Info,
            "@ _isCheckDriveExist==false")]
        public string updateServerPath;

        private bool _isCheckDriveExist;

        [TitleGroup("UpdateAssetButton", alignment: TitleAlignments.Centered)] [HideLabel][ShowIf("@ _isCheckDriveExist&&BuildAssetDataSetting.environmentType== EnvironmentType.Release",true)]
        public BuildAssetEntity onUpdateBuildPipelineEntity;


        private void OnBuildPipeline()
        {
            if (EditorUtility.DisplayDialog("提示", $"开始构建资源包[{selectedPackageNames}]！", "Yes", "No"))
            {
                EditorTools.ClearUnityConsole();
                EditorApplication.delayCall += BuildAssetDataSetting.viewer.ExecuteBuild;
            }
            else
            {
                Debug.LogWarning("[Build] 打包已经取消");
            }
        }

        private void OnUpdateBuildPipeline()
        {

            if (EditorUtility.DisplayDialog("提示", $"开始上传至服务器[{selectedPackageNames}]！", "Yes", "No"))
            {
                Stary.Evo.Editor.FileUtility.CopyDirectory(
                    $"{AssetBundleBuilderHelper.GetDefaultBuildOutputRoot()}/{EditorUserBuildSettings.activeBuildTarget}/{BuildAssetDataSetting.packageName}/{BuildAssetDataSetting.packageVersion}",
                    updateServerPath);
                CreatePackageVersionJson();
                
                
                BuildAssetDataSetting.GetBuildPackageVersion(true);
                
                EditorUtility.DisplayDialog("提示", $"上传服务器完成！", "确定");
            }
            else
            {
                Debug.LogWarning("[Update] 上传已经取消");
            }
        }

        #endregion
        
        protected void Init() 
        {
            //Update
            //检测Z盘
            _isCheckDriveExist = Stary.Evo.Editor.FileUtility.CheckDriveExists("Z");

            onBuildPipelineEntity =
                new BuildAssetEntity("打包", $"打包资源包【版本：{BuildAssetDataSetting.packageVersion}】", OnBuildPipeline);
            onUpdateBuildPipelineEntity =
                new BuildAssetEntity("更新", $"更新至服务器【版本：{BuildAssetDataSetting.packageVersion}】", OnUpdateBuildPipeline);
            
        }

        private Vector2 scroll;

        protected override void DrawEditor(int index)
        {
            scroll = GUILayout.BeginScrollView(scroll);
            {
                base.DrawEditor(index);
                BuildServerPath();
            }
            GUILayout.EndScrollView();
        }

        
        /// <summary>
        /// 生成服务器路径
        /// </summary>
        private void BuildServerPath()
        {
            if (!_isCheckDriveExist)
            {
                return;
            }
            updateServerPath =
                $"Z:/{Application.productName}/{BuildAssetDataSetting.packageName}/{EditorUserBuildSettings.activeBuildTarget}/{BuildAssetDataSetting.packageVersion}";
            if (!Directory.Exists(updateServerPath))
                Directory.CreateDirectory(updateServerPath);

            //更新Button文字
            onBuildPipelineEntity.SetButtonName($"打包资源包【版本：{BuildAssetDataSetting.packageVersion}】");
            onUpdateBuildPipelineEntity.SetButtonName($"更新至服务器【版本：{BuildAssetDataSetting.packageVersion}】");
        }

        private void CreatePackageVersionJson()
        {
            string mainResDomainPath = $"Assets/Domain/{selectedPackageNames}/Conf/HotfixMainResDomain.asset";
            HotfixMainResDomain mainResDomain  =
                AssetDatabase.LoadAssetAtPath<HotfixMainResDomain>(mainResDomainPath);
            
            if (mainResDomain != null)
            {
                mainResDomain.hotfixMainResDomainEntity.packageVersion = BuildAssetDataSetting.packageVersion;
                mainResDomain.hotfixMainResDomainEntity.pathconfig =
                    $"{Application.productName}/{BuildAssetDataSetting.packageName}/{EditorUserBuildSettings.activeBuildTarget}/{BuildAssetDataSetting.packageVersion}";
            }

            AssetDatabase.Refresh();
            // 保存更改
            AssetDatabase.SaveAssets();
            string serverPath = $"Z:/HybridclrConfigData/{BuildAssetDataSetting.packageName}/{EditorUserBuildSettings.activeBuildTarget}/";
            //直接保存服务器路径下，本地不保存
            EditorFrameworkUtils.SaveJson(mainResDomain.hotfixMainResDomainEntity, serverPath, Application.productName);
        }
    }
}