using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

using System.IO;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
using PhotoTkutimes.Models;
using System.Xml.Linq;

namespace PhotoTkutimes.Controllers
{
    [Route("fdoc/")]
    [ApiController]
    public class DocxController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        public DocxController(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        [HttpGet("{no}.doc")]
        public IActionResult Get(int no)
        {
            DtlPageData pageData = new DtlPageData();
            pageData = DtlPageData.getDtlPageData(_configuration, no, "");

            string _title = "";
            string _paperno = "";
            string _type = "";
            string _dt = "";
            List<string> _content = new List<string>();
            char[] c = { '\n' };
            if (pageData.dtlNews.Count > 0)
            {
                _title = pageData.dtlNews[0].Title1;
                _paperno = string.Format("淡江時報 第 {0} 期", pageData.dtlNews[0].News_no);
                _type = pageData.dtlNews[0].PgTyp;
                _dt = pageData.dtlNews[0].DMdf.ToString("yyyyMMddHHmmss");
                if (pageData.dtlNews[0].news_content != null)
                {
                    _content = pageData.dtlNews[0].news_content.Split(c).ToList();
                    //_content = content;
                }

            }

            string docpath = string.Format("{0}_{1}.docx", no, _dt);
            string filepath = string.Format("{1}{0}", docpath, Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/doc/"));
            if (System.IO.File.Exists(filepath))
            {
                return File(Path.Combine("doc", docpath), "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            }
            try
            {
                using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
                {
                    // Insert other code here. 
                    //MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
                    MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
                    Justification textcenter = new Justification() { Val = JustificationValues.Center };

                    // 實例化 Document(w) 部分
                    mainPart.Document = new Document();
                    Body body = mainPart.Document.AppendChild(new Body());
                    // 建立 Paragraph 類別物件，於 Body 本文中加入段落 Paragraph(p)
                    //Paragraph paragraph = body.AppendChild(new Paragraph());
                    // 建立 Run 類別物件，於 段落 Paragraph(p) 中加入文字屬性 Run(r) 範圍

                    Run papernoRun = new Run();
                    RunProperties papernoRunProp = papernoRun.AppendChild(new RunProperties());
                    papernoRun.AppendChild(new Text(_paperno));
                    RunFonts papernoFonts = new RunFonts() { Ascii = "Segoe UI", HighAnsi = "Segoe UI", EastAsia = "Segoe UI" };
                    FontSize papernoSize = new FontSize() { Val = "28" }; //設置字體大小爲18磅，以半磅爲單位                
                    DocumentFormat.OpenXml.Wordprocessing.Color papernoColor = new DocumentFormat.OpenXml.Wordprocessing.Color() { Val = "FF0000" };
                    papernoRunProp.AppendChild(papernoFonts);
                    papernoRunProp.AppendChild(papernoSize);
                    papernoRunProp.AppendChild(papernoColor);
                    wordDocument.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(papernoRun))
                    {

                        ParagraphProperties = new ParagraphProperties()
                        {
                            Justification = new Justification() { Val = JustificationValues.Right }
                        }
                    });

                    //papernoRunProp.AppendChild(new Justification() { Val = JustificationValues.Right });
                    //paragraph.AppendChild(papernoRun);

                    //Paragraph paragraphTitle = body.AppendChild(new Paragraph());
                    Run titleRun = new Run();/// paragraph.AppendChild(new Run());
                    RunProperties titleRunProp = titleRun.AppendChild(new RunProperties());
                    titleRun.AppendChild(new Text(_title));
                    RunFonts titleFonts = new RunFonts() { Ascii = "Segoe UI", HighAnsi = "Segoe UI", EastAsia = "Segoe UI" };
                    FontSize titleSize = new FontSize() { Val = "32" }; //設置字體大小爲18磅，以半磅爲單位
                    DocumentFormat.OpenXml.Wordprocessing.Color titleColor = new DocumentFormat.OpenXml.Wordprocessing.Color() { Val = "000000" };

                    titleRunProp.AppendChild(titleFonts);
                    titleRunProp.AppendChild(titleSize);
                    titleRunProp.AppendChild(titleColor);
                    titleRunProp.Append(new Bold());
                    //paragraphTitle.AppendChild(titleRun);
                    wordDocument.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(titleRun))
                    {

                        ParagraphProperties = new ParagraphProperties()
                        {
                            Justification = new Justification() { Val = JustificationValues.Center }
                        }
                    });

                    Run typeRun = new Run();/// paragraph.AppendChild(new Run());
                    RunProperties typeRunProp = typeRun.AppendChild(new RunProperties());
                    typeRun.AppendChild(new Text(_type));
                    RunFonts typeFonts = new RunFonts() { Ascii = "Segoe UI", HighAnsi = "Segoe UI", EastAsia = "Segoe UI" };
                    FontSize typeSize = new FontSize() { Val = "28" }; //設置字體大小爲18磅，以半磅爲單位
                    DocumentFormat.OpenXml.Wordprocessing.Color typeColor = new DocumentFormat.OpenXml.Wordprocessing.Color() { Val = "888888" };

                    typeRunProp.AppendChild(typeFonts);
                    typeRunProp.AppendChild(typeSize);
                    typeRunProp.AppendChild(typeColor);
                    typeRunProp.Append(new Bold());
                    //paragraphTitle.AppendChild(titleRun);
                    wordDocument.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(typeRun))
                    {

                        ParagraphProperties = new ParagraphProperties()
                        {
                            Justification = new Justification() { Val = JustificationValues.Right }
                        }
                    });

                    Run contentRun = new Run();/// paragraph.AppendChild(new Run());
                    RunProperties contentRunProp = contentRun.AppendChild(new RunProperties());
                    try
                    {
                        for (int i = 0; i < _content.Count; i++)
                        {
                            contentRun.AppendChild(new Text(_content[i]));
                            contentRun.AppendChild(new Break());
                        }
                    }
                    catch { }

                    RunFonts contentFonts = new RunFonts() { Ascii = "Segoe UI", HighAnsi = "Segoe UI", EastAsia = "Segoe UI" };
                    FontSize contentSize = new FontSize() { Val = "28" }; //設置字體大小爲18磅，以半磅爲單位
                    DocumentFormat.OpenXml.Wordprocessing.Color contentColor = new DocumentFormat.OpenXml.Wordprocessing.Color() { Val = "000000" };

                    contentRunProp.AppendChild(contentFonts);
                    contentRunProp.AppendChild(contentSize);
                    contentRunProp.AppendChild(contentColor);
                    //contentRunProp.Append(new Bold());
                    //paragraphTitle.AppendChild(titleRun);
                    wordDocument.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(contentRun))
                    {

                        ParagraphProperties = new ParagraphProperties()
                        {
                            Justification = new Justification() { Val = JustificationValues.Left }
                        }
                    });

                    //Paragraph paragraphImages = body.AppendChild(new Paragraph());
                    //Run run = paragraphImages.AppendChild(new Run());



                    //ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
                    //using (FileStream stream = new FileStream(fileName, FileMode.Open))
                    //{
                    //    imagePart.FeedData(stream);
                    //}
                    //DocxImgHelper.AddImageToBody(wordDocument, mainPart.GetIdOfPart(imagePart));
                    if (pageData.dtlImg != null && pageData.dtlImg.Count > 0)
                    {
                        foreach (DtlImg img in pageData.dtlImg)
                        {
                            string fileName = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Photos/", img.ImgPath, "m", img.ImgNme);
                            if (!System.IO.File.Exists(fileName))
                            {
                                continue;
                            }
                            var imgdata = new ImageData(fileName);
                            var imgRun = DocxImgHelper.GenerateImageRun(wordDocument, imgdata);
                            //imgRun.Append(textcenter);

                            //run.AppendChild(
                            //    new Paragraph(new Run(imgRun))
                            //    {
                            //        ParagraphProperties = new ParagraphProperties()
                            //        {
                            //            Justification = new Justification() { Val = JustificationValues.Center }
                            //        }
                            //    });

                            wordDocument.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(imgRun))
                            {

                                ParagraphProperties = new ParagraphProperties()
                                {
                                    Justification = new Justification() { Val = JustificationValues.Center }
                                }
                            });
                        }
                    }
                    return File(Path.Combine("doc", docpath), "application/msword");

                }
            }
            catch
            {
                return BadRequest("error");
            }

        }
    }
}
