using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using System.IO;
using UnityEngine;

public class TYPostProcessWeb : IPostprocessBuildWithReport
{
    public int callbackOrder => int.MaxValue;
    private string buildPath;

    // 导出完成后调用的方法
    public void OnPostprocessBuild(BuildReport report)
    {
        string platform = report.summary.platform.ToString();
        if (platform == "WebGL" || platform == "MiniGame")
        {
            buildPath = report.summary.outputPath;
            Debug.Log("channel compile buildPath: " + buildPath);
            CopyTyResouceFile();
        }
    }

    private void CopyTyResouceFile()
    {
        string destinationDir = string.Empty;
        string sourceDir = string.Empty;
        string channelType = TYPreProcessWeb.GetBuildChannelType();
        Debug.Log("TYPostProcessWeb channelType: " + channelType);

        if (channelType == TYWebBuildConfig.MiniGameChannelType.ALI)
        {
            // 阿里小游戏
            destinationDir = ProcessDestinationDir("alipay");
            if (!Directory.Exists(destinationDir))
            { 
                destinationDir = ProcessDestinationDir("alipaygame");
            }
            sourceDir = ProcessSourceDir("aliminigame");
        }

        if (!string.IsNullOrEmpty(destinationDir) && !string.IsNullOrEmpty(sourceDir))
        {
            Debug.Log("TYPostProcessWeb CopyTyResouceFile, sourceDir: " + sourceDir);
            Debug.Log("TYPostProcessWeb CopyTyResouceFile, destinationDir: " + destinationDir);
            CopyFilesToDirectory(sourceDir, destinationDir);
        } else {
            Debug.Log("TYPostProcessWeb CopyTyResouceFile, current channel dont need copy resource file.");
        }

    }

    private string ProcessDestinationDir(string finnalOutputPath)
    {
        return Path.Combine(Directory.GetParent(buildPath).FullName, finnalOutputPath);
    }

    private string ProcessSourceDir(string ChannelResPath)
    {
        return Path.Combine(Application.dataPath, TYWebBuildConfig.TY_WEB_CHANNEL_RESOURCE_DIR, ChannelResPath);
    }

    public static void CopyFilesToDirectory(string sourceDir, string destinationDir)
    {
        if (!Directory.Exists(destinationDir))
        {
            Debug.LogError("目标文件目录不存在");
            return;
        }

        // 获取源目录下的所有文件
        string[] files = Directory.GetFiles(sourceDir);

        foreach (string file in files)
        {
            // 获取文件的文件名（不包含路径）
            string fileName = Path.GetFileName(file);

            // 跳过以 .meta 结尾的文件
            if (fileName.EndsWith(".meta"))
            {
                continue;
            }

            if (fileName == "TyJsBridge.js")
            {
                continue;
            }

            // 目标文件的完整路径
            string destFile = Path.Combine(destinationDir, fileName);

            try
            {
                // 复制文件到目标目录（如果目标文件已经存在，覆盖它）
                File.Copy(file, destFile, true);
                Debug.Log($"File copied: {fileName}");
            }
            catch (System.Exception e)
            {
                Debug.Log($"Failed to copy file {fileName}: {e.Message}");
            }
        }
    }
}
