388 lines
15 KiB
C#
388 lines
15 KiB
C#
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;
|
||
|
||
/// <summary>
|
||
/// ShuWenController 的摘要描述
|
||
/// </summary>
|
||
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.ShuWens.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.ShuWens.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.ShuWens.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
|
||
{
|
||
|
||
}
|
||
shuwen.IsGenerating = false;
|
||
shuwen.UpdateTime = DateTime.Now;
|
||
_db.SaveChanges();
|
||
return Ok("已啟動生成任務");
|
||
}
|
||
public string ProcessDesserts2(List<pro_order_detail> items)
|
||
{
|
||
var xiaozai = new List<Dictionary<string, Dictionary<string, object>>>();
|
||
var chaodu = new List<Dictionary<string, Dictionary<string, object>>>();
|
||
|
||
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<string>();
|
||
|
||
foreach (var mid in midItems ?? new JArray())
|
||
{
|
||
bool isShuWen = mid["IsShuWen"]?.Value<bool>() == 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<string>)existing[orderNo]["biaoti"];
|
||
data.AddRange(famNames);
|
||
existing[orderNo]["biaoti"] = data.Distinct().ToList();
|
||
}
|
||
else
|
||
{
|
||
xiaozai.Add(new Dictionary<string, Dictionary<string, object>>
|
||
{
|
||
{
|
||
orderNo,
|
||
new Dictionary<string, object>
|
||
{
|
||
{ "user", userObject },
|
||
{ "biaoti", new List<string>(famNames) }
|
||
}
|
||
}
|
||
});
|
||
}
|
||
}
|
||
else if (item.actItem.subject.Contains("超"))
|
||
{
|
||
var leftNames = new List<string>();
|
||
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<Dictionary<string, object>>)existing[orderNo]["entry"];
|
||
var existingYangshang = entryList.FirstOrDefault(e => IsSamePeople(e["yangshang"]?.ToString(), leftFamName));
|
||
if (existingYangshang != null)
|
||
{
|
||
var oldBiaoti = (List<string>)existingYangshang["biaoti"];
|
||
oldBiaoti.AddRange(famNames);
|
||
existingYangshang["biaoti"] = oldBiaoti.Distinct().ToList();
|
||
}
|
||
else
|
||
{
|
||
entryList.Add(new Dictionary<string, object>
|
||
{
|
||
{ "yangshang", leftFamName },
|
||
{ "biaoti", new List<string>(famNames) }
|
||
});
|
||
}
|
||
}
|
||
else
|
||
{
|
||
chaodu.Add(new Dictionary<string, Dictionary<string, object>>
|
||
{
|
||
{
|
||
orderNo,
|
||
new Dictionary<string, object>
|
||
{
|
||
{ "user", userObject },
|
||
{
|
||
"entry",
|
||
new List<Dictionary<string, object>>
|
||
{
|
||
new Dictionary<string, object>
|
||
{
|
||
{ "yangshang", leftFamName },
|
||
{ "biaoti", new List<string>(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)
|
||
{
|
||
var data = _db.ShuWens.Where(a => a.ActivityNum == activitynum).FirstOrDefault();
|
||
if (data == null)
|
||
{
|
||
//return;
|
||
}
|
||
string json = data.ShuWenList;
|
||
string ActivityName = _db.activities.Where(a => a.num == data.ActivityNum).FirstOrDefault().subject;
|
||
if (json == null)
|
||
{
|
||
//return;
|
||
}
|
||
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;
|
||
}
|
||
|
||
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<JObject>())
|
||
{
|
||
foreach (var prop in item.Properties())
|
||
{
|
||
string orderNo = prop.Name;
|
||
//var names = prop.Value.ToObject<List<string>>();
|
||
var detail = prop.Value as JObject;
|
||
string username = detail?["user"]?["name"]?.ToString();
|
||
var biaotiList = detail?["biaoti"]?.ToObject<List<string>>() ?? new List<string>();
|
||
|
||
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<JObject>())
|
||
{
|
||
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<List<string>>() ?? new List<string>();
|
||
|
||
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<Paragraph>().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);
|
||
}
|
||
|
||
|
||
} |