using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;

public class ExporterWindow : EditorWindow
{
    public static void OpenExporterWindow() {
        ExporterWindow win = EditorWindow.GetWindow<ExporterWindow>();
        win.Show();
    }

    ExporterCfg config;
    BuildRules ruleConfig;
    private void OnEnable()
    {
        config = Exporter.LoadConfig();
        ruleConfig = Exporter.LoadRules();
    }

    void OpenBuildRuleWindow()
    {
        BuildRuleWindow.OpenWindow();
    }

    private void OnGUI()
    {
        EditorGUILayout.BeginVertical(EditorStyles.helpBox);

        EditorGUILayout.BeginHorizontal(EditorStyles.helpBox);
        EditorGUILayout.LabelField("打包目录:", GUILayout.Width(150));
        EditorGUILayout.LabelField(config.AssetFolderName);
        
        if (GUILayout.Button("...", GUILayout.Width(100)))
        {
            string outpath = EditorUtility.OpenFolderPanel("选中要打包的目录", config.AssetFolderName, "");
            if (!string.IsNullOrEmpty(outpath))
            {
                outpath = outpath.Replace(Application.dataPath + "/", "");
                config.AssetFolderName = outpath;
            }
        }
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.Space(10);
        //输出路径
        config.ExportToStreamingAsset = EditorGUILayout.Toggle("打包到streamingassets", config.ExportToStreamingAsset);
        if (!config.ExportToStreamingAsset)
        {
            EditorGUILayout.BeginHorizontal(EditorStyles.helpBox);
            EditorGUILayout.LabelField("输出路径:", GUILayout.Width(150));
            EditorGUILayout.LabelField(config.ResultPath);
            if (GUILayout.Button("...", GUILayout.Width(100)))
            {
                string outpath = EditorUtility.OpenFolderPanel("选中生成路劲", config.ResultPath, "");
                if (!string.IsNullOrEmpty(outpath))
                {
                    config.ResultPath = outpath;
                }
            }
            EditorGUILayout.EndHorizontal();
        }




        EditorGUILayout.Space(10);
        config.assetbundleInputType = (AssetBundleInputType)EditorGUILayout.EnumPopup("AssetBundle输入类型", config.assetbundleInputType);
        if (config.assetbundleInputType == AssetBundleInputType.Random)
        {

            EditorGUILayout.BeginVertical(EditorStyles.helpBox);
            EditorGUILayout.LabelField("忽略的文件后缀名");
            for (int i = 0; i < config.ignorestuffixes.Count; i++)
            {
                EditorGUILayout.BeginHorizontal();
                config.ignorestuffixes[i] = EditorGUILayout.TextField(config.ignorestuffixes[i]);
                if (GUILayout.Button("-"))
                {
                    config.ignorestuffixes.RemoveAt(i);
                }
                EditorGUILayout.EndHorizontal();
            }
            if (GUILayout.Button("+"))
            {
                config.ignorestuffixes.Add("");
            }
            EditorGUILayout.EndVertical();

            EditorGUILayout.Space(10);

            EditorGUILayout.BeginVertical(EditorStyles.helpBox);
            EditorGUILayout.LabelField("忽略的文件");
            for (int i = 0; i < config.ignorefiles.Count; i++)
            {
                EditorGUILayout.BeginHorizontal();
                Object pathobj = AssetDatabase.LoadAssetAtPath(config.ignorefiles[i], typeof(Object));
                pathobj = EditorGUILayout.ObjectField(pathobj, typeof(Object), true);
                config.ignorefiles[i] = AssetDatabase.GetAssetPath(pathobj);//
                EditorGUILayout.LabelField(config.ignorefiles[i]);
                if (GUILayout.Button("-"))
                {
                    config.ignorefiles.RemoveAt(i);
                }
                EditorGUILayout.EndHorizontal();
            }
            if (GUILayout.Button("+"))
            {
                config.ignorefiles.Add("");
            }
            EditorGUILayout.EndVertical();

            //场景
            EditorGUILayout.BeginVertical(EditorStyles.helpBox);
            EditorGUILayout.LabelField("场景");
            for (int i = 0; i < config.scenes.Count; i++)
            {
                EditorGUILayout.BeginHorizontal();
                SceneAsset pathobj = AssetDatabase.LoadAssetAtPath(config.scenes[i], typeof(SceneAsset)) as SceneAsset;
                pathobj = (SceneAsset)EditorGUILayout.ObjectField(pathobj, typeof(SceneAsset), true);
                config.scenes[i] = AssetDatabase.GetAssetPath(pathobj);//
                EditorGUILayout.LabelField(config.scenes[i]);
                if (GUILayout.Button("-"))
                {
                    config.scenes.RemoveAt(i);
                }
                EditorGUILayout.EndHorizontal();
            }
            if (GUILayout.Button("+"))
            {
                config.scenes.Add("");
            }
            EditorGUILayout.EndVertical();

        }
        else
        {
            if (config.assetbundleInputType == AssetBundleInputType.Custom)
            {
                if(GUILayout.Button("编辑规则",GUILayout.Width(70),GUILayout.Height(40)))
                {
                    OpenBuildRuleWindow();
                }
                //EditorGUI.BeginChangeCheck();
                //EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                //EditorGUILayout.LabelField("规则");
                //var rules = ruleConfig.rules;

                //EditorGUILayout.BeginHorizontal();
                //EditorGUILayout.LabelField("default AB名：", ruleConfig.defaultRule.assetBundleName);
                //var defaultObj = AssetDatabase.LoadAssetAtPath(ruleConfig.defaultRule.searchPath, typeof(Object));
                //defaultObj = EditorGUILayout.ObjectField("路径：", defaultObj, typeof(Object), true);
                //if (ruleConfig.defaultRule.searchPath != AssetDatabase.GetAssetPath(defaultObj))
                //{
                //    var path = AssetDatabase.GetAssetPath(defaultObj).Replace("\\", "/");
                   
                //    ruleConfig.defaultRule.searchPath = path;
                //}
                //EditorGUILayout.EndHorizontal();

                //EditorGUILayout.BeginHorizontal();
                //EditorGUILayout.LabelField("shader AB名：", ruleConfig.shaderRule.assetBundleName);
                //var pathobj = AssetDatabase.LoadAssetAtPath(ruleConfig.shaderRule.searchPath, typeof(Object));
                //pathobj = EditorGUILayout.ObjectField("路径：", pathobj, typeof(Object), true);
                //if (ruleConfig.shaderRule.searchPath != AssetDatabase.GetAssetPath(pathobj))
                //{
                //    var path = AssetDatabase.GetAssetPath(pathobj).Replace("\\", "/");
                //    ruleConfig.shaderRule.assetBundleName = path.Substring(path.LastIndexOf("/") + 1).ToLower();
                //    ruleConfig.shaderRule.searchPath = path;
                //}
                //EditorGUILayout.EndHorizontal();
                //var lst = EditorGUIUtility.labelWidth;
                //EditorGUIUtility.labelWidth = 50;

               
                //for (int i = 0; i < rules.Count; i++)
                //{
                //    EditorGUILayout.BeginHorizontal();
                //    rules[i].isMultiPiece = EditorGUILayout.ToggleLeft("多个AB", rules[i].isMultiPiece, GUILayout.MaxWidth(70));
                //    if (rules[i].isMultiPiece)
                //        rules[i].assetBundleName = EditorGUILayout.TextField("AB目录：", rules[i].assetBundleName, GUILayout.MaxWidth(150));
                //    else
                //        rules[i].assetBundleName = EditorGUILayout.TextField("AB名：",rules[i].assetBundleName, GUILayout.MaxWidth(150));
                //    rules[i].sharedAssetBundle = EditorGUILayout.TextField("共享AB：", rules[i].sharedAssetBundle, GUILayout.MaxWidth(150));
                //    rules[i].searchPattern = EditorGUILayout.TextField("通配符：", rules[i].searchPattern, GUILayout.MaxWidth(100));
                //    var shaderpathobj = AssetDatabase.LoadAssetAtPath(rules[i].searchPath, typeof(Object));
                //    EditorGUI.BeginChangeCheck();
                //    shaderpathobj = EditorGUILayout.ObjectField("路径：", shaderpathobj, typeof(Object), true);
                //    if (EditorGUI.EndChangeCheck())
                //    {
                //        var path = AssetDatabase.GetAssetPath(shaderpathobj).Replace("\\", "/");
                //        rules[i].assetBundleName = path.Substring(path.LastIndexOf("/") + 1).ToLower();
                //        rules[i].searchPath = path;
                //    }
                //    EditorGUILayout.LabelField(rules[i].searchPath);
                //    if (GUILayout.Button("-"))
                //    {
                //        rules.RemoveAt(i);
                //    }
                //    EditorGUILayout.EndHorizontal();
                //}

                //EditorGUILayout.BeginHorizontal();
                //if (GUILayout.Button("+"))
                //{
                //    ruleConfig.rules.Add(new BuildRule());
                //}
                //if (GUILayout.Button("规则生成结果"))
                //{
                //    ruleConfig.Apply();
                //    config.Save();
                //}
                //EditorGUILayout.EndHorizontal();

                //EditorGUILayout.EndVertical();
                //EditorGUIUtility.labelWidth = lst;
                //if(EditorGUI.EndChangeCheck())
                //{

                //}
            }
            else
            {
                config.autoAssignBundleName = EditorGUILayout.Toggle("避免重复依赖", config.autoAssignBundleName);
            }
        }

		EditorGUILayout.Space(10);

        config.incrementalAB = EditorGUILayout.Toggle("增量打包(不重新收集资产数据，调试时用。)", config.incrementalAB);
        using (new EditorGUI.DisabledScope(config.incrementalAB))
        {
            config.clearfolder = EditorGUILayout.Toggle("清空打包路径", config.clearfolder);
            config.deleteManifestAfter = EditorGUILayout.Toggle("删除Manifest", config.deleteManifestAfter);
        }

        config.lastBuildTarget = (BuildTarget)EditorGUILayout.EnumPopup("目标平台", (BuildTarget)config.lastBuildTarget);

        if (EditorUtility.IsDirty(config))
        {
            EditorUtility.SetDirty(config);
        }

        EditorGUILayout.BeginHorizontal();
        //if (GUILayout.Button("ClearAll", GUILayout.Height(40)))
        //{
        //    Exporter.ClearAll();
        //    GUIUtility.ExitGUI();
        //}

        if (GUILayout.Button("Build", GUILayout.Height(40)))
        {
            if (config.clearfolder) {
                Exporter.ClearAll();
            }
            if (config.assetbundleInputType == AssetBundleInputType.Random)
            {
                Exporter.CreateABForAssetFolder(config.lastBuildTarget, true);
            }
            else if (config.assetbundleInputType == AssetBundleInputType.AssetBundleBrowser)
            {
                Exporter.CreateABForAssetBundleBrowser(config.lastBuildTarget);
            }
            else if (config.assetbundleInputType == AssetBundleInputType.Custom)
            {
                Exporter.CreateABForAssetFolderRule(config.lastBuildTarget, config.incrementalAB ? false: config.deleteManifestAfter, config.incrementalAB ? false :config.clearfolder,"",config.incrementalAB);
            }
            //AssetBundleBuilder.Build((BuildTarget)BuildPlatform, BuildOptions);
            GUIUtility.ExitGUI(); // Fix "EndLayoutGroup: BeginLayoutGroup must be called first" issue
        }

        /*if (GUILayout.Button("Build(win)", GUILayout.Height(40)))
        {
            Exporter.CreateABForAssetFolder(BuildTarget.StandaloneWindows64, true);
            //AssetBundleBuilder.Build((BuildTarget)BuildPlatform, BuildOptions);
            GUIUtility.ExitGUI(); // Fix "EndLayoutGroup: BeginLayoutGroup must be called first" issue
        }
        if (GUILayout.Button("Build(android)", GUILayout.Height(40)))
        {
            Exporter.CreateABForAssetFolder(BuildTarget.Android, true);
            //AssetBundleBuilder.Build((BuildTarget)BuildPlatform, BuildOptions);
            GUIUtility.ExitGUI(); // Fix "EndLayoutGroup: BeginLayoutGroup must be called first" issue
        }
        if (GUILayout.Button("Build(ios)", GUILayout.Height(40)))
        {
            Exporter.CreateABForAssetFolder(BuildTarget.iOS, true);
            //AssetBundleBuilder.Build((BuildTarget)BuildPlatform, BuildOptions);
            GUIUtility.ExitGUI(); // Fix "EndLayoutGroup: BeginLayoutGroup must be called first" issue
        }*/
        CustomBuild = GUILayout.Toggle(CustomBuild,"单独打包",GUI.skin.button, GUILayout.Height(40));
        if (GUILayout.Button("显示ab包", GUILayout.Height(40)))
        {
            ShowABWindow.Open();
            //Exporter.LoadConfig();
            //buildrules = Exporter.LoadRules();
        }

        if (GUILayout.Button("拷贝资源到StreamingAsset(打整包时使用)", GUILayout.Height(40))) {
            Exporter.CopytoStreamingAssets(config.lastBuildTarget);
            //return;

            //Exporter.CopytoStreamingAssetsNew(BuildTarget.StandaloneWindows64);
            //Exporter.CopytoStreamingAssetsNew(BuildTarget.iOS);
            //Exporter.CopytoStreamingAssetsNew(BuildTarget.Android);
        }
       
        //if (GUILayout.Button("显示未标记ab资源", GUILayout.Height(40)))
        //{
        //    ShowNoMarkAbResource.Open(config.lastBuildTarget);

        //}
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.EndVertical();

        if(CustomBuild)
            OnGUI_CustomBuildAssetBundle();
    }

    

    bool CustomBuild = false;
    string SearchString;
    Vector2 scrollviewpos = new Vector2();
    public void OnGUI_CustomBuildAssetBundle()
    {
        if (ruleConfig == null)
            return;

        SearchString = EditorGUILayout.TextField(SearchString);
        var assetbundle = ruleConfig.GetBuilds();
        scrollviewpos = EditorGUILayout.BeginScrollView(scrollviewpos);
        foreach (var b in assetbundle)
            if (string.IsNullOrEmpty(SearchString) || b.assetBundleName.Contains(SearchString))
            OnGUI_SingleAssetBundle(b);


        EditorGUILayout.EndScrollView();

        
    }
    Dictionary<string, bool> toggle = new Dictionary<string, bool>();
    public void OnGUI_SingleAssetBundle(AssetBundleBuild b)
    {
        EditorGUILayout.BeginVertical(GUI.skin.box);
        EditorGUILayout.BeginHorizontal();

        bool open = false;
        if (!toggle.TryGetValue(b.assetBundleName, out open))
            toggle.Add(b.assetBundleName, false);

        toggle[b.assetBundleName] = EditorGUILayout.Foldout(open, $"包名:{b.assetBundleName}");

        //EditorGUILayout.LabelField();
        EditorGUILayout.LabelField("文件数量:", b.assetNames.Length.ToString());

        if(GUILayout.Button($"打包({b.assetBundleName})"))
        {
            var outputPath = Exporter.GetOutputPath(config.lastBuildTarget);
            if(!Directory.Exists(outputPath))
            {
                Directory.CreateDirectory(outputPath);
            }
            BuildPipeline.BuildAssetBundles(outputPath, new AssetBundleBuild[] { b }, config.lastBuildOptions, config.lastBuildTarget);
        }
        EditorGUILayout.EndHorizontal();

        if (open)
        {
            EditorGUI.indentLevel++;
            EditorGUILayout.BeginVertical();
            for (int i = 0; i < b.assetNames.Length; i++)
            {
                EditorGUILayout.TextField($"{b.assetNames[i]}");
            }
            EditorGUILayout.EndVertical();
            EditorGUI.indentLevel--;
        }
        EditorGUILayout.EndVertical();

    }

    private void OnDisable()
    {
        EditorUtility.SetDirty(config);
    }
}
