using Assets.Native.tools.excel.Model;
using Assets.Native.tools.excel.Util;
using ClosedXML.Excel;
using CommonUtil;
using EditorUtils;
using iHuman.UnitySz.Framework;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using static iHuman.UnitySz.Framework.ResLinkAsset;

public class ExpandCreator
{
    const string artPathRoot = "Assets/art/game/expand/";
    const string scriptPathRoot = "Assets/gamesrc/expand/";
    const string templatePath = "Assets/gamesrc/expand/template/expandTemplate.lua";
    const string svnProcPath = "C:\\Program Files\\TortoiseSVN\\bin\\TortoiseProc.exe";

    [MenuItem("Assets/自定义创建/拓环节/创建文件")]
    public static void createNewExpand()
    {
        string[] strs = Selection.assetGUIDs;

        if (strs != null)
        {
            foreach (string str in strs)
            {
                string id = GetID(str);
                if (!String.IsNullOrEmpty(id))
                {
                    CreateSoundAsset(id);
                    CreateSrcFolder(id);
                    CreateRegisterFile(id);
                    var gamesrcFolder = Path.Combine(scriptPathRoot, @$"expand{id}");
                    //创建reslink文件
                    var expandResLinkName = $"expand{id}reslink.asset";
                    string expandResFolder = Path.Combine(artPathRoot, @$"expand{id}");
                    var expandResLinkPath = Path.Combine(gamesrcFolder, expandResLinkName);
                    if (!File.Exists(expandResLinkPath))
                    {
                        UnityEngine.Debug.Log("[创建reslink文件]" + expandResLinkPath);
                        ResLinkAsset asset = ScriptableObject.CreateInstance<ResLinkAsset>();
                        //加载SCENE
                        string expandScenePath = Path.Combine(expandResFolder, @$"expand{id}.unity");
                        var obj = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(expandScenePath);
                        var item = new Item { Key = "SCENE", Val = obj };
                        asset.assets.Add(item);
                        AddAssets(asset, expandResFolder);
                        // 保存ScriptableObject资源
                        AssetDatabase.CreateAsset(asset, expandResLinkPath);
                        ResLinkEditor.Save(asset);
                    }
                    else
                    {
                        ResLinkAsset asset = AssetDatabase.LoadAssetAtPath<ResLinkAsset>(expandResLinkPath);
                        AddAssets(asset, expandResFolder);
                        ResLinkEditor.Save(asset);
                        EditorUtility.SetDirty(asset);
                        AssetDatabase.SaveAssets();
                    }
                    AssetDatabase.Refresh();
                }
                else
                {
                    var assetPath = AssetDatabase.GUIDToAssetPath(str);
                    UnityEngine.Debug.LogWarning(@$"所选{assetPath}不合法");
                }
            }
        }

    }

    public static void AddAssets(ResLinkAsset asset, string path)
    {
        //加载sound
        var soundDir = Path.Combine(path, "sound");
        UnityEngine.Debug.Log($"soundDir:{soundDir}");
        AddAsset(asset, soundDir, "*.ogg");
    }


    public static void AddAsset(ResLinkAsset asset, string dirPath, string extension = null)
    {
        if (Directory.Exists(dirPath))
        {
            string[] paths = null;
            if(string.IsNullOrEmpty(extension))
            {
                paths = Directory.GetFiles(dirPath);
            }
            else
            {
                paths = Directory.GetFiles(dirPath, extension);
            }
            foreach (string path in paths)
            {
                string key = Path.GetFileNameWithoutExtension(path);
                if (!Contains(asset.assets, key))
                {
                    var obj = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(path);
                    if(obj == null)
                    {
                        // 强制Unity重新导入资源
                        AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);

                        // 刷新编辑器，确保更改被识别
                        AssetDatabase.Refresh();
                        obj = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(path);
                    }
                    if (obj is Texture2D)
                    {
                        obj = AssetDatabase.LoadAssetAtPath<Sprite>(path);
                    }
                    if(asset.Contains(key)){
                        
                    }else{
                        var item = new Item { Key = key, Val = obj };
                        asset.assets.Add(item);
                    }
                }

            }
        }
    }

    public static void CreateSrcFolder(string id)
    {
        var gamesrcFolder = Path.Combine(scriptPathRoot, @$"expand{id}");

        if (!Directory.Exists(gamesrcFolder))
        {
            UnityEngine.Debug.Log("[创建目录]" + gamesrcFolder);
            Directory.CreateDirectory(gamesrcFolder);
        }
    }

    public static void CreateRegisterFile(string id){
        var gamesrcFolder = Path.Combine(scriptPathRoot, @$"expand{id}");

        //创建register文件
        var expandRegisterName = $"Expand{id}register.lua";
        var expandRegisterPath = Path.Combine(gamesrcFolder, expandRegisterName);
        if (!File.Exists(expandRegisterPath))
        {
            UnityEngine.Debug.Log("[创建expandRegisterPath文件]" + expandRegisterPath);
            var realId = int.Parse(id).ToString();
            var a = $@"SceneCfg.addSubScene(""Expand"", ""Expand{id}"", {{""gamesrc/expand/expand{id}/Expand{id}"", ""拓游戏{realId}"", ""_dir"" }})";
            using (StreamWriter writer = new StreamWriter(expandRegisterPath, false, Encoding.Default))
            {
                writer.Write(a);
                writer.Flush();
            }
        }
    }

    [MenuItem("Assets/自定义创建/拓环节/加载音频文件(覆盖)")]
    public static void CreateSoundAsset()
    {
        string[] strs = Selection.assetGUIDs;

        if (strs != null)
        {
            foreach (string str in strs)
            {
                string id = GetID(str);
                if (!String.IsNullOrEmpty(id))
                {
                    CreateSoundAsset(id, true);
                }
                else
                {
                    var assetPath = AssetDatabase.GUIDToAssetPath(str);
                    UnityEngine.Debug.LogWarning(@$"所选{assetPath}不合法");
                }
            }
        }
    }

    /// <summary>
    /// 拉取音频资源
    /// </summary>
    /// <param name="id"> ID </param>
    /// <param name="isNeedCover"> 是否需要覆盖 </param>
    public static void CreateSoundAsset(string id, bool isNeedCover = false)
    {
        var destinationFolder = Path.Combine(artPathRoot, @$"expand{id}/sound");
        string svnPath = @$"https://10.3.254.33/repos/hongen_read/product/sound/拓/{id}";
        CheckoutFolder(svnPath, destinationFolder, isNeedCover);
    }

    public static void CheckoutFolder(string svnPath, string destFolder, bool isNeedCover = false)
    {

        if (isNeedCover && Directory.Exists(destFolder))
        {
            Directory.Delete(destFolder, true);
        }

        if (!Directory.Exists(destFolder))
        {
            Directory.CreateDirectory(destFolder);
        }

        string sourceFolder = SvnUtil.getDir(svnPath, "files");
        if (String.IsNullOrEmpty(sourceFolder))
        {
            UnityEngine.Debug.Log(@$"{svnPath}不存在。");
        }
        else
        {
            string[] files = Directory.GetFiles(sourceFolder);
            foreach (string file in files)
            {
                string fileName = Path.GetFileName(file);
                string destinationPath = Path.Combine(destFolder, fileName);
                if (!File.Exists(destinationPath))
                {
                    File.Move(Path.Combine(sourceFolder, fileName), destinationPath);
                }
            }
            AssetDatabase.Refresh();
            UnityEngine.Debug.Log("资源克隆完成。");
        }

    }

    [MenuItem("Assets/自定义创建/拓环节/定位Src")]
    public static void PingSrcFolder()
    {

        string assetGUID = Selection.assetGUIDs[0];
        string id = GetID(assetGUID);
        if (!String.IsNullOrEmpty(id))
        {
            DirUtil.skipToDir(Path.Combine(scriptPathRoot, @$"expand{id}"));
        }
        else
        {
            DirUtil.skipToDir(scriptPathRoot);
        }

    }

    [MenuItem("Assets/自定义创建/拓环节/定位Art")]
    public static void PingArtFolder()
    {

        string assetGUID = Selection.assetGUIDs[0];
        string id = GetID(assetGUID);
        if (!String.IsNullOrEmpty(id))
        {
            DirUtil.skipToDir(Path.Combine(artPathRoot, @$"expand{id}"));
        }
        else
        {
            DirUtil.skipToDir(artPathRoot);
        }

    }

    public static string GetID(string assetGUID)
    {
        var folderName = AssetDatabase.GUIDToAssetPath(assetGUID);
        if (!AssetDatabase.IsValidFolder(folderName))
        {
            folderName = Path.GetDirectoryName(folderName);
        }
        Match match = Regex.Match(folderName, @"\d+"); // 匹配一个或多个数字
        string id = match.Success ? match.Value : "";
        return id;
    }

    static public bool Contains(List<Item> assets, string key)
    {
        if (String.IsNullOrEmpty(key))
        {
            return false;
        }
        foreach (Item asset in assets)
        {
            if (asset.Key == key)
            {
                return true;
            }
        }
        return false;
    }
    [MenuItem("Assets/自定义创建/拓环节/svn提交")]
    public static void ExpandCommit(){
        string[] strs = Selection.assetGUIDs;

        if (strs != null)
        {
            foreach (string str in strs)
            {
                string id = GetID(str);
                if (!String.IsNullOrEmpty(id))
                {
                    //提交src和 提交art
                    string expandSrcFolder = Path.Combine(scriptPathRoot, @$"expand{id}");
                    string expandResFolder = Path.Combine(artPathRoot, @$"expand{id}");
                    _commit(expandResFolder);
                    _commit(expandSrcFolder);
                }
            }
        }
    }

    public static void _commit(string dirPath){
        string command = "commit";
        ProcessStartInfo startInfo = new ProcessStartInfo
        {
            FileName = svnProcPath,
            Arguments = $"/command:{command} /path:\"{dirPath}\" /closeonend:0",
            UseShellExecute = false,
            CreateNoWindow = true
        };
        Process process = new Process { StartInfo = startInfo };
        process.Start();
    }
    public static void DeleteKey(List<ResLinkAsset.Item> asset, string key){
        foreach(ResLinkAsset.Item item in asset){
            if(item.Key == key){
                //把这个key直接删除
                asset.Remove(item);
                break;
            }
        }
    }
}

