kyy
2025-07-14 fbbb2e3801dc7a1073d555278f92353d5c14ab86
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
using ConsoleApp1;
using MES.Service.service.PLM;
using MES.Service.util;
using Microsoft.AspNetCore.Mvc;
using System.Dynamic;
using System.IO;
using PdfiumViewer;
using MES.Service.Dto.service;
using System.Drawing;
using System.Collections.Generic;
using System.Threading.Tasks;
using Oracle.ManagedDataAccess.Client;
using Microsoft.Extensions.Configuration;
using System;
using System.Text.RegularExpressions;
using IronSoftware.Drawing;
 
namespace MESApplication.Controllers.PLM
{
    [ApiController]
    [Route("api/PLM")]
    public class PLMController : ControllerBase
    {
        private readonly PLMManager m = new();
        private readonly WarehouseDownloadDoc wdd = new();
        private readonly IConfiguration _configuration;
 
        public PLMController(IConfiguration configuration)
        {
            _configuration = configuration;
        } // RetrieveDrawings 调取图纸
 
        [HttpPost("RetrieveDrawings")]
        public async Task<ResponseResult> RetrieveDrawings(PurchaseInventory dto)
        {
            try
            {
                dynamic resultInfos = new ExpandoObject();
                var retrieveDrawings =
                    m.RetrieveDrawings(dto.ItemNo); // 自定义保存根目录
                // string saveRootDirectory = @"D:\LTSMES\PLM";                
                string saveRootDirectory = @"E:\SOPimage";
                string
                    saveDirectory =
                        Path.Combine(saveRootDirectory,
                            dto.ItemNo); // 在循环处理所有 PDF 文件之前,如果该 itemNo 已存在表中,则进行删除操作
                await DeleteRecordsByItemNo(dto.ItemNo);
                // 在循环处理所有 PDF 文件之前,检查并删除旧文件夹(如果存在),然后重新创建
                if (Directory.Exists(saveDirectory))
                {
                    Directory.Delete(saveDirectory, true);
                }
 
                Directory.CreateDirectory(saveDirectory);
                foreach (var retrieveDrawing in retrieveDrawings)
                {
                    var streamFile = wdd.SendRequest("Download", retrieveDrawing.FRelevantObject);
                    var fileStreamResult = File(streamFile, "application/octet-stream", retrieveDrawing.FName);
                    var saveResult = await SavePdfAsync(fileStreamResult, saveRootDirectory, dto.ItemNo, dto.Cx,
                        retrieveDrawing.FName);
                }
 
                return new ResponseResult { status = 0, message = "OK", data = resultInfos };
            }
            catch (Exception ex)
            {
                return ResponseResult.ResponseError(ex);
            }
        } // ✅ 直接保存 PDF,不再转换为图片
 
        private async Task<dynamic> SavePdfAsync(FileStreamResult fileStreamResult, string saveRootDirectory,
            string itemNo, string cx, string fPhysicalFileName)
        {
            try
            {
                // 确保目录存在
                string saveDirectory = Path.Combine(saveRootDirectory, itemNo);
                if (!Directory.Exists(saveDirectory))
                {
                    Directory.CreateDirectory(saveDirectory);
                } // 保存 PDF 文件
 
                string outputFilePath = Path.Combine(saveDirectory,
                    $"{Path.GetFileNameWithoutExtension(fPhysicalFileName)}.pdf");
                using (var fileStream = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write))
                {
                    await fileStreamResult.FileStream.CopyToAsync(fileStream);
                }
 
                Console.WriteLine(
                    $"PDF 文件已保存: {outputFilePath}"); // 生成新的 URL(指向 PDF 文件)
                string
                    url =
                        $"http://192.168.1.92:89/{itemNo}/{Path.GetFileName(outputFilePath)}"; // 提取文件名中的最后一个'_'到'.pdf'之间的字母数字部分,并加上“工序”前缀
                string extractedNumber = ExtractNumberFromFileName(fPhysicalFileName);
                string
                    process = string.IsNullOrEmpty(extractedNumber)
                        ? string.Empty
                        : $"工序{extractedNumber}"; // ✅ 插入数据库(URL 指向 PDF,并更新工序字段)
                await InsertUrlIntoDatabase(url, itemNo, cx, process);
                return new { PdfFilePath = outputFilePath };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"PDF 保存失败: {ex.Message}");
                return new { ErrorMessage = "PDF 保存失败", Exception = ex.Message };
            }
        } // 提取文件名中的最后一个'_'到'.pdf'之间的字母数字部分,忽略括号等内容
 
        private string ExtractNumberFromFileName(string fileName)
        {
            // 使用正则表达式提取最后一个'_'到'.pdf'之间的字母数字部分,忽略括号等字符
            var match = Regex.Match(fileName, @"_([A-Za-z0-9]+)(?=\(?\.pdf$)");
            if (match.Success)
            {
                // 如果匹配成功,返回提取的部分
                return match.Groups[1].Value;
            }
            else
            {
                // 如果没有找到符合条件的部分,返回空字符串
                return string.Empty;
            }
        } // 将 URL、itemNo、cx 和工序字段插入到数据库中 
 
 
        private async Task InsertUrlIntoDatabase(string url, string itemNo, string cx, string gx)
        {
            string connectionString = _configuration["AppSettings:DataBaseConn"];
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                await connection.OpenAsync();
                string insertQuery =
                    "INSERT INTO MES_SOP_URL_TABLE (id, URL, ITEM_NO, CX, GX, CREATE_DATE) VALUES (SEQ_SOP_URL.NEXTVAL, :url, :item_no, :cx, :gx, :create_date)";
                using (OracleCommand insertCommand = new OracleCommand(insertQuery, connection))
                {
                    // 使用 Parameters.Add 方法添加参数
                    insertCommand.Parameters.Add("url", OracleDbType.Varchar2).Value = url;
                    insertCommand.Parameters.Add("item_no", OracleDbType.Varchar2).Value = itemNo;
                    insertCommand.Parameters.Add("cx", OracleDbType.Varchar2).Value = cx;
                    insertCommand.Parameters.Add("gx", OracleDbType.Varchar2).Value = gx;
                    insertCommand.Parameters.Add("create_date", OracleDbType.Date).Value = DateTime.Now;
                    await insertCommand.ExecuteNonQueryAsync();
                }
            }
        } // 删除指定 itemNo 的记录      
 
        private async Task DeleteRecordsByItemNo(string itemNo)
        {
            string connectionString = _configuration["AppSettings:DataBaseConn"];
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                await connection.OpenAsync();
                string deleteQuery = "DELETE FROM MES_SOP_URL_TABLE WHERE ITEM_NO = :item_no";
                using (OracleCommand deleteCommand = new OracleCommand(deleteQuery, connection))
                {
                    deleteCommand.Parameters.Add("item_no", OracleDbType.Varchar2).Value = itemNo;
                    await deleteCommand.ExecuteNonQueryAsync();
                }
            }
        }
    }
}