Files
lserp_cs_6.0/插件库/Lskj.PubBomImport/FrmProgress.cs
T
tdx 68965068bd SVN r588
SVN-Revision: r588
2025-05-15 12:18:47 +00:00

2427 lines
160 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Net;
using Lskj.Control;
using System.Threading.Tasks;
using Lskj.Core;
using DevExpress.XtraGrid.Columns;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using Lskj.Model;
using Lskj.Control.BrowserSetting;
using Lskj.Business;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Lskj.Business.Impl;
using System.Text.RegularExpressions;
using Lskj.Util;
using System.Web;
using Lskj.Control.Model;
using System.Data.SqlClient;
namespace Lskj.PubBomImport
{
/// <summary>
/// 下载进度窗口
/// </summary>
public partial class FrmProgress : Form
{
public FrmMain frmMain;
public DynamicBomImport Model;
public System.Windows.Forms.Timer ImportTimer = new System.Windows.Forms.Timer();
public FrmProgress()
{
InitializeComponent();
this.ControlBox = false;
}
/// <summary>
/// 开始导入
/// </summary>
/// <param name="dirPaths"></param>
public void StartImportInDir(string dirPath)
{
try
{
Model = frmMain.Model;
DirectoryInfo directoryInfo = new DirectoryInfo(dirPath);
FileInfo[] fileInfos = directoryInfo.GetFiles();
FileInfo parentInfo = fileInfos.Where(n => n.Name.StartsWith("MX") && n.Extension.Equals(".xlsx", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
if (parentInfo != null)
{
if (Directory.Exists("BomImportTemp"))
{
Directory.Delete("BomImportTemp", true);
}
Directory.CreateDirectory("BomImportTemp");
FrmBillInfo frmBillInfo = new FrmBillInfo();
DataTable parentTable = ExcelToDatatable(parentInfo.FullName, Model, "", 5);
parentTable = parentTable.Rows.Cast<DataRow>().Where(n => int.TryParse(n["序号"] + "", out _) && !string.IsNullOrEmpty(n["图号"] + "")).ToList().CopyToDataTable();
Dictionary<string, string> childFileDic = new Dictionary<string, string>();
foreach (DataRow parentRow in parentTable.Rows)
{
string fileName = (parentRow["图号"] + "").Trim();
if (fileName.StartsWith("QD") || fileName.StartsWith("ZZQD"))
{
FileInfo childInfo = fileInfos.Where(n => n.Name.StartsWith(fileName)).FirstOrDefault();
if (childInfo == null)
{
string fileSql = $"select webpath,sName from P_fm_FileTab where sName like '{fileName}%' and speciesno = '010106' and parentId in (select dirid from p_fm_directorytab where dllcoid = '1000202'";
DataRow fileRow = BaseImpl.GetDataRowResult(fileSql);
string webpath = fileRow != null ? fileRow["webpath"] + "" : "";
string sName = fileRow != null ? fileRow["sName"] + "" : "";
if (string.IsNullOrEmpty(webpath))
{
throw new Exception($"Bom明细附件{fileName}不存在\r\nBom导入失败");
}
else
{
using (WebClient webClient = new WebClient())
{
try
{
webpath = webpath.StartsWith("/") ? webpath : $"/{webpath}";
string url = $"{SystemInfo.Instance.OAUrl}/{webpath}";
string tempFileName = $"BomImportTemp/{sName}";
webClient.DownloadFile(url, tempFileName);
childFileDic.Add(fileName, tempFileName);
}
catch (Exception)
{
throw new Exception($"Bom明细附件{fileName}获取失败\r\nBom导入失败");
}
}
}
}
}
}
StringBuilder stringBuilder = new StringBuilder();
foreach (DataRow dataRow in parentTable.Rows)
{
string code = (dataRow["图号"] + "").Trim();
if (code.StartsWith("QD") || code.StartsWith("ZZQD"))
{
stringBuilder.AppendLine($"if not exists (select productid from p_ProductTab where productid = '{dataRow["图号"] + ""}')");
stringBuilder.AppendLine($"begin insert into p_ProductTab (productid,appellation,bak,SpeciesNo) values ('{(dataRow["图号"] + "").Replace("'", "''")}','{(dataRow["名称"] + "").Replace("'", "''")}','{(dataRow["备注"] + "").Replace("'", "''")}','0199') end;");
}
}
if (!string.IsNullOrEmpty(stringBuilder.ToString()))
{
SqlHelper.ExecuteNonQuery(stringBuilder.ToString());
}
frmBillInfo.OnControlSourceBind += (s, args) =>
{
Task task = new Task(() =>
{
try
{
SetProcessBar(0, 0);
SetProcessMsg($"正在导入:{Path.GetFileName(parentInfo.FullName)}");
DataTable childTable = new DataTable();
foreach (GridColumn gridColumn in frmBillInfo.GcMainView.Columns)
{
if (!childTable.Columns.Contains(gridColumn.FieldName))
{
childTable.Columns.Add(gridColumn.FieldName, gridColumn.ColumnType);
}
}
foreach (DataRow parentRow in parentTable.Rows)
{
string code = parentRow["图号"] + "";
if (code.StartsWith("QD") || code.StartsWith("ZZQD"))
{
FileInfo childInfo = fileInfos.Where(n => n.Name.StartsWith(code)).FirstOrDefault();
if (childInfo == null)
{
string tempFileName = childFileDic[code];
childInfo = new FileInfo(tempFileName);
}
if (childInfo != null)
{
DataRow childRow = childTable.NewRow();
childRow["ProductId"] = parentRow["图号"] + "";
childRow["appellation"] = parentRow["名称"] + "";
childRow["bak"] = parentRow["备注"] + "";
childRow["tamount"] = parentRow["套数"] + "";
childRow["amount"] = parentRow["套数"] + "";
childTable.Rows.Add(childRow);
}
}
}
SetProcessBar(20, 0);
frmBillInfo.GcMainView.GridControl.DataSource = childTable;
SetProcessBar(40, 0);
string controlSql = "select '' as billdocument_id,'0' affirmer,'0' rtagid,'{材料代码}' as productid";
frmBillInfo.InitializeHeader(Model.MaintabFocusedRow, controlSql);
SetProcessBar(60, 0);
string billNo = "";
frmBillInfo.BillSave(ref billNo);
SetProcessBar(80, 0);
frmBillInfo.OnBillAdd();
string productId = Model.MaintabFocusedRow["材料代码"] + "";
string billdocumentId = Model.MaintabFocusedRow["单据编号"] + "";
string idValue = BaseImpl.GetResult($"select top 1 billdocument_id from bom_billListTab where ParentProduct = '{productId}'") + "";
string updateParentVerSql = @"update bom_BillListTab set Ver = '{0}' where Billdocument_Id='{1}' and ProductId='{0}'";
SqlHelper.ExecuteNonQuery(string.Format(updateParentVerSql, idValue, billdocumentId));
//上传文件
bool isUpload = UploadFile(parentInfo.FullName, idValue, out string msg, out string _);
SetProcessBar(100, (1 / (parentTable.Rows.Count + 1)) * 100);
SetProcessLabelAllMsg($"总进度:{1}/{parentTable.Rows.Count + 1}");
int.TryParse(Model.FirstRowIndex, out int index);
frmMain.FirstRowIndex = index;
foreach (DataRow dataRow in parentTable.Rows)
{
int childIndex = parentTable.Rows.IndexOf(dataRow);
int nowCount = 1 + childIndex;
int allCount = (int)((decimal)(1 + childIndex) / (parentTable.Rows.Count + 1) * 100);
int finishCount = (int)((decimal)(1 + nowCount) / (parentTable.Rows.Count + 1) * 100);
int.TryParse(dataRow["套数"] + "", out int tamount);
string code = (dataRow["图号"] + "").Trim();
if (code.StartsWith("QD") || code.StartsWith("ZZQD"))
{
DataRow productRow = BaseImpl.GetDataRowResult($"select top 1 billdocument_id from bom_BillTab where productid='{code}'");
if (productRow == null)
{
FileInfo childInfo = fileInfos.Where(n => n.Name.StartsWith(code)).FirstOrDefault();
if (childInfo == null)
{
string tempFileName = childFileDic[code];
childInfo = new FileInfo(tempFileName);
}
if (childInfo != null)
{
if ((code.StartsWith("QD") || code.StartsWith("ZZQD")))
{
SetProcessBar(0, allCount);
SetProcessMsg($"正在导入:{Path.GetFileName(childInfo.FullName)}");
DataTable detailTable = new DataTable();
frmMain.Invoke(new Action(() =>
{
detailTable = frmMain.ToExcelDataTable(childInfo.FullName, out int count, out int errorCount, true);
}));
foreach (DataRow detailRow in detailTable.Rows)
{
int.TryParse(detailRow["amount"] + "", out int lastAmount);
detailRow["tamount"] = tamount;
detailRow["amount"] = lastAmount;
}
frmBillInfo.GcMainView.GridControl.DataSource = detailTable;
SetProcessBar(20, allCount);
frmBillInfo.InitializeHeader(dataRow, Model.BillMasterSql);
SetProcessBar(40, allCount);
string childBillNo = "";
frmBillInfo.BillSave(ref childBillNo);
SetProcessBar(60, allCount);
frmBillInfo.OnBillAdd();
//记录历史版本号
string updateHistoryVerSql = @"update bom_BillListTab set historyVer = '{0}' where Billdocument_Id='{1}'";
SqlHelper.ExecuteNonQuery(string.Format(updateHistoryVerSql, code, childBillNo));
//备份Bom清单明细
string bakBomListSql = @"delete bom_BillListlogTab where parentProduct = '{0}' and historyVer = (select top 1 historyVer from bom_BillListTab where parentProduct = '{0}');insert into bom_BillListlogTab select * from bom_BillListTab where parentProduct = '{0}';";
SqlHelper.ExecuteNonQuery(string.Format(bakBomListSql, code));
//更新明细关联版本号
string updateChildVerSql = @"update bom_BillListTab set Ver = (select top 1 billdocument_id from bom_billListTab where ParentProduct = '{0}') where Billdocument_Id = (select top 1 billdocument_id from bom_billListTab where ParentProduct = '{1}') and ProductId='{0}'";
SqlHelper.ExecuteNonQuery(string.Format(updateChildVerSql, code, productId));
SetProcessBar(80, allCount);
isUpload = UploadFile(childInfo.FullName, idValue, out msg, out string _);
SetProcessBar(100, finishCount);
SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{parentTable.Rows.Count + 1}");
}
}
}
}
else
{
FileInfo childInfo = fileInfos.Where(n => n.Name.StartsWith(code)).FirstOrDefault();
if (childInfo != null)
{
isUpload = UploadFile(childInfo.FullName, idValue, out msg, out string _);
SetProcessBar(100, finishCount);
SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{parentTable.Rows.Count + 1}");
}
}
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
}
finally
{
this.DialogResult = DialogResult.OK;
this.Close();
ImportTimer?.Dispose();
}
});
task.Start();
};
frmBillInfo.OnLoad(Model);
frmMain.ParentView = frmBillInfo.GcMainView;
}
else
{
throw new Exception("未包含结构文件");
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.DialogResult = DialogResult.OK;
Close();
ImportTimer?.Dispose();
}
}
/// <summary>
/// 开始导入
/// </summary>
/// <param name="dirPaths"></param>
public void StartImportInMxFile(string dirPath)
{
try
{
Model = frmMain.Model;
FileInfo parentInfo = new FileInfo(dirPath);
if (parentInfo != null && parentInfo.Name.Trim().StartsWith("MX"))
{
if (Directory.Exists("BomImportTemp"))
{
Directory.Delete("BomImportTemp", true);
}
Directory.CreateDirectory("BomImportTemp");
DataTable parentTable = ExcelToDatatable(parentInfo.FullName, Model, "", 5);
parentTable = parentTable.Rows.Cast<DataRow>().Where(n => int.TryParse(n["序号"] + "", out _) && !string.IsNullOrEmpty(n["图号"] + "")).ToList().CopyToDataTable();
Dictionary<string, string> childFileDic = new Dictionary<string, string>();
foreach (DataRow parentRow in parentTable.Rows)
{
string fileName = (parentRow["图号"] + "").Trim();
if (fileName.StartsWith("QD") || fileName.StartsWith("ZZQD"))
{
string fileSql = $"select webpath,sName from P_fm_FileTab where sName like '{fileName}%' and speciesno = '010106' and parentId in (select dirid from p_fm_directorytab where dllcoid = '1000202'";
DataRow fileRow = BaseImpl.GetDataRowResult(fileSql);
string webpath = fileRow != null ? fileRow["webpath"] + "" : "";
string sName = fileRow != null ? fileRow["sName"] + "" : "";
if (string.IsNullOrEmpty(webpath))
{
throw new Exception($"Bom明细附件{fileName}不存在\r\nBom导入失败");
}
else
{
using (WebClient webClient = new WebClient())
{
try
{
webpath = webpath.StartsWith("/") ? webpath : $"/{webpath}";
string url = $"{SystemInfo.Instance.OAUrl}/{webpath}";
string tempFileName = $"BomImportTemp/{sName}";
webClient.DownloadFile(url, tempFileName);
childFileDic.Add(fileName, tempFileName);
}
catch (Exception)
{
throw new Exception($"Bom明细附件{fileName}获取失败\r\nBom导入失败");
}
}
}
}
}
StringBuilder stringBuilder = new StringBuilder();
foreach (DataRow dataRow in parentTable.Rows)
{
string code = (dataRow["图号"] + "").Trim();
if (code.StartsWith("QD") || code.StartsWith("ZZQD"))
{
stringBuilder.AppendLine($"if not exists (select productid from p_ProductTab where productid = '{dataRow["图号"] + ""}')");
stringBuilder.AppendLine($"begin insert into p_ProductTab (productid,appellation,bak,SpeciesNo) values ('{(dataRow["图号"] + "").Replace("'", "''")}','{(dataRow["名称"] + "").Replace("'", "''")}','{(dataRow["备注"] + "").Replace("'", "''")}','0199') end;");
}
}
if (!string.IsNullOrEmpty(stringBuilder.ToString()))
{
SqlHelper.ExecuteNonQuery(stringBuilder.ToString());
}
FrmBillInfo frmBillInfo = new FrmBillInfo();
frmBillInfo.OnControlSourceBind += (s, args) =>
{
Task task = new Task(() =>
{
try
{
SetProcessBar(0, 0);
SetProcessMsg($"正在导入:{Path.GetFileName(parentInfo.FullName)}");
DataTable childTable = new DataTable();
foreach (GridColumn gridColumn in frmBillInfo.GcMainView.Columns)
{
if (!childTable.Columns.Contains(gridColumn.FieldName))
{
childTable.Columns.Add(gridColumn.FieldName, gridColumn.ColumnType);
}
}
foreach (DataRow parentRow in parentTable.Rows)
{
string code = (parentRow["图号"] + "").Trim();
if (code.StartsWith("QD") || code.StartsWith("ZZQD"))
{
string tempFileName = childFileDic[code];
FileInfo childInfo = new FileInfo(tempFileName);
if (childInfo != null)
{
DataRow childRow = childTable.NewRow();
childRow["ProductId"] = parentRow["图号"] + "";
childRow["appellation"] = parentRow["名称"] + "";
childRow["bak"] = parentRow["备注"] + "";
childRow["tamount"] = parentRow["套数"] + "";
childRow["amount"] = parentRow["套数"] + "";
childTable.Rows.Add(childRow);
}
else
{
throw new Exception($"Bom明细附件{code}获取失败\r\nBom导入失败");
}
}
}
SetProcessBar(20, 0);
frmBillInfo.GcMainView.GridControl.DataSource = childTable;
SetProcessBar(40, 0);
string controlSql = "select '' as billdocument_id,'0' affirmer,'0' rtagid,'{材料代码}' as productid";
frmBillInfo.InitializeHeader(Model.MaintabFocusedRow, controlSql);
SetProcessBar(60, 0);
string billNo = "";
frmBillInfo.BillSave(ref billNo);
SetProcessBar(80, 0);
frmBillInfo.OnBillAdd();
string productId = Model.MaintabFocusedRow["材料代码"] + "";
string billdocumentId = Model.MaintabFocusedRow["单据编号"] + "";
string idValue = BaseImpl.GetResult($"select top 1 billdocument_id from bom_billListTab where ParentProduct = '{productId}'") + "";
string updateParentVerSql = @"update bom_BillListTab set Ver = '{0}' where Billdocument_Id='{1}' and ProductId='{0}'";
SqlHelper.ExecuteNonQuery(string.Format(updateParentVerSql, idValue, billdocumentId));
//上传文件
bool isUpload = UploadFile(parentInfo.FullName, idValue, out string msg, out string _);
SetProcessBar(100, (1 / (parentTable.Rows.Count + 1)) * 100);
SetProcessLabelAllMsg($"总进度:{1}/{parentTable.Rows.Count + 1}");
int.TryParse(Model.FirstRowIndex, out int index);
frmMain.FirstRowIndex = index;
foreach (DataRow dataRow in parentTable.Rows)
{
int childIndex = parentTable.Rows.IndexOf(dataRow);
int nowCount = 1 + childIndex;
int allCount = (int)((decimal)(1 + childIndex) / (parentTable.Rows.Count + 1) * 100);
int finishCount = (int)((decimal)(1 + nowCount) / (parentTable.Rows.Count + 1) * 100);
int.TryParse(dataRow["套数"] + "", out int tamount);
string code = (dataRow["图号"] + "").Trim();
if (code.StartsWith("QD") || code.StartsWith("ZZQD"))
{
DataRow productRow = BaseImpl.GetDataRowResult($"select top 1 billdocument_id from bom_BillTab where productid='{code}'");
if (productRow == null)
{
string tempFileName = childFileDic[code];
FileInfo childInfo = new FileInfo(tempFileName);
if (childInfo != null)
{
SetProcessBar(0, allCount);
SetProcessMsg($"正在导入:{Path.GetFileName(childInfo.FullName)}");
DataTable detailTable = new DataTable();
frmMain.Invoke(new Action(() =>
{
detailTable = frmMain.ToExcelDataTable(childInfo.FullName, out int count, out int errorCount, true);
}));
foreach (DataRow detailRow in detailTable.Rows)
{
int.TryParse(detailRow["amount"] + "", out int lastAmount);
detailRow["tamount"] = tamount;
detailRow["amount"] = lastAmount;
}
frmBillInfo.GcMainView.GridControl.DataSource = detailTable;
SetProcessBar(20, allCount);
frmBillInfo.InitializeHeader(dataRow, Model.BillMasterSql);
SetProcessBar(40, allCount);
string childBillNo = "";
frmBillInfo.BillSave(ref childBillNo);
SetProcessBar(60, allCount);
frmBillInfo.OnBillAdd();
//记录历史版本号
string updateHistoryVerSql = @"update bom_BillListTab set historyVer = '{0}' where Billdocument_Id='{1}'";
SqlHelper.ExecuteNonQuery(string.Format(updateHistoryVerSql, code, childBillNo));
//备份Bom清单明细
string bakBomListSql = @"delete bom_BillListlogTab where parentProduct = '{0}' and historyVer = (select top 1 historyVer from bom_BillListTab where parentProduct = '{0}');insert into bom_BillListlogTab select * from bom_BillListTab where parentProduct = '{0}';";
SqlHelper.ExecuteNonQuery(string.Format(bakBomListSql, code));
//更新明细关联版本
string updateChildVerSql = @"update bom_BillListTab set Ver = (select top 1 billdocument_id from bom_billListTab where ParentProduct = '{0}') where Billdocument_Id = (select top 1 billdocument_id from bom_billListTab where ParentProduct = '{1}') and ProductId='{0}'";
SqlHelper.ExecuteNonQuery(string.Format(updateChildVerSql, code, productId));
SetProcessBar(80, allCount);
SetProcessBar(100, finishCount);
SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{parentTable.Rows.Count + 1}");
}
else
{
throw new Exception($"Bom明细附件{code}获取失败\r\nBom导入失败");
}
}
}
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
}
finally
{
this.DialogResult = DialogResult.OK;
this.Close();
ImportTimer?.Dispose();
}
});
task.Start();
};
frmBillInfo.OnLoad(Model);
frmMain.ParentView = frmBillInfo.GcMainView;
}
else
{
MessageUtil.Show("不是MX文件");
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}
}
/// <summary>
/// 开始导入3
/// </summary>
/// <param name="dirPaths"></param>
public void StartImportInQDFile()
{
try
{
string namepattern = @"^(.*-S[A-Z]\d*)(.*)$";
//string namepattern = @"^(.+?)\s+(.+)$";
string pattern = @"^(.*?)(\d+)?$";
string primaryValue = StaticControl.RightMenuMyControl.PrimaryValue;
string productCode = "";
ControlModel controlModel = StaticControl.RightMenuMyControl.ControlModels.Where(n => n.LabelText.Equals("物料编码")).FirstOrDefault();
if (controlModel != null)
{
productCode = StaticControl.RightMenuMyControl.GetControlValue(controlModel);
}
if (string.IsNullOrEmpty(productCode))
{
throw new Exception($"物料编码不能为空");
}
string beforeName = "";
ControlModel beforeNameModel = StaticControl.RightMenuMyControl.ControlModels.Where(n => n.LabelText.Equals("原文件名")).FirstOrDefault();
if (beforeNameModel != null)
{
beforeName = StaticControl.RightMenuMyControl.GetControlValue(beforeNameModel);
}
if (string.IsNullOrEmpty(beforeName))
{
throw new Exception($"原文件名不能为空");
}
string topProductId = "";
ControlModel topModel = StaticControl.RightMenuMyControl.ControlModels.Where(n => n.LabelText.Equals("顶级编码")).FirstOrDefault();
if (topModel == null)
{
MessageUtil.Show($"顶级编码不存在");
}
topProductId = StaticControl.RightMenuMyControl.GetControlValue(topModel);
GetFileCodeInfo(beforeName, out string beforeSourceCode, out string beforeSourceName, out string beforeSourceBB, out int beforeSourceBC);
List<LabelRemarkEdit> labelRemarkList = new List<LabelRemarkEdit>();
List<ControlModel> uploadModels = StaticControl.RightMenuMyControl.ControlModels.Where(n => n.FileUploadControl).ToList();
foreach (ControlModel uploadModel in uploadModels)
{
BaseUserControl uploadControl = StaticControl.RightMenuMyControl.FindControl(uploadModel);
if (uploadControl != null && uploadControl is LabelRemarkEdit labelRemarkEdit && !string.IsNullOrEmpty(labelRemarkEdit.filepath) && File.Exists(labelRemarkEdit.filepath))
{
labelRemarkList.Add(labelRemarkEdit);
}
}
FrmBillInfo frmBillInfo = new FrmBillInfo();
frmBillInfo.OnControlSourceBind += (s, args) =>
{
Task task = new Task(() =>
{
try
{
foreach (LabelRemarkEdit labelRemark in labelRemarkList)
{
int childIndex = labelRemarkList.IndexOf(labelRemark);
int allCount = (int)((decimal)(childIndex) / (labelRemarkList.Count) * 100);
int finishCount = (int)((decimal)(1 + childIndex) / (labelRemarkList.Count) * 100);
string dirPath = labelRemark.filepath;
FileInfo parentInfo = null;
if (string.IsNullOrEmpty(dirPath))
{
continue;
}
parentInfo = new FileInfo(dirPath);
//如果是QD文件
if (parentInfo != null && (parentInfo.Name.Trim().StartsWith("QD")))
{
GetFileCodeInfo(Path.GetFileNameWithoutExtension(parentInfo.Name).Trim(), out string sourceCode, out string sourceName, out string sourceBB, out int sourceBC);
StringBuilder stringBuilder = new StringBuilder();
if (sourceCode.StartsWith("QD"))
{
stringBuilder.AppendLine($"if not exists (select productid from p_ProductTab where productid = '{sourceCode}')");
stringBuilder.AppendLine($"begin insert into p_ProductTab (productid,appellation,bak,SpeciesNo) values ('{sourceCode.Replace("'", "''")}','{sourceName.Replace("'", "''")}','','0199') end;");
}
if (!string.IsNullOrEmpty(stringBuilder.ToString()))
{
SqlHelper.ExecuteNonQuery(stringBuilder.ToString());
}
StringBuilder insertbulider = new StringBuilder();
string mxCode = BaseImpl.GetResult($"select MxFileName from FileAttachmentMapping where MaterialCode = '{topProductId}' and RelatedAttachmentName = '{beforeSourceCode}';") + "";
insertbulider.AppendLine($"delete FileAttachmentMapping where MaterialCode = '{topProductId}' and RelatedAttachmentName = '{beforeSourceCode}';");
insertbulider.AppendLine($"insert into FileAttachmentMapping (MaterialCode,MxFileName,RelatedAttachmentName,OperatorUser,ChangeStatus) values ('{topProductId}','{mxCode}','{sourceCode}','{ERPInfo.Instance.UserName}','变更');");
//更新或新增并备份清单
int.TryParse(Model.FirstRowIndex, out int index);
frmMain.FirstRowIndex = index;
//DataTable historyTable = BaseImpl.GetDataTableResult($"select * from bom_BillListlogTab where ParentProduct = '{productCode}' and historyVer = '{code}'");
//if (historyTable != null && historyTable.Rows.Count > 0)
//{
// //已经存在该版本则不进行任何操作
// continue;
//}
FileInfo childInfo = new FileInfo(dirPath);
if (childInfo != null)
{
frmBillInfo.OnBillAdd();
SetProcessBar(0, allCount);
SetProcessMsg($"正在导入:{Path.GetFileName(childInfo.FullName)}");
DataTable detailTable = new DataTable();
frmMain.Invoke(new Action(() =>
{
detailTable = frmMain.ToExcelDataTable(childInfo.FullName, out int count, out int errorCount, true);
}));
foreach (DataRow detailRow in detailTable.Rows)
{
int.TryParse(detailRow["amount"] + "", out int amount);
detailRow["tamount"] = amount;
detailRow["amount"] = amount;
detailRow["bak"] = sourceCode;
detailRow["bombb"] = sourceBB;
detailRow["bombc"] = sourceBC;
}
SetProcessBar(20, allCount);
string billMasterSql = $"select (select top 1 billdocument_id from bom_BillTab where productid='{sourceCode}') as billdocument_id,'0' affirmer,'0' rtagid,'{sourceCode}' as productid,'{sourceCode}' as bak,'{sourceBB}' as bombb,'{sourceBC}' as bombc";
// 处理单据表头数据
DataRow masterRow = BillImpl.GetDataRowResult(billMasterSql);
SetProcessBar(40, allCount);
frmBillInfo.AddOrUpdateBill(masterRow, detailTable);
SetProcessBar(60, allCount);
string guid = Guid.NewGuid() + "";
frmBillInfo.BillSaveSql(guid);
BaseImpl.ExecSqlValue($"update p_bomImportExecTab set afterSql = '{insertbulider.ToString().Replace("'", "''")}' where guid = '{guid}'");
SetProcessBar(80, allCount);
//记录guid
string updateGuidSql = @"update QMS_wenjiangenggaitab set qms_wjgg_uuid = '{0}' where qms_wjgg_billdocument_Id = '{1}'";
SqlHelper.ExecuteNonQuery(string.Format(updateGuidSql, guid, primaryValue));
frmBillInfo.OnBillAdd();
//记录历史版本号
//string updateHistoryVerSql = @"update bom_BillListTab set historyVer = '{0}' where Billdocument_Id='{1}'";
//SqlHelper.ExecuteNonQuery(string.Format(updateHistoryVerSql, code, billNo));
//备份Bom清单明细
//string bakBomListSql = @"delete bom_BillListlogTab where parentProduct = '{0}' and historyVer = (select top 1 historyVer from bom_BillListTab where parentProduct = '{0}');insert into bom_BillListlogTab select * from bom_BillListTab where parentProduct = '{0}';";
//SqlHelper.ExecuteNonQuery(string.Format(bakBomListSql, productCode));
//上传文件
//bool isUpload = UploadFile(childInfo.FullName, code, out string msg, out string _);
//SetProcessBar(100, finishCount);
//SetProcessLabelAllMsg($"总进度:{childIndex + 1}/{selectRows.Count }");
}
else
{
throw new Exception($"Bom明细获取失败\r\nBom导入失败");
}
}
//如果是ZZQD文件
else if (parentInfo != null && (parentInfo.Name.Trim().StartsWith("ZZQD")))
{
productCode = topProductId;
GetFileCodeInfo(Path.GetFileNameWithoutExtension(parentInfo.Name).Trim(), out string sourceCode, out string sourceName, out string sourceBB, out int sourceBC);
StringBuilder insertbulider = new StringBuilder();
string mxCode = BaseImpl.GetResult($"select MxFileName from FileAttachmentMapping where MaterialCode = '{topProductId}' and RelatedAttachmentName = '{beforeSourceCode}';") + "";
insertbulider.AppendLine($"delete FileAttachmentMapping where MaterialCode = '{topProductId}' and RelatedAttachmentName = '{beforeSourceCode}';");
insertbulider.AppendLine($"insert into FileAttachmentMapping (MaterialCode,MxFileName,RelatedAttachmentName,OperatorUser,ChangeStatus) values ('{topProductId}','{mxCode}','{sourceCode}','{ERPInfo.Instance.UserName}','变更');");
//更新或新增并备份清单
int.TryParse(Model.FirstRowIndex, out int index);
frmMain.FirstRowIndex = index;
//DataTable historyTable = BaseImpl.GetDataTableResult($"select * from bom_BillListlogTab where ParentProduct = '{productCode}' and historyVer = '{code}'");
//if (historyTable != null && historyTable.Rows.Count > 0)
//{
// //已经存在该版本则不进行任何操作
// continue;
//}
FileInfo childInfo = new FileInfo(dirPath);
if (childInfo != null)
{
frmBillInfo.OnBillAdd();
SetProcessBar(0, allCount);
SetProcessMsg($"正在导入:{Path.GetFileName(childInfo.FullName)}");
DataTable detailTable = new DataTable();
frmMain.Invoke(new Action(() =>
{
detailTable = frmMain.ToExcelDataTable(childInfo.FullName, out int count, out int errorCount, true);
}));
foreach (DataRow detailRow in detailTable.Rows)
{
int.TryParse(detailRow["amount"] + "", out int lastAmount);
detailRow["tamount"] = 1;
detailRow["amount"] = lastAmount;
detailRow["bak"] = sourceCode;
detailRow["bombb"] = sourceBB;
detailRow["bombc"] = sourceBC;
}
SetProcessBar(20, allCount);
string billMasterSql = $"select (select top 1 billdocument_id from bom_BillTab where productid='{productCode}') as billdocument_id,'0' affirmer,'0' rtagid,'{productCode}' as productid";
// 处理单据表头数据
DataRow masterRow = BillImpl.GetDataRowResult(billMasterSql);
if (masterRow == null)
{
throw new Exception($"BOM建立单{productCode}不存在");
}
SetProcessBar(40, allCount);
frmBillInfo.AddOrUpdateBillByZZQD(masterRow, detailTable);
SetProcessBar(60, allCount);
string guid = Guid.NewGuid() + "";
frmBillInfo.BillSaveSql(guid);
BaseImpl.ExecSqlValue($"update p_bomImportExecTab set afterSql = '{insertbulider.ToString().Replace("'", "''")}' where guid = '{guid}'");
SetProcessBar(80, allCount);
//记录guid
string updateGuidSql = @"update QMS_wenjiangenggaitab set qms_wjgg_uuid = '{0}' where qms_wjgg_billdocument_Id = '{1}'";
SqlHelper.ExecuteNonQuery(string.Format(updateGuidSql, guid, primaryValue));
frmBillInfo.OnBillAdd();
//记录历史版本号
//string updateHistoryVerSql = @"update bom_BillListTab set historyVer = '{0}' where Billdocument_Id='{1}'";
//SqlHelper.ExecuteNonQuery(string.Format(updateHistoryVerSql, code, billNo));
//备份Bom清单明细
//string bakBomListSql = @"delete bom_BillListlogTab where parentProduct = '{0}' and historyVer = (select top 1 historyVer from bom_BillListTab where parentProduct = '{0}');insert into bom_BillListlogTab select * from bom_BillListTab where parentProduct = '{0}';";
//SqlHelper.ExecuteNonQuery(string.Format(bakBomListSql, productCode));
//上传文件
//bool isUpload = UploadFile(childInfo.FullName, code, out string msg, out string _);
//SetProcessBar(100, finishCount);
//SetProcessLabelAllMsg($"总进度:{childIndex + 1}/{selectRows.Count }");
}
else
{
throw new Exception($"Bom明细获取失败\r\nBom导入失败");
}
}
//如果是MX文件
else if (parentInfo != null && (parentInfo.Name.Trim().StartsWith("MX")))
{
productCode = topProductId;
GetFileCodeInfo(Path.GetFileNameWithoutExtension(parentInfo.Name).Trim(), out string sourceCode, out string sourceName, out string sourceBB, out int sourceBC);
//更新或新增并备份清单
int.TryParse(Model.FirstRowIndex, out int index);
frmMain.FirstRowIndex = index;
//DataTable historyTable = BaseImpl.GetDataTableResult($"select * from bom_BillListlogTab where ParentProduct = '{productCode}' and historyVer = '{code}'");
//if (historyTable != null && historyTable.Rows.Count > 0)
//{
// //已经存在该版本则不进行任何操作
// continue;
//}
if (parentInfo != null)
{
if (Directory.Exists("BomImportTemp"))
{
Directory.Delete("BomImportTemp", true);
}
Directory.CreateDirectory("BomImportTemp");
DataTable parentTable = ExcelToDatatable(parentInfo.FullName, Model, "", 5);
parentTable = parentTable.Rows.Cast<DataRow>().Where(n => int.TryParse(n["序号"] + "", out _) && !string.IsNullOrEmpty(n["图号"] + "")).ToList().CopyToDataTable();
Dictionary<string, string> childFileDic = new Dictionary<string, string>();
foreach (DataRow parentRow in parentTable.Rows)
{
string fileName = (parentRow["图号"] + "").Trim();
if (fileName.StartsWith("QD") || fileName.StartsWith("ZZQD"))
{
string fileSql = $"select webpath,sName from P_fm_FileTab where sName like '{fileName}%' and speciesno = '010106' and parentId in (select dirid from p_fm_directorytab where dllcoid = '1000202') and isdisabled = '0'";
DataRow fileRow = BaseImpl.GetDataRowResult(fileSql);
string webpath = fileRow != null ? fileRow["webpath"] + "" : "";
string sName = fileRow != null ? fileRow["sName"] + "" : "";
if (string.IsNullOrEmpty(webpath))
{
throw new Exception($"Bom明细附件{fileName}不存在\r\nBom导入失败");
}
else
{
using (WebClient webClient = new WebClient())
{
try
{
webpath = webpath.StartsWith("/") ? webpath : $"/{webpath}";
string url = $"{SystemInfo.Instance.OAUrl}/{webpath}";
string tempFileName = $"BomImportTemp/{sName}";
webClient.DownloadFile(url, tempFileName);
childFileDic.Add(fileName, tempFileName);
}
catch (Exception)
{
throw new Exception($"Bom明细附件{fileName}获取失败\r\nBom导入失败");
}
}
}
}
}
StringBuilder stringBuilder = new StringBuilder();
foreach (DataRow dataRow in parentTable.Rows)
{
string childCode = (dataRow["图号"] + "").Trim();
if (childCode.StartsWith("QD") || childCode.StartsWith("ZZQD"))
{
stringBuilder.AppendLine($"if not exists (select productid from p_ProductTab where productid = '{childCode}')");
stringBuilder.AppendLine($"begin insert into p_ProductTab (productid,appellation,bak,SpeciesNo) values ('{childCode.Replace("'", "''")}','{(dataRow["名称"] + "").Replace("'", "''")}','{(dataRow["备注"] + "").Replace("'", "''")}','0199') end;");
}
}
if (!string.IsNullOrEmpty(stringBuilder.ToString()))
{
SqlHelper.ExecuteNonQuery(stringBuilder.ToString());
}
frmBillInfo.OnBillAdd();
SetProcessBar(0, 0);
SetProcessMsg($"正在导入:{Path.GetFileName(parentInfo.FullName)}");
DataTable childTable = frmBillInfo.GcMainView.GridControl.DataSourceTable().Clone();
StringBuilder insertbulider = new StringBuilder();
insertbulider.AppendLine($"delete FileAttachmentMapping where MaterialCode = '{productCode}';");
//insertbulider.AppendLine($"insert into FileAttachmentMapping (MaterialCode,MxFileName,RelatedAttachmentName,OperatorUser,ChangeStatus) values ('{productCode}','{sourceCode }','{sourceCode}','{ERPInfo.Instance.UserName}','变更');");
foreach (DataRow parentRow in parentTable.Rows)
{
int.TryParse(parentRow["套数"] + "", out int tamount);
string childCode = parentRow["图号"] + "";
insertbulider.AppendLine($"insert into FileAttachmentMapping (MaterialCode,MxFileName,RelatedAttachmentName,OperatorUser,ChangeStatus) values ('{productCode}','{sourceCode }','{childCode}','{ERPInfo.Instance.UserName}','变更');");
if (childCode.StartsWith("QD") || childCode.StartsWith("ZZQD"))
{
string tempFileName = childFileDic[childCode];
FileInfo childInfo = new FileInfo(tempFileName);
if (childInfo == null)
{
throw new Exception($"MX明细中不包含文件{childCode}");
}
if (childInfo != null)
{
GetFileCodeInfo(Path.GetFileNameWithoutExtension(childInfo.Name).Trim(), out string childsourceCode, out string childsourceName, out string childsourceBB, out int childsourceBC);
if (childCode.StartsWith("ZZQD"))
{
DataTable zzqdTable = ExcelToDatatable(childInfo.FullName, Model, "", index);
//frmMain.Invoke(new Action(() =>
//{
// zzqdTable = frmMain.ToExcelDataTable(childInfo.FullName, out int count, out int errorCount, true);
//}));
DataView filterDataView = new DataView(zzqdTable);
try
{
if (!string.IsNullOrEmpty(Model.ReadTableCond))
{
filterDataView.RowFilter = Model.ReadTableCond;
}
}
catch (Exception)
{
}
zzqdTable = filterDataView.ToTable();
foreach (DataRow zzqdItem in zzqdTable.Rows)
{
DataRow childRow = childTable.NewRow();
childRow["ProductId"] = zzqdItem["物料编码"] + "";
childRow["appellation"] = zzqdItem["名称"] + "";
childRow["bak"] = childsourceCode;
childRow["bombb"] = childsourceBB;
childRow["bombc"] = childsourceBC;
childRow["tamount"] = parentRow["套数"] + "";
int.TryParse(zzqdItem["数量"] + "", out int amount);
childRow["amount"] = amount * tamount;
childTable.Rows.Add(childRow);
}
}
else if (childCode.StartsWith("QD"))
{
DataRow childRow = childTable.NewRow();
childRow["ProductId"] = parentRow["图号"] + "";
childRow["appellation"] = parentRow["名称"] + "";
childRow["bak"] = childsourceCode;
childRow["bombb"] = childsourceBB;
childRow["bombc"] = childsourceBC;
childRow["tamount"] = parentRow["套数"] + "";
childRow["amount"] = parentRow["套数"] + "";
childTable.Rows.Add(childRow);
}
}
}
}
SetProcessBar(20, 0);
if (childTable.Rows.Count == 0)
{
throw new Exception($"MX明细数据为空");
}
string billMasterSql = $"select (select top 1 billdocument_id from bom_BillTab where productid='{productCode}') as billdocument_id,'0' affirmer,'0' rtagid,'{productCode}' as productid,'{sourceCode}' as bak,'{sourceBB}' as bombb,'{sourceBC}' as bombc";
// 处理单据表头数据
DataRow masterRow = BillImpl.GetDataRowResult(billMasterSql);
if (masterRow == null)
{
throw new Exception($"BOM建立单{productCode}不存在");
}
SetProcessBar(40, allCount);
frmBillInfo.AddOrUpdateBill(masterRow, childTable);
SetProcessBar(60, allCount);
string guid = Guid.NewGuid() + "";
frmBillInfo.BillSaveSql(guid);
BaseImpl.ExecSqlValue($"update p_bomImportExecTab set afterSql = '{insertbulider.ToString().Replace("'", "''")}' where guid = '{guid}'");
SetProcessBar(80, allCount);
//记录guid
string updateGuidSql = @"update QMS_wenjiangenggaitab set qms_wjgg_uuid = '{0}' where qms_wjgg_billdocument_Id = '{1}'";
SqlHelper.ExecuteNonQuery(string.Format(updateGuidSql, guid, primaryValue));
frmBillInfo.OnBillAdd();
//记录历史版本号
//string updateHistoryVerSql = @"update bom_BillListTab set historyVer = '{0}' where Billdocument_Id='{1}'";
//SqlHelper.ExecuteNonQuery(string.Format(updateHistoryVerSql, code, billNo));
//备份Bom清单明细
//string bakBomListSql = @"delete bom_BillListlogTab where parentProduct = '{0}' and historyVer = (select top 1 historyVer from bom_BillListTab where parentProduct = '{0}');insert into bom_BillListlogTab select * from bom_BillListTab where parentProduct = '{0}';";
//SqlHelper.ExecuteNonQuery(string.Format(bakBomListSql, productCode));
//上传文件
//bool isUpload = UploadFile(childInfo.FullName, code, out string msg, out string _);
//SetProcessBar(100, finishCount);
//SetProcessLabelAllMsg($"总进度:{childIndex + 1}/{selectRows.Count }");
}
else
{
throw new Exception($"Bom明细获取失败\r\nBom导入失败");
}
}
else
{
GetFileCodeInfo(Path.GetFileNameWithoutExtension(parentInfo.Name).Trim(), out string sourceCode, out string sourceName, out string sourceBB, out int sourceBC);
string guid = Guid.NewGuid() + "";
SqlHelper.ExecuteNonQuery($"insert into p_bomImportExecTab (guid,detailTable,masterSql,detailSql,billNo,detailGuid,UserId,billWay,billSeq,auditFlag,comfirm,newVer) " +
$"values ('{guid}','','','','','','{ERPInfo.Instance.UserId}','','','0','','')");
//记录guid
string updateGuidSql = @"update QMS_wenjiangenggaitab set qms_wjgg_uuid = '{0}' where qms_wjgg_billdocument_Id = '{1}'";
SqlHelper.ExecuteNonQuery(string.Format(updateGuidSql, guid, primaryValue));
//记录文件变更
StringBuilder insertbulider = new StringBuilder();
string mxCode = BaseImpl.GetResult($"select MxFileName from FileAttachmentMapping where MaterialCode = '{topProductId}' and RelatedAttachmentName = '{beforeSourceCode}';") + "";
insertbulider.AppendLine($"delete FileAttachmentMapping where MaterialCode = '{topProductId}' and RelatedAttachmentName = '{beforeSourceCode}';");
insertbulider.AppendLine($"insert into FileAttachmentMapping (MaterialCode,MxFileName,RelatedAttachmentName,OperatorUser,ChangeStatus) values ('{topProductId}','{mxCode}','{sourceCode}','{ERPInfo.Instance.UserName}','变更');");
BaseImpl.ExecSqlValue($"update p_bomImportExecTab set afterSql = '{insertbulider.ToString().Replace("'", "''")}' where guid = '{guid}'");
}
}
this.DialogResult = DialogResult.OK;
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.DialogResult = DialogResult.Cancel;
}
finally
{
this.Close();
ImportTimer?.Dispose();
}
});
task.Start();
};
frmBillInfo.OnLoad(Model);
frmMain.ParentView = frmBillInfo.GcMainView;
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}
}
/// <summary>
/// 开始导入3
/// </summary>
/// <param name="dirPaths"></param>
public void StartImportInQDFile(string dirPath)
{
try
{
Model = frmMain.Model;
string pattern = @"([A-Za-z]+)(\d*)$";
//原物料名称
string productCode = Model.MaintabFocusedRow != null && Model.MaintabFocusedRow.Table.Columns.Contains("qms_laddf_productid") ? Model.MaintabFocusedRow["qms_laddf_productid"] + "" : "";
Match match = Regex.Match(productCode, pattern);
if (match.Success)
{
string sourceModel = match.Groups[1].Value;
string sourceVersion = match.Groups[2].Value;
sourceVersion = string.IsNullOrEmpty(sourceVersion) ? "0" : sourceVersion;
//修改后的文件名
string newProductCode = Model.MaintabFocusedRow != null && Model.MaintabFocusedRow.Table.Columns.Contains("qms_laddf_appellationV123") ? Model.MaintabFocusedRow["qms_laddf_appellationV123"] + "" : "";
FileInfo parentInfo = new FileInfo(dirPath);
if (parentInfo != null && (parentInfo.Name.Trim().StartsWith("QD") || parentInfo.Name.Trim().StartsWith("ZZQD")))
{
string code = "";
string name = "";
string newcode = newProductCode.Trim();
string newname = "";
string namepattern = @"^(.*-S[A-Z]\d*)(.*)$";
Match newProductCodematch = Regex.Match(Path.GetFileNameWithoutExtension(newProductCode).Trim(), namepattern);
Match namematch = Regex.Match(Path.GetFileNameWithoutExtension(parentInfo.Name).Trim(), namepattern);
if (namematch.Success)
{
code = namematch.Groups[1].Value;
name = namematch.Groups[2].Value;
}
if (newProductCodematch.Success)
{
newcode = newProductCodematch.Groups[1].Value;
newname = newProductCodematch.Groups[2].Value;
}
if (!newcode.Equals(code))//选择的文件和版本文件名不匹配
{
throw new Exception($"选择的文件名{code}和数据文件名{newProductCode}不匹配");
}
match = Regex.Match(code, pattern);
if (match.Success)
{
DataTable historyTable = BaseImpl.GetDataTableResult($"select * from bom_BillListlogTab where ParentProduct = '{productCode}' and historyVer = '{code}'");
if (historyTable != null && historyTable.Rows.Count > 0)
{
throw new Exception($"版本{code}已存在");
}
string newModel = match.Groups[1].Value;
string newVersion = match.Groups[2].Value;
newVersion = string.IsNullOrEmpty(newVersion) ? "0" : newVersion;
//新建或修改清单
StringBuilder stringBuilder = new StringBuilder();
if (code.StartsWith("QD") || code.StartsWith("ZZQD"))
{
stringBuilder.AppendLine($"if not exists (select productid from p_ProductTab where productid = '{code}')");
stringBuilder.AppendLine($"begin insert into p_ProductTab (productid,appellation,bak,SpeciesNo) values ('{code.Replace("'", "''")}','{name.Replace("'", "''")}','','0199') end;");
}
if (!string.IsNullOrEmpty(stringBuilder.ToString()))
{
SqlHelper.ExecuteNonQuery(stringBuilder.ToString());
}
//更新并备份清单
FrmBillInfo frmBillInfo = new FrmBillInfo();
frmBillInfo.OnControlSourceBind += (s, args) =>
{
Task task = new Task(() =>
{
try
{
int.TryParse(Model.FirstRowIndex, out int index);
frmMain.FirstRowIndex = index;
if (code.StartsWith("QD") || code.StartsWith("ZZQD"))
{
FileInfo childInfo = new FileInfo(dirPath);
if (childInfo != null)
{
frmBillInfo.OnBillAdd();
SetProcessBar(0, 0);
SetProcessMsg($"正在导入:{Path.GetFileName(childInfo.FullName)}");
DataTable detailTable = new DataTable();
frmMain.Invoke(new Action(() =>
{
detailTable = frmMain.ToExcelDataTable(childInfo.FullName, out int count, out int errorCount, true);
}));
foreach (DataRow detailRow in detailTable.Rows)
{
int.TryParse(detailRow["amount"] + "", out int lastAmount);
detailRow["tamount"] = 1;
detailRow["amount"] = lastAmount;
}
SetProcessBar(20, 0);
string billMasterSql = $"select (select top 1 billdocument_id from bom_BillTab where productid='{productCode}') as billdocument_id,'0' affirmer,'0' rtagid,'{productCode}' as productid";
billMasterSql = ReplaceHelper.ReplaceRowParam(Model.MaintabFocusedRow, billMasterSql);
// 处理单据表头数据
DataRow masterRow = BillImpl.GetDataRowResult(billMasterSql);
SetProcessBar(40, 0);
frmBillInfo.AddOrUpdateBill(masterRow, detailTable);
SetProcessBar(60, 0);
//备份Bom清单明细
string bakBomListSql = @"delete bom_BillListlogTab where parentProduct = '{0}' and historyVer = (select top 1 historyVer from bom_BillListTab where parentProduct = '{0}');insert into bom_BillListlogTab select * from bom_BillListTab where parentProduct = '{0}';";
SqlHelper.ExecuteNonQuery(string.Format(bakBomListSql, productCode));
string billNo = "";
frmBillInfo.BillSave(ref billNo);
SetProcessBar(80, 0);
frmBillInfo.OnBillAdd();
//记录历史版本号
string updateHistoryVerSql = @"update bom_BillListTab set historyVer = '{0}' where Billdocument_Id='{1}'";
SqlHelper.ExecuteNonQuery(string.Format(updateHistoryVerSql, code, billNo));
//上传文件
bool isUpload = UploadFile(childInfo.FullName, billNo, out string msg, out string _);
SetProcessBar(100, 100);
SetProcessLabelAllMsg($"总进度:1/1");
}
else
{
throw new Exception($"Bom明细获取失败\r\nBom导入失败");
}
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
}
finally
{
this.DialogResult = DialogResult.OK;
this.Close();
ImportTimer?.Dispose();
}
});
task.Start();
};
frmBillInfo.OnLoad(Model);
frmMain.ParentView = frmBillInfo.GcMainView;
}
else
{
throw new Exception($"文件名{code}不符合规则");
}
}
else
{
MessageUtil.Show("不是QD或ZZQD文件");
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}
}
else
{
throw new Exception($"文件名{productCode}不符合规则");
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}
}
/// <summary>
/// 开始导入5
/// </summary>
/// <param name="dirPaths"></param>
public void StartImportInFiles(List<DataRow> selectRows)
{
try
{
if (Directory.Exists("BomImportTemp"))
{
Directory.Delete("BomImportTemp", true);
}
Directory.CreateDirectory("BomImportTemp");
int execOrder = 1;
DataRow mxRow = selectRows.Where(n => (n[Model.AfterBomFieldName] + "").StartsWith("MX")).FirstOrDefault();
if (mxRow != null)
{
string mxFileName = mxRow[Model.AfterBomFieldName] + "";
string mxDirPath = mxRow["BomFieldNameDir"] + "";
string productId = mxRow["BomMxMainProduct"] + "";
if (string.IsNullOrEmpty(productId))
{
throw new Exception($"保存失败\r\n请重新进行BOM上传后保存");
}
DataRow billRow = BaseImpl.GetDataRowResult($"select qms_maddf_billdocument_id from qms_BillFileAddMaintab where qms_maddf_productid = '{productId}'");
if (billRow != null)
{
throw new Exception($"物料编码{productId}的BOM新增单已存在");
}
DataRow billbomRow = BaseImpl.GetDataRowResult($"select top 1 billdocument_id from bom_BillTab where productid='{productId}'");
if (billRow != null)
{
throw new Exception($"物料编码{productId}的BOM建立单已存在\r\n请进行修改操作");
}
FileInfo mxInfo = new FileInfo(mxDirPath);
if (mxInfo != null)
{
GetFileCodeInfo(Path.GetFileNameWithoutExtension(mxInfo.Name).Trim(), out string mxsourceCode, out string mxname, out string mxsourceBB, out int mxsourceBC);
DataTable mxfiletable = BaseImpl.GetDataTableResult($"select sname,fileId from p_fm_filetab where parentid in (select dirid from P_fm_DirectoryTab where pid = '{productId}' and dllcoid = '1000202') and speciesno = '010106' and sname like '{mxsourceCode}%'");
if (mxfiletable.Rows.Count > 0)
{
throw new Exception($"{mxsourceCode}的附件已存在\r\n请进行变更");
}
int mxMaxBc = 0;
string mxMaxBcFileId = "-1";
foreach (DataRow mxfileRow in mxfiletable.Rows)
{
string fileName = mxfileRow["sname"] + "";
string fileId = mxfileRow["fileId"] + "";
GetFileCodeInfo(fileName, out string fileCode, out string name, out string fileBB, out int fileBC);
if (fileBC >= mxMaxBc)
{
mxMaxBc = fileBC;
mxMaxBcFileId = fileId;
}
}
if (mxsourceBC > mxMaxBc && mxfiletable.Rows.Count > 0)
{
throw new Exception($"{mxsourceCode}的版次为{mxsourceBC},大于最大版次{mxMaxBc}\r\n请进行变更");
}
mxsourceBC = mxsourceBC >= mxMaxBc ? mxsourceBC : mxMaxBc;
FrmBillInfo frmBillInfo = new FrmBillInfo();
DataTable parentTable = ExcelToDatatable(mxInfo.FullName, Model, "", 5);
parentTable = parentTable.Rows.Cast<DataRow>().Where(n => int.TryParse(n["序号"] + "", out _) && !string.IsNullOrEmpty(n["图号"] + "") && !string.IsNullOrEmpty(n["名称"] + "")).ToList().CopyToDataTable();
StringBuilder stringBuilder = new StringBuilder();
foreach (DataRow dataRow in parentTable.Rows)
{
string code = (dataRow["图号"] + "").Trim();
if (code.StartsWith("QD") || code.StartsWith("ZZQD"))
{
stringBuilder.AppendLine($"if not exists (select productid from p_ProductTab where productid = '{code}')");
stringBuilder.AppendLine($"begin insert into p_ProductTab (productid,appellation,bak,SpeciesNo) values ('{code.Replace("'", "''")}','{(dataRow["名称"] + "").Replace("'", "''")}','{(dataRow["备注"] + "").Replace("'", "''")}','0199') end;");
}
}
if (!string.IsNullOrEmpty(stringBuilder.ToString()))
{
SqlHelper.ExecuteNonQuery(stringBuilder.ToString());
}
frmBillInfo.OnControlSourceBind += (s, args) =>
{
Task task = new Task(() =>
{
try
{
int.TryParse(Model.FirstRowIndex, out int index);
frmMain.FirstRowIndex = index;
bool isUpload = false;
string msg = "";
DataRow parentProductRow = BaseImpl.GetDataRowResult($"select top 1 billdocument_id from bom_BillTab where productid='{productId}'");
Dictionary<string, DataRow> maxBcFileDic = new Dictionary<string, DataRow>();
Dictionary<string, DataTable> fileTableDic = new Dictionary<string, DataTable>();
if (parentProductRow == null)
{
frmBillInfo.OnBillAdd();
SetProcessBar(0, 0);
SetProcessMsg($"正在导入:{Path.GetFileName(mxInfo.FullName)}");
DataTable childTable = frmBillInfo.GcMainView.GridControl.DataSourceTable().Clone();
StringBuilder insertbulider = new StringBuilder();
insertbulider.AppendLine($"delete FileAttachmentMapping where MaterialCode = '{productId}';");
//insertbulider.AppendLine($"insert into FileAttachmentMapping (MaterialCode,MxFileName,RelatedAttachmentName,OperatorUser,ChangeStatus) values ('{productId}','{mxsourceCode }','{mxsourceCode}','{ERPInfo.Instance.UserName}','新增');");
foreach (DataRow parentRow in parentTable.Rows)
{
int.TryParse(parentRow["套数"] + "", out int tamount);
string code = (parentRow["图号"] + "").Trim();
insertbulider.AppendLine($"insert into FileAttachmentMapping (MaterialCode,MxFileName,RelatedAttachmentName,OperatorUser,ChangeStatus) values ('{productId}','{mxsourceCode }','{code}','{ERPInfo.Instance.UserName}','新增');");
DataTable filetable = BaseImpl.GetDataTableResult($"select sname,fileId,webpath from p_fm_filetab where parentid in (select dirid from P_fm_DirectoryTab where pid = '{code}' and dllcoid = '1000202') and speciesno = '010106' and sname like '{code}%'");
fileTableDic[code] = filetable;
int childMaxBc = -1;
foreach (DataRow fileRow in filetable.Rows)
{
string fileName = fileRow["sname"] + "";
string fileId = fileRow["fileId"] + "";
GetFileCodeInfo(fileName, out string fileCode, out string name, out string fileBB, out int fileBC);
if (fileBC >= childMaxBc)
{
childMaxBc = fileBC;
maxBcFileDic[code] = fileRow;
}
}
//判断code是否已经上传,如果已经上传则不再上传,
//如果附件不存在文件夹中,则直接使用最新的
//如果附件不存在则提示
FileInfo childInfo = null;
DataRow childInfoRow = selectRows.Where(n => (n[Model.AfterBomFieldName] + "").StartsWith(code)).FirstOrDefault();
if (childInfoRow != null)
{
string childFileName = childInfoRow[Model.AfterBomFieldName] + "";
string childDirPath = childInfoRow["BomFieldNameDir"] + "";
childInfo = new FileInfo(childDirPath);
}
if ((childInfo == null || filetable.Rows.Count > 0) && maxBcFileDic.ContainsKey(code) && maxBcFileDic[code] != null)
{
using (WebClient webClient = new WebClient())
{
try
{
string webpath = maxBcFileDic[code]["webpath"] + "";
string sName = maxBcFileDic[code]["sName"] + "";
webpath = webpath.StartsWith("/") ? webpath : $"/{webpath}";
string url = $"{SystemInfo.Instance.OAUrl}/{webpath}";
string tempFileName = $"BomImportTemp/{sName}";
if (!File.Exists(tempFileName))
{
webClient.DownloadFile(url, tempFileName);
}
childInfo = new FileInfo(tempFileName);
}
catch (Exception)
{
throw new Exception($"Bom明细附件{code}获取失败\r\nBom导入失败");
}
}
}
if (childInfo != null)
{
GetFileCodeInfo(Path.GetFileNameWithoutExtension(childInfo.Name).Trim(), out string childsourceCode, out string childname, out string childsourceBB, out int childsourceBC);
//如果文件夹中有附件,则比较版次,如果大于最大版次,则提示
if (childsourceBC > childMaxBc && filetable.Rows.Count > 0)
{
throw new Exception($"{childsourceCode}的版次为{childsourceBC},大于最大版次{childMaxBc}\r\n请进行变更");
}
childsourceBC = childsourceBC >= childMaxBc ? childsourceBC : childMaxBc;
if (code.StartsWith("ZZQD"))
{
DataTable zzqdTable = ExcelToDatatable(childInfo.FullName, Model, "", index);
DataView filterDataView = new DataView(zzqdTable);
try
{
if (!string.IsNullOrEmpty(Model.ReadTableCond))
{
filterDataView.RowFilter = Model.ReadTableCond;
}
}
catch (Exception)
{
}
zzqdTable = filterDataView.ToTable();
foreach (DataRow zzqdItem in zzqdTable.Rows)
{
DataRow childRow = childTable.NewRow();
childRow["ProductId"] = zzqdItem["物料编码"] + "";
childRow["appellation"] = zzqdItem["名称"] + "";
childRow["bak"] = childsourceCode;
childRow["bombb"] = childsourceBB;
childRow["bombc"] = childsourceBC;
childRow["tamount"] = parentRow["套数"] + "";
int.TryParse(zzqdItem["数量"] + "", out int amount);
childRow["amount"] = amount * tamount;
childTable.Rows.Add(childRow);
}
}
else if (code.StartsWith("QD"))
{
DataRow childRow = childTable.NewRow();
childRow["ProductId"] = parentRow["图号"] + "";
childRow["appellation"] = parentRow["名称"] + "";
childRow["bak"] = childsourceCode;
childRow["bombb"] = childsourceBB;
childRow["bombc"] = childsourceBC;
childRow["tamount"] = parentRow["套数"] + "";
childRow["amount"] = parentRow["套数"] + "";
childTable.Rows.Add(childRow);
}
}
else
{
if (filetable.Rows.Count == 0)
{
throw new Exception($"{code}的附件不存在,请检查文件");
}
}
}
SetProcessBar(20, 0);
if (childTable.Rows.Count == 0)
{
throw new Exception($"MX明细数据不能空");
}
SetProcessBar(40, 0);
string billMasterSql = $"select (select top 1 billdocument_id from bom_BillTab where productid='{productId}') as billdocument_id,'0' affirmer,'0' rtagid,'{productId}' as productid,'{mxsourceCode}' as bak,'{mxsourceBB}' as bombb,'{mxsourceBC}' as bombc";
// 处理单据表头数据
DataRow masterRow = BillImpl.GetDataRowResult(billMasterSql);
SetProcessBar(60, 0);
frmBillInfo.AddOrUpdateBill(masterRow, childTable);
string guid = Guid.NewGuid() + "";
frmBillInfo.BillSaveSql(guid);
BaseImpl.ExecSqlValue($"update p_bomImportExecTab set afterSql = '{insertbulider.ToString().Replace("'", "''")}' where guid = '{guid}'");
SetProcessBar(80, 0);
//上传文件
string uploadFileId = mxMaxBcFileId;
if (mxfiletable.Rows.Count == 0)
{
isUpload = UploadFileToAudit(mxInfo.FullName, productId, "010106", out msg, out uploadFileId);
if (!isUpload)
{
throw new Exception($"{mxInfo.Name}附件上传失败\r\n{msg}");
}
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (mxRow.Table.Columns.Contains("qms_laddf_FileId"))
{
int.TryParse(uploadFileId, out int qms_laddf_FileId);
mxRow["qms_laddf_FileId"] = qms_laddf_FileId;
}
if (mxRow.Table.Columns.Contains("qms_laddf_Exec"))
{
mxRow["qms_laddf_Exec"] = guid;
}
if (mxRow.Table.Columns.Contains("qms_laddf_ExecOrder"))
{
mxRow["qms_laddf_ExecOrder"] = execOrder;
}
}));
execOrder += 1;
}
else
{
string uploadFileId = mxMaxBcFileId;
if (mxfiletable.Rows.Count == 0)
{
isUpload = UploadFileToAudit(mxInfo.FullName, mxsourceCode, "010106", out msg, out uploadFileId);
if (!isUpload)
{
throw new Exception($"{mxInfo.Name}附件上传失败\r\n{msg}");
}
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (mxRow.Table.Columns.Contains("qms_laddf_FileId"))
{
int.TryParse(uploadFileId, out int qms_laddf_FileId);
mxRow["qms_laddf_FileId"] = qms_laddf_FileId;
}
}));
}
SetProcessBar(100, (1 / (parentTable.Rows.Count + 1)) * 100);
SetProcessLabelAllMsg($"总进度:{1}/{parentTable.Rows.Count + 1}");
foreach (DataRow dataRow in parentTable.Rows)
{
int childIndex = parentTable.Rows.IndexOf(dataRow);
int nowCount = 1 + childIndex;
int allCount = (int)((decimal)(1 + childIndex) / (parentTable.Rows.Count + 1) * 100);
int finishCount = (int)((decimal)(1 + nowCount) / (parentTable.Rows.Count + 1) * 100);
int.TryParse(dataRow["套数"] + "", out int tamount);
string code = (dataRow["图号"] + "").Trim();
DataTable filetable = fileTableDic.ContainsKey(code) ? fileTableDic[code] : null;
if (code.StartsWith("QD"))
{
if (filetable.Rows.Count == 0)
{
FileInfo childInfo = null;
DataRow childInfoRow = selectRows.Where(n => (n[Model.AfterBomFieldName] + "").StartsWith(code)).FirstOrDefault();
if (childInfoRow != null)
{
string childFileName = childInfoRow[Model.AfterBomFieldName] + "";
string childDirPath = childInfoRow["BomFieldNameDir"] + "";
childInfo = new FileInfo(childDirPath);
}
if ((childInfo == null || filetable.Rows.Count > 0) && maxBcFileDic.ContainsKey(code) && maxBcFileDic[code] != null)
{
using (WebClient webClient = new WebClient())
{
try
{
string webpath = maxBcFileDic[code]["webpath"] + "";
string sName = maxBcFileDic[code]["sName"] + "";
webpath = webpath.StartsWith("/") ? webpath : $"/{webpath}";
string url = $"{SystemInfo.Instance.OAUrl}/{webpath}";
string tempFileName = $"BomImportTemp/{sName}";
if (!File.Exists(tempFileName))
{
webClient.DownloadFile(url, tempFileName);
}
childInfo = new FileInfo(tempFileName);
}
catch (Exception)
{
throw new Exception($"Bom明细附件{code}获取失败\r\nBom导入失败");
}
}
}
if (childInfo == null)
{
throw new Exception($"MX明细中的{code}文件不存在");
}
if (childInfo != null)
{
GetFileCodeInfo(Path.GetFileNameWithoutExtension(childInfo.Name).Trim(), out string qdsourceCode, out string qdname, out string qdsourceBB, out int qdsourceBC);
DataRow productRow = BaseImpl.GetDataRowResult($"select top 1 billdocument_id from bom_BillTab where productid='{code}'");
if (productRow == null)
{
if ((code.StartsWith("QD") || code.StartsWith("ZZQD")))
{
frmBillInfo.OnBillAdd();
SetProcessBar(0, allCount);
SetProcessMsg($"正在导入:{Path.GetFileName(childInfo.FullName)}");
DataTable detailTable = new DataTable();
frmMain.Invoke(new Action(() =>
{
detailTable = frmMain.ToExcelDataTable(childInfo.FullName, out int count, out int errorCount, true);
}));
foreach (DataRow detailRow in detailTable.Rows)
{
int.TryParse(detailRow["amount"] + "", out int amount);
//数量暂定为自身数量
detailRow["tamount"] = amount;
detailRow["amount"] = amount;
}
if (detailTable.Rows.Count == 0)
{
throw new Exception($"{code}明细数据为空");
}
SetProcessBar(40, allCount);
string childBillMasterSql = $"select (select top 1 billdocument_id from bom_BillTab where productid='{code}') as billdocument_id,'0' affirmer,'0' rtagid,'{code}' as productid,'{qdsourceCode}' as bak,'{qdsourceBB}' as bombb,'{qdsourceBC}' as bombc";
// 处理单据表头数据
DataRow childMasterRow = BillImpl.GetDataRowResult(childBillMasterSql);
SetProcessBar(60, allCount);
frmBillInfo.AddOrUpdateBill(childMasterRow, detailTable);
string childGuid = Guid.NewGuid() + "";
frmBillInfo.BillSaveSql(childGuid);
SetProcessBar(80, allCount);
//记录历史版本号
//string updateHistoryVerSql = @"update bom_BillListTab set historyVer = '{0}' where Billdocument_Id='{1}'";
//SqlHelper.ExecuteNonQuery(string.Format(updateHistoryVerSql, code, childBillNo));
//备份Bom清单明细
//string bakBomListSql = @"delete bom_BillListlogTab where parentProduct = '{0}' and historyVer = (select top 1 historyVer from bom_BillListTab where parentProduct = '{0}');insert into bom_BillListlogTab select * from bom_BillListTab where parentProduct = '{0}';";
//SqlHelper.ExecuteNonQuery(string.Format(bakBomListSql, code));
//确认不关联
//更新明细关联版本号
//string updateChildVerSql = @"update bom_BillListTab set Ver = (select top 1 billdocument_id from bom_billListTab where ParentProduct = '{0}') where Billdocument_Id = (select top 1 billdocument_id from bom_billListTab where ParentProduct = '{1}') and ProductId='{0}'";
//SqlHelper.ExecuteNonQuery(string.Format(updateChildVerSql, code, productId));
SetProcessBar(80, allCount);
string uploadFileId = maxBcFileDic.ContainsKey(code) ? maxBcFileDic[code]["fileId"] + "" : "-1";
if (filetable.Rows.Count == 0)
{
isUpload = UploadFileToAudit(childInfo.FullName, qdsourceCode, "010106", out msg, out uploadFileId);
if (!isUpload)
{
throw new Exception($"{code}附件上传失败\r\n{msg}");
}
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (childInfoRow.Table.Columns.Contains("qms_laddf_FileId"))
{
int.TryParse(uploadFileId, out int qms_laddf_FileId);
childInfoRow["qms_laddf_FileId"] = qms_laddf_FileId;
}
if (childInfoRow.Table.Columns.Contains("qms_laddf_Exec"))
{
childInfoRow["qms_laddf_Exec"] = childGuid;
}
if (childInfoRow.Table.Columns.Contains("qms_laddf_ExecOrder"))
{
childInfoRow["qms_laddf_ExecOrder"] = execOrder;
}
}));
execOrder += 1;
SetProcessBar(100, finishCount);
SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{parentTable.Rows.Count + 1}");
}
}
else
{
SetProcessBar(0, allCount);
string uploadFileId = maxBcFileDic.ContainsKey(code) ? maxBcFileDic[code]["fileId"] + "" : "-1";
if (filetable.Rows.Count == 0)
{
isUpload = UploadFileToAudit(childInfo.FullName, qdsourceCode, "010106", out msg, out uploadFileId);
if (!isUpload)
{
throw new Exception($"{code}附件上传失败\r\n{msg}");
}
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (childInfoRow.Table.Columns.Contains("qms_laddf_FileId"))
{
int.TryParse(uploadFileId, out int qms_laddf_FileId);
childInfoRow["qms_laddf_FileId"] = qms_laddf_FileId;
}
}));
SetProcessBar(100, finishCount);
SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{parentTable.Rows.Count + 1}");
}
}
else
{
throw new Exception($"目录中不包含文件{code}");
}
}
}
else
{
if (filetable.Rows.Count == 0)
{
FileInfo childInfo = null;
DataRow childInfoRow = selectRows.Where(n => (n[Model.AfterBomFieldName] + "").StartsWith(code)).FirstOrDefault();
if (childInfoRow != null)
{
string childFileName = childInfoRow[Model.AfterBomFieldName] + "";
string childDirPath = childInfoRow["BomFieldNameDir"] + "";
childInfo = new FileInfo(childDirPath);
}
if ((childInfo == null || filetable.Rows.Count > 0) && maxBcFileDic.ContainsKey(code) && maxBcFileDic[code] != null)
{
using (WebClient webClient = new WebClient())
{
try
{
string webpath = maxBcFileDic[code]["webpath"] + "";
string sName = maxBcFileDic[code]["sName"] + "";
webpath = webpath.StartsWith("/") ? webpath : $"/{webpath}";
string url = $"{SystemInfo.Instance.OAUrl}/{webpath}";
string tempFileName = $"BomImportTemp/{sName}";
if (!File.Exists(tempFileName))
{
webClient.DownloadFile(url, tempFileName);
}
childInfo = new FileInfo(tempFileName);
}
catch (Exception)
{
throw new Exception($"Bom明细附件{code}获取失败\r\nBom导入失败");
}
}
}
if (childInfo == null)
{
throw new Exception($"目录中不包含文件{code}");
}
if (childInfo != null)
{
GetFileCodeInfo(Path.GetFileNameWithoutExtension(childInfo.Name).Trim(), out string qdsourceCode, out string qdname, out string qdsourceBB, out int qdsourceBC);
string uploadFileId = maxBcFileDic.ContainsKey(code) ? maxBcFileDic[code]["fileId"] + "" : "-1";
if (filetable.Rows.Count == 0)
{
isUpload = UploadFileToAudit(childInfo.FullName, qdsourceCode, "010106", out msg, out uploadFileId);
if (!isUpload)
{
throw new Exception($"{code}附件上传失败\r\n{msg}");
}
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (childInfoRow.Table.Columns.Contains("qms_laddf_FileId"))
{
int.TryParse(uploadFileId, out int qms_laddf_FileId);
childInfoRow["qms_laddf_FileId"] = qms_laddf_FileId;
}
}));
SetProcessBar(100, finishCount);
SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{parentTable.Rows.Count + 1}");
}
else
{
throw new Exception($"目录中不包含文件{code}");
}
}
}
}
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.OK;
Close();
ImportTimer?.Dispose();
}));
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}));
}
});
task.Start();
};
frmBillInfo.OnLoad(Model);
frmMain.ParentView = frmBillInfo.GcMainView;
}
else
{
throw new Exception("未包含MX文件");
}
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}
}
/// <summary>
/// 根据已上传的数据进行Bom修改
/// </summary>
/// <param name="selectRows"></param>
public void StartExecBomUpdate(string billdocument)
{
try
{
if (string.IsNullOrEmpty(billdocument))
{
throw new Exception($"单据编号不能为空");
}
DataRow sourceRow = BaseImpl.GetDataRowResult($"select * from QMS_wenjiangenggaitab where qms_wjgg_billdocument_id = '{billdocument}'");
if (sourceRow == null)
{
throw new Exception($"Bom变更单{billdocument}不存在");
}
Task task = new Task(() =>
{
try
{
string execGuid = sourceRow["qms_wjgg_uuid"] + "";
string productid = sourceRow["qms_wjgg_productid"] + "";
string afterFilename = sourceRow["qms_wjgg_NewFileName"] + "";
string topProductId = sourceRow["qms_wjgg_Top"] + "";
int.TryParse(sourceRow["fileId"] + "", out int copyFileId);
int.TryParse(sourceRow["qms_wjgg_fileId"] + "", out int coverFileId);
int coverTag = (sourceRow["qms_wjgg_iscover"] + "").Equals("True") ? 1 : 0;
Model = frmMain.Model;
DataRow execRow = BaseImpl.GetDataRowResult($"select * from p_bomImportExecTab where isnull(success,0) = 0 and guid = '{execGuid}'");
if (execRow != null)
{
string masterSql = execRow["masterSql"] + "";
string detailSql = execRow["detailSql"] + "";
string afterSql = execRow["afterSql"] + "";
string detailTable = execRow["detailTable"] + "";
string detailGuid = execRow["detailGuid"] + "";
string billSeq = execRow["billSeq"] + "";
int.TryParse(execRow["billWay"] + "", out int billWay);
int.TryParse(execRow["comfirm"] + "", out int comfirm);
int.TryParse(execRow["auditFlag"] + "", out int auditFlag);
int.TryParse(execRow["newVer"] + "", out int newVer);
string billNo = execRow["billNo"] + "";
if (!string.IsNullOrEmpty(masterSql) && !string.IsNullOrEmpty(detailSql))
{
int result = BillImpl.BillSave(masterSql, detailSql, detailTable, ref billNo, detailGuid, billSeq, billWay, comfirm, out string tipMsg, auditFlag, newVer);
if (result == 1)
{
GetFileCodeInfo(afterFilename, out string fileCode, out string name, out string fileBB, out int fileBC);
BaseImpl.ExecSqlValue(afterSql);
BaseImpl.ExecSqlValue($"update p_bomImportExecTab set success = 1 where guid = '{execGuid}'");
List<SqlParameter> sqlParamList = new List<SqlParameter>();
sqlParamList.Add(new SqlParameter("@copyFileId", SqlDbType.Int) { Value = copyFileId });
sqlParamList.Add(new SqlParameter("@copyToModule", SqlDbType.VarChar, 100) { Value = "1000202" });
sqlParamList.Add(new SqlParameter("@copyToIdValue", SqlDbType.VarChar, 100) { Value = fileCode });
sqlParamList.Add(new SqlParameter("@coverFileId", SqlDbType.Int) { Value = coverFileId });
sqlParamList.Add(new SqlParameter("@coverTag", SqlDbType.Int) { Value = coverTag });
BaseImpl.ExecProcedure("p_CopyAttcFileInfo", sqlParamList.ToArray());
}
else
{
throw new Exception($"保存Bom失败\r\n{tipMsg}");
}
}
else
{
GetFileCodeInfo(afterFilename, out string fileCode, out string name, out string fileBB, out int fileBC);
BaseImpl.ExecSqlValue(afterSql);
BaseImpl.ExecSqlValue($"update p_bomImportExecTab set success = 1 where guid = '{execGuid}'");
List<SqlParameter> sqlParamList = new List<SqlParameter>();
sqlParamList.Add(new SqlParameter("@copyFileId", SqlDbType.Int) { Value = copyFileId });
sqlParamList.Add(new SqlParameter("@copyToModule", SqlDbType.VarChar, 100) { Value = "1000202" });
sqlParamList.Add(new SqlParameter("@copyToIdValue", SqlDbType.VarChar, 100) { Value = fileCode });
sqlParamList.Add(new SqlParameter("@coverFileId", SqlDbType.Int) { Value = coverFileId });
sqlParamList.Add(new SqlParameter("@coverTag", SqlDbType.Int) { Value = coverTag });
BaseImpl.ExecProcedure("p_CopyAttcFileInfo", sqlParamList.ToArray());
}
}
SetProcessBar(100, 100);
SetProcessLabelAllMsg($"总进度:1/1");
this.DialogResult = DialogResult.OK;
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.DialogResult = DialogResult.Cancel;
}
finally
{
this.Close();
ImportTimer?.Dispose();
}
});
task.Start();
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}
}
/// <summary>
/// 根据已上传的数据进行Bom生成
/// </summary>
/// <param name="selectRows"></param>
public void StartCreateBom(string parentProductId)
{
try
{
if (string.IsNullOrEmpty(parentProductId))
{
throw new Exception($"物料编码不能为空");
}
string billdocumentId = BaseImpl.GetResult($"select qms_maddf_billdocument_id from qms_BillFileAddMaintab where qms_maddf_productid = '{parentProductId}'") + "";
if (string.IsNullOrEmpty(billdocumentId))
{
throw new Exception($"未查询到物料编码{parentProductId}的Bom单据号");
}
if (Directory.Exists("BomImportTemp"))
{
Directory.Delete("BomImportTemp", true);
}
Directory.CreateDirectory("BomImportTemp");
DataTable sourceTable = BaseImpl.GetDataTableResult($"select qms_laddf_productid,qms_laddf_FileId,qms_laddf_Exec from qms_BillFileAddlisttab where qms_laddf_billdocument_id = '{billdocumentId}' order by qms_laddf_ExecOrder");
Task task = new Task(() =>
{
try
{
foreach (DataRow sourceRow in sourceTable.Rows)
{
string productid = sourceRow["qms_laddf_productid"] + "";
string fileId = sourceRow["qms_laddf_FileId"] + "";
string execGuid = sourceRow["qms_laddf_Exec"] + "";
int childIndex = sourceTable.Rows.IndexOf(sourceRow);
int nowCount = 1 + childIndex;
int allCount = (int)((decimal)(childIndex) / (sourceTable.Rows.Count) * 100);
int finishCount = (int)((decimal)(1 + childIndex) / (sourceTable.Rows.Count) * 100);
Model = frmMain.Model;
DataRow execRow = BaseImpl.GetDataRowResult($"select * from p_bomImportExecTab where isnull(success,0) = 0 and guid = '{execGuid}'");
if (!string.IsNullOrEmpty(execGuid) && execRow != null)
{
string masterSql = execRow["masterSql"] + "";
string detailSql = execRow["detailSql"] + "";
string afterSql = execRow["afterSql"] + "";
string detailTable = execRow["detailTable"] + "";
string detailGuid = execRow["detailGuid"] + "";
string billSeq = execRow["billSeq"] + "";
int.TryParse(execRow["billWay"] + "", out int billWay);
int.TryParse(execRow["comfirm"] + "", out int comfirm);
int.TryParse(execRow["auditFlag"] + "", out int auditFlag);
int.TryParse(execRow["newVer"] + "", out int newVer);
string billNo = execRow["billNo"] + "";
if (!string.IsNullOrEmpty(masterSql) && !string.IsNullOrEmpty(detailSql))
{
int result = BillImpl.BillSave(masterSql, detailSql, detailTable, ref billNo, detailGuid, billSeq, billWay, comfirm, out string tipMsg, auditFlag, newVer);
if (result == 1)
{
BaseImpl.ExecSqlValue(afterSql);
BaseImpl.ExecSqlValue($"update p_bomImportExecTab set success = 1 where guid = '{execGuid}'");
}
else
{
throw new Exception($"保存Bom失败\r\n{tipMsg}");
}
}
else
{
BaseImpl.ExecSqlValue(afterSql);
BaseImpl.ExecSqlValue($"update p_bomImportExecTab set success = 1 where guid = '{execGuid}'");
}
}
//using (WebClient webClient = new WebClient())
//{
// try
// {
// int.TryParse(fileId, out int convertFileId);
// DataRow fileRow = BaseImpl.GetDataRowResult($"select webpath,sname from p_fm_filetab where fileId = '{fileId}'");
// if (convertFileId > 0 && fileRow != null)
// {
// string webpath = fileRow["webpath"] + "";
// string sName = fileRow["sname"] + "";
// webpath = webpath.StartsWith("/") ? webpath : $"/{webpath}";
// string url = $"{SystemInfo.Instance.OAUrl}/{webpath}";
// string tempFileName = $"BomImportTemp/{sName}";
// webClient.DownloadFile(url, tempFileName);
// bool isUpload = UploadFileToAudit(tempFileName, productid, "010106", out string msg, out string otherFieldId);
// }
// }
// catch (Exception)
// {
// throw new Exception($"Bom明细附件{productid}获取失败\r\nBom导入失败");
// }
//}
BaseImpl.ExecSqlValue($"update p_fm_filetab set isdisabled = 0 where fileid = '{fileId}'");
SetProcessBar(100, finishCount);
SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{sourceTable.Rows.Count + 1}");
}
this.DialogResult = DialogResult.OK;
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.DialogResult = DialogResult.Cancel;
}
finally
{
this.Close();
ImportTimer?.Dispose();
}
});
task.Start();
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}
}
/// <summary>
/// 显示当前文件
/// </summary>
/// <param name="text"></param>
private void SetProcessMsg(string text)
{
this.labelCurrentItem.Invoke(new Action(() =>
{
this.labelCurrentItem.Text = text;
}));
}
private void SetProcessLabelAllMsg(string text)
{
this.lblAll.Invoke(new Action(() =>
{
this.lblAll.Text = text;
}));
}
/// <summary>
/// 显示当前进度
/// </summary>
/// <param name="current"></param>
/// <param name="total"></param>
private void SetProcessBar(int current, int total)
{
this.Invoke(new Action(() =>
{
this.progressBarCurrent.Value = current;
this.progressBarTotal.Value = total;
}));
}
/// <summary>
/// 获取表格数据
/// </summary>
/// <param name="fileName"></param>
/// <param name="sheetName"></param>
/// <param name="isFirstRowColumn"></param>
/// <returns></returns>
public DataTable ExcelToDatatable(string fileName, DynamicBomImport Model, string sheetName = "", int firstRowIndex = 0)
{
DataTable data = new DataTable();
FileStream fs;
IWorkbook workbook = null;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
{
workbook = new XSSFWorkbook(fs);
}
else if (fileName.IndexOf(".xls") > 0) // 2003版本
{
workbook = new HSSFWorkbook(fs);
}
ISheet sheet;
if (!string.IsNullOrEmpty(sheetName))
{
sheet = workbook.GetSheet(sheetName);//根据给定的sheet名称获取数据
}
else
{
//也可以根据sheet编号来获取数据
sheet = workbook.GetSheetAt(0);//获取第几个sheet表(此处表示如果没有给定sheet名称,默认是第一个sheet表)
}
if (sheet != null)
{
int startRow = firstRowIndex + 1;
IRow firstRow = sheet.GetRow(firstRowIndex);
IRow bandRow = null;
int cellCount = firstRow.LastCellNum;
for (int i = firstRow.FirstCellNum; i < firstRow.LastCellNum; i++)//第一行列数循环
{
ICell titleCell = firstRow.GetCell(i);
ICell bandCell = null;
bool isBandTitle = false;
if (titleCell.IsMergedCell)
{
CellRangeAddress mergrRange = FindMergedRegion(sheet, firstRowIndex, i);
startRow = mergrRange.LastRow + 1;
if (mergrRange != null)
{
if (mergrRange.FirstColumn < mergrRange.LastColumn && !Model.CustomerServiceApp)
{
isBandTitle = true;
bandRow = sheet.GetRow(mergrRange.LastRow + 1);
titleCell = firstRow.GetCell(mergrRange.FirstColumn);
bandCell = bandRow.GetCell(i);
CellRangeAddress bandMergrRange = FindMergedRegion(sheet, mergrRange.LastRow + 1, i);
if (bandMergrRange != null)
{
startRow = bandMergrRange.LastRow + 1;
}
else
{
startRow = mergrRange.LastRow + 2;
}
}
else
{
startRow = mergrRange.LastRow + 1;
}
}
}
string fieldName = "";
if (!isBandTitle || bandRow == null)
{
fieldName = GetCellValue(titleCell);
}
else
{
fieldName = $"{GetCellValue(titleCell)}|{GetCellValue(bandCell)}";
}
if (string.IsNullOrEmpty(fieldName) && titleCell.IsMergedCell)
{
cellCount -= 1;
continue;
}
DataColumn column = new DataColumn(fieldName);//获取标题
data.Columns.Add(column);//添加列
}
//最后一行的标号
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; i++)//循环遍历所有行
{
IRow row = sheet.GetRow(i);//第几行
if (row == null)
{
continue; //没有数据的行默认是null;
}
//将excel表每一行的数据添加到datatable的行中
DataRow dataRow = data.NewRow();
int dataRowIndex = 0;
for (int j = firstRow.FirstCellNum; j < cellCount; j++)
{
ICell cell = row.GetCell(j);
if (cell != null && cell.IsMergedCell)
{
CellRangeAddress mergrRange = FindMergedRegion(sheet, i, j);
if (j == mergrRange.FirstColumn)
{
dataRow[dataRowIndex] = GetCellValue(row.GetCell(j));
dataRowIndex += 1;
}
else
{
continue;
}
}
else
{
if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
{
dataRow[dataRowIndex] = GetCellValue(row.GetCell(j));
dataRowIndex += 1;
}
}
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch (IOException ex)
{
throw new IOException(string.Format("读取模板内容失败,原因:{0}", ex.Message));
}
catch (Exception ex)
{
throw new Exception(string.Format("读取模板内容失败,原因:{0}", ex.Message));
}
}
/// <summary>
/// 获取单元格值
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
public static string GetCellValue(ICell cell)
{
string cellValue = "";
try
{
if (cell != null)
{
// 根据单元格类型获取值
switch (cell.CellType)
{
case CellType.String:
cellValue = cell.StringCellValue;
break;
case CellType.Numeric:
cellValue = cell.NumericCellValue.ToString();
break;
case CellType.Boolean:
cellValue = cell.BooleanCellValue.ToString();
break;
case CellType.Formula://单元格中带有公式,根据类型继续判断
switch (cell.CachedFormulaResultType)
{
case CellType.String:
cellValue = cell.StringCellValue;
break;
case CellType.Numeric:
cellValue = cell.NumericCellValue.ToString();
break;
case CellType.Boolean:
cellValue = cell.BooleanCellValue.ToString();
break;
case CellType.Blank:
break;
default:
cellValue.ToString();
break;
}
break;
default:
cellValue = cell.ToString();
break;
}
}
}
catch (Exception)
{
}
return cellValue;
}
/// <summary>
/// 获取合并区域
/// </summary>
/// <param name="sheet"></param>
/// <param name="rowIndex"></param>
/// <param name="columnIndex"></param>
/// <returns></returns>
private CellRangeAddress FindMergedRegion(ISheet sheet, int rowIndex, int columnIndex)
{
int mergedRegionsCount = sheet.NumMergedRegions;
for (int i = 0; i < mergedRegionsCount; i++)
{
CellRangeAddress mergedRegion = sheet.GetMergedRegion(i);
if (mergedRegion.IsInRange(rowIndex, columnIndex))
{
return mergedRegion; // 返回合并区域
}
}
return null; // 未找到合并区域
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="filePath"></param>
/// <param name="msg"></param>
/// <returns></returns>
private bool UploadFile(string filePath, string idValue, out string msg, out string outFileId)
{
bool isUpload = false;
string File = filePath;
string returnMsg = "";
string fileId = "";
string postUrl = "";
try
{
//获取文件信息
FileInfo fileInfo = new FileInfo(File);
string suffix = Path.GetExtension(File);
string name = fileInfo.Name;
DateTime creationTime = fileInfo.CreationTime;
byte[] fileBytes = ConvertFileToBytes(File);
string fileStream = Convert.ToBase64String(fileBytes);
string userId = ERPInfo.Instance.UserId;
DateTime uploadTime = DateTime.Now;
string speciesno = "010102";
// 检查扩展名是否为 .xlsx 或 .xls
if (suffix.Equals(".xlsx", StringComparison.OrdinalIgnoreCase) ||
suffix.Equals(".xls", StringComparison.OrdinalIgnoreCase))
{
speciesno = "010101";
}
//上传文件到服务器目录
postUrl = "{0}Api/FileUploadApi.ashx?moduleId={1}&idValue={2}&speciesno={8}&folder={3}&totsize={4}&position={5}&filename={6}&method={7}";
if (!string.IsNullOrEmpty(idValue))
{
string token = "";
string loginUrl = $"{SystemInfo.Instance.OAUrl}/Api/SysUserAjaxApi.ashx";
HttpTools.setting("application/x-www-form-urlencoded", null, null, HttpTools.Encode.UTF8);
Dictionary<string, string> loginPmsDic = new Dictionary<string, string>();
loginPmsDic.Add("method", "Login");
loginPmsDic.Add("username", HttpUtility.UrlEncode(ERPInfo.Instance.UserName));
loginPmsDic.Add("password", HttpUtility.UrlEncode(ERPInfo.Instance.InPassWord));
HttpWebResponse loginResponse = HttpTools.Post(loginUrl, "", loginPmsDic, HttpTools.Method.POST, out CookieCollection loginCookie, out string loginResult);
if (loginResponse != null && !string.IsNullOrEmpty(loginResult))
{
JObject jObject = JsonConvert.DeserializeObject<JObject>(loginResult);
if (jObject.ContainsKey("success"))
{
if ((jObject["success"] + "").Equals("True"))
{
if (jObject.ContainsKey("token"))
{
token = jObject["token"] + "";
}
}
}
}
if (!string.IsNullOrEmpty(token))
{
//string selectSql = $"select * from P_fm_FileTab where parentid in (select dirid from P_fm_DirectoryTab where pid = '{idValue}' and dllcoid = '1000202') and speciesno = '{speciesno}' and sname = '{name.Replace(" ", "")}'";
//DataTable deleteTable = BaseImpl.GetDataTableResult(selectSql);
//if (deleteTable != null && deleteTable.Rows.Count > 0)
//{
// foreach (DataRow deleteRow in deleteTable.Rows)
// {
// string field = HttpUtility.UrlEncode(deleteRow["fileId"] + "");
// string webpath = HttpUtility.UrlEncode(deleteRow["webpath"] + "");
// //删除文件
// string deleteUrl = "{0}Api/FileUploadApi.ashx?fileId={1}&filename={2}&method={3}";
// deleteUrl = string.Format(deleteUrl, SystemInfo.Instance.OAUrl, field, webpath, "DoDelete");
// HttpHelper.Setting("application/x-www-form-urlencoded", null, null);
// Dictionary<string, string> deleteHeaderDic = new Dictionary<string, string>();
// deleteHeaderDic.Add("Authorization", $"Bearer {token}");
// HttpWebResponse deleteWebResponse = HttpHelper.Post(deleteUrl, fileStream, null, deleteHeaderDic, out string deleteResult);
// }
//}
postUrl = string.Format(postUrl, SystemInfo.Instance.OAUrl, "1000202", HttpUtility.UrlEncode(idValue), "file", fileBytes.Length, 0, HttpUtility.UrlEncode(name), "DoWebUpload", speciesno);
HttpTools.setting("application/x-www-form-urlencoded", null, null);
string result = "";
CookieCollection cookieCollection = null;
Dictionary<string, string> headerDic = new Dictionary<string, string>();
headerDic.Add("Authorization", $"Bearer {token}");
HttpWebResponse webResponse = HttpTools.Post(postUrl, fileStream, null, headerDic, HttpTools.Method.POST, out cookieCollection, out result);
if (webResponse != null && !string.IsNullOrEmpty(result))
{
JObject jsonObject = (JObject)JsonConvert.DeserializeObject(result);
string isSuccess = jsonObject["success"] + "";
if (isSuccess.Equals("True", StringComparison.CurrentCultureIgnoreCase))
{
if (jsonObject.ContainsKey("other"))
{
fileId = jsonObject["other"] + "";
}
isUpload = true;
}
else
{
if (jsonObject.ContainsKey("msg"))
{
returnMsg = jsonObject["msg"] + "";
}
isUpload = false;
}
}
else
{
returnMsg = "上传请求失败";
isUpload = false;
}
}
else
{
returnMsg = loginResult;
isUpload = false;
}
}
else
{
returnMsg = "上传节点值不能为空";
isUpload = false;
}
}
catch (Exception ex)
{
returnMsg = ex.Message;
throw new Exception($"文件{Path.GetFileName(filePath)}上传失败\r\n{ex.Message}");
isUpload = false;
}
msg = returnMsg;
outFileId = fileId;
return isUpload;
}
private bool UploadFileToAudit(string filePath, string idValue, string speciesno, out string msg, out string outFileId)
{
bool isUpload = false;
string File = filePath;
string returnMsg = "";
string fileId = "";
string postUrl = "";
try
{
//获取文件信息
FileInfo fileInfo = new FileInfo(File);
string suffix = Path.GetExtension(File);
string name = fileInfo.Name;
DateTime creationTime = fileInfo.CreationTime;
byte[] fileBytes = ConvertFileToBytes(File);
string fileStream = Convert.ToBase64String(fileBytes);
string userId = ERPInfo.Instance.UserId;
DateTime uploadTime = DateTime.Now;
string code = "";
string namepattern = @"^(.*-S[A-Z]\d*)(.*)$";
Match namematch = Regex.Match(Path.GetFileNameWithoutExtension(fileInfo.Name).Trim(), namepattern);
if (namematch.Success)
{
code = namematch.Groups[1].Value;
}
//上传文件到服务器目录
postUrl = "{0}Api/FileUploadApi.ashx?moduleId={1}&idValue={2}&speciesno={8}&folder={3}&totsize={4}&position={5}&filename={6}&method={7}";
if (!string.IsNullOrEmpty(idValue))
{
string token = "";
string loginUrl = $"{SystemInfo.Instance.OAUrl}/Api/SysUserAjaxApi.ashx";
HttpTools.setting("application/x-www-form-urlencoded", null, null, HttpTools.Encode.UTF8);
Dictionary<string, string> loginPmsDic = new Dictionary<string, string>();
loginPmsDic.Add("method", "Login");
loginPmsDic.Add("username", HttpUtility.UrlEncode(ERPInfo.Instance.UserName));
loginPmsDic.Add("password", HttpUtility.UrlEncode(ERPInfo.Instance.InPassWord));
HttpWebResponse loginResponse = HttpTools.Post(loginUrl, "", loginPmsDic, HttpTools.Method.POST, out CookieCollection loginCookie, out string loginResult);
if (loginResponse != null && !string.IsNullOrEmpty(loginResult))
{
JObject jObject = JsonConvert.DeserializeObject<JObject>(loginResult);
if (jObject.ContainsKey("success"))
{
if ((jObject["success"] + "").Equals("True"))
{
if (jObject.ContainsKey("token"))
{
token = jObject["token"] + "";
}
}
}
}
if (!string.IsNullOrEmpty(token))
{
//string selectSql = $"select * from P_fm_FileTab where parentid in (select dirid from P_fm_DirectoryTab where pid = '{idValue}' and dllcoid = '1000202') and speciesno = '{speciesno}' and sname = '{name.Replace(" ", "")}'";
//DataTable deleteTable = BaseImpl.GetDataTableResult(selectSql);
//if (deleteTable != null && deleteTable.Rows.Count > 0)
//{
// foreach (DataRow deleteRow in deleteTable.Rows)
// {
// string field = HttpUtility.UrlEncode(deleteRow["fileId"] + "");
// string webpath = HttpUtility.UrlEncode(deleteRow["webpath"] + "");
// //删除文件
// string deleteUrl = "{0}Api/FileUploadApi.ashx?fileId={1}&filename={2}&method={3}";
// deleteUrl = string.Format(deleteUrl, SystemInfo.Instance.OAUrl, field, webpath, "DoDelete");
// HttpHelper.Setting("application/x-www-form-urlencoded", null, null);
// Dictionary<string, string> deleteHeaderDic = new Dictionary<string, string>();
// deleteHeaderDic.Add("Authorization", $"Bearer {token}");
// HttpWebResponse deleteWebResponse = HttpHelper.Post(deleteUrl, fileStream, null, deleteHeaderDic, out string deleteResult);
// }
//}
postUrl = string.Format(postUrl, SystemInfo.Instance.OAUrl, "1000202", HttpUtility.UrlEncode(idValue), "file", fileBytes.Length, 0, HttpUtility.UrlEncode(name), "DoWebUpload", speciesno);
HttpTools.setting("application/x-www-form-urlencoded", null, null);
string result = "";
CookieCollection cookieCollection = null;
Dictionary<string, string> headerDic = new Dictionary<string, string>();
headerDic.Add("Authorization", $"Bearer {token}");
HttpWebResponse webResponse = HttpTools.Post(postUrl, fileStream, null, headerDic, HttpTools.Method.POST, out cookieCollection, out result);
if (webResponse != null && !string.IsNullOrEmpty(result))
{
JObject jsonObject = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result);
string isSuccess = jsonObject["success"] + "";
if (isSuccess.Equals("True", StringComparison.CurrentCultureIgnoreCase))
{
if (jsonObject.ContainsKey("other"))
{
fileId = jsonObject["other"] + "";
BaseImpl.ExecSqlValue($"update p_fm_filetab set isdisabled = 2 where fileid = '{fileId}'");
}
isUpload = true;
}
else
{
if (jsonObject.ContainsKey("msg"))
{
returnMsg = jsonObject["msg"] + "";
}
isUpload = false;
}
}
else
{
returnMsg = "上传请求失败";
isUpload = false;
}
}
else
{
returnMsg = loginResult;
isUpload = false;
}
}
else
{
returnMsg = "上传节点值不能为空";
isUpload = false;
}
}
catch (Exception ex)
{
returnMsg = ex.Message;
throw new Exception($"文件{Path.GetFileName(filePath)}上传失败\r\n{ex.Message}");
isUpload = false;
}
msg = returnMsg;
outFileId = fileId;
return isUpload;
}
/// <summary>
/// 附件转换byte[]
/// </summary>
/// <param name="filePath">附件路径</param>
/// <returns>二进制</returns>
private byte[] ConvertFileToBytes(string filePath)
{
byte[] bytContent = null;
System.IO.FileStream fs = null;
System.IO.BinaryReader br = null;
try
{
fs = new FileStream(filePath, System.IO.FileMode.Open);
}
catch (Exception)
{
throw;
}
finally
{
if (fs != null)
br = new BinaryReader((Stream)fs);
if (br != null)
bytContent = br.ReadBytes((Int32)fs.Length);
if (fs != null)
fs.Dispose();
}
return bytContent;
}
/// <summary>
/// 解析code信息
/// </summary>
/// <param name="sourceCode"></param>
/// <param name="code"></param>
/// <param name="name"></param>
/// <param name="bb"></param>
/// <param name="bc"></param>
private void GetFileCodeInfo(string sourceCode, out string code, out string name, out string bb, out int bc)
{
string namepattern = @"^(.*-S[A-Z]\d*)(.*)$";
string pattern = @"^(.*?)(\d+)?$";
string childcode = "";
string childname = "";
string childsourceCode = "";