// 穿越环节配置文件生成器
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.Linq;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using static iHuman.UnitySz.Framework.ResLinkAsset;

public class ThroughGen
{
    const string artPathRoot = "Assets/art/game/gushi/through/";
    const string commonArtPath = "Assets/art/game/gushi/through/common";
    const string codePathRoot = "Assets/gamesrc/poetry/through";
    public static string svnSoundRootPath = "https://10.3.254.33/repos/hongen_read/product/sound/古诗/2穿越";
    [MenuItem("Assets/自定义创建/古诗/去穿越reslink")]
    public static void genThroughResLink() {
        string[] strs = Selection.assetGUIDs;
        string trunkPath = System.Environment.CurrentDirectory;
        if (strs != null)
        {
            foreach (string str in strs)
            {
                string id = GetID(str);
                // string dstSoundPath = Path.Combine(trunkPath, artPathRoot, $"{id}", "sound");
                // if(!Directory.Exists(dstSoundPath)){
                //     Directory.CreateDirectory(dstSoundPath);
                // }
                // CreateSoundAsset(id, dstSoundPath);
                genOneThroughReslink(id);
            }
            AssetDatabase.Refresh();
        }
    }

    public static void genOneThroughReslink(string id){
        if (!String.IsNullOrEmpty(id))
        {
            var gamesrcFolder = Path.Combine(codePathRoot, @$"{id}");
            if (!Directory.Exists(gamesrcFolder))
            {
                Debug.Log("[创建目录]" + gamesrcFolder);
                Directory.CreateDirectory(gamesrcFolder);
            }

            //创建reslink文件
            var practiceResLinkName = $"through{id}reslink.asset";
            string practiceResFolder = Path.Combine(artPathRoot, @$"{id}");
            string practiceResLinkPath = Path.Combine(gamesrcFolder, practiceResLinkName);
            string practiceResLinkLuaPath = Path.Combine(gamesrcFolder, $"through{id}reslink.lua");
            if (File.Exists(practiceResLinkPath))
            {
                File.Delete(practiceResLinkPath);
            }
            if (!File.Exists(practiceResLinkPath))
            {
                Debug.Log("[创建reslink文件]" + practiceResLinkPath);
                ResLinkAsset asset = ScriptableObject.CreateInstance<ResLinkAsset>();

                AddAssets(asset, practiceResFolder);
                // 保存ScriptableObject资源
                AssetDatabase.CreateAsset(asset, practiceResLinkPath);
                ResLinkEditor.Save(asset);
            }
        }
    }

    public static void CreateSoundAsset(string id, string dstSoundPath){

        //V01
        string svnSoundV01Path = svnSoundRootPath + $"/古诗去穿越召唤诗人/{id}_V01.ogg";
        _CopyOneFile(svnSoundV01Path, dstSoundPath + $"/{id}_V01.ogg");
    }
    public static bool _CopyOneFile(string svnFilePath, string dstFilePath){
        if(!SvnUtil.isExit(svnFilePath)){
            return false;
        }
        string filePath = SvnUtil.getFile(svnFilePath);
        if(filePath != null){
            
            if(File.Exists(dstFilePath)){
                File.Delete(dstFilePath);
            }
            File.Move(filePath, dstFilePath);
            return true;
        }
        return false;
    }

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

        //加载视频
        // var videoDir = Path.Combine(path, "video");
        // Debug.Log($"videoDir:{videoDir}");
        // AddAsset(asset, videoDir, "*.mp4");
        // AddAsset(asset, videoDir, "*.txt");

        //加载scene
    }

    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 (!path.EndsWith(".meta") && !asset.Contains(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);
                    }

                    var item = new Item { Key = key, Val = obj };
                    asset.assets.Add(item);
                }

            }
        }
    }
    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;
    }

}