using Model; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System.IO; using System.Net.Http; using System.Net; using DocumentFormat.OpenXml; using static Model.admin_log; using DocumentFormat.OpenXml.Bibliography; using PagedList; /// /// ShuWenController 的摘要描述 /// public class ShuWenController : ApiController { private Model.ezEntities _db = new Model.ezEntities(); public ShuWenController() { // // TODO: 在這裡新增建構函式邏輯 // } [HttpGet] [Route("api/shuwen/getshuwen")] public IHttpActionResult GetShuWen(int? activitynum) { if (!activitynum.HasValue) { return BadRequest("請提供有效的 activitynum 參數。"); } var shuwen = _db.ShuWen.Where(a => a.ActivityNum == activitynum).FirstOrDefault(); if(shuwen == null) { return Ok(new { message = "1", data = shuwen, latest = false }); } var latest = _db.pro_order_detail.Where(b => b.pro_order.activity_num == activitynum) .Where(c => c.UpdateTime > shuwen.UpdateTime).Count() > 0 ? false : true; return Ok(new { message = "1", data = shuwen , latest= latest}); } [HttpGet] [Route("api/shuwen/StartGenerate")] public IHttpActionResult CreateShuWen(int? activitynum) { if (!activitynum.HasValue) { return BadRequest("請提供有效的 activitynum 參數。"); } var shuwen = _db.ShuWen.Where(a => a.ActivityNum == activitynum).FirstOrDefault(); if (shuwen == null) { var now = DateTime.Now; shuwen = new Model.ShuWen(); shuwen.ActivityNum = activitynum.Value; shuwen.CreateTime = now; shuwen.UpdateTime = now; shuwen.IsGenerating = true; _db.ShuWen.Add(shuwen); } else if (shuwen.IsGenerating) { return Ok("任务正在处理中"); } shuwen.IsGenerating = true; _db.SaveChanges(); try { shuwen.ShuWenList = ProcessDesserts2(_db.pro_order_detail.Where(a => a.pro_order.activity_num == activitynum.Value).ToList()); } catch (Exception ex) { return BadRequest("生成舒文失败:" + ex.Message); } shuwen.IsGenerating = false; shuwen.UpdateTime = DateTime.Now; _db.SaveChanges(); return Ok("已啟動生成任務"); } public string ProcessDesserts2(List items) { var xiaozai = new List>>(); var chaodu = new List>>(); foreach (var item in items) { string json = item.f_num_tablet; try { JObject obj = JObject.Parse(json); var midItems = obj["mid_items"] as JArray; var famNames = new List(); foreach (var mid in midItems ?? new JArray()) { bool isShuWen = mid["IsShuWen"]?.Value() == true; string famName = mid["fam_name"]?.ToString(); if (isShuWen && !string.IsNullOrWhiteSpace(famName)) { famNames.Add(famName.Trim()); } } if (famNames.Count == 0) continue; string orderNo = item.order_no; var userObject = new { name = item.pro_order.follower.u_name, }; if (item.actItem.subject.Contains("消")) { var existing = xiaozai.FirstOrDefault(d => d.ContainsKey(orderNo)); if (existing != null) { var data = (List)existing[orderNo]["biaoti"]; data.AddRange(famNames); existing[orderNo]["biaoti"] = data.Distinct().ToList(); } else { xiaozai.Add(new Dictionary> { { orderNo, new Dictionary { { "user", userObject }, { "biaoti", new List(famNames) } } } }); } } else if (item.actItem.subject.Contains("超")) { var leftNames = new List(); if (obj["left_items"] != null && obj["left_items"].HasValues) { var leftItems = obj["left_items"] as JArray; foreach (var left in leftItems ?? new JArray()) { leftNames.Add(left["fam_name"]?.ToString()); } } else { continue; } if(leftNames.Count() == 0) continue; var existing = chaodu.FirstOrDefault(d => d.ContainsKey(orderNo)); string leftFamName = string.Join(" ", leftNames).Trim(); if (existing != null) { var entryList = (List>)existing[orderNo]["entry"]; var existingYangshang = entryList.FirstOrDefault(e => IsSamePeople(e["yangshang"]?.ToString(), leftFamName)); if (existingYangshang != null) { var oldBiaoti = (List)existingYangshang["biaoti"]; oldBiaoti.AddRange(famNames); existingYangshang["biaoti"] = oldBiaoti.Distinct().ToList(); } else { entryList.Add(new Dictionary { { "yangshang", leftFamName }, { "biaoti", new List(famNames) } }); } } else { chaodu.Add(new Dictionary> { { orderNo, new Dictionary { { "user", userObject }, { "entry", new List> { new Dictionary { { "yangshang", leftFamName }, { "biaoti", new List(famNames) } } } } } } }); } } } catch (JsonReaderException) { } } var result = new { xiaozai = xiaozai, chaodu = chaodu }; return JsonConvert.SerializeObject(result, Formatting.None); } [HttpGet] [Route("api/shuwen/download")] public HttpResponseMessage DownloadShuWenWord(int? activitynum) { try { var data = _db.ShuWen.Where(a => a.ActivityNum == activitynum).FirstOrDefault(); if (data == null) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "活動編號不能為空"); } string json = data.ShuWenList; string ActivityName = _db.activities.Where(a => a.num == data.ActivityNum).FirstOrDefault().subject; if (json == null) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "疏文列表为空,无法生成 Word"); } string fileName = $"疏文名單_{DateTime.Now:yyyyMMddHHmmss}.docx"; var stream = new MemoryStream(); GenerateShuWenWord_OpenXml(json, stream, ActivityName); stream.Position = 0; var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(stream) }; response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = fileName }; return response; } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message); } } public void GenerateShuWenWord_OpenXml(string json, Stream outputStream, string ActivityName ="") { JObject root = JObject.Parse(json); using (var doc = WordprocessingDocument.Create(outputStream, WordprocessingDocumentType.Document, true)) { var mainPart = doc.AddMainDocumentPart(); mainPart.Document = new Document(new Body()); var body = mainPart.Document.Body; var sectionProps = new SectionProperties( new PageSize() { Orient = PageOrientationValues.Landscape }, new TextDirection() { Val = TextDirectionValues.TopToBottomRightToLeft } ); mainPart.Document.Body.Append(sectionProps); // === 處理 xiaozai === var xiaozai = root["xiaozai"] as JArray; if (xiaozai != null) { foreach (var item in xiaozai.Children()) { foreach (var prop in item.Properties()) { string orderNo = prop.Name; //var names = prop.Value.ToObject>(); var detail = prop.Value as JObject; string username = detail?["user"]?["name"]?.ToString(); var biaotiList = detail?["biaoti"]?.ToObject>() ?? new List(); AddPageBreak(body); var orderActItem = _db.pro_order_detail.Where(a => a.order_no == orderNo && a.actItem.act_bom.Where(b => b.package_num == null && b.item_num == a.actItem_num).Count() == 1).FirstOrDefault(); if(orderActItem != null) { username = orderActItem.actItem.subject; } body.Append(CreateHeading($"{ActivityName} {username} 消災祈福名單")); /*foreach (var name in biaotiList) { body.Append(CreateParagraph(" " + name)); }*/ var combinedNames = string.Join(" ", biaotiList); combinedNames = combinedNames.Replace(" ", " "); body.Append(CreateParagraph(combinedNames)); } } } // === 處理 chaodu === var chaodu = root["chaodu"] as JArray; if (chaodu != null) { foreach (var item in chaodu.Children()) { foreach (var prop in item.Properties()) { string orderNo = prop.Name; //var persons = prop.Value as JArray; var detail = prop.Value as JObject; string username = detail?["user"]?["name"]?.ToString(); var entries = detail?["entry"] as JArray; var orderActItem = _db.pro_order_detail.Where(a => a.order_no == orderNo && a.actItem.act_bom.Where(b => b.package_num == null && b.item_num == a.actItem_num).Count() == 1).FirstOrDefault(); if (orderActItem != null) { username = orderActItem.actItem.subject; } AddPageBreak(body); body.Append(CreateHeading($"{ActivityName} {username} 超薦名單")); foreach (var person in entries) { string yangshang = person["yangshang"]?.ToString(); var biaotiList = person["biaoti"]?.ToObject>() ?? new List(); foreach (var b in biaotiList) { body.Append(CreateParagraph(" " + b)); } body.Append(CreateParagraph("陽上報恩人:" + yangshang)); } } } } } } private Paragraph CreateHeading(string text) { return new Paragraph( new Run(new RunProperties( new FontSize() { Val = "50" } ), new Text(text)) ) { ParagraphProperties = new ParagraphProperties( new Justification() { Val = JustificationValues.Start }, new Bold(), new SpacingBetweenLines() { After = "200" }, new TextDirection() { Val = TextDirectionValues.TopToBottomRightToLeft } ) }; } private Paragraph CreateParagraph(string text) { return new Paragraph( new Run(new RunProperties( new FontSize() { Val = "40" } ), new Text(text)) ) { ParagraphProperties = new ParagraphProperties( new TextDirection() { Val = TextDirectionValues.TopToBottomRightToLeft } ) } ; } private void AddPageBreak(Body body) { if (body.Elements().Any()) { body.Append(new Paragraph(new Run(new DocumentFormat.OpenXml.Wordprocessing.Break() { Type = BreakValues.Page }))); } } bool IsSamePeople(string a, string b) { var listA = a.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Distinct().OrderBy(x => x).ToList(); var listB = b.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Distinct().OrderBy(x => x).ToList(); return listA.SequenceEqual(listB); } }