using Hotline.Share.Dtos.ExportWord;
using XF.Domain.Dependency;

namespace Hotline.Application.ExportWord
{
    public class WordHelperService : IWordHelperService, IScopeDependency
    {
        public byte[] WordByte<T>(string templatePath, T data) where T : IWordExportTemplate
        {
            return new WordExportService(new WordExportProvider()).TemplateCreateWord(templatePath, data).WordBytes;
        }

        public Stream WordStream<T>(string templatePath, T data) where T : IWordExportTemplate
        {
            var bytes = new WordExportService(new WordExportProvider()).TemplateCreateWord(templatePath, data).WordBytes;
            Stream stream = new MemoryStream(bytes);
            return stream;
        }

        /// <summary>
        /// ZipStream 压缩
        /// </summary>
        /// <param name="streams">Dictionary（string, Stream） 文件名和Stream</param>
        /// <returns></returns>
        public byte[] ConvertZipStream(Dictionary<string, Stream> streams)
        {
            byte[] buffer = new byte[6500];
            MemoryStream returnStream = new();
            var zipMs = new MemoryStream();
            using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(zipMs))
            {
                zipStream.SetLevel(9);//设置 压缩等级 (9级 500KB 压缩成了96KB)
                foreach (var kv in streams)
                {
                    string fileName = kv.Key;
                    using (var streamInput = kv.Value)
                    {
                        ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);
                        zipEntry.IsUnicodeText = true;
                        zipStream.PutNextEntry(zipEntry);

                        while (true)
                        {
                            var readCount = streamInput.Read(buffer, 0, buffer.Length);
                            if (readCount > 0)
                            {
                                zipStream.Write(buffer, 0, readCount);
                            }
                            else
                            {
                                break;
                            }
                        }
                        zipStream.Flush();
                    }
                }
                zipStream.Finish();
                zipMs.Position = 0;
                zipMs.CopyTo(returnStream, 5600);
            }
            returnStream.Position = 0;

            //Stream转Byte[]
            byte[] returnBytes = new byte[returnStream.Length];
            returnStream.Read(returnBytes, 0, returnBytes.Length);
            returnStream.Seek(0, SeekOrigin.Begin);

            return returnBytes;
        }
    }
}
