Files
HJGL_DS/HJGL_DS/FineUIPro.Web/HJGL/DataIn/DrawingRecognitionContent.aspx.cs
T
2026-06-15 10:58:37 +08:00

738 lines
30 KiB
C#

using Aspose.Words.Rendering;
using BLL;
using BLL.Common;
using FineUIPro.Web.HJGL.Match;
using Model;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using UglyToad.PdfPig;
using UglyToad.PdfPig.Content;
using UglyToad.PdfPig.Writer;
namespace FineUIPro.Web.HJGL.DataIn
{
public partial class DrawingRecognitionContent : PageBase
{
public string URL
{
get
{
return (string)ViewState["URL"];
}
set
{
ViewState["URL"] = value;
}
}
public string fileName
{
get
{
return (string)ViewState["fileName"];
}
set
{
ViewState["fileName"] = value;
}
}
public string fileUrl
{
get
{
return (string)ViewState["fileUrl"];
}
set
{
ViewState["fileUrl"] = value;
}
}
public DataTable dt
{
get
{
return (DataTable)ViewState["DataTable"];
}
set
{
ViewState["DataTable"] = value;
}
}
public DataTable dtOther
{
get
{
return (DataTable)ViewState["dtOther"];
}
set
{
ViewState["dtOther"] = value;
}
}
public DataTable dtIsoInfo
{
get
{
return (DataTable)ViewState["dtIsoInfo"];
}
set
{
ViewState["dtIsoInfo"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Request.Params["fileUrl"]))
{
URL = Funs.HJGLUrl + Request.Params["fileUrl"].Replace("\\", "/");
string rootPath = Server.MapPath("~/");
fileUrl = rootPath + Request.Params["fileUrl"];
fileName = Request.Params["fileName"];
// 加载PDF文档
if (!File.Exists(fileUrl))
{
return;
}
}
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
TabStrip1.Hidden = true;
contentPanel1.Hidden =false ;
string rootPath = Server.MapPath("~/");
Dictionary<string,List<int>> dic= new Dictionary<string, List<int>>();
foreach (DataRow row in dt.Rows)
{
if (!dic.ContainsKey(row["pipe_no"].ToString()))
{
dic.Add(row["pipe_no"].ToString().Trim(),new List<int>());
}
dic[row["pipe_no"].ToString().Trim()].Add(int.Parse(row["page_no"].ToString()));
}
using (var pdf = PdfDocument.Open(fileUrl))
{
for (int i = 0; i < pdf.NumberOfPages; i++)
{
var page = pdf.GetPage(i + 1);
var rotation = page.Rotation;
string outputPath = "";
string isono = "";
foreach (string key in dic.Keys)
{
if (dic[key].IndexOf(i + 1) >= 0)
{
isono = key;
outputPath = $"{rootPath}/File/PDF/Pipe/" + key;
if (!Directory.Exists(outputPath))
{
Directory.CreateDirectory(outputPath);
}
string fileName = key;
var row = dtOther.Select(" page='" + (i + 1) + "' and region_type='C' ").FirstOrDefault();
if (row != null)
{
if (!string.IsNullOrEmpty(row["text"].ToString()))
{
fileName = row["text"].ToString();
}
}
outputPath = $"{outputPath}/" + fileName + DateTime.Now.ToString("yyyyMMddHHmm") + ".pdf";
}
}
using (var writer = new PdfDocumentBuilder())
{
PdfPageBuilder newPage = null;
if (rotation.Value != 0 && rotation.Value != 180)
{
newPage = writer.AddPage(page.Height, page.Width);
}
else
{
newPage = writer.AddPage(page.Width, page.Height);
}
newPage.CopyFrom(page);
// 3. 关键:清除旋转标记 + 反向旋转内容(修正视觉方向)
// 清除 /Rotate 标记
newPage.SetRotation(new PageRotationDegrees(rotation.Value));
var newPdf = writer.Build();
File.WriteAllBytes(outputPath, newPdf);
var isoInfo = Funs.DB.HJGL_PW_IsoInfo.FirstOrDefault(x => x.ISO_IsoNo == isono && x.ProjectId==CurrUser.LoginProjectId);
if (isoInfo != null)
{
Regex NumberRegex = new Regex(@"\d+\.?\d*");
DataRow[] rows = dt.Select(" pipe_no='" + isono + "' and category='PIPE'");
if (rows != null && rows.Length > 0)
{
string description = rows[0]["description"].ToString();
if (!isoInfo.ISO_Dia.HasValue || !isoInfo.ISO_Sch.HasValue || string.IsNullOrEmpty(isoInfo.MaterialStandardId))
{
string res = OpenAIhelper.ChatCompletion("请根据 " + description + ",识别外径,壁厚,材质标准(请严格按照国家标准返回),结果仅以JSON格式返回,不要解释,不要多余文字,不要markdown,例如 {\r\n \"外径\": \"33.4 mm\",\r\n \"壁厚\": \"6.35 mm\",\r\n \"材质标准\": \"GB/T 9948\"\r\n}");
ErrLogInfo.WriteLog(res);
JObject jobject = JObject.Parse(res);
string dia = jobject.Value<string>("外径");
string sch = jobject.Value<string>("壁厚");
string materialStandard = jobject.Value<string>("材质标准");
MatchCollection matchCollection1 = NumberRegex.Matches(dia);
foreach (var match in matchCollection1)
{
// 使用 TryParse 确保转换安全,避免异常
if (decimal.TryParse(match.ToString(), out decimal number))
{
isoInfo.ISO_Dia = number;
}
}
MatchCollection matchCollection2 = NumberRegex.Matches(sch);
foreach (var match in matchCollection2)
{
// 使用 TryParse 确保转换安全,避免异常
if (decimal.TryParse(match.ToString(), out decimal number))
{
isoInfo.ISO_Sch = number;
}
}
isoInfo.MaterialStandardId = Funs.DB.HJGL_BS_MaterialStandard.Where(x => x.MaterialStandardCode == materialStandard).Select(x => x.MaterialStandardId).FirstOrDefault();
}
decimal length = 0;
foreach(DataRow row in rows)
{
MatchCollection matches = NumberRegex.Matches(row["qty"].ToString());
foreach (var match in matches)
{
// 使用 TryParse 确保转换安全,避免异常
if (decimal.TryParse(match.ToString(), out decimal number))
{
length += number;
}
}
}
isoInfo.PipeLineLength = length;
}
DataRow[] rowsPipe = dtIsoInfo.Select(" pipeline_id='" + isono + "' ");
if (rowsPipe != null && rowsPipe.Length > 0)
{
string isNeedHead = rowsPipe[0]["post_weld_heat_treatment"].ToString();
if (isNeedHead == "N")
{
isoInfo.IsHot = "0";
isoInfo.IsHotType = null;
}
else
{
isoInfo.IsHot = "1";
}
}
Funs.DB.SubmitChanges();
//保存文件到附件
UploadFileService.SaveAttachUrl(UploadFileService.GetSourceByAttachUrl(outputPath.Replace(rootPath, ""), 10, null), outputPath.Replace(rootPath, ""), Const.HJGL_PipelineManageMenuId, isoInfo.ISO_ID);
}
}
}
}
}
public static string HeaderCorrespondence(string uploadUrl, string data, string method, string contenttype)
{
// 5. 创建HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uploadUrl);
request.Method = string.IsNullOrEmpty(method) ? "GET" : method;
request.ContentType = string.IsNullOrEmpty(contenttype) ? "application/json;charset=utf-8" : contenttype;
if (uploadUrl.IndexOf("https") >= 0)
{
request.ProtocolVersion = HttpVersion.Version10;
}
if (!string.IsNullOrEmpty(data))
{
Stream RequestStream = request.GetRequestStream();
byte[] bytes = Encoding.UTF8.GetBytes(data);
RequestStream.Write(bytes, 0, bytes.Length);
RequestStream.Close();
}
HttpWebResponse response = null;
Stream ResponseStream = null;
StreamReader StreamReader = null;
try
{
response = (HttpWebResponse)request.GetResponse();
ResponseStream = response.GetResponseStream();
StreamReader = new StreamReader(ResponseStream, Encoding.GetEncoding("utf-8"));
string re = StreamReader.ReadToEnd();
StreamReader.Close();
ResponseStream.Close();
return re;
}
catch (WebException ex)
{
response = (HttpWebResponse)ex.Response;
ResponseStream = response.GetResponseStream();
StreamReader = new StreamReader(ResponseStream, Encoding.GetEncoding("utf-8"));
string re = StreamReader.ReadToEnd();
return re;
}
finally
{
if (StreamReader != null)
{
StreamReader.Close();
}
if (ResponseStream != null)
{
ResponseStream.Close();
}
if (response != null)
{
response.Close();
}
}
}
protected void btnAudit_Click(object sender, EventArgs e)
{
TabStrip1.Hidden = false;
contentPanel1.Hidden = true;
btnAudit.Hidden = true;
btnSave.Hidden = false;
if (!string.IsNullOrEmpty(resultdata.Value))
{
JObject jobject = JObject.Parse(resultdata.Value);
JArray jArray = jobject.Value<JArray>("material_rows");
JArray jArrayOther = jobject.Value<JArray>("other_regions");
JArray jArrayIsoInfo = jobject.Value<JArray>("drawing_info");
dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("pipe_no");
dt.Columns.Add("drawing_number");
dt.Columns.Add("seq_no");
dt.Columns.Add("category");
dt.Columns.Add("description");
dt.Columns.Add("spec");
dt.Columns.Add("qty");
dt.Columns.Add("page_no");
dt.Columns.Add("remark");
dtOther = new DataTable();
dtOther.Columns.Add("id");
dtOther.Columns.Add("region_type");
dtOther.Columns.Add("region_label");
dtOther.Columns.Add("page");
dtOther.Columns.Add("text");
dtIsoInfo = new DataTable();
dtIsoInfo.Columns.Add("id");
dtIsoInfo.Columns.Add("page_no");
dtIsoInfo.Columns.Add("drawing_number");
dtIsoInfo.Columns.Add("pipeline_id");
dtIsoInfo.Columns.Add("operation_pressure_mpa");
dtIsoInfo.Columns.Add("operation_temp_c");
dtIsoInfo.Columns.Add("design_pressure_mpa");
dtIsoInfo.Columns.Add("design_temp_c");
dtIsoInfo.Columns.Add("test_pressure_mpa");
dtIsoInfo.Columns.Add("hydraulic_test_pressure");
dtIsoInfo.Columns.Add("pipe_diameter_dn");
dtIsoInfo.Columns.Add("pipe_spec_grade");
dtIsoInfo.Columns.Add("heat_insulation");
dtIsoInfo.Columns.Add("insulation_thickness_mm");
dtIsoInfo.Columns.Add("post_weld_heat_treatment");
dtIsoInfo.Columns.Add("radiographic_examination");
foreach (JObject item in jArrayOther)
{
var row = dtOther.NewRow();
row["id"] = item.Value<string>("id");
row["region_type"] = item.Value<string>("region_type");
row["region_label"] = item.Value<string>("region_label");
row["page"] = item.Value<string>("page");
row["text"] = item.Value<string>("text");
dtOther.Rows.Add(row);
}
// 遍历并提取数据
foreach (JObject item in jArray)
{
var row = dt.NewRow();
row["id"] = item.Value<string>("id");
row["pipe_no"] = item.Value<string>("pipe_no");
row["drawing_number"] = item.Value<string>("drawing_number");
row["seq_no"] = item.Value<string>("seq_no");
row["category"] = item.Value<string>("category");
row["description"] = item.Value<string>("description");
row["spec"] = item.Value<string>("spec");
row["qty"] = item.Value<string>("qty");
row["page_no"] = item.Value<string>("page_no");
row["remark"] = item.Value<string>("remark");
if (string.IsNullOrEmpty(row["drawing_number"].ToString()))
{
var rowOther = dtOther.Select("page= " + row["page_no"].ToString()).FirstOrDefault();
row["drawing_number"] = rowOther["text"];
}
dt.Rows.Add(row);
}
foreach (JObject item in jArrayIsoInfo)
{
var row = dtIsoInfo.NewRow();
row["id"] = item.Value<string>("id");
row["page_no"] = item.Value<string>("page_no");
row["drawing_number"] = item.Value<string>("drawing_number");
row["pipeline_id"] = item.Value<string>("pipeline_id");
row["operation_temp_c"] = item.Value<string>("operation_temp_c");
row["design_pressure_mpa"] = item.Value<string>("design_pressure_mpa");
row["design_temp_c"] = item.Value<string>("design_temp_c");
row["test_pressure_mpa"] = item.Value<string>("test_pressure_mpa");
row["hydraulic_test_pressure"] = item.Value<string>("hydraulic_test_pressure");
row["pipe_diameter_dn"] = item.Value<string>("pipe_diameter_dn");
row["pipe_spec_grade"] = item.Value<string>("pipe_spec_grade");
row["heat_insulation"] = item.Value<string>("heat_insulation");
row["insulation_thickness_mm"] = item.Value<string>("insulation_thickness_mm");
row["post_weld_heat_treatment"] = item.Value<string>("post_weld_heat_treatment");
row["radiographic_examination"] = item.Value<string>("radiographic_examination");
dtIsoInfo.Rows.Add(row);
}
BindGrid();
}
}
private void BindGrid()
{
Grid1.DataSource = dt;
Grid1.DataBind();
// Grid2: 按图号合并 — 图号、类型、规格、描述相同的,数量累加
if (dt != null && dt.Rows.Count > 0)
{
DataTable dtGroupByDrawing = new DataTable();
dtGroupByDrawing.Columns.Add("id");
dtGroupByDrawing.Columns.Add("drawing_number");
dtGroupByDrawing.Columns.Add("category");
dtGroupByDrawing.Columns.Add("spec");
dtGroupByDrawing.Columns.Add("qty");
dtGroupByDrawing.Columns.Add("description");
var groups2 = dt.AsEnumerable()
.GroupBy(r => new
{
drawing_number = r.Field<string>("drawing_number") ?? "",
category = r.Field<string>("category") ?? "",
spec = r.Field<string>("spec") ?? "",
description = r.Field<string>("description") ?? ""
})
.Select(g => new
{
g.Key.drawing_number,
g.Key.category,
g.Key.spec,
g.Key.description,
qty = g.Sum(r => Funs.GetNewDecimalOrZero(r.Field<string>("qty")))
});
foreach (var g in groups2)
{
DataRow newRow = dtGroupByDrawing.NewRow();
newRow["id"] = Guid.NewGuid().ToString();
newRow["drawing_number"] = g.drawing_number;
newRow["category"] = g.category;
newRow["spec"] = g.spec;
newRow["qty"] = g.qty;
newRow["description"] = g.description;
dtGroupByDrawing.Rows.Add(newRow);
}
Grid2.DataSource = dtGroupByDrawing;
}
else
{
Grid2.DataSource = null;
}
Grid2.DataBind();
// Grid3: 按管线号合并 — 类型、规格、描述相同的,数量累加(不展示图号)
if (dt != null && dt.Rows.Count > 0)
{
DataTable dtGroupByPipe = new DataTable();
dtGroupByPipe.Columns.Add("id");
dtGroupByPipe.Columns.Add("pipe_no");
dtGroupByPipe.Columns.Add("category");
dtGroupByPipe.Columns.Add("spec");
dtGroupByPipe.Columns.Add("qty");
dtGroupByPipe.Columns.Add("description");
var groups3 = dt.AsEnumerable()
.GroupBy(r => new
{
pipe_no = r.Field<string>("pipe_no") ?? "",
category = r.Field<string>("category") ?? "",
spec = r.Field<string>("spec") ?? "",
description = r.Field<string>("description") ?? ""
})
.Select(g => new
{
g.Key.pipe_no,
g.Key.category,
g.Key.spec,
g.Key.description,
qty = g.Sum(r => Funs.GetNewDecimalOrZero(r.Field<string>("qty")))
});
foreach (var g in groups3)
{
DataRow newRow = dtGroupByPipe.NewRow();
newRow["id"] = Guid.NewGuid().ToString();
newRow["pipe_no"] = g.pipe_no;
newRow["category"] = g.category;
newRow["spec"] = g.spec;
newRow["qty"] = g.qty;
newRow["description"] = g.description;
dtGroupByPipe.Rows.Add(newRow);
}
Grid3.DataSource = dtGroupByPipe;
}
else
{
Grid3.DataSource = null;
}
Grid3.DataBind();
// 材料汇总表:按类型、规格、描述汇总数量
DataTable dtSummary = new DataTable();
dtSummary.Columns.Add("id");
dtSummary.Columns.Add("category");
dtSummary.Columns.Add("spec");
dtSummary.Columns.Add("qty");
dtSummary.Columns.Add("description");
if (dt != null && dt.Rows.Count > 0)
{
var groups = dt.AsEnumerable()
.GroupBy(r => new
{
cat = r["category"].ToString().Trim(),
sp = r["spec"].ToString().Trim(),
desc = r["description"].ToString().Trim()
})
.OrderBy(g => g.Key.cat)
.ThenBy(g => g.Key.sp);
int idx = 1;
foreach (var g in groups)
{
var row = dtSummary.NewRow();
row["id"] = idx++;
row["category"] = g.Key.cat;
row["spec"] = g.Key.sp;
row["description"] = g.Key.desc;
decimal totalQty = 0;
foreach (var r in g)
{
if (decimal.TryParse(r["qty"].ToString(), out decimal qty))
totalQty += qty;
}
row["qty"] = totalQty.ToString();
dtSummary.Rows.Add(row);
}
}
Grid4.DataSource = dtSummary;
Grid4.DataBind();
}
#region
/// <summary>
/// Grid行双击事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Grid1_RowDoubleClick(object sender, GridRowClickEventArgs e)
{
if (Grid1.SelectedRowIndexArray.Length == 0)
{
Alert.ShowInTop("请选择一条记录!", MessageBoxIcon.Warning);
return;
}
if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_DataInMenuId, Const.BtnAdd))
{
if (DrawingRecognitionContentEdit.dicDt.ContainsKey(CurrUser.UserId))
{
DrawingRecognitionContentEdit.dicDt[CurrUser.UserId ]= dt;
}
else
{
DrawingRecognitionContentEdit.dicDt.Add(CurrUser.UserId, dt);
}
PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("DrawingRecognitionContentEdit.aspx?Index={0}", Grid1.SelectedRowIndex, "维护 - ")));
}
else
{
ShowNotify("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
}
}
#endregion
protected void Window1_Close(object sender, WindowCloseEventArgs e)
{
BindGrid();
}
#region
/// <summary>
/// 从URL中获取文件名(不含扩展名)
/// </summary>
private string GetUrlFileName()
{
if (!string.IsNullOrEmpty(fileName))
{
try
{
return System.IO.Path.GetFileNameWithoutExtension(fileName);
}
catch { }
}
return "";
}
/// <summary>
/// 导出材料表
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnOut1_Click(object sender, EventArgs e)
{
Response.ClearContent();
string filename = Funs.GetNewFileName();
string prefix = GetUrlFileName();
Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(prefix + "材料表" + filename, System.Text.Encoding.UTF8) + ".xls");
Response.ContentType = "application/excel";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.Write(GetGridTableHtml(Grid1));
Response.End();
}
/// <summary>
/// 导出其他区域
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnOut2_Click(object sender, EventArgs e)
{
Response.ClearContent();
string filename = Funs.GetNewFileName();
string prefix = GetUrlFileName();
Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(prefix + "图纸材料表" + filename, System.Text.Encoding.UTF8) + ".xls");
Response.ContentType = "application/excel";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.Write(GetGridTableHtml(Grid2));
Response.End();
}
/// <summary>
/// 导出图纸信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnOut3_Click(object sender, EventArgs e)
{
Response.ClearContent();
string filename = Funs.GetNewFileName();
string prefix = GetUrlFileName();
Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(prefix + "管道材料表" + filename, System.Text.Encoding.UTF8) + ".xls");
Response.ContentType = "application/excel";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.Write(GetGridTableHtml(Grid3));
Response.End();
}
/// <summary>
/// 导出材料汇总表
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnOut4_Click(object sender, EventArgs e)
{
Response.ClearContent();
string filename = Funs.GetNewFileName();
string prefix = GetUrlFileName();
Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(prefix + "材料汇总表" + filename, System.Text.Encoding.UTF8) + ".xls");
Response.ContentType = "application/excel";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.Write(GetGridTableHtml(Grid4));
Response.End();
}
/// <summary>
/// 导出方法
/// </summary>
/// <param name="grid"></param>
/// <returns></returns>
private string GetGridTableHtml(Grid grid)
{
StringBuilder sb = new StringBuilder();
sb.Append("<meta http-equiv=\"content-type\" content=\"application/excel; charset=UTF-8\"/>");
sb.Append("<table cellspacing=\"0\" rules=\"all\" border=\"1\" style=\"border-collapse:collapse;\">");
sb.Append("<tr>");
foreach (GridColumn column in grid.Columns)
{
sb.AppendFormat("<td>{0}</td>", column.HeaderText);
}
sb.Append("</tr>");
int i = 0;
foreach (GridRow row in grid.Rows)
{
sb.Append("<tr>");
i++;
foreach (GridColumn column in grid.Columns)
{
if (column.ColumnID == "SortIndex")
{
sb.AppendFormat("<td>{0}</td>", i.ToString());
}
else
{
string html = row.Values[column.ColumnIndex].ToString();
sb.AppendFormat("<td>{0}</td>", html);
}
}
sb.Append("</tr>");
}
sb.Append("</table>");
return sb.ToString();
}
#endregion
}
}