using Aspose.Slides;
using Aspose.Words.Lists;
using Cysharp.Threading.Tasks;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using TMPro;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;

public static class LoadPPTTest
{

    /// <summary>
    /// 
    /// </summary>
    private static Dictionary<string, List<Texture2D>> texturesDic = new Dictionary<string, List<Texture2D>>();
    /// <summary>
    /// PPT所有路径
    /// </summary>
    private static string[] pptsPath = null;
    /// <summary>
    /// 加载单个课程所有图片
    /// </summary>
    /// <param name="pptName"></param>
    /// <returns></returns>
    public static List<Texture2D> LoadPPTItems(string pptName)
    {
        string pptPath = GetPPTPathByName(pptName);
        return GetTexture2DsByName(pptName, pptPath);
        //target.StartCoroutine(LoadAllPPTFiles(pptPath));
    }



    public static string[] PPTName()
    {
        ///切割pptsPath
        return pptsPath;
    }


    private static List<Texture2D> GetTexture2DsByName(string pptName, string pptPath)
    {
        if (!texturesDic.ContainsKey(pptName))
        {
            texturesDic.Add(pptName, LoadAllPPTFiles(pptPath));
            return LoadAllPPTFiles(pptPath);
        }
        else
        {
            foreach (var item in texturesDic.Keys)
            {
                if (item.Equals(pptName))
                    return texturesDic[item];
            }
        }
        return null;
    }
    /// <summary>
    /// 获取当前课程PPT目录
    /// </summary>
    /// <param name="pptName">名称</param>
    /// <returns></returns>
    private static string GetPPTPathByName(string pptName)
    {
        foreach (var item in pptsPath)
        {
            if (item.Contains(pptName))
                return item;
        }
        return null;
    }

    /// <summary>
    /// 获取文件夹下所有.pptx文件
    /// </summary>
    /// <param name="folderPath"></param>
    public static void PPTFiles(string folderPath)
    {
        string fullPPTFolderPath = Path.Combine(Application.streamingAssetsPath, folderPath);
        pptsPath = Directory.GetFiles(fullPPTFolderPath, "*.pptx");
    }


    //public static async UniTask LoadAllPPTFiles(string pptName, string folderPath)
    //{
    //    List<Texture2D> texture2Ds = new List<Texture2D>();
    //    Presentation presentation = new Presentation(folderPath);
    //    // 遍历文档(只做示例使用自己根据需求拓展)
    //    for (int i = 0; i < presentation.Slides.Count; i++)
    //    {
    //        await UniTask.Yield();
    //        ISlide slide = presentation.Slides[i];
    //        var bitmap = slide.GetThumbnail(1f, 1f);
    //        // 声明内存流,将图片转换为内存流,再由流转换为byte数组,然后用texture2d加载byte数组
    //        using (MemoryStream ms = new MemoryStream())
    //        {
    //            bitmap.Save(ms, ImageFormat.Jpeg);
    //            byte[] buff = new byte[ms.Length];
    //            ms.Seek(0, SeekOrigin.Begin);
    //            await ms.ReadAsync(buff, 0, (int)ms.Length);
    //            Texture2D texture2D = new Texture2D(2, 2);
    //            texture2D.LoadImage(buff);
    //            texture2Ds.Add(texture2D);
    //        }
    //    }
    //    texturesDic.Add(pptName, texture2Ds);
    //    Debug.Log("所有PPT加载完成!");
    //}

    public static List<Texture2D> LoadAllPPTFiles(string folderPath)
    {
        List<Texture2D> texture2Ds = new List<Texture2D>();
        Presentation presentation = new Presentation(folderPath);

        // 遍历文档(只做示例使用自己根据需求拓展)
        for (int i = 0; i < presentation.Slides.Count; i++)
        {
            ISlide slide = presentation.Slides[i];
            var bitmap = slide.GetThumbnail(1f, 1f);

            // 声明内存流,将图片转换为内存流,再由流转换为byte数组,然后用texture2d加载byte数组
            using (MemoryStream ms = new MemoryStream())
            {
                bitmap.Save(ms, ImageFormat.Jpeg);
                byte[] buff = new byte[ms.Length];
                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(buff, 0, (int)ms.Length);

                // 注意这个image的命名空间为system.drawing不是unity.ui,这个图片的目的是提供图片的宽高
                System.Drawing.Image sizeImage = System.Drawing.Image.FromStream(ms);

                Texture2D texture2D = new Texture2D(sizeImage.Width, sizeImage.Height);
                texture2D.LoadImage(buff);
                texture2Ds.Add(texture2D);
            }
        }
        Debug.Log("所有PPT加载完成!");
        return texture2Ds;
    }
    // 逐个加载每个PPT文件

    /// <summary>
    /// 分割ppt路径名称
    /// </summary>
    /// <param name="pptname"></param>
    public static string PathName(string pptname)
    {
        if (string.IsNullOrEmpty(pptname))
        {
            Debug.LogError("路径不能为空!");
            return null;
        }
        string standardizedPath = pptname.Replace('\\', '/');
        // 获取无扩展名的文件名
        string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(standardizedPath);
        Debug.Log("文件名: " + fileNameWithoutExtension);
        return fileNameWithoutExtension;
    }

    /// <summary>
    /// 从文件名中提取开头的数字(如 "1-第一章" -> 返回 1)
    /// </summary>
    public static int ExtractLeadingNumber(string fileName)
    {
        if (string.IsNullOrEmpty(fileName)) return 0;
        // 找到第一个数字序列
        var numStr = new string(fileName.TakeWhile(char.IsDigit).ToArray());
        return int.TryParse(numStr, out int num) ? num : 0;
    }
}

//public class LoadPPTTest : MonoBehaviour
//{
//    public static LoadPPTTest Instance;

//    private void Start()
//    {
//        Instance = this;
//        //LoadPPTTest.Instance.LoadPPTGO(Application.streamingAssetsPath + "/PPT/1-第一章 绪论.pptx");
//    }
//    public IEnumerator LoadPPTGOCoroutine(string pptPath ,GameObject imageprefab, Transform content)
//    {
//        //清理content下的旧物体
//        for (int i = 0; i < content.childCount; i++)
//        {
//            Destroy(content.GetChild(i).gameObject);
//        }

//        yield return null;


//        Presentation presentation = new Aspose.Slides.Presentation(pptPath);
//        int totalSlides = presentation.Slides.Count;
//        // 逐页处理 PPT 幻灯片
//        for (int i = 0; i < totalSlides; i++)
//        {
//            ISlide slide = presentation.Slides[i];
//            var bitmap = slide.GetThumbnail(1f, 1f);

//            // 使用内存流将图片转换为 Texture2D
//            using (MemoryStream ms = new MemoryStream())
//            {
//                bitmap.Save(ms, ImageFormat.Jpeg);
//                byte[] buff = new byte[ms.Length];
//                ms.Seek(0, SeekOrigin.Begin);
//                ms.Read(buff, 0, (int)ms.Length);

//                // 获取图片宽高
//                System.Drawing.Image sizeImage = System.Drawing.Image.FromStream(ms);

//                // 创建 Texture2D 并加载图片数据
//                Texture2D texture2D = new Texture2D(sizeImage.Width, sizeImage.Height);
//                texture2D.LoadImage(buff);

//                // 实例化 Image 并设置到 content 下
//                Image image = Instantiate(imageprefab, content).GetComponent<Image>();
//                image.rectTransform.sizeDelta = new Vector2(sizeImage.Width, sizeImage.Height);
//                image.sprite = Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height), Vector2.zero);
//            }

//            // 每处理一页后暂停一帧,分散负载
//            yield return null;
//        }
//    }

//    public void LoadPPTGO(string pptPath, GameObject imageprefab, Transform content)
//    {
//        StartCoroutine(LoadPPTGOCoroutine(pptPath, imageprefab, content));
//    }
//}