using Assets.Native.tools.excel.Util;
using CommonUtil;
using iHuman.UnitySz.Framework;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using TMPro;
using UnityEditor.SceneManagement;
using Assets.Native.tools.excel.Model;
using UnityEngine.SceneManagement;
using UnityEditor.TestTools.TestRunner.Api;
using Newtonsoft.Json;
using EditorUtils;
using System;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Linq;

public class SayCreator
{
    const string artPathRoot = "Assets/art/game/say";
    const string scriptPathRoot = "Assets/gamesrc/say";
    const string fontPath = "Assets/art/app/fonts/fangzhengcuyuan.ttf";
    const string labaPath = "Assets/art/game/say/common/prefab/laba.prefab";

    // [MenuItem("Assets/自定义创建/say/批处理执行(慎用)")]
    public static void createAllSayFont()
    {
        var dirList = Directory.GetDirectories(artPathRoot, "say*");
        foreach (var dir in dirList)
        {
            string sayId = DirUtil.getSayId(dir);
            if (sayId == null)
            {
                Debug.LogError("sayId is null at path: " + dir);
                return;
            }
            // creatLabaFont(sayId);
            // createSayResLink(sayId);
            // delSlider(sayId);
            createLabaLuaFile(sayId, true);
            // delTalkController(sayId);
            // createSayLabaConfig(sayId);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
    }

    // [MenuItem("Assets/自定义创建/say/delTalkController")]
    public static void delTalkController()
    {
        string curPath = DirUtil.getCurPath();
        string sayId = DirUtil.getSayId(curPath);
        if (sayId == null)
        {
            Debug.LogError("sayId is null at path: " + curPath);
            return;
        }
        delTalkController(sayId);
    }

    public static void delTalkController(string sayId)
    {
        string dirPath = string.Format("say{0}", sayId);
        var scenePath = Path.Combine(artPathRoot, dirPath, $"{dirPath}.unity");
        if (!File.Exists(scenePath))
        {
            return;
        }

        Scene scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive);
        GameObject[] rootObjects = scene.GetRootGameObjects();
        foreach (GameObject rootObject in rootObjects)
        {
            // TalkController[] TalkControllerList = rootObject.GetComponentsInChildren<TalkController>(true);
            // foreach (var talkController in TalkControllerList)
            // {
            //     var gameObject = talkController.gameObject;
            //     var sr = gameObject.GetComponent<UnityEngine.Timeline.SignalReceiver>();
            //     if (sr != null)
            //     {
            //         GameObject.DestroyImmediate(sr, true);
            //     }
            //     GameObject.DestroyImmediate(talkController, true);
            //     EditorUtility.SetDirty(gameObject);
            // }
        }
        EditorSceneManager.MarkSceneDirty(scene);
        EditorSceneManager.SaveScene(scene);
        EditorSceneManager.CloseScene(scene, true);

        var v01Path = Path.Combine(artPathRoot, dirPath, "V01.prefab");
        if (!File.Exists(v01Path))
        {
            return;
        }
        GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(v01Path);

        if (prefab != null)
        {
            // TalkController[] TalkControllerList = prefab.GetComponentsInChildren<TalkController>(true);
            // foreach (var talkController in TalkControllerList)
            // {
            //     var gameObject = talkController.gameObject;
            //     var sr = gameObject.GetComponent<UnityEngine.Timeline.SignalReceiver>();
            //     if (sr != null)
            //     {
            //         GameObject.DestroyImmediate(sr, true);
            //     }
            //     GameObject.DestroyImmediate(talkController, true);
            //     EditorUtility.SetDirty(gameObject);
            // }
            // EditorUtility.SetDirty(prefab);
        }


        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();

    }

    private static void CopyWorksheet(ClosedXML.Excel.IXLWorksheet source, ClosedXML.Excel.IXLWorksheet destination)
    {
        // 复制所有单元格的内容
        foreach (var sourceCell in source.CellsUsed())
        {
            var destinationCell = destination.Cell(sourceCell.Address.RowNumber, sourceCell.Address.ColumnNumber);

            // 复制值
            destinationCell.Value = sourceCell.Value;

            // 复制样式
            destinationCell.Style = sourceCell.Style;
            if (sourceCell.Value.ToString() == "声音编号" || sourceCell.Value.ToString() == "录音内容")
            {
                destinationCell.Style.Font.FontColor = ClosedXML.Excel.XLColor.White;
            }

            // destinationCell.Style.Font.Bold = sourceCell.Style.Font.Bold;
            // destinationCell.Style.Font.FontColor = sourceCell.Style.Font.FontColor;
            // destinationCell.Style.Font.FontSize = sourceCell.Style.Font.FontSize;
            // destinationCell.Style.Font.FontName = sourceCell.Style.Font.FontName;
            // destinationCell.Style.Fill.BackgroundColor = sourceCell.Style.Fill.BackgroundColor;
            // destinationCell.Style.Border.BottomBorder = sourceCell.Style.Border.BottomBorder;
            // destinationCell.Style.Border.TopBorder = sourceCell.Style.Border.TopBorder;
            // destinationCell.Style.Border.LeftBorder = sourceCell.Style.Border.LeftBorder;
            // destinationCell.Style.Border.RightBorder = sourceCell.Style.Border.RightBorder;
            // destinationCell.Style.NumberFormat.Format = sourceCell.Style.NumberFormat.Format;
            // 复制行高
            foreach (var row in source.RowsUsed())
            {
                var destinationRow = destination.Row(row.RowNumber());
                destinationRow.Height = row.Height;
            }

            // 复制列宽
            foreach (var column in source.ColumnsUsed())
            {
                var destinationColumn = destination.Column(column.ColumnNumber());
                destinationColumn.Width = column.Width;
            }

            // 可以添加更多样式属性的复制，如果需要
        }
    }
    public static void CopyExcelFile(string sourceFilePath)
    {
        // 打开源工作簿
        using (var sourceWorkbook = new ClosedXML.Excel.XLWorkbook(sourceFilePath))
        {
            // 创建目标工作簿
            using (var destinationWorkbook = new ClosedXML.Excel.XLWorkbook())
            {
                // 遍历源工作簿中的所有工作表
                foreach (var sourceWorksheet in sourceWorkbook.Worksheets)
                {
                    // 在目标工作簿中添加一个新的工作表
                    var destinationWorksheet = destinationWorkbook.Worksheets.Add(sourceWorksheet.Name);
                    CopyWorksheet(sourceWorksheet, destinationWorksheet);
                }
                File.Delete(sourceFilePath);
                // 保存目标工作簿
                destinationWorkbook.SaveAs(sourceFilePath);
            }
        }
    }

    static void CleanNullValues(ClosedXML.Excel.IXLWorksheet worksheet)
    {
        foreach (var cell in worksheet.CellsUsed())
        {
            cell.Style.Alignment.WrapText = true; // 设置自动换行
            cell.Style.Fill.PatternType = ClosedXML.Excel.XLFillPatternValues.None; // 重置填充模式为无
        }
    }

    // [MenuItem("Assets/自定义创建/say/getip")]
    public static void getIp()
    {
        var dirList = Directory.GetDirectories(artPathRoot, "say*");
        Dictionary<string, int> dic = new Dictionary<string, int>();
        foreach (var dir in dirList)
        {
            string sayId = DirUtil.getSayId(dir);
            if (sayId == null)
            {
                Debug.LogError("sayId is null at path: " + dir);
                return;
            }
            dic.Add(sayId, getIpName(sayId));
        }
        // dic.Add("0005", 1);
        int index = 1;
        string excelDir = "F:/ihuman/hongen_read/SVN/product/口语表达音频脚本";
        // foreach (var file in Directory.GetFiles(excelDir))
        // {
        //     string fileName = Path.GetFileName(file);
        //     string sayId = fileName.Substring(0, 4);
        //     index = index + 1;
        //     addExcelCommonInfo(file, sayId, dic[sayId]);
        // }
        string excelFile = "F:/ihuman/hongen_read/SVN/product/ip.xlsx";
        if (File.Exists(excelFile))
        {
            File.Delete(excelFile);
        }

        using (var ipWorkbook = new ClosedXML.Excel.XLWorkbook())
        {
            var common = ipWorkbook.AddWorksheet("common");
            common.Cell(1, 1).Value = "sayId";
            common.Cell(1, 2).Value = "roleId(1彩虹 2风暴 3闪电  4流星)";
            common.Cell(1, 3).Value = "totalRound(问题数 默认是4)";
            // int index = 1;
            foreach (var file in Directory.GetFiles(excelDir))
            {
                index = index + 1;
                string fileName = Path.GetFileName(file);
                string sayId = fileName.Substring(0, 4);
                if (!dic.ContainsKey(sayId))
                {
                    continue;
                }
                common.Cell(index, 1).Value = sayId;
                common.Cell(index, 2).Value = dic[sayId];
                common.Cell(index, 3).Value = sayId == "0005" ? 3 : 4;
                bool isAdd = addExcelCommonInfo(file, sayId, dic[sayId]);
                common.Cell(index, 4).Value = isAdd ? "已导出" : "";
                if (!isAdd)
                {
                    common.Cell(index, 4).Style.Fill.BackgroundColor = ClosedXML.Excel.XLColor.Red;
                }
            }
            // 保存工作簿
            ipWorkbook.SaveAs(excelFile);
        }
    }

    public static bool addExcelCommonInfo(string filePath, string sayId, int roleId)
    {
        // CopyExcelFile(filePath);
        var workbook = ExcelUtil.GetWorkBook(filePath);

        ClosedXML.Excel.IXLWorksheet common;
        if (!workbook.TryGetWorksheet("common", out common))
        {
            common = workbook.Worksheets.Add("common");
        }
        common.Clear();
        common.Cell(1, 1).Value = "roleId(1彩虹 2风暴 3闪电  4流星)";
        common.Cell(1, 2).Value = "totalRound(问题数 默认是4)";
        common.Cell(2, 1).Value = roleId;
        common.Cell(2, 2).Value = sayId == "0005" ? 3 : 4;

        foreach (var column in common.ColumnsUsed())
        {
            column.Width = 30;
        }

        ClosedXML.Excel.IXLWorksheet pinyin;
        if (workbook.TryGetWorksheet("pinyin", out pinyin))
        {
            ClosedXML.Excel.IXLWorksheet laba;
            if (workbook.TryGetWorksheet("laba", out laba))
            {
                laba.Delete();
                pinyin.Name = "laba";
            }
        }
        try
        {
            workbook.Save();
            return roleId > 0;
        }
        catch
        {

        }
        return false;
    }

    public static int getIpName(string sayId)
    {
        string dirPath = string.Format("say{0}", sayId);
        string scenePath = Path.Combine(artPathRoot, dirPath, $"{dirPath}.unity");
        if (!File.Exists(scenePath))
        {
            return 0;
        }
        var scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive);
        GameObject[] rootObjects = scene.GetRootGameObjects();
        GameObject gameRoot = null;
        int id = 0;
        foreach (var rootObject in rootObjects)
        {
            if (rootObject.name == "GameRoot")
            {
                gameRoot = rootObject;
                List<GameObject> ipList = gameRoot._SearchPattern("ip_*", true);
                foreach (var ip in ipList)
                {
                    int addId = 0;
                    switch (ip.name)
                    {
                        case "ip_shandian":
                            addId = 3;
                            break;
                        case "ip_caihong":
                            addId = 1;
                            break;
                        case "ip_fengbao":
                            addId = 2;
                            break;
                        case "ip_liuxing":
                            addId = 4;
                            break;
                    }
                    if (id == 0)
                    {
                        id = id + addId;
                    }
                    else
                    {
                        if (addId > 0)
                        {
                            EditorSceneManager.CloseScene(scene, true);
                            return 0;
                        }

                    }
                }

            }
        }
        EditorSceneManager.CloseScene(scene, true);
        return id;
    }

    // [MenuItem("Assets/自定义创建/say/delSlider")]
    public static void delSlider()
    {
        string curPath = DirUtil.getCurPath();
        string sayId = DirUtil.getSayId(curPath);
        if (sayId == null)
        {
            Debug.LogError("sayId is null at path: " + curPath);
            return;
        }
        delSlider(sayId);
    }

    public static void delSlider(string sayId)
    {
        string dirPath = string.Format("say{0}", sayId);
        var scenePath = Path.Combine(artPathRoot, dirPath, $"{dirPath}.unity");
        if (!File.Exists(scenePath))
        {
            return;
        }

        List<LabaController> tList = new List<LabaController>();
        Scene scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive);
        GameObject[] rootObjects = scene.GetRootGameObjects();
        foreach (GameObject rootObject in rootObjects)
        {
            var Slider = rootObject.Seek("Slider");
            if (Slider != null)
            {
                GameObject.DestroyImmediate(Slider, true);
                break;
            }
        }
        EditorSceneManager.MarkSceneDirty(scene);
        EditorSceneManager.SaveScene(scene);
        EditorSceneManager.CloseScene(scene, true);

        var v01Path = Path.Combine(artPathRoot, dirPath, "V01.prefab");
        if (!File.Exists(v01Path))
        {
            return;
        }
        GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(v01Path);

        if (prefab != null)
        {
            var Slider = prefab.Seek("Slider");
            if (Slider != null)
            {
                GameObject.DestroyImmediate(Slider, true);
            }
            EditorUtility.SetDirty(prefab);
        }


        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();

    }

    // [MenuItem("Assets/自定义创建/say/生成laba字体文件")]
    public static void creatLabaFontByAsset()
    {
        string curPath = DirUtil.getCurPath();
        string sayId = DirUtil.getSayId(curPath);
        if (sayId == null)
        {
            Debug.LogError("sayId is null at path: " + curPath);
            return;
        }
        creatLabaFont(sayId);
    }

    [MenuItem("Assets/自定义创建/say/更新音频文件")]
    public static void updateSound()
    {
        string curPath = DirUtil.getCurPath();
        string sayId = DirUtil.getSayId(curPath);
        if (sayId == null)
        {
            Debug.LogError("sayId is null at path: " + curPath);
            return;
        }
        copySayAudio(sayId);
    }

    [MenuItem("Assets/自定义创建/say/Canvas层级检查")]
    public static void CheckCanvasLayer()
    {
        string curPath = DirUtil.getCurPath();
        string sayId = DirUtil.getSayId(curPath);
        if (sayId == null)
        {
            Debug.LogError("sayId is null at path: " + curPath);
            return;
        }
        string dirPath = string.Format("say{0}", sayId);
        string scenePath = Path.Combine(artPathRoot, dirPath, $"{dirPath}.unity");
        if (!File.Exists(scenePath))
        {
            return;
        }
        Scene scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive);
        GameObject[] rootObjects = scene.GetRootGameObjects();
        var gameRoot = rootObjects.Where(go => go.name == "GameRoot").FirstOrDefault();
        void SetLayerRecursively(GameObject go, int layer)
        {
            if (go == null)
            {
                return;
            }
            go.layer = layer;
            foreach (Transform child in go.transform)
            {
                if (null == child) continue;
                SetLayerRecursively(child.gameObject, layer);
            }
        }
        if (gameRoot == null)
        {
            Debug.LogError($"Say{sayId} GameRoot不存在");
            return;
        }
        var canvas = gameRoot.GetComponentInChildren<Canvas>();
        if (canvas == null)
        {
            Debug.LogError($"Say{sayId} Canvas不存在");
        }
        else
        {
            // if(canvas.rendercamera == null) {
            //     Debug.LogError($"Say{sayId} Canvas没有设置RenderCamera");
            // }
            if (canvas.renderMode != RenderMode.ScreenSpaceCamera)
            {
                // Debug.LogError($"Say{sayId} Canvas的RenderMode不是ScreenSpaceCamera");
                canvas.renderMode = RenderMode.ScreenSpaceCamera;
            }
            var camera = GameObject.Find("GameUICamera").GetComponent<Camera>();
            if (canvas.worldCamera != camera)
            {
                canvas.worldCamera = camera;
            }
            SetLayerRecursively(canvas.gameObject, LayerMask.NameToLayer("UI"));
        }
        Debug.Log($"Say{sayId} Canvas层级检查完成");
        EditorSceneManager.CloseScene(scene, true);
    }
    public static string PathReplace(string path)
    {
        return path.Replace('\\', '/');
    }

    public static void CopyDirectory(string sourceDir, string destinationDir)
    {
        sourceDir = PathReplace(sourceDir);
        destinationDir = PathReplace(destinationDir);
        if (Directory.Exists(destinationDir))
        {
            DirectoryInfo destinationDirectoryInfo = new DirectoryInfo(destinationDir);
            FileInfo[] destinationFiles = destinationDirectoryInfo.GetFiles();
            foreach (FileInfo file in destinationFiles)
            {
                string tempPath = Path.Combine(sourceDir, file.Name);
                if (!File.Exists(tempPath))
                {
                    File.Delete(tempPath);
                }
            }
        }

        // 获取源目录中的所有文件和子目录
        DirectoryInfo dir = new DirectoryInfo(sourceDir);
        DirectoryInfo[] dirs = dir.GetDirectories();

        // 如果目标目录不存在，则创建
        Directory.CreateDirectory(destinationDir);

        // 复制源目录中的所有文件
        FileInfo[] files = dir.GetFiles();
        foreach (FileInfo file in files)
        {
            string tempPath = Path.Combine(destinationDir, file.Name);
            file.CopyTo(tempPath, true);
        }

        // // 递归复制源目录中的所有子目录
        // foreach (DirectoryInfo subdir in dirs)
        // {
        //     string tempPath = Path.Combine(destinationDir, subdir.Name);
        //     CopyDirectory(subdir.FullName, tempPath);
        // }
    }

    public static void copySayAudio(string sayId)
    {
        string dirPath = string.Format("say{0}", sayId);
        string soundDir = Path.Combine(artPathRoot, dirPath, "sound");
        SvnUtil.update(soundDir);
        string svnDir = SvnUtil.getDir($"https://10.3.254.33/repos/hongen_read/product/sound/说/{sayId}", "files");
        if (!Directory.Exists(svnDir))
        {
            EditorUtility.DisplayDialog("", $"音频同学未上传{sayId}音频文件", "确认");
            return;
        }
        CopyDirectory(svnDir, soundDir);
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
        SvnUtil.commitFolder(soundDir, @$"{dirPath}:上传音效");
        EditorUtility.DisplayDialog("", "音频更新成功", "确认");
    }

    public static void creatLabaFont(string sayId)
    {
        string dirPath = string.Format("say{0}", sayId);
        string fontDir = Path.Combine(artPathRoot, dirPath, "font");
        if (Directory.Exists(fontDir))
        {
            Directory.Delete(fontDir, true);
        }
        var scenePath = Path.Combine(artPathRoot, dirPath, $"{dirPath}.unity");
        if (!File.Exists(scenePath))
        {
            return;
        }

        List<LabaController> tList = new List<LabaController>();
        Scene scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive);
        GameObject[] rootObjects = scene.GetRootGameObjects();
        foreach (GameObject rootObject in rootObjects)
        {
            LabaController[] TArray = rootObject.GetComponentsInChildren<LabaController>(true);
            tList.AddRange(TArray);
        }

        string labaStr = "";
        foreach (var labaController in tList)
        {
            labaController.UpdateLaba();
            labaStr = labaStr + labaController.KeyWord;
        }
        TMP_FontAsset fontAsset = TMP_FontAsset_CreationUtil.CreateFontAssetFromSelectedObject(new TextAsset(labaStr), AssetDatabase.LoadAssetAtPath<Font>(fontPath), fontDir, $"{sayId}_laba", 512, 512);
        // fontAsset.material.SetColor("_OutlineColor", new Color(0x3C / 255f, 0x98 / 255f, 0x5D / 255f));
        // fontAsset.material.SetFloat("_OutlineWidth", 0.25f);
        // EditorUtility.SetDirty(fontAsset.material);

        foreach (var labaController in tList)
        {
            labaController.fontAsset = fontAsset;
            labaController.UpdateLaba();
            EditorUtility.SetDirty(labaController);
        }


        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();

        EditorSceneManager.MarkSceneDirty(scene);
        EditorSceneManager.SaveScene(scene);
        EditorSceneManager.CloseScene(scene, true);
    }

    public static string getSceneTalkStr(string sceneGuid, TMP_FontAsset fontAsset = null)
    {
        string talkStr = "";
        string scenePath = AssetDatabase.GUIDToAssetPath(sceneGuid);
        Scene scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive);
        GameObject[] rootObjects = scene.GetRootGameObjects();
        foreach (GameObject rootObject in rootObjects)
        {
            // 遍历根 GameObject 及其所有子对象，寻找 Image 组件
            // TalkController[] TalkControllerList = rootObject.GetComponentsInChildren<TalkController>(true);
            // foreach (var talkController in TalkControllerList)
            // {
            //     talkStr = talkStr + getTalkControllerStr(talkController);
            //     if (fontAsset != null)
            //     {
            //         var tmp = talkController.text.GetComponent<TextMeshProUGUI>();
            //         tmp.font = fontAsset;
            //         EditorUtility.SetDirty(tmp);
            //     }

            // }
        }
        EditorSceneManager.MarkSceneDirty(scene);
        EditorSceneManager.SaveScene(scene);
        // 卸载场景
        EditorSceneManager.CloseScene(scene, true);
        return talkStr;
    }

    public static string getPrefabTalkStr(string prefabGuid, TMP_FontAsset fontAsset = null)
    {
        string talkStr = "";
        string prefabPath = AssetDatabase.GUIDToAssetPath(prefabGuid);
        GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);

        if (prefab != null)
        {
            // // 获取预制体中的所有 Image 组件
            // TalkController[] TalkControllerList = prefab.GetComponentsInChildren<TalkController>(true);
            // foreach (var talkController in TalkControllerList)
            // {
            //     talkStr = talkStr + getTalkControllerStr(talkController);
            //     if (fontAsset != null)
            //     {
            //         var tmp = talkController.text.GetComponent<TextMeshProUGUI>();
            //         tmp.font = fontAsset;
            //     }

            // }
            // EditorUtility.SetDirty(prefab);
        }
        return talkStr;
    }

    // public static string getTalkControllerStr(TalkController talkController)
    // {
    //     string talkStr = "";
    //     var strList = talkController.textList;
    //     foreach (var str in strList)
    //     {
    //         talkStr = talkStr + str;
    //     }
    //     return talkStr;
    // }

    // [MenuItem("Assets/自定义创建/say/编辑Excel")]
    public static void EditExcel()
    {
        string excelFile = "F:/ihuman/hongen_read/SVN/product/口语表达音频脚本";
        foreach (var file in Directory.GetFiles(excelFile))
        {
            var workbook = ExcelUtil.GetWorkBook(file);
            var laba = ExcelUtil.GetWorkSheet(workbook, "laba");
            laba.Cell(1, 1).Value = "Text";
            laba.Cell(1, 2).Value = "Type(绿1黄2)";
            workbook.Save();
        }
    }
    // [MenuItem("Assets/自定义创建/say/生成laba lua文件(程序使用)")]
    public static void createLabaLuaFile()
    {
        string curPath = DirUtil.getCurPath();
        string sayId = DirUtil.getSayId(curPath);
        if (sayId == null)
        {
            Debug.LogError("sayId is null at path: " + curPath);
            return;
        }
        createSayLabaConfig(sayId);
    }

    public static void createLabaLuaFile(string sayId, bool isBatch = false)
    {
        string svnDir = "https://10.3.254.33/repos/hongen_read/product/口语表达音频脚本";
        string excelFile = SvnUtil.getFileByPattern(svnDir, sayId);
        if (excelFile == null)
        {
            // EditorUtility.DisplayDialog("", $"{sayId}没有配表", "确认");
            return;
        }

        List<SayLabaModel> labaInfo = ExcelUtil.ReadExcelWithReflection<SayLabaModel>(excelFile, "laba");
        Dictionary<string, SayLabaOutPutModel> dic = new Dictionary<string, SayLabaOutPutModel>();
        for (int index = 0; index < labaInfo.Count; index++)
        {
            SayLabaModel model = labaInfo[index];
            SayLabaOutPutModel outputModel = new SayLabaOutPutModel();

            outputModel.isLong = model.isLong == 1 ? true : false;
            outputModel.Text = model.Text == null ? "" : model.Text;
            outputModel.pinyin = model.pinyin == null ? "" : model.pinyin;
            if (model.Type != null && model.Type != "")
            {
                try
                {
                    outputModel.Type = int.Parse(model.Type);
                }
                finally
                {
                    // outputModel.Type = 1;
                }
            }
            else
            {
                outputModel.Type = 1;
            }
            dic.Add($"A0{index + 1}", outputModel);

        }

        SayCommonModel commonInfo = ExcelUtil.ReadExcelWithReflection<SayCommonModel>(excelFile, "common")[0];
        commonInfo.Laba = dic;


        createLabaLuaFile(sayId, commonInfo);
    }

    private static void createLabaLuaFile(string sayId, SayCommonModel modelDic, bool isBatch = false)
    {
        var labaPath = Path.Combine(scriptPathRoot, string.Format("say{0}", sayId), "LabaCfg.lua");
        if (File.Exists(labaPath))
        {
            File.Delete(labaPath);
        }
        var outPutPath = Path.Combine(scriptPathRoot, string.Format("say{0}", sayId), "Cfg.lua");
        if (File.Exists(outPutPath))
        {
            File.Delete(outPutPath);
        }
        string result = JsonConvert.SerializeObject(modelDic, Formatting.Indented);
        result = JsonToLua.ConvertContent(result);
        File.WriteAllText(outPutPath, result);
        if (!isBatch)
        {
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
    }

    [MenuItem("Assets/自定义创建/say/更新laba配置")]
    public static void createSayLabaConfig()
    {
        string curPath = DirUtil.getCurPath();
        string sayId = DirUtil.getSayId(curPath);
        if (sayId == null)
        {
            Debug.LogError("sayId is null at path: " + curPath);
            return;
        }
        createSayLabaConfig(sayId);
    }

    public static void createSayLabaConfig(string sayId)
    {
        string svnDir = "https://10.3.254.33/repos/hongen_read/product/口语表达音频脚本";
        string excelFile = SvnUtil.getFileByPattern(svnDir, sayId);
        if (excelFile == null)
        {
            EditorUtility.DisplayDialog("", $"{sayId}没有配表", "确认");
            return;
        }

        List<SayLabaModel> labaInfo = ExcelUtil.ReadExcelWithReflection<SayLabaModel>(excelFile, "laba");
        initLabaInfo(sayId, labaInfo);
    }

    private static void initLabaInfo(string sayId, List<SayLabaModel> modelList)
    {

        string dirPath = string.Format("say{0}", sayId);
        string scenePath = Path.Combine(artPathRoot, dirPath, $"{dirPath}.unity");
        var scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive);
        GameObject[] rootObjects = scene.GetRootGameObjects();
        GameObject gameRoot = null;
        foreach (var rootObject in rootObjects)
        {
            if (rootObject.name == "GameRoot")
            {
                gameRoot = rootObject;
            }
        }
        if (gameRoot == null)
        {
            Debug.LogError("gameRoot is null at sayId: " + sayId);
            return;
        }
        var labaParent = gameRoot.Seek("laba");
        if (labaParent == null)
        {
            labaParent = new GameObject("laba");
            gameRoot.AddChild(labaParent);
            labaParent.SetScalef(1);
            labaParent.SetPosition(Vector3.zero);
        }
        string fontStr = "";
        foreach (SayLabaModel model in modelList)
        {
            fontStr = fontStr + model.Text;
        }
        string fontDir = Path.Combine(artPathRoot, dirPath, "font");
        string oldFontPath = Path.Combine(fontDir, $"{sayId}.asset");
        oldFontPath = oldFontPath.Replace("\\", "/");
        if (File.Exists(oldFontPath))
        {
            File.Delete(oldFontPath);
        }
        TMP_FontAsset fontAsset = TMP_FontAsset_CreationUtil.CreateFontAssetFromSelectedObject(new TextAsset(fontStr), AssetDatabase.LoadAssetAtPath<Font>(fontPath), fontDir, $"{sayId}_laba", 256, 256);
        int index = 0;
        foreach (SayLabaModel model in modelList)
        {
            index = index + 1;
            string ID = $"A0{index}";
            var laba = gameRoot.Seek(ID);
            GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(labaPath);
            if (laba == null)
            {
                laba = (GameObject)PrefabUtility.InstantiatePrefab(prefab, labaParent.transform);
                laba.name = ID;
                laba.SetScalef(1);
                laba.SetPosition(Vector3.zero);
            }
            var labaController = laba.GetComponent<LabaController>();
            if (model.Type != null && model.Type != "")
            {
                try
                {
                    labaController.Type = int.Parse(model.Type);
                }
                finally
                {

                }

            }


            labaController.KeyWord = model.Text;
            labaController.IsLong = model.isLong == 0 ? false : true;
            labaController.fontAsset = fontAsset;
            labaController.UpdateLaba();
            EditorUtility.SetDirty(labaController);
            EditorUtility.SetDirty(laba);
        }
        EditorUtility.SetDirty(labaParent);
        EditorSceneManager.MarkSceneDirty(scene);
        EditorSceneManager.SaveScene(scene);
        EditorSceneManager.CloseScene(scene, true);
    }

    [MenuItem("Assets/自定义创建/say/生成说环节relLink及Cfg.lua文件")]
    public static void createSayResLink()
    {
        string curPath = DirUtil.getCurPath();
        string sayId = DirUtil.getSayId(curPath);
        if (sayId == null)
        {
            Debug.LogError("sayId is null at path: " + curPath);
            return;
        }
        createSayResLink(sayId);
        createLabaLuaFile(sayId);
    }
    public static void createSayResLink(string sayId)
    {
        string dirPath = string.Format("say{0}", sayId);
        string srcPath = Path.Combine(scriptPathRoot, dirPath);

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

        string jsonResLinkPath = Path.Combine(srcPath, "json.asset");
        if (File.Exists(jsonResLinkPath))
        {
            File.Delete(jsonResLinkPath);
        }
        string artPath = Path.Combine(artPathRoot, dirPath);
        string jsonPath = Path.Combine(artPath, "json");
        if (Directory.Exists(jsonPath))
        {
            string[] all = Directory.GetFiles(jsonPath, $"*.*", SearchOption.AllDirectories);
            if (all != null && all.Length > 0)
            {
                var jsonResLink = createResLinkAsset(jsonResLinkPath);
                List<string> list = new List<string>(all);
                list.Sort((a, b) =>
                {
                    if (a.Length != b.Length)
                    {
                        return a.Length.CompareTo(b.Length);
                    }
                    else
                    {
                        return a.CompareTo(b);
                    }
                });
                foreach (string str in list)
                {
                    if (str.EndsWith(".meta"))
                    {
                        continue;
                    }
                    int index = str.IndexOf("Assets/");
                    string unityPath = str.Substring(index);
                    UnityEngine.Object ac = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(unityPath);
                    jsonResLink.assets.Add(ResLinkEditor.CreateItem($"{Path.GetFileNameWithoutExtension(str)}", ac, 0, null));
                }
                ResLinkEditor.Save(jsonResLink);
                EditorUtility.SetDirty(jsonResLink);
            }
        }
        string soundResLinkPath = Path.Combine(srcPath, "SOUND.asset");
        if (File.Exists(soundResLinkPath))
        {
            File.Delete(soundResLinkPath);
        }
        string soundPath = Path.Combine(artPath, "sound");
        if (Directory.Exists(soundPath))
        {
            string[] all = Directory.GetFiles(soundPath, $"*.*", SearchOption.AllDirectories);
            if (all != null && all.Length > 0)
            {
                var soundResLink = createResLinkAsset(soundResLinkPath);
                List<string> list = new List<string>(all);
                list.Sort((a, b) =>
                {
                    if (a.Length != b.Length)
                    {
                        return a.Length.CompareTo(b.Length);
                    }
                    else
                    {
                        return a.CompareTo(b);
                    }
                });
                foreach (string str in list)
                {
                    if (str.EndsWith(".meta"))
                    {
                        continue;
                    }
                    int index = str.IndexOf("Assets/");
                    string unityPath = str.Substring(index);
                    UnityEngine.Object ac = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(unityPath);
                    soundResLink.assets.Add(ResLinkEditor.CreateItem($"{Path.GetFileNameWithoutExtension(str)}", ac, 0, null));
                }
                ResLinkEditor.Save(soundResLink);
                EditorUtility.SetDirty(soundResLink);
            }
        }


        string path = Path.Combine(srcPath, string.Format("Say{0}ResLink.asset", sayId));
        if (File.Exists(path))
        {
            File.Delete(path);
        }

        var resLink = createResLinkAsset(path);

        string scenePath = Path.Combine(artPath, string.Format("Say{0}.unity", sayId));
        if (File.Exists(scenePath))
        {
            resLink.assets.Add(ResLinkEditor.CreateItem("SCENE", AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(scenePath), 0, null));
        }
        if (File.Exists(soundResLinkPath))
        {
            resLink.assets.Add(ResLinkEditor.CreateItem("SOUND", AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(soundResLinkPath), 0, null));
        }

        if (File.Exists(jsonResLinkPath))
        {
            resLink.assets.Add(ResLinkEditor.CreateItem("JSON", AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(jsonResLinkPath), 0, null));
        }

        string V01Path = Path.Combine(artPath, "V01.prefab");
        if (File.Exists(V01Path))
        {
            resLink.assets.Add(ResLinkEditor.CreateItem("V01UI", AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(V01Path), 0, null));
        }

        ResLinkEditor.Save(resLink);
        EditorUtility.SetDirty(resLink);
        UnityEditor.AssetDatabase.SaveAssets();
        UnityEditor.AssetDatabase.Refresh();
    }

    [MenuItem("Assets/自定义创建/say/跳转到art目录")]
    public static void skipToArtDir()
    {
        string curPath = DirUtil.getCurPath();
        string sayId = DirUtil.getSayId(curPath);
        if (sayId != null)
        {
            string dirPath = string.Format("say{0}", sayId);
            string artPath = Path.Combine(artPathRoot, dirPath);
            DirUtil.skipToDir(artPath);
        }
        else
        {

            DirUtil.skipToDir(artPathRoot);
        }

    }

    [MenuItem("Assets/自定义创建/say/跳转到src目录")]
    public static void skipToSrcDir()
    {
        string curPath = DirUtil.getCurPath();
        string sayId = DirUtil.getSayId(curPath);
        if (sayId != null)
        {
            string dirPath = string.Format("say{0}", sayId);
            string srcPath = Path.Combine(scriptPathRoot, dirPath);
            DirUtil.skipToDir(srcPath);
        }
        else
        {

            DirUtil.skipToDir(scriptPathRoot);
        }
    }
    public static ResLinkAsset createResLinkAsset(string path)
    {
        // 创建一个新的 ResLinkAsset 实例
        ResLinkAsset resLinkAsset = ScriptableObject.CreateInstance<ResLinkAsset>();
        UnityEditor.AssetDatabase.CreateAsset(resLinkAsset, path);
        UnityEditor.AssetDatabase.SaveAssets();
        UnityEditor.AssetDatabase.Refresh();

        Debug.Log("Created ResLinkAsset at path: " + path);
        return resLinkAsset;
    }
}

