using Lskj.Business;
using Lskj.Business.Impl;
using Lskj.Control;
using Lskj.Control.BrowserSetting;
using Lskj.Control.Model;
using Lskj.Core;
using Lskj.Model;
using Lskj.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Lskj.PubBomImport
{
///
/// 下载进度窗口
///
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;
}
///
/// Bom结构补充,新增QD或图纸
///
///
public void StartImportInQDOrZZFiles(List selectRows)
{
try
{
int execOrder = 1;
FrmBillInfo frmBillInfo = new FrmBillInfo();
foreach (DataRow selectRow in selectRows)
{
string fileName = selectRow[Model.AfterBomFieldName] + "";
string dirPath = selectRow["BomFieldNameDir"] + "";
//string productId = selectRow["BomMxMainProduct"] + "";
FileInfo fileInfo = new FileInfo(dirPath);
if (fileInfo != null)
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name).Trim();
GetFileCodeInfo(fileNameWithoutExtension, out string sourceCode, out string sourceName, out string sourceBB, out int sourceBC, true);
//if (sourceCode.StartsWith("ZZQD"))
//{
// throw new Exception($"不允许补充ZZQD文件{sourceCode}\r\n请进行变更");
//}
if (sourceCode.StartsWith("MX"))
{
throw new Exception($"不允许补充MX文件{sourceCode}\r\n请进行变更");
}
else
{
if (!string.IsNullOrEmpty(sourceCode) && !string.IsNullOrEmpty(sourceBB))
{
DataTable filetable = BaseImpl.GetDataTableResult($"select sname,fileId from p_fm_filetab where parentid in (select dirid from P_fm_DirectoryTab where pid = '{sourceCode}' and dllcoid = '1000202') and speciesno = '010106' and sname like '{sourceCode}%'");
if (filetable.Rows.Count > 0)
{
throw new Exception($"{sourceCode}的附件已存在\r\n请进行变更");
}
if (!sourceBB.Equals("SA"))
{
throw new Exception($"{fileInfo.Name}\r\n版本不为SA不允许新增,请进行修改");
}
if (sourceBC > 0)
{
throw new Exception($"{fileInfo.Name}\r\n不为0的版次不允许新增,请进行修改");
}
if (sourceCode.StartsWith("QD"))
{
int createCode = ProductSaveUnique(sourceCode.Replace("'", "''"), sourceName.Replace("'", "''"), "", "1000202_1", out string pid, out string msg);
if ((createCode + "").Equals("-1"))
{
throw new Exception($"虚拟物料创建失败\r\n{msg}");
}
}
}
else
{
throw new Exception($"文件{fileNameWithoutExtension}名称不符合规范");
}
}
}
else
{
throw new Exception($"{fileName}的文件不存在");
}
}
frmBillInfo.OnControlSourceBind += (s, args) =>
{
Task task = new Task(() =>
{
try
{
int.TryParse(Model.FirstRowIndex, out int index);
frmMain.FirstRowIndex = index;
foreach (DataRow selectRow in selectRows)
{
int childIndex = selectRows.IndexOf(selectRow);
int nowCount = 1 + childIndex;
int allCount = (int)((decimal)(1 + childIndex) / (selectRows.Count + 1) * 100);
int finishCount = (int)((decimal)(1 + nowCount) / (selectRows.Count + 1) * 100);
string fileName = selectRow[Model.AfterBomFieldName] + "";
string dirPath = selectRow["BomFieldNameDir"] + "";
FileInfo fileInfo = new FileInfo(dirPath);
if (fileInfo != null)
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name).Trim();
GetFileCodeInfo(fileNameWithoutExtension, out string sourceCode, out string sourceName, out string sourceBB, out int sourceBC, true);
if (sourceCode.StartsWith("QD"))
{
DataRow productRow = BaseImpl.GetDataRowResult($"select top 1 billdocument_id from bom_BillTab where productid = (select top 1 productid from p_ProductTab where spec = '{sourceCode}')");
if (productRow == null)//如果不存在bom建立单
{
string childGuid = Guid.NewGuid() + "";
frmBillInfo.OnBillAdd();
SetProcessBar(0, allCount);
SetProcessMsg($"正在导入:{Path.GetFileName(fileInfo.FullName)}");
DataTable detailTable = new DataTable();
frmMain.Invoke(new Action(() =>
{
detailTable = frmMain.ToExcelDataTable(fileInfo.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($"{sourceCode}明细数据为空");
}
SetProcessBar(40, allCount);
string childBillMasterSql = $"select (select top 1 billdocument_id from bom_BillTab where productid = (select top 1 productid from p_ProductTab where spec = '{sourceCode}')) as billdocument_id,'0' affirmer,'0' rtagid,(select top 1 productid from p_ProductTab where spec = '{sourceCode}') as productid,'{sourceCode}' as bak,'{sourceBB}' as bombb,'{sourceBC}' as bombc";
// 处理单据表头数据
DataRow childMasterRow = BillImpl.GetDataRowResult(childBillMasterSql);
SetProcessBar(60, allCount);
frmBillInfo.AddOrUpdateBill(childMasterRow, detailTable);
frmBillInfo.BillSaveSql(childGuid);
SetProcessBar(80, allCount);
bool isUpload = UploadFileToAudit(fileInfo.FullName, sourceCode, "010106", out string msg, out string uploadFileId);
if (!isUpload)
{
throw new Exception($"{sourceCode}附件上传失败\r\n{msg}");
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (selectRow.Table.Columns.Contains("qms_laddf_uploadtag"))
{
selectRow["qms_laddf_uploadtag"] = 1;
}
if (selectRow.Table.Columns.Contains("qms_laddf_FileId"))
{
int.TryParse(uploadFileId, out int qms_laddf_FileId);
selectRow["qms_laddf_FileId"] = qms_laddf_FileId;
}
if (selectRow.Table.Columns.Contains("qms_laddf_Exec"))
{
selectRow["qms_laddf_Exec"] = childGuid;
}
if (selectRow.Table.Columns.Contains("qms_laddf_ExecOrder"))
{
selectRow["qms_laddf_ExecOrder"] = execOrder;
}
}));
execOrder += 1;
SetProcessBar(100, finishCount);
SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{selectRows.Count + 1}");
}
else
{
SetProcessBar(0, allCount);
bool isUpload = UploadFileToAudit(fileInfo.FullName, sourceCode, "010106", out string msg, out string uploadFileId);
if (!isUpload)
{
throw new Exception($"{sourceCode}附件上传失败\r\n{msg}");
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (selectRow.Table.Columns.Contains("qms_laddf_uploadtag"))
{
selectRow["qms_laddf_uploadtag"] = 1;
}
if (selectRow.Table.Columns.Contains("qms_laddf_FileId"))
{
int.TryParse(uploadFileId, out int qms_laddf_FileId);
selectRow["qms_laddf_FileId"] = qms_laddf_FileId;
}
}));
SetProcessBar(100, finishCount);
SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{selectRows.Count + 1}");
}
}
else
{
SetProcessBar(0, allCount);
bool isUpload = UploadFileToAudit(fileInfo.FullName, sourceCode, "010106", out string msg, out string uploadFileId);
if (!isUpload)
{
throw new Exception($"{sourceCode}附件上传失败\r\n{msg}");
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (selectRow.Table.Columns.Contains("qms_laddf_uploadtag"))
{
selectRow["qms_laddf_uploadtag"] = 1;
}
if (selectRow.Table.Columns.Contains("qms_laddf_FileId"))
{
int.TryParse(uploadFileId, out int qms_laddf_FileId);
selectRow["qms_laddf_FileId"] = qms_laddf_FileId;
}
}));
SetProcessBar(100, finishCount);
SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{selectRows.Count + 1}");
}
}
else
{
throw new Exception($"{fileName}的文件不存在");
}
}
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;
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}));
}
}
///
/// Bom结构补充,新增其它文件,无版本控制
///
///
public void StartImportInOtherFiles(List selectRows, bool CanNotAllowSA = true)
{
try
{
int execOrder = 1;
FrmBillInfo frmBillInfo = new FrmBillInfo();
string bomOtherAddMode = selectRows[0]["qms_laddf_mode"] + "";
string speciesno = selectRows[0]["BomAddSpeciesNo"] + "";
if (string.IsNullOrEmpty(bomOtherAddMode))
{
throw new Exception("未选择上传模式");
}
if (string.IsNullOrEmpty(speciesno))
{
throw new Exception("未选择文件分类");
}
if (bomOtherAddMode.Equals("9040"))//有规则
{
Dictionary maxfileRowDic = new Dictionary();
foreach (DataRow selectRow in selectRows)
{
string fileName = selectRow[Model.AfterBomFieldName] + "";
string dirPath = selectRow["BomFieldNameDir"] + "";
FileInfo fileInfo = new FileInfo(dirPath);
if (fileInfo != null)
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name).Trim();
bool isMatch = GetOtherFileCodeInfo(fileInfo.Name, out string code, out string spec, out string name, out string extension, out string bb, out int bc);
if (!isMatch)
{
throw new Exception($"{fileInfo.Name}\r\n文件名不符合规则");
}
if (string.IsNullOrEmpty(code))
{
throw new Exception($"编码解析为空");
}
if (string.IsNullOrEmpty(spec))
{
throw new Exception($"规格解析为空");
}
if (string.IsNullOrEmpty(name))
{
throw new Exception($"名称解析为空");
}
if (!fileNameWithoutExtension.StartsWith("LX"))
{
throw new Exception($"文件{fileNameWithoutExtension}名称不符合规则\r\n不以LX开头");
}
else
{
if (CanNotAllowSA)
{
if (!bb.Equals("SA"))
{
throw new Exception($"{fileInfo.Name}\r\n版本不为SA不允许新增,请进行修改");
}
if (bc > 0)
{
throw new Exception($"{fileInfo.Name}\r\n不为0的版次不允许新增,请进行修改");
}
}
DataRow productRow = BaseImpl.GetDataRowResult($"select ProductId from p_productTab where ProductId = '{code}'");
if (productRow == null)
{
throw new Exception($"物料编码{code}不存在,无法新增");
}
DataRow maxRow = BaseImpl.GetDataRowResult($"exec dbo.p_CheckLxFileRevision N'{fileInfo.Name}','{speciesno}';");
maxfileRowDic[fileInfo.Name] = maxRow;
if (maxRow != null)//如果存在则不允许上传
{
throw new Exception("已存在该版本附件无法新增");
//int.TryParse(maxRow["版本号"] + "", out int oldbb);
//int.TryParse(maxRow["新文件版本号"] + "", out int newbb);
//if (newbb > oldbb)
//{
// throw new Exception($"{fileInfo.Name}\r\n版本号大于最大版本号{oldbb},请进行修改");
//}
}
}
}
else
{
throw new Exception($"{fileName}的文件不存在");
}
}
frmBillInfo.OnControlSourceBind += (s, args) =>
{
Task task = new Task(() =>
{
try
{
int.TryParse(Model.FirstRowIndex, out int index);
frmMain.FirstRowIndex = index;
foreach (DataRow selectRow in selectRows)
{
string productId = selectRow["BomMxMainProduct"] + "";
int childIndex = selectRows.IndexOf(selectRow);
int nowCount = 1 + childIndex;
int allCount = (int)((decimal)(1 + childIndex) / (selectRows.Count + 1) * 100);
int finishCount = (int)((decimal)(1 + nowCount) / (selectRows.Count + 1) * 100);
string fileName = selectRow[Model.AfterBomFieldName] + "";
string dirPath = selectRow["BomFieldNameDir"] + "";
FileInfo fileInfo = new FileInfo(dirPath);
if (fileInfo != null)
{
DataRow maxRow = maxfileRowDic.ContainsKey(fileInfo.Name) ? maxfileRowDic[fileInfo.Name] : null;
if (maxRow != null)//如果存在则不允许上传
{
throw new Exception("已存在附件无法新增");
//uploadFileId = maxRow["fileid"] + "";
//int.TryParse(maxRow["版本号"] + "", out int oldbb);
//int.TryParse(maxRow["新文件版本号"] + "", out int newbb);
//if (newbb > oldbb)
//{
// throw new Exception($"{fileInfo.Name}\r\n版本号大于最大版本号,请进行修改");
//}
}
else
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name).Trim();
GetOtherFileCodeInfo(fileInfo.Name, out string code, out string spec, out string name, out string extension, out string bb, out int bc);
SetProcessBar(0, allCount);
bool isUpload = UploadFileToAudit(fileInfo.FullName, code, speciesno, out string msg, out string uploadFileId);
if (!isUpload)
{
throw new Exception($"{fileNameWithoutExtension}附件上传失败\r\n{msg}");
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (selectRow.Table.Columns.Contains("qms_laddf_uploadtag"))
{
selectRow["qms_laddf_uploadtag"] = 1;
}
if (selectRow.Table.Columns.Contains("qms_laddf_FileId"))
{
int.TryParse(uploadFileId, out int qms_laddf_FileId);
selectRow["qms_laddf_FileId"] = qms_laddf_FileId;
}
}));
SetProcessBar(100, finishCount);
SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{selectRows.Count + 1}");
}
}
else
{
throw new Exception($"{fileName}的文件不存在");
}
}
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();
};
}
else if (bomOtherAddMode.Equals("9041"))//无规则
{
foreach (DataRow selectRow in selectRows)
{
string productId = selectRow["BomMxMainProduct"] + "";
if (string.IsNullOrEmpty(productId))
{
throw new Exception($"物料编码不能为空");
}
string fileName = selectRow[Model.AfterBomFieldName] + "";
string dirPath = selectRow["BomFieldNameDir"] + "";
FileInfo fileInfo = new FileInfo(dirPath);
if (fileInfo != null)
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name).Trim();
if (fileNameWithoutExtension.StartsWith("ZZQD"))
{
throw new Exception($"不允许补充ZZQD文件{fileNameWithoutExtension}");
}
else if (fileNameWithoutExtension.StartsWith("MX"))
{
throw new Exception($"不允许补充MX文件{fileNameWithoutExtension}");
}
else if (fileNameWithoutExtension.StartsWith("QD"))
{
throw new Exception($"不允许补充QD文件{fileNameWithoutExtension}");
}
else
{
DataTable filetable = 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 = '{speciesno}' and sname = '{fileInfo.Name}'");
if (filetable.Rows.Count > 0)
{
throw new Exception($"{fileNameWithoutExtension}的附件已存在");
}
}
}
else
{
throw new Exception($"{fileName}的文件不存在");
}
}
frmBillInfo.OnControlSourceBind += (s, args) =>
{
Task task = new Task(() =>
{
try
{
int.TryParse(Model.FirstRowIndex, out int index);
frmMain.FirstRowIndex = index;
foreach (DataRow selectRow in selectRows)
{
string productId = selectRow["BomMxMainProduct"] + "";
int childIndex = selectRows.IndexOf(selectRow);
int nowCount = 1 + childIndex;
int allCount = (int)((decimal)(1 + childIndex) / (selectRows.Count + 1) * 100);
int finishCount = (int)((decimal)(1 + nowCount) / (selectRows.Count + 1) * 100);
string fileName = selectRow[Model.AfterBomFieldName] + "";
string dirPath = selectRow["BomFieldNameDir"] + "";
FileInfo fileInfo = new FileInfo(dirPath);
if (fileInfo != null)
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name).Trim();
SetProcessBar(0, allCount);
bool isUpload = UploadFileToAudit(fileInfo.FullName, productId, speciesno, out string msg, out string uploadFileId);
if (!isUpload)
{
throw new Exception($"{fileNameWithoutExtension}附件上传失败\r\n{msg}");
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (selectRow.Table.Columns.Contains("qms_laddf_uploadtag"))
{
selectRow["qms_laddf_uploadtag"] = 1;
}
if (selectRow.Table.Columns.Contains("qms_laddf_FileId"))
{
int.TryParse(uploadFileId, out int qms_laddf_FileId);
selectRow["qms_laddf_FileId"] = qms_laddf_FileId;
}
}));
SetProcessBar(100, finishCount);
SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{selectRows.Count + 1}");
}
else
{
throw new Exception($"{fileName}的文件不存在");
}
}
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();
};
}
else
{
throw new Exception("上传模式编码不合法");
}
frmBillInfo.OnLoad(Model);
frmMain.ParentView = frmBillInfo.GcMainView;
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}));
}
}
///
/// 变更LX-版本
///
///
public void StartUpdateInOtherBBFiles(List selectRows)
{
try
{
int execOrder = 1;
FrmBillInfo frmBillInfo = new FrmBillInfo();
string bomOtherAddMode = selectRows[0]["qms_laddf_mode"] + "";
string speciesno = selectRows[0]["BomAddSpeciesNo"] + "";
string productId = selectRows[0]["BomMxMainProduct"] + "";
string oldProductId = selectRows[0]["BomAddOldProductId"] + "";
string guid = "";
ControlModel guidModel = StaticControl.RightMenuMyControl.ControlModels.Where(n => n.LabelText.Equals("唯一编码")).FirstOrDefault();
if (guidModel != null)
{
guid = StaticControl.RightMenuMyControl.GetControlValue(guidModel);
}
if (string.IsNullOrEmpty(guid))
{
throw new Exception($"唯一编码不能为空");
}
GridControlEx gridControlEx = null;
if (StaticControl.BomUnionPage != null && StaticControl.BomUnionPage.Tag is GridControlEx gridDetailControl)
{
gridControlEx = gridDetailControl;
}
DataTable dataTable = gridControlEx.GridControl.DataSourceTable();
int[] bomRowIndexs = gridControlEx.GridView.GetSelectedRows();
//if (bomRowIndexs.Count() <= 0)
//{
// throw new Exception("请选择需要变更的Bom");
//}
if (string.IsNullOrEmpty(oldProductId))
{
throw new Exception("无旧物料编码");
}
if (string.IsNullOrEmpty(bomOtherAddMode))
{
throw new Exception("未选择上传模式");
}
if (string.IsNullOrEmpty(speciesno))
{
throw new Exception("未选择文件分类");
}
if (bomOtherAddMode.Equals("9040"))//有规则
{
Dictionary maxfileRowDic = new Dictionary();
foreach (DataRow selectRow in selectRows)
{
string fileName = selectRow[Model.AfterBomFieldName] + "";
string dirPath = selectRow["BomFieldNameDir"] + "";
FileInfo fileInfo = new FileInfo(dirPath);
if (fileInfo != null)
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name).Trim();
bool isMatch = GetOtherFileCodeInfo(fileInfo.Name, out string code, out string spec, out string name, out string extension, out string bb, out int bc);
if (!isMatch)
{
throw new Exception($"{fileInfo.Name}\r\n文件名不符合规则");
}
if (string.IsNullOrEmpty(code))
{
throw new Exception($"编码解析为空");
}
if (string.IsNullOrEmpty(spec))
{
throw new Exception($"规格解析为空");
}
if (string.IsNullOrEmpty(name))
{
throw new Exception($"名称解析为空");
}
if (!fileNameWithoutExtension.StartsWith("LX"))
{
throw new Exception($"文件{fileNameWithoutExtension}名称不符合规则\r\n不以LX开头");
}
else
{
if (!productId.Trim().Equals(code))
{
throw new Exception($"{fileInfo.Name}\r\n编码与文件名不匹配");
}
if (bc > 0)
{
throw new Exception($"{fileInfo.Name}\r\n不为0的版次不允许新增,请进行修改");
}
DataRow productRow = BaseImpl.GetDataRowResult($"select ProductId from p_productTab where ProductId = '{code}'");
if (productRow == null)
{
throw new Exception($"物料编码{code}不存在,无法新增");
}
DataRow maxRow = BaseImpl.GetDataRowResult($"exec dbo.p_CheckLxFileRevision N'{fileInfo.Name}','{speciesno}';");
maxfileRowDic[fileInfo.Name] = maxRow;
if (maxRow != null)//如果存在则不允许上传
{
throw new Exception("已存在该版本附件无法新增");
//int.TryParse(maxRow["版本号"] + "", out int oldbb);
//int.TryParse(maxRow["新文件版本号"] + "", out int newbb);
//if (newbb > oldbb)
//{
// throw new Exception($"{fileInfo.Name}\r\n版本号大于最大版本号{oldbb},请进行修改");
//}
}
}
}
else
{
throw new Exception($"{fileName}的文件不存在");
}
}
frmBillInfo.OnControlSourceBind += (s, args) =>
{
Task task = new Task(() =>
{
try
{
int.TryParse(Model.FirstRowIndex, out int index);
frmMain.FirstRowIndex = index;
foreach (DataRow selectRow in selectRows)
{
int childIndex = selectRows.IndexOf(selectRow);
int nowCount = 1 + childIndex;
int allCount = (int)((decimal)(1 + childIndex) / (selectRows.Count + 1) * 100);
int finishCount = (int)((decimal)(1 + nowCount) / (selectRows.Count + 1) * 100);
string fileName = selectRow[Model.AfterBomFieldName] + "";
string dirPath = selectRow["BomFieldNameDir"] + "";
FileInfo fileInfo = new FileInfo(dirPath);
if (fileInfo != null)
{
DataRow maxRow = maxfileRowDic.ContainsKey(fileInfo.Name) ? maxfileRowDic[fileInfo.Name] : null;
string uploadFileId = "";
if (maxRow != null)//如果存在则不允许上传
{
throw new Exception("已存在该版本附件无法新增");
//uploadFileId = maxRow["fileid"] + "";
//int.TryParse(maxRow["版本号"] + "", out int oldbb);
//int.TryParse(maxRow["新文件版本号"] + "", out int newbb);
//if (newbb > oldbb)
//{
// throw new Exception($"{fileInfo.Name}\r\n版本号大于最大版本号,请进行修改");
//}
}
else
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name).Trim();
GetOtherFileCodeInfo(fileInfo.Name, out string code, out string spec, out string name, out string extension, out string bb, out int bc);
SetProcessBar(0, allCount);
bool isUpload = UploadFileToAudit(fileInfo.FullName, code, speciesno, out string msg, out uploadFileId);
if (!isUpload)
{
throw new Exception($"{fileNameWithoutExtension}附件上传失败\r\n{msg}");
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (selectRow.Table.Columns.Contains("qms_laddf_uploadtag"))
{
selectRow["qms_laddf_uploadtag"] = 1;
}
}));
SetProcessBar(100, finishCount);
SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{selectRows.Count + 1}");
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (selectRow.Table.Columns.Contains("qms_laddf_FileId"))
{
int.TryParse(uploadFileId, out int qms_laddf_FileId);
selectRow["qms_laddf_FileId"] = qms_laddf_FileId;
}
}));
}
else
{
throw new Exception($"{fileName}的文件不存在");
}
}
foreach (int bomRowIndex in bomRowIndexs)
{
DataRow dataRow = gridControlEx.GridView.GetDataRow(bomRowIndex);
string sql = $@"delete from bom_bgRwTab where guid = '{guid}';
insert bom_bgRwTab (guid,productid,appellation,spec,yproductid,yappellation,yspec,xdopname,xddate,BomOperatorId,comid) OUTPUT INSERTED.BGID
select '{guid}','{dataRow["productid"] + ""}','{dataRow["appellation"] + ""}','{dataRow["spec"] + ""}',productid,appellation,spec,'{ERPInfo.Instance.UserName}',getdate(),(select top 1 OperatorId from bom_billTab WITH (NOLOCK) where productid = '{dataRow["productid"] + ""}'),2
from p_producttab where productid = '{dataRow["Yproductid"] + ""}'";
string insertId = SqlHelper.ExecuteScalar(sql) + "";
string updateSql = $@"update bom_bgRwTab set billdocumentId = (
'BG' + CONVERT(VARCHAR(8), getdate(), 112) + RIGHT('0000' +
CAST((select COUNT(*) FROM bom_bgRwTab WHERE BGID > (select max(BGID) from bom_bgRwTab where XdDate < (CAST(GETDATE() AS DATE))) and BGID <= '{insertId}') AS VARCHAR(4)), 4))
where BGID = '{insertId}'";
SqlHelper.ExecuteNonQuery(updateSql);
}
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();
};
}
else
{
throw new Exception("仅支持有规则附件");
}
frmBillInfo.OnLoad(Model);
frmMain.ParentView = frmBillInfo.GcMainView;
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}));
}
}
///
/// 批量修改多个其它文件{版次变化直接上传}
///
///
public void StartUpdateInOtherFiles(List selectRows)
{
try
{
int execOrder = 1;
FrmBillInfo frmBillInfo = new FrmBillInfo();
string speciesno = selectRows[0]["BomAddSpeciesNo"] + "";
if (string.IsNullOrEmpty(speciesno))
{
throw new Exception("未选择文件分类");
}
Dictionary maxfileRowDic = new Dictionary();
foreach (DataRow selectRow in selectRows)
{
string fileName = selectRow[Model.AfterBomFieldName] + "";
string dirPath = selectRow["BomFieldNameDir"] + "";
FileInfo fileInfo = new FileInfo(dirPath);
if (fileInfo != null)
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name).Trim();
bool isMatch = GetOtherFileCodeInfo(fileInfo.Name, out string code, out string spec, out string name, out string extension, out string bb, out int bc);
if (!isMatch)
{
throw new Exception($"{fileInfo.Name}\r\n文件名不符合规则");
}
if (string.IsNullOrEmpty(code))
{
throw new Exception($"编码解析为空");
}
if (string.IsNullOrEmpty(spec))
{
throw new Exception($"规格解析为空");
}
if (string.IsNullOrEmpty(name))
{
throw new Exception($"名称解析为空");
}
if (!fileNameWithoutExtension.StartsWith("LX"))
{
throw new Exception($"文件{fileNameWithoutExtension}名称不符合规则\r\n不以LX开头");
}
else
{
if (bc <= 0)
{
throw new Exception($"{fileInfo.Name}\r\n为0的版次不允许进行版次修改");
}
DataRow productRow = BaseImpl.GetDataRowResult($"select ProductId from p_productTab where ProductId = '{code}'");
if (productRow == null)
{
throw new Exception($"物料编码{code}不存在,无法修改");
}
DataRow maxRow = BaseImpl.GetDataRowResult($"exec dbo.p_CheckLxFileRevision N'{fileInfo.Name}','{speciesno}';");
maxfileRowDic[fileInfo.Name] = maxRow;
if (maxRow != null)//如果存在则不允许上传
{
int.TryParse(maxRow["版本号"] + "", out int oldbb);
int.TryParse(maxRow["新文件版本号"] + "", out int newbb);
if (newbb <= oldbb)
{
throw new Exception($"{fileInfo.Name}\r\n版本号小于等于最大版本号{oldbb},无法修改");
}
}
else
{
throw new Exception($"{fileInfo.Name}\r\n不存在可以修改的附件");
}
}
}
else
{
throw new Exception($"{fileName}的文件不存在");
}
}
frmBillInfo.OnControlSourceBind += (s, args) =>
{
Task task = new Task(() =>
{
try
{
int.TryParse(Model.FirstRowIndex, out int index);
frmMain.FirstRowIndex = index;
foreach (DataRow selectRow in selectRows)
{
string productId = selectRow["BomMxMainProduct"] + "";
int childIndex = selectRows.IndexOf(selectRow);
int nowCount = 1 + childIndex;
int allCount = (int)((decimal)(1 + childIndex) / (selectRows.Count + 1) * 100);
int finishCount = (int)((decimal)(1 + nowCount) / (selectRows.Count + 1) * 100);
string fileName = selectRow[Model.AfterBomFieldName] + "";
string dirPath = selectRow["BomFieldNameDir"] + "";
FileInfo fileInfo = new FileInfo(dirPath);
if (fileInfo != null)
{
DataRow maxRow = maxfileRowDic.ContainsKey(fileInfo.Name) ? maxfileRowDic[fileInfo.Name] : null;
string uploadFileId = "";
if (maxRow != null)//如果存在则修改
{
int.TryParse(maxRow["fileid"] + "", out int fileId);
int.TryParse(maxRow["版本号"] + "", out int oldbb);
int.TryParse(maxRow["新文件版本号"] + "", out int newbb);
if (newbb <= oldbb)
{
throw new Exception($"{fileInfo.Name}\r\n版本号小于等于最大版本号{oldbb},无法修改");
}
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name).Trim();
GetOtherFileCodeInfo(fileInfo.Name, out string code, out string spec, out string name, out string extension, out string bb, out int bc);
SetProcessBar(0, allCount);
bool isUpload = UploadFileToAudit(fileInfo.FullName, code, speciesno, out string msg, out uploadFileId);
if (!isUpload)
{
throw new Exception($"{fileNameWithoutExtension}附件上传失败\r\n{msg}");
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (selectRow.Table.Columns.Contains("qms_laddf_uniofileid"))
{
selectRow["qms_laddf_uniofileid"] = fileId;
}
if (selectRow.Table.Columns.Contains("qms_laddf_uploadtag"))
{
selectRow["qms_laddf_uploadtag"] = 1;
}
}));
SetProcessBar(100, finishCount);
SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{selectRows.Count + 1}");
}
else
{
throw new Exception($"{fileInfo.Name}\r\n不存在可以修改的附件");
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (selectRow.Table.Columns.Contains("qms_laddf_FileId"))
{
int.TryParse(uploadFileId, out int qms_laddf_FileId);
selectRow["qms_laddf_FileId"] = qms_laddf_FileId;
}
}));
}
else
{
throw new Exception($"{fileName}的文件不存在");
}
}
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;
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}));
}
}
///
/// 单个修改其它文件,有可能存在无规则的文件,直接按照版本变化上传
///
///
public void StartUpdateInOtherFile(List selectRows)
{
try
{
int execOrder = 1;
FrmBillInfo frmBillInfo = new FrmBillInfo();
string speciesno = selectRows[0]["BomAddSpeciesNo"] + "";
string productId = selectRows[0]["BomMxMainProduct"] + "";
string guid = selectRows[0]["qms_laddf_guId"] + "";
string oldfileId = selectRows[0]["BomAddChangeFileId"] + "";
if (string.IsNullOrEmpty(guid))
{
throw new Exception("Guid标识不能为空");
}
if (string.IsNullOrEmpty(oldfileId))
{
throw new Exception("更改文件Id不能为空");
}
if (string.IsNullOrEmpty(speciesno))
{
throw new Exception("未选择文件分类");
}
if (selectRows.Count > 1)
{
throw new Exception("仅支持单个附件变更");
}
GridControlEx gridControlEx = null;
if (StaticControl.BomUnionPage != null && StaticControl.BomUnionPage.Tag is GridControlEx gridDetailControl)
{
gridControlEx = gridDetailControl;
}
DataTable dataTable = gridControlEx.GridControl.DataSourceTable();
int[] bomRowIndexs = gridControlEx.GridView.GetSelectedRows();
List bomRows = new List();
foreach (int bomRowIndex in bomRowIndexs)
{
bomRows.Add(gridControlEx.GridView.GetDataRow(bomRowIndex));
}
DataRow selectRow = selectRows[0];
string fileName = selectRow[Model.AfterBomFieldName] + "";
string dirPath = selectRow["BomFieldNameDir"] + "";
FileInfo fileInfo = new FileInfo(dirPath);
if (fileInfo != null)
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name).Trim();
bool isMatch = GetOtherFileCodeInfo(fileInfo.Name, out string code, out string spec, out string name, out string extension, out string bb, out int bc);
if (!isMatch)
{
//如果不符合规则,则进行版本更新,会根据选择的文件向多个文件夹进行上传文件
DataRow productRow = BaseImpl.GetDataRowResult($"select ProductId from p_productTab where ProductId = '{productId}'");
if (productRow == null)
{
throw new Exception($"物料编码{code}不存在,无法修改");
}
DataRow fileRow = BaseImpl.GetDataRowResult($"select sname,fileId from p_fm_filetab where parentid in (select dirid from P_fm_DirectoryTab where pid = '{productId}' and dllcoid = '1000202') and speciesno = '{speciesno}' and sname = '{fileInfo.Name}%'");
if (fileRow != null)//如果存在则不允许上传
{
throw new Exception($"{productId}下已存在附件{fileInfo.Name}");
}
foreach (DataRow bomRow in bomRows)
{
string childname = (bomRow["附件名称"] + "").Replace("'", "''");
string childspeciesno = (bomRow["目录ID"] + "").Replace("'", "''");
string childproductid = (bomRow["目录名称"] + "").Trim();
DataRow childfileRow = BaseImpl.GetDataRowResult($"select sname,fileId from p_fm_filetab where parentid in (select dirid from P_fm_DirectoryTab where pid = '{childproductid}' and dllcoid = '1000202') and speciesno = '{childspeciesno}' and sname = '{fileInfo.Name}%'");
if (childfileRow != null)//如果存在则不允许上传
{
throw new Exception($"{childproductid}下已存在附件{fileInfo.Name}");
}
}
}
else
{
//如果符合规则,则直接改变当前编码下的文件
throw new Exception("只允许更改其它无规则文件");
}
}
else
{
throw new Exception($"{fileName}的文件不存在");
}
frmBillInfo.OnControlSourceBind += (s, args) =>
{
Task task = new Task(() =>
{
try
{
int.TryParse(Model.FirstRowIndex, out int index);
frmMain.FirstRowIndex = index;
if (fileInfo != null)
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name).Trim();
bool isMatch = GetOtherFileCodeInfo(fileInfo.Name, out string code, out string spec, out string name, out string extension, out string bb, out int bc);
if (!isMatch)
{
//先上传自身
SetProcessBar(0, 0);
bool isUpload = UploadFileToAudit(fileInfo.FullName, productId, speciesno, out string msg, out string uploadFileId);
if (!isUpload)
{
throw new Exception($"{productId}\r\n{fileNameWithoutExtension}附件上传失败\r\n{msg}");
}
SqlHelper.ExecuteNonQuery($"delete bom_filetab where billno = '{guid}'");
string oldfilename = BaseImpl.GetResult($"select sname from p_fm_filetab where fileid = '{oldfileId}'") + "";
SqlHelper.ExecuteNonQuery($"insert into bom_filetab (billno,fileid,newfileid,filename,newfilename,speciesno,pid) values ('{guid}','{oldfileId}','{uploadFileId}','{oldfilename}','{fileInfo.Name}','{speciesno}','{productId}')");
SetProcessBar(100, (1 / (bomRows.Count() + 1)) * 100);
SetProcessLabelAllMsg($"总进度:1/{bomRows.Count() + 1}");
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (selectRow.Table.Columns.Contains("qms_laddf_uploadtag"))
{
selectRow["qms_laddf_uploadtag"] = 1;
}
if (selectRow.Table.Columns.Contains("qms_laddf_FileId"))
{
int.TryParse(uploadFileId, out int qms_laddf_FileId);
selectRow["qms_laddf_FileId"] = qms_laddf_FileId;
}
}));
int indexorder = 1;
foreach (DataRow bomRow in bomRows)
{
string childfileId = bomRow["文件ID"] + "";
string childname = (bomRow["附件名称"] + "").Replace("'", "''");
string childspeciesno = (bomRow["目录ID"] + "").Replace("'", "''");
string childproductid = (bomRow["目录名称"] + "").Trim();
SetProcessBar(0, (1 / (bomRows.Count() + indexorder + 1)) * 100);
bool isChildUpload = UploadFileToAudit(fileInfo.FullName, childproductid, childspeciesno, out string childmsg, out string childuploadFileId);
if (!isChildUpload)
{
throw new Exception($"{childproductid}{fileNameWithoutExtension}附件上传失败\r\n{childmsg}");
}
SqlHelper.ExecuteNonQuery($"insert into bom_filetab (billno,fileid,newfileid,filename,newfilename,speciesno,pid) values ('{guid}','{childfileId}','{childuploadFileId}','{childname}','{fileInfo.Name}','{childspeciesno}','{childproductid}')");
SetProcessBar(100, (1 / (bomRows.Count() + indexorder + 1)) * 100);
SetProcessLabelAllMsg($"总进度:{indexorder + 1}/{bomRows.Count() + 1}");
indexorder += 1;
}
}
else
{
throw new Exception("只允许更改其它无规则文件");
}
}
else
{
throw new Exception($"{fileName}的文件不存在");
}
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;
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}));
}
}
///
/// 修改单个文件
///
///
public void StartImportInQDFile()
{
string primaryValue = StaticControl.RightMenuMyControl.PrimaryValue;
try
{
if (string.IsNullOrEmpty(primaryValue))
{
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)
{
topProductId = StaticControl.RightMenuMyControl.GetControlValue(topModel);
}
if (string.IsNullOrEmpty(topProductId))
{
MessageUtil.Show($"顶级编码不能为空");
}
DataTable dataTable = SqlHelper.ExecuteDataTable($"select * from FileAttachmentMapping where MaterialCode = '{topProductId}'");
GetFileCodeInfo(beforeName, out string beforeSourceCode, out string beforeSourceName, out string beforeSourceBB, out int beforeSourceBC, false);
List labelRemarkList = new List();
List 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);
}
}
LabelRemarkEdit labelRemark = null;
if (labelRemarkList.Count > 0)
{
labelRemark = labelRemarkList[0];
}
if (labelRemark == null)
{
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.OK;
this.Close();
ImportTimer?.Dispose();
}));
return;
}
string dirPath = labelRemark.filepath;
FileInfo parentInfo = null;
if (string.IsNullOrEmpty(dirPath))
{
throw new Exception("变更文件目录地址不存在");
}
parentInfo = new FileInfo(dirPath);
if (parentInfo != null && (parentInfo.Name.Trim().StartsWith("ZZQD")))
{
FrmBillInfo frmBillInfo = new FrmBillInfo();
frmBillInfo.OnControlSourceBind += (s, args) =>
{
Task task = new Task(() =>
{
try
{
int childIndex = 0;
int allCount = (int)((decimal)(childIndex) / 1 * 100);
int finishCount = (int)((decimal)(1 + childIndex) / 1 * 100);
//如果是ZZQD文件
if (parentInfo != null && (parentInfo.Name.Trim().StartsWith("ZZQD")))
{
GetFileCodeInfo(parentInfo.Name.Trim(), out string sourceCode, out string sourceName, out string sourceBB, out int sourceBC, false);
DataTable filetable = BaseImpl.GetDataTableResult($"select sname,fileId,webpath from p_fm_filetab where parentid in (select dirid from P_fm_DirectoryTab where pid = '{sourceCode}' and dllcoid = '1000202') and speciesno = '010106' and sname like '{sourceCode}%'");
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, false);
if (fileBC >= childMaxBc)
{
childMaxBc = fileBC;
}
}
if (beforeSourceCode.Equals(sourceCode) && sourceBC <= childMaxBc)//变更版次
{
throw new Exception($"变更版本{sourceBB}的版次{sourceBC}必须大于最大版次{childMaxBc}\r\n不允许变更");
}
if (!beforeSourceCode.Equals(sourceCode) && filetable.Rows.Count > 0)//变更版本
{
throw new Exception($"变更版本{sourceBB}已存在,请进行版次变更");
}
//变更ZZQD将原本的ZZQD数据进行档案备份
CopyZZQDToCopy(topProductId);
//更新或新增并备份清单
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_copy 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);
if (masterRow == null)
{
throw new Exception($"BOM建立单{topProductId}不存在");
}
SetProcessBar(40, allCount);
frmBillInfo.AddOrUpdateBill(masterRow, detailTable);
//frmBillInfo.AddOrUpdateBillByZZQD(masterRow, detailTable);
SetProcessBar(60, allCount);
string guid = Guid.NewGuid() + "";
frmBillInfo.BillSaveSql(guid, sourceCode);
//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导入失败");
}
}
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.OK;
}));
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.Cancel;
}));
BaseImpl.ExecSqlValue($"delete QMS_wenjiangenggaitab where qms_wjgg_billdocument_Id = '{primaryValue}'");
}
finally
{
this.Invoke(new Action(() =>
{
this.Close();
ImportTimer?.Dispose();
}));
}
});
task.Start();
};
Model.ChangeModuleCode("9100102");//改变模块编码
frmBillInfo.OnLoad(Model);
frmMain.ParentView = frmBillInfo.GcMainView;
}
else
{
FrmBillInfo frmBillInfo = new FrmBillInfo();
frmBillInfo.OnControlSourceBind += (s, args) =>
{
Task task = new Task(() =>
{
try
{
int childIndex = 0;
int allCount = (int)((decimal)(childIndex) / 1 * 100);
int finishCount = (int)((decimal)(1 + childIndex) / 1 * 100);
//如果是QD文件
if (parentInfo != null && (parentInfo.Name.Trim().StartsWith("QD")))
{
GetFileCodeInfo(parentInfo.Name.Trim(), out string sourceCode, out string sourceName, out string sourceBB, out int sourceBC, false);
DataTable filetable = BaseImpl.GetDataTableResult($"select sname,fileId,webpath from p_fm_filetab where parentid in (select dirid from P_fm_DirectoryTab where pid = '{sourceCode}' and dllcoid = '1000202') and speciesno = '010106' and sname like '{sourceCode}%'");
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, false);
if (fileBC >= childMaxBc)
{
childMaxBc = fileBC;
}
}
if (beforeSourceCode.Equals(sourceCode) && sourceBC <= childMaxBc)//变更版次
{
throw new Exception($"变更版本{sourceBB}的版次{sourceBC}小于最大版次{childMaxBc}\r\n不允许变更");
}
if (!beforeSourceCode.Equals(sourceCode) && filetable.Rows.Count > 0)//变更版本
{
throw new Exception($"变更版本{sourceBB}已存在,请进行版次变更");
}
if (sourceCode.StartsWith("QD"))
{
int createCode = ProductSaveUnique(sourceCode.Replace("'", "''"), sourceName.Replace("'", "''"), "", "1000202_1", out string pid, out string msg);
if ((createCode + "").Equals("-1"))
{
throw new Exception($"虚拟物料创建失败\r\n{msg}");
}
}
//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($"delete FileAttachmentMapping where MaterialCode = '{topProductId}' and RelatedAttachmentName = '{sourceCode}';");
//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);
}));
var qdCodeRows = detailTable.AsEnumerable();
foreach (DataRow qdItem in detailTable.Rows)
{
string qdCode = (qdItem["ProductId"] + "").Trim();
int qdCount = qdCodeRows.Where(n => (n["ProductId"] + "").Trim().StartsWith(qdCode)).Count();
if (qdCount > 1)//只允许存在一个
{
throw new Exception($"{sourceCode}中的{qdCode}重复,请修改");
}
}
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 = (select top 1 productid from p_ProductTab where spec = '{sourceCode}')) as billdocument_id,'0' affirmer,'0' rtagid,(select top 1 productid from p_ProductTab where spec = '{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导入失败");
}
}
//如果是MX文件
else if (parentInfo != null && (parentInfo.Name.Trim().StartsWith("MX")))
{
GetFileCodeInfo(parentInfo.Name.Trim(), out string sourceCode, out string sourceName, out string sourceBB, out int sourceBC, false);
DataTable filetable = BaseImpl.GetDataTableResult($"select sname,fileId,webpath from p_fm_filetab where parentid in (select dirid from P_fm_DirectoryTab where pid = '{topProductId}' and dllcoid = '1000202') and speciesno = '010106' and sname like '{sourceCode}%'");
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, false);
if (fileBC >= childMaxBc)
{
childMaxBc = fileBC;
}
}
if (beforeSourceCode.Equals(sourceCode) && sourceBC <= childMaxBc)//变更版次
{
throw new Exception($"变更版本{sourceBB}的版次{sourceBC}必须大于最大版次{childMaxBc}\r\n不允许变更");
}
if (!beforeSourceCode.Equals(sourceCode) && filetable.Rows.Count > 0)//变更版本
{
throw new Exception($"变更版本{sourceBB}已存在,请进行版次变更");
}
//变更MX将原本的ZZQD数据进行档案备份
CopyZZQDToCopy(topProductId);
//更新或新增并备份清单
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().Where(n => int.TryParse(n["序号"] + "", out _) && !string.IsNullOrEmpty(n["图号"] + "")).ToList().CopyToDataTable();
Dictionary childFileDic = new Dictionary();
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($"{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($"{fileName}的明细附件下载失败\r\nBom导入失败");
}
}
}
}
}
StringBuilder stringBuilder = new StringBuilder();
foreach (DataRow dataRow in parentTable.Rows)
{
string childCode = (dataRow["图号"] + "").Trim();
if (childCode.StartsWith("QD"))
{
int createCode = ProductSaveUnique(childCode.Replace("'", "''"), (dataRow["名称"] + "").Replace("'", "''"), (dataRow["备注"] + "").Replace("'", "''"), "1000202_1", out string pid, out string msg);
if ((createCode + "").Equals("-1"))
{
throw new Exception($"虚拟物料创建失败\r\n{msg}");
}
}
if (childCode.StartsWith("RJ"))
{
string rjProductid = BaseImpl.GetResult($"(select top 1 productid from p_ProductTab where productid = '{childCode}')") + "";
if (string.IsNullOrEmpty(rjProductid))
{
throw new Exception($"RJ软件物料编码不存在");
}
}
}
if (!string.IsNullOrEmpty(stringBuilder.ToString()))
{
SqlHelper.ExecuteNonQuery(stringBuilder.ToString());
}
frmBillInfo.OnBillAdd();
SetProcessBar(0, 0);
SetProcessMsg($"正在导入:{Path.GetFileName(parentInfo.FullName)}");
string zzqdTag = "";
DataTable childTable = frmBillInfo.GcMainView.GridControl.DataSourceTable().Clone();
StringBuilder insertbulider = new StringBuilder();
insertbulider.AppendLine($"delete FileAttachmentMapping where MaterialCode = '{topProductId}';");
//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["图号"] + "";
GetFileCodeInfo(childCode, out string childsourceCode0, out string childsourceName0, out string childsourceBB0, out int childsourceBC0, true);
if (!childCode.StartsWith("RJ"))
{
if (childsourceBC0 > 0)
{
throw new Exception($"{childsourceCode0}的版次为{childsourceBC0}\r\n录入的版次不允许大于0");
}
}
string unionTzName = parentRow.Table.Columns.Contains("关联清单") ? (parentRow["关联清单"] + "").Trim() : "";
insertbulider.AppendLine($"insert into FileAttachmentMapping (MaterialCode,MxFileName,RelatedAttachmentName,OperatorUser,ChangeStatus,UnionTZName) values ('{topProductId}','{sourceCode }','{childCode}','{ERPInfo.Instance.UserName}','变更','{unionTzName}');");
if (childCode.StartsWith("QD") || childCode.StartsWith("ZZQD"))
{
string tempFileName = childFileDic.ContainsKey(childCode) ? childFileDic[childCode] : "";
FileInfo childInfo = null;
if (!string.IsNullOrEmpty(tempFileName))
{
childInfo = new FileInfo(tempFileName);
}
if (childInfo == null)
{
//throw new Exception($"MX明细中不包含文件{childCode}");
GetFileCodeInfo(childCode, out string childsourceCode, out string childsourceName, out string childsourceBB, out int childsourceBC, true);
if (childCode.StartsWith("QD"))
{
DataRow childRow = childTable.NewRow();
childRow["ProductId"] = BaseImpl.GetResult($"(select top 1 productid from p_ProductTab where spec = '{childCode}')");
childRow["appellation"] = parentRow["名称"] + "";
childRow["bak"] = childCode;
childRow["bombb"] = childsourceBB;
childRow["bombc"] = 0;
childRow["tamount"] = parentRow["套数"] + "";
childRow["amount"] = parentRow["套数"] + "";
childTable.Rows.Add(childRow);
}
else if (childCode.StartsWith("ZZQD"))
{
zzqdTag = childCode;
//throw new Exception($"{sourceCode}未获取到ZZQD附件");
}
}
if (childInfo != null)
{
GetFileCodeInfo(childInfo.Name.Trim(), out string childsourceCode, out string childsourceName, out string childsourceBB, out int childsourceBC, false);
if (childCode.StartsWith("ZZQD"))
{
zzqdTag = childCode;
//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["物料编码"] + "").Trim();
// 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"] = BaseImpl.GetResult($"(select top 1 productid from p_ProductTab where spec = '{childCode}')");
childRow["appellation"] = parentRow["名称"] + "";
childRow["bak"] = childsourceCode;
childRow["bombb"] = childsourceBB;
childRow["bombc"] = childsourceBC;
childRow["tamount"] = parentRow["套数"] + "";
childRow["amount"] = parentRow["套数"] + "";
childTable.Rows.Add(childRow);
}
}
}
if (childCode.StartsWith("RJ"))
{
DataRow childRow = childTable.NewRow();
childRow["ProductId"] = BaseImpl.GetResult($"(select top 1 productid from p_ProductTab where productid = '{childCode}')");
childRow["appellation"] = parentRow["名称"] + "";
childRow["bak"] = childCode;
childRow["bombb"] = "";
childRow["bombc"] = "0";
childRow["tamount"] = parentRow["套数"] + "";
childRow["amount"] = parentRow["套数"] + "";
childTable.Rows.Add(childRow);
}
}
SetProcessBar(20, 0);
if (childTable.Rows.Count == 0 && !zzqdTag.StartsWith("ZZQD"))
{
throw new Exception($"MX明细数据为空");
}
string billMasterSql = $"select (select top 1 billdocument_id from bom_BillTab where productid='{topProductId}') as billdocument_id,'0' affirmer,'0' rtagid,'{topProductId}' as productid,'{sourceCode}' as bak,'{sourceBB}' as bombb,'{sourceBC}' as bombc";
// 处理单据表头数据
DataRow masterRow = BillImpl.GetDataRowResult(billMasterSql);
if (masterRow == null)
{
throw new Exception($"BOM建立单{topProductId}不存在");
}
SetProcessBar(40, allCount);
frmBillInfo.AddOrUpdateBill(masterRow, childTable);
SetProcessBar(60, allCount);
string guid = Guid.NewGuid() + "";
frmBillInfo.BillSaveSql(guid, zzqdTag);
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(parentInfo.Name.Trim(), out string sourceCode, out string sourceName, out string sourceBB, out int sourceBC, false);
DataTable filetable = BaseImpl.GetDataTableResult($"select sname,fileId,webpath from p_fm_filetab where parentid in (select dirid from P_fm_DirectoryTab where pid = '{sourceCode}' and dllcoid = '1000202') and speciesno = '010106' and sname like '{sourceCode}%'");
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, false);
if (fileBC >= childMaxBc)
{
childMaxBc = fileBC;
}
}
if (beforeSourceCode.Equals(sourceCode) && sourceBC <= childMaxBc)//变更版次
{
throw new Exception($"变更版本{sourceBB}的版次{sourceBC}必须大于最大版次{childMaxBc}\r\n不允许变更");
}
if (!beforeSourceCode.Equals(sourceCode) && filetable.Rows.Count > 0)//变更版本
{
throw new Exception($"变更版本{sourceBB}已存在,请进行版次变更");
}
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($"delete FileAttachmentMapping where MaterialCode = '{topProductId}' and RelatedAttachmentName = '{sourceCode}';");
//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.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.OK;
}));
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.Cancel;
}));
BaseImpl.ExecSqlValue($"delete QMS_wenjiangenggaitab where qms_wjgg_billdocument_Id = '{primaryValue}'");
}
finally
{
this.Invoke(new Action(() =>
{
this.Close();
ImportTimer?.Dispose();
}));
}
});
task.Start();
};
frmBillInfo.OnLoad(Model);
frmMain.ParentView = frmBillInfo.GcMainView;
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
BaseImpl.ExecSqlValue($"delete QMS_wenjiangenggaitab where qms_wjgg_billdocument_Id = '{primaryValue}'");
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.Cancel;
this.Close();
ImportTimer?.Dispose();
}));
}
}
///
/// bom结构上传
///
///
public void StartImportInFiles(List selectRows)
{
try
{
if (Directory.Exists("BomImportTemp"))
{
Directory.Delete("BomImportTemp", true);
}
Directory.CreateDirectory("BomImportTemp");
int execOrder = 1;
var mxRows = selectRows.Where(n => (n[Model.AfterBomFieldName] + "").StartsWith("MX"));
if (mxRows.Count() > 1)
{
throw new Exception($"不允许出现多个MX文件");
}
DataRow mxRow = mxRows.FirstOrDefault();
if (mxRow != null)
{
string mxFileName = mxRow[Model.AfterBomFieldName] + "";
string productId = mxRow["BomMxMainProduct"] + "";
string mxDirPath = mxRow["BomFieldNameDir"] + "";
string addState = mxRow["BomMxAddState"] + "";
if (string.IsNullOrEmpty(productId))
{
throw new Exception($"保存失败\r\n请重新进行BOM上传后保存");
}
if (addState.Equals("新增"))
{
DataRow billRow = BaseImpl.GetDataRowResult($"select qms_maddf_billdocument_id from qms_BillFileAddMaintab where qms_maddf_productid = '{productId}' and isnull(qms_maddf_addMode,'0') = '0'");
if (billRow != null)
{
throw new Exception($"物料编码{productId}的BOM新增单已存在审批流\r\n请进行审批");
}
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请进行修改操作");
}
}
else
{
DataRow billbomRow = BaseImpl.GetDataRowResult($"select top 1 billdocument_id from bom_BillTab where productid='{productId}' and stepover = '1'");
if (billbomRow != null)
{
throw new Exception($"物料编码{productId}的BOM建立单已终审\r\n禁止修改操作");
}
}
GetFileCodeInfo(mxFileName.Trim(), out string mxsourceCode, out string mxname, out string mxsourceBB, out int mxsourceBC, false);
DataTable mxfiletable = BaseImpl.GetDataTableResult($"select sname,fileId,webpath 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}%'");
FileInfo mxInfo = null;
if (!string.IsNullOrEmpty(mxDirPath))
{
mxInfo = new FileInfo(mxDirPath);
}
if (mxInfo != null || mxfiletable.Rows.Count > 0)
{
if (mxfiletable.Rows.Count > 0)
{
throw new Exception($"{mxsourceCode}已存在附件,请进行MX修改");
}
if (!mxsourceBB.Equals("SA"))
{
throw new Exception($"{mxInfo.Name}\r\n版本不为SA不允许新增,请进行修改");
}
if (mxsourceBC > 0)
{
throw new Exception($"{mxInfo.Name}\r\n不为0的版次不允许新增,请进行修改");
}
if (mxInfo != null)
{
FrmBillInfo frmBillInfo = new FrmBillInfo();
DataTable parentTable = ExcelToDatatable(mxInfo.FullName, Model, "", 5);
parentTable = parentTable.Rows.Cast().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"))
{
int createCode = ProductSaveUnique(code.Replace("'", "''"), (dataRow["名称"] + "").Replace("'", "''"), (dataRow["备注"] + "").Replace("'", "''"), "1000202_1", out string pid, out string msg);
if ((createCode + "").Equals("-1"))
{
throw new Exception($"虚拟物料创建失败\r\n{msg}");
}
}
if (code.StartsWith("RJ"))
{
string rjProductid = BaseImpl.GetResult($"(select top 1 productid from p_ProductTab where productid = '{code}')") + "";
if (string.IsNullOrEmpty(rjProductid))
{
throw new Exception($"RJ软件物料编码不存在");
}
}
}
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 = "";
Dictionary maxBcFileDic = new Dictionary();
Dictionary fileTableDic = new Dictionary();
#region 新增或修改MX
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}','新增');");
var mxCodeRows = parentTable.AsEnumerable();
foreach (DataRow parentRow in parentTable.Rows)
{
int.TryParse(parentRow["套数"] + "", out int tamount);
string code = (parentRow["图号"] + "").Trim();
GetFileCodeInfo(code, out string childsourceCode0, out string childsourceName0, out string childsourceBB0, out int childsourceBC0, true);
if (!code.StartsWith("RJ"))
{
if (childsourceBC0 > 0)
{
throw new Exception($"{childsourceCode0}的版次为{childsourceBC0}\r\n录入的版次不允许大于0");
}
}
string unionTzName = parentRow.Table.Columns.Contains("关联清单") ? (parentRow["关联清单"] + "").Trim() : "";
int codeCount = mxCodeRows.Where(n => (n["图号"] + "").Trim().StartsWith(code)).Count();
if (codeCount > 1)//只允许存在一个
{
throw new Exception($"MX中的{code}重复,请修改");
}
insertbulider.AppendLine($"insert into FileAttachmentMapping (MaterialCode,MxFileName,RelatedAttachmentName,OperatorUser,ChangeStatus,UnionTZName) values ('{productId}','{mxsourceCode }','{code}','{ERPInfo.Instance.UserName}','新增','{unionTzName}');");
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, false);
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"] + "";
if (!string.IsNullOrEmpty(childDirPath))
{
childInfo = new FileInfo(childDirPath);
}
}
if ((childInfo == null || filetable.Rows.Count > 0) && !code.StartsWith("RJ") && 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 (code.StartsWith("RJ"))
{
DataRow childRow = childTable.NewRow();
childRow["ProductId"] = BaseImpl.GetResult($"(select top 1 productid from p_ProductTab where productid = '{code}')");//RJ的物料编码是什么开头的?保持原逻辑吗?
childRow["appellation"] = parentRow["名称"] + "";
childRow["bak"] = code;
childRow["bombb"] = "";
childRow["bombc"] = "0";
childRow["tamount"] = parentRow["套数"] + "";
childRow["amount"] = parentRow["套数"] + "";
childTable.Rows.Add(childRow);
}
else
{
if (childInfo != null)
{
GetFileCodeInfo(childInfo.Name.Trim(), out string childsourceCode, out string childname, out string childsourceBB, out int childsourceBC, false);
//如果文件夹中有附件,则比较版次,如果大于最大版次,则提示
if (childsourceBC > childMaxBc && filetable.Rows.Count > 0)
{
throw new Exception($"{childsourceCode}的版次为{childsourceBC},大于最大版次{childMaxBc}\r\n请进行变更");
}
if (filetable.Rows.Count == 0 && !childsourceBB.Equals("SA"))
{
throw new Exception($"{childInfo.Name}\r\n版本不为SA不允许新增,请进行修改");
}
if (filetable.Rows.Count == 0 && childsourceBC > 0)
{
throw new Exception($"{childsourceCode}的版次为{childsourceBC},不允许新增版次大于0的附件");
}
childsourceBC = childsourceBC >= childMaxBc ? childsourceBC : childMaxBc;
if (code.StartsWith("QD") || code.StartsWith("ZZQD"))
{
DataTable qdTable = ExcelToDatatable(childInfo.FullName, Model, "", index);
DataView filterDataView = new DataView(qdTable);
try
{
if (!string.IsNullOrEmpty(Model.ReadTableCond))
{
filterDataView.RowFilter = Model.ReadTableCond;
}
}
catch (Exception)
{
}
qdTable = filterDataView.ToTable();
var qdCodeRows = qdTable.AsEnumerable();
foreach (DataRow qdItem in qdTable.Rows)
{
string qdCode = (qdItem["物料编码"] + "").Trim();
int qdCount = qdCodeRows.Where(n => (n["物料编码"] + "").Trim().StartsWith(qdCode)).Count();
if (qdCount > 1)//只允许存在一个
{
throw new Exception($"{childsourceCode}中的{qdCode}重复,请修改");
}
}
if (code.StartsWith("ZZQD"))
{
foreach (DataRow zzqdItem in qdTable.Rows)
{
DataRow childRow = childTable.NewRow();
childRow["ProductId"] = (zzqdItem["物料编码"] + "").Trim();
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"] = BaseImpl.GetResult($"(select top 1 productid from p_ProductTab where spec = '{code}')");
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 && !code.StartsWith("RJ"))
{
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 uploadMxFileId = "";
if (mxfiletable.Rows.Count == 0)
{
isUpload = UploadFileToAudit(mxInfo.FullName, productId, "010106", out msg, out uploadMxFileId);
if (!isUpload)
{
throw new Exception($"{mxInfo.Name}附件上传失败\r\n{msg}");
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (mxRow.Table.Columns.Contains("qms_laddf_uploadtag"))
{
mxRow["qms_laddf_uploadtag"] = 1;
}
}));
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (mxRow.Table.Columns.Contains("qms_laddf_FileId"))
{
int.TryParse(uploadMxFileId, 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;
#endregion
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"))
{
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"] + "";
if (!string.IsNullOrEmpty(childDirPath))
{
childInfo = new FileInfo(childDirPath);
}
}
if ((childInfo == null || filetable.Rows.Count > 0) && !code.StartsWith("RJ") && 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 && !code.StartsWith("RJ"))
{
throw new Exception($"MX明细中的{code}文件不存在");
}
if (childInfo != null)
{
GetFileCodeInfo(childInfo.Name.Trim(), out string qdsourceCode, out string qdname, out string qdsourceBB, out int qdsourceBC, false);
DataRow productRow = BaseImpl.GetDataRowResult($"select top 1 billdocument_id from bom_BillTab where productid = (select top 1 productid from p_ProductTab where spec = '{code}')");
if (productRow == null)
{
string childGuid = childInfoRow != null && !string.IsNullOrEmpty(childInfoRow["qms_laddf_Exec"] + "") ? childInfoRow["qms_laddf_Exec"] + "" : Guid.NewGuid() + "";
string uploadFileId = maxBcFileDic.ContainsKey(code) ? maxBcFileDic[code]["fileId"] + "" : "-1";
if (filetable.Rows.Count == 0)
{
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 = (select top 1 productid from p_ProductTab where spec = '{code}')) as billdocument_id,'0' affirmer,'0' rtagid,(select top 1 productid from p_ProductTab where spec = '{code}') as productid,'{qdsourceCode}' as bak,'{qdsourceBB}' as bombb,'{qdsourceBC}' as bombc";
// 处理单据表头数据
DataRow childMasterRow = BillImpl.GetDataRowResult(childBillMasterSql);
SetProcessBar(60, allCount);
frmBillInfo.AddOrUpdateBill(childMasterRow, detailTable);
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);
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_uploadtag"))
{
childInfoRow["qms_laddf_uploadtag"] = 1;
}
}));
}
}
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_uploadtag"))
{
childInfoRow["qms_laddf_uploadtag"] = 1;
}
}));
}
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
{
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"] + "";
if (!string.IsNullOrEmpty(childDirPath))
{
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 && !code.StartsWith("RJ"))
{
throw new Exception($"目录中不包含文件{code}");
}
if (childInfo != null)
{
SetProcessBar(0, allCount);
string uploadFileId = maxBcFileDic.ContainsKey(code) ? maxBcFileDic[code]["fileId"] + "" : "-1";
if (filetable.Rows.Count == 0)
{
GetFileCodeInfo(childInfo.Name.Trim(), out string qdsourceCode, out string qdname, out string qdsourceBB, out int qdsourceBC, false);
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_uploadtag"))
{
childInfoRow["qms_laddf_uploadtag"] = 1;
}
}));
}
}
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文件");
}
}
else
{
throw new Exception("未包含MX文件");
}
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}));
}
}
///
/// bom结构上传(总部)
///
///
public void StartImportInFileByZB(List selectRows)
{
try
{
if (Directory.Exists("BomImportTemp"))
{
Directory.Delete("BomImportTemp", true);
}
Directory.CreateDirectory("BomImportTemp");
int execOrder = 1;
if (selectRows.Count > 1)
{
throw new Exception($"不允许选择多个文件");
}
DataRow mxRow = selectRows[0];
if (mxRow != null)
{
string mxFileName = mxRow[Model.AfterBomFieldName] + "";
string mxDirPath = mxRow["BomFieldNameDir"] + "";
string productId = mxRow["BomMxMainProduct"] + "";
string addState = mxRow["BomMxAddState"] + "";
string selectModelValue = "";
string selectVerValue = "";
string selectBakValue = "";
ControlModel selectModel = StaticControl.RightMenuMyControl.ControlModels.Where(n => n.LabelText.Equals("生成模式")).FirstOrDefault();
ControlModel selectVerModel = StaticControl.RightMenuMyControl.ControlModels.Where(n => n.LabelText.Equals("覆盖版本")).FirstOrDefault();
ControlModel selectBakModel = StaticControl.RightMenuMyControl.ControlModels.Where(n => n.LabelText.Equals("备注信息")).FirstOrDefault();
if (selectModel != null)
{
selectModelValue = StaticControl.RightMenuMyControl.GetControlValue(selectModel);
}
if (selectVerModel != null)
{
selectVerValue = StaticControl.RightMenuMyControl.GetControlValue(selectVerModel);
}
if (selectBakModel != null)
{
selectBakValue = StaticControl.RightMenuMyControl.GetControlValue(selectBakModel);
}
if (string.IsNullOrEmpty(selectModelValue))
{
throw new Exception($"未选择生成模式");
}
if (selectModelValue.Equals("1"))
{
if (string.IsNullOrEmpty(selectVerValue))
{
throw new Exception($"覆盖模式未选择被覆盖版本");
}
}
if (string.IsNullOrEmpty(Model.MainFieldDic))
{
throw new Exception($"字段对应关系配置异常");
}
if (string.IsNullOrEmpty(productId))
{
throw new Exception($"保存失败\r\n请重新进行BOM上传后保存");
}
//if (addState.Equals("新增"))
//{
// DataRow billRow = BaseImpl.GetDataRowResult($"select qms_maddf_billdocument_id from qms_BillFileAddMaintab where qms_maddf_productid = '{productId}' and isnull(qms_maddf_addMode,'0') = '7' and isnull(qms_maddf_addMode,'0') = '7' ");
// if (billRow != null)
// {
// throw new Exception($"物料编码{productId}的BOM新增单已存在审批流\r\n请进行审批");
// }
// 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请进行修改操作");
// }
//}
//else
//{
// DataRow billbomRow = BaseImpl.GetDataRowResult($"select top 1 billdocument_id from bom_BillTab where productid='{productId}' and stepover = '1'");
// if (billbomRow != null)
// {
// throw new Exception($"物料编码{productId}的BOM建立单已终审\r\n禁止修改操作");
// }
//}
FileInfo mxInfo = null;
if (!string.IsNullOrEmpty(mxDirPath))
{
mxInfo = new FileInfo(mxDirPath);
}
if (mxInfo != null)
{
DataTable mxfiletable = BaseImpl.GetDataTableResult($"select sname,fileId,webpath from p_fm_filetab where parentid in (select dirid from P_fm_DirectoryTab where pid = '{productId}' and dllcoid = '1000202') and speciesno = '010106' and sname = '{mxInfo.Name}'");
if (mxfiletable.Rows.Count > 0)
{
throw new Exception($"该文件已存在,请确认后再创建BOM");
}
FrmBillInfo frmBillInfo = new FrmBillInfo();
int.TryParse(Model.FirstRowIndex + "", out int firstRowIndex);
DataTable parentTable = ExcelToDatatable(mxInfo.FullName, Model, Model.SheetName, firstRowIndex);
//string[] condArray = Model.ReadTableCond.Split('^');
//string endCond = condArray.Length > 1 ? condArray[1] : "";
//if (!string.IsNullOrEmpty(endCond))
//{
// List condRows = new List();
// foreach (DataRow item in parentTable.Rows)
// {
// if (ReplaceHelper.ReplaceRowParamCond(item, endCond))
// {
// break;
// }
// else
// {
// condRows.Add(item);
// }
// }
// parentTable = condRows.CopyToDataTable();
//}
string endCond = "'{物料编码}'='END'";
List condRows = new List();
foreach (DataRow item in parentTable.Rows)
{
if (ReplaceHelper.ReplaceRowParamCond(item, endCond))
{
break;
}
else
{
condRows.Add(item);
}
}
parentTable = condRows.CopyToDataTable();
parentTable = parentTable.Rows.Cast().Where(n => int.TryParse(n["序号"] + "", out _) && !string.IsNullOrEmpty(n["物料编码"] + "")).ToList().CopyToDataTable();
//StringBuilder stringBuilder = new StringBuilder();
//foreach (DataRow dataRow in parentTable.Rows)
//{
// string code = (dataRow["图号"] + "").Trim();
// if (code.StartsWith("QD"))
// {
// int createCode = ProductSaveUnique(code.Replace("'", "''"), (dataRow["名称"] + "").Replace("'", "''"), (dataRow["备注"] + "").Replace("'", "''"), "1000202_1", out string pid, out string msg);
// if ((createCode + "").Equals("-1"))
// {
// throw new Exception($"虚拟物料创建失败\r\n{msg}");
// }
// }
//}
//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 = "";
Dictionary maxBcFileDic = new Dictionary();
Dictionary fileTableDic = new Dictionary();
#region 新增或修改MX
frmBillInfo.OnBillAdd();
SetProcessBar(0, 0);
SetProcessMsg($"正在导入:{Path.GetFileName(mxInfo.FullName)}");
string fileNameExtension = Path.GetFileName(mxInfo.FullName).Replace("'", "''");
DataTable childTable = frmBillInfo.GcMainView.GridControl.DataSourceTable().Clone();
var mxCodeRows = parentTable.AsEnumerable();
string[] fieldDic = Model.MainFieldDic.Split(',');
foreach (DataRow parentRow in parentTable.Rows)
{
string code = (parentRow["物料编码"] + "").Trim();
int codeCount = mxCodeRows.Where(n => (n["物料编码"] + "").Trim().StartsWith(code)).Count();
//if (codeCount > 1)//只允许存在一个
//{
// throw new Exception($"文件中的物料编码{code}重复,请修改");
//}
DataRow childRow = childTable.NewRow();
foreach (string item in fieldDic)
{
string[] fieldArray = item.Split('^');
string key0 = fieldArray[0];
string key1 = fieldArray[1];
childRow[key0] = parentRow[key1] + "";
}
//childRow["ProductId"] = parentRow["物料编码"] + "";
//childRow["appellation"] = parentRow["名称"] + "";
//childRow["bak"] = parentRow["备注"] + "";
//childRow["tamount"] = parentRow["数量"] + "";
//childRow["amount"] = parentRow["数量"] + "";
childTable.Rows.Add(childRow);
}
SetProcessBar(20, 0);
if (childTable.Rows.Count == 0)
{
throw new Exception($"明细数据不能空");
}
SetProcessBar(40, 0);
string billMasterSql = $"select (select top 1 billdocument_id from {frmBillInfo.billModel.MasterTable} where productid='{productId}') as billdocument_id,'0' affirmer,'0' rtagid,'{productId}' as productid,'{selectBakValue}' as bak,'{fileNameExtension}' as bombb,'' as bombc";
if (selectModelValue.Equals("2"))
{
billMasterSql = $"select '' as billdocument_id,'0' affirmer,'0' rtagid,'{productId}' as productid,'{selectBakValue}' as bak,'{fileNameExtension}' as bombb,'' as bombc";
}
else if (selectModelValue.Equals("1"))
{
billMasterSql = $"select (select top 1 billdocument_id from {frmBillInfo.billModel.MasterTable} where productid='{productId}' and billdocument_id = '{selectVerValue}') as billdocument_id,'0' affirmer,'0' rtagid,'{productId}' as productid,'{selectBakValue}' as bak,'{fileNameExtension}' as bombb,'' as bombc";
}
// 处理单据表头数据
DataRow masterRow = BillImpl.GetDataRowResult(billMasterSql);
SetProcessBar(60, 0);
frmBillInfo.AddOrUpdateBill(masterRow, childTable, selectModelValue);
string guid = Guid.NewGuid() + "";
frmBillInfo.BillSaveSql(guid);
SetProcessBar(80, 0);
//上传文件
string uploadMxFileId = "";
if (mxfiletable.Rows.Count == 0)
{
isUpload = UploadFileToAudit(mxInfo.FullName, productId, "010106", out msg, out uploadMxFileId);
if (!isUpload)
{
throw new Exception($"{mxInfo.Name}附件上传失败\r\n{msg}");
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (mxRow.Table.Columns.Contains("qms_laddf_uploadtag"))
{
mxRow["qms_laddf_uploadtag"] = 1;
}
}));
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (mxRow.Table.Columns.Contains("qms_laddf_FileId"))
{
int.TryParse(uploadMxFileId, 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;
#endregion
SetProcessBar(100, (1 / (parentTable.Rows.Count + 1)) * 100);
SetProcessLabelAllMsg($"总进度:{1}/{parentTable.Rows.Count + 1}");
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("文件不存在");
}
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}));
}
}
///
/// 一级bom结构上传
///
///
public void StartImportInFirstFiles(List selectRows)
{
try
{
if (Directory.Exists("BomImportTemp"))
{
Directory.Delete("BomImportTemp", true);
}
Directory.CreateDirectory("BomImportTemp");
int execOrder = 1;
var mxRows = selectRows.Where(n => (n[Model.AfterBomFieldName] + "").StartsWith("MX"));
if (mxRows.Count() > 1)
{
throw new Exception($"不允许出现多个MX文件");
}
DataRow mxRow = mxRows.FirstOrDefault();
if (mxRow != null)
{
string mxFileName = mxRow[Model.AfterBomFieldName] + "";
string mxDirPath = mxRow["BomFieldNameDir"] + "";
string productId = mxRow["BomMxMainProduct"] + "";
string addState = mxRow["BomMxAddState"] + "";
if (string.IsNullOrEmpty(productId))
{
throw new Exception($"保存失败\r\n请重新进行BOM上传后保存");
}
if (addState.Equals("新增"))
{
DataRow billRow = BaseImpl.GetDataRowResult($"select qms_maddf_billdocument_id from qms_BillFileAddMaintab where qms_maddf_productid = '{productId}' and isnull(qms_maddf_addMode,'0') = '2'");
if (billRow != null)
{
throw new Exception($"物料编码{productId}的BOM新增单已存在审批流\r\n请进行审批");
}
//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请进行修改操作");
//}
}
else
{
//DataRow billbomRow = BaseImpl.GetDataRowResult($"select top 1 billdocument_id from bom_BillTab where productid='{productId}' and stepover = '1'");
//if (billbomRow != null)
//{
// throw new Exception($"物料编码{productId}的BOM建立单已终审\r\n禁止修改操作");
//}
}
GetFileCodeInfo(mxFileName.Trim(), out string mxsourceCode, out string mxname, out string mxsourceBB, out int mxsourceBC, false);
DataTable mxfiletable = BaseImpl.GetDataTableResult($"select sname,fileId,webpath 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}%'");
FileInfo mxInfo = null;
if (!string.IsNullOrEmpty(mxDirPath))
{
mxInfo = new FileInfo(mxDirPath);
}
if (mxInfo != null || mxfiletable.Rows.Count > 0)
{
if (mxfiletable.Rows.Count > 0)
{
throw new Exception($"{mxsourceCode}已存在,请进行MX修改");
}
if (!mxsourceBB.Equals("SA"))
{
throw new Exception($"{mxInfo.Name}\r\n版本不为SA不允许新增,请进行修改");
}
if (mxsourceBC > 0)
{
throw new Exception($"{mxInfo.Name}\r\n不为0的版次不允许新增,请进行修改");
}
if (mxInfo != null)
{
FrmBillInfo frmBillInfo = new FrmBillInfo();
DataTable parentTable = ExcelToDatatable(mxInfo.FullName, Model, "", 5);
parentTable = parentTable.Rows.Cast().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"))
{
int createCode = ProductSaveUnique(code.Replace("'", "''"), (dataRow["名称"] + "").Replace("'", "''"), (dataRow["备注"] + "").Replace("'", "''"), "1000202_1", out string pid, out string msg);
if ((createCode + "").Equals("-1"))
{
throw new Exception($"虚拟物料创建失败\r\n{msg}");
}
}
if (code.StartsWith("RJ"))
{
string rjProductid = BaseImpl.GetResult($"(select top 1 productid from p_ProductTab where productid = '{code}')") + "";
if (string.IsNullOrEmpty(rjProductid))
{
throw new Exception($"RJ软件物料编码不存在");
}
}
}
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 = "";
Dictionary maxBcFileDic = new Dictionary();
Dictionary fileTableDic = new Dictionary();
#region 新增或修改MX
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}','新增');");
var mxCodeRows = parentTable.AsEnumerable();
foreach (DataRow parentRow in parentTable.Rows)
{
int.TryParse(parentRow["套数"] + "", out int tamount);
string code = (parentRow["图号"] + "").Trim();
string unionTzName = parentRow.Table.Columns.Contains("关联清单") ? (parentRow["关联清单"] + "").Trim() : "";
int codeCount = mxCodeRows.Where(n => (n["图号"] + "").Trim().StartsWith(code)).Count();
if (codeCount > 1)//只允许存在一个
{
throw new Exception($"MX中的{code}重复,请修改");
}
insertbulider.AppendLine($"insert into FileAttachmentMapping (MaterialCode,MxFileName,RelatedAttachmentName,OperatorUser,ChangeStatus,UnionTZName) values ('{productId}','{mxsourceCode }','{code}','{ERPInfo.Instance.UserName}','新增','{unionTzName}');");
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, false);
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"] + "";
if (!string.IsNullOrEmpty(childDirPath))
{
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 (code.StartsWith("RJ"))
{
DataRow childRow = childTable.NewRow();
childRow["ProductId"] = BaseImpl.GetResult($"(select top 1 productid from p_ProductTab where productid = '{code}')");//RJ的物料编码是什么开头的?保持原逻辑吗?
childRow["appellation"] = parentRow["名称"] + "";
childRow["bak"] = code;
childRow["bombb"] = "";
childRow["bombc"] = "0";
childRow["tamount"] = parentRow["套数"] + "";
childRow["amount"] = parentRow["套数"] + "";
childTable.Rows.Add(childRow);
}
else
{
if (childInfo != null)
{
GetFileCodeInfo(childInfo.Name.Trim(), out string childsourceCode, out string childname, out string childsourceBB, out int childsourceBC, false);
//如果文件夹中有附件,则比较版次,如果大于最大版次,则提示
if (childsourceBC > childMaxBc && filetable.Rows.Count > 0)
{
throw new Exception($"{childsourceCode}的版次为{childsourceBC},大于最大版次{childMaxBc}\r\n请进行变更");
}
if (filetable.Rows.Count == 0 && !childsourceBB.Equals("SA"))
{
throw new Exception($"{childInfo.Name}\r\n版本不为SA不允许新增,请进行修改");
}
if (filetable.Rows.Count == 0 && childsourceBC > 0)
{
throw new Exception($"{childsourceCode}的版次为{childsourceBC},不允许新增版次大于0的附件");
}
childsourceBC = childsourceBC >= childMaxBc ? childsourceBC : childMaxBc;
if (code.StartsWith("ZZQD"))
{
DataTable qdTable = ExcelToDatatable(childInfo.FullName, Model, "", index);
DataView filterDataView = new DataView(qdTable);
try
{
if (!string.IsNullOrEmpty(Model.ReadTableCond))
{
filterDataView.RowFilter = Model.ReadTableCond;
}
}
catch (Exception)
{
}
qdTable = filterDataView.ToTable();
var qdCodeRows = qdTable.AsEnumerable();
foreach (DataRow qdItem in qdTable.Rows)
{
string qdCode = (qdItem["物料编码"] + "").Trim();
int qdCount = qdCodeRows.Where(n => (n["物料编码"] + "").Trim().StartsWith(qdCode)).Count();
if (qdCount > 1)//只允许存在一个
{
throw new Exception($"{childsourceCode}中的{qdCode}重复,请修改");
}
}
if (code.StartsWith("ZZQD"))
{
foreach (DataRow zzqdItem in qdTable.Rows)
{
DataRow childRow = childTable.NewRow();
childRow["ProductId"] = (zzqdItem["物料编码"] + "").Trim();
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
{
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}'");
BaseImpl.ExecSqlValue($"update p_bomImportExecTab set userid = '1' where guid = '{guid}'");
SetProcessBar(80, 0);
//上传文件
string uploadMxFileId = "";
if (mxfiletable.Rows.Count == 0)
{
isUpload = UploadFileToAudit(mxInfo.FullName, productId, "010106", out msg, out uploadMxFileId);
if (!isUpload)
{
throw new Exception($"{mxInfo.Name}附件上传失败\r\n{msg}");
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (mxRow.Table.Columns.Contains("qms_laddf_uploadtag"))
{
mxRow["qms_laddf_uploadtag"] = 1;
}
}));
}
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (mxRow.Table.Columns.Contains("qms_laddf_FileId"))
{
int.TryParse(uploadMxFileId, 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;
#endregion
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;
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"] + "";
if (!string.IsNullOrEmpty(childDirPath))
{
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 && !code.StartsWith("RJ"))
{
throw new Exception($"目录中不包含文件{code}");
}
if (childInfo != null)
{
SetProcessBar(0, allCount);
string uploadFileId = maxBcFileDic.ContainsKey(code) ? maxBcFileDic[code]["fileId"] + "" : "-1";
if (filetable.Rows.Count == 0)
{
GetFileCodeInfo(childInfo.Name.Trim(), out string qdsourceCode, out string qdname, out string qdsourceBB, out int qdsourceBC, false);
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_uploadtag"))
{
childInfoRow["qms_laddf_uploadtag"] = 1;
}
}));
}
}
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文件");
}
}
else
{
throw new Exception("未包含MX文件");
}
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}));
}
}
///
/// 修改终审同步
///
///
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, false);
BaseImpl.ExecSqlValue(afterSql);
BaseImpl.ExecSqlValue($"update p_bomImportExecTab set success = 1 where guid = '{execGuid}'");
BaseImpl.ExecSqlValue($"update bom_bgRwTab set ComID = 1 where productid = '{productid}'");
List sqlParamList = new List();
sqlParamList.Add(new SqlParameter("@copyFileId", SqlDbType.Int) { Value = copyFileId });
sqlParamList.Add(new SqlParameter("@copyToModule", SqlDbType.VarChar, 100) { Value = "1000202" });
if (fileCode.StartsWith("MX"))
{
sqlParamList.Add(new SqlParameter("@copyToIdValue", SqlDbType.VarChar, 100) { Value = topProductId });
}
else
{
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, false);
BaseImpl.ExecSqlValue(afterSql);
BaseImpl.ExecSqlValue($"update p_bomImportExecTab set success = 1 where guid = '{execGuid}'");
BaseImpl.ExecSqlValue($"update bom_bgRwTab set ComID = 1 where productid = '{productid}'");
List sqlParamList = new List();
sqlParamList.Add(new SqlParameter("@copyFileId", SqlDbType.Int) { Value = copyFileId });
sqlParamList.Add(new SqlParameter("@copyToModule", SqlDbType.VarChar, 100) { Value = "1000202" });
if (fileCode.StartsWith("MX"))
{
sqlParamList.Add(new SqlParameter("@copyToIdValue", SqlDbType.VarChar, 100) { Value = topProductId });
}
else
{
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.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.OK;
}));
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.Cancel;
}));
}
finally
{
this.Invoke(new Action(() =>
{
this.Close();
ImportTimer?.Dispose();
}));
}
});
task.Start();
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}));
}
}
///
/// 结构上传终审同步
///
///
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}' and (isnull(qms_maddf_addMode,'0') = '0' or isnull(qms_maddf_addMode,'0') = '2')") + "";
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}'");
}
}
BaseImpl.ExecSqlValue($"update p_fm_filetab set isdisabled = 0 where fileid = '{fileId}'");
SetProcessBar(100, finishCount);
SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{sourceTable.Rows.Count + 1}");
}
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.OK;
}));
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.Cancel;
}));
}
finally
{
this.Invoke(new Action(() =>
{
this.Close();
ImportTimer?.Dispose();
}));
}
});
task.Start();
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}));
}
}
///
/// 结构补充终审同步
///
///
public void StartCreateBomAdd(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}' and isnull(qms_maddf_addMode,'0') = '1'") + "";
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}'");
}
}
BaseImpl.ExecSqlValue($"update p_fm_filetab set isdisabled = 0 where fileid = '{fileId}'");
SetProcessBar(100, finishCount);
SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{sourceTable.Rows.Count + 1}");
}
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.OK;
}));
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.Cancel;
}));
}
finally
{
this.Invoke(new Action(() =>
{
this.Close();
ImportTimer?.Dispose();
}));
}
});
task.Start();
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.Invoke(new Action(() =>
{
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}));
}
}
public int ProductSaveUnique(string spec, string appellation, string bak, string billSeq, out string productId, out string tipMsg)
{
productId = string.Empty;
tipMsg = string.Empty;
try
{
/*----------------------------------------------------
* 1) 组装存储过程参数
*--------------------------------------------------*/
// ProductId OUTPUT
SqlParameter pProductId = new SqlParameter("@ProductId", SqlDbType.VarChar, 100)
{
Direction = ParameterDirection.Output
};
// 存储过程 RETURN 值
SqlParameter pReturn = new SqlParameter("@return", SqlDbType.Int)
{
Direction = ParameterDirection.ReturnValue
};
// 中文字段可根据服务器排序规则切换参数类型
bool useNVar = ERPInfo.Instance.ChangeParameterType;
SqlParameter[] param =
{
new SqlParameter("@Spec", SqlDbType.VarChar, 50),
useNVar
? new SqlParameter("@Appellation", SqlDbType.NVarChar, 200)
: new SqlParameter("@Appellation", SqlDbType.VarChar, 200),
useNVar
? new SqlParameter("@Bak", SqlDbType.NVarChar, 200)
: new SqlParameter("@Bak", SqlDbType.VarChar, 200),
new SqlParameter("@BillSeq", SqlDbType.VarChar, 40),
pProductId,
pReturn
};
param[0].Value = spec;
param[1].Value = appellation ?? string.Empty;
param[2].Value = bak ?? string.Empty;
param[3].Value = string.IsNullOrWhiteSpace(billSeq) ? (object)DBNull.Value : billSeq;
SqlHelper.ExecuteNonQuery(
CommandType.StoredProcedure,
"sp_InsertProductUnique",
param);
/*----------------------------------------------------
* 3) 处理返回值与提示信息
*--------------------------------------------------*/
productId = pProductId.Value == DBNull.Value ? string.Empty
: pProductId.Value.ToString();
int retCode = (pReturn.Value == DBNull.Value) ? -1
: Convert.ToInt32(pReturn.Value);
// 根据返回值给出业务提示
switch (retCode)
{
case 0:
tipMsg = "保存成功!";
break;
case 1:
tipMsg = "规格已存在,直接返回现有编码。";
break;
default:
tipMsg = "发生异常,请查看日志!";
break;
}
return retCode;
}
catch (Exception ex)
{
tipMsg = ex.Message;
throw; // 继续向外抛,让调用层捕获日志
}
}
///
/// 显示当前文件
///
///
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;
}));
}
///
/// 显示当前进度
///
///
///
private void SetProcessBar(int current, int total)
{
this.Invoke(new Action(() =>
{
this.progressBarCurrent.Value = current;
this.progressBarTotal.Value = total;
}));
}
///
/// 获取表格数据
///
///
///
///
///
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 || row.ZeroHeight)
{
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 (dataRow.Table.Columns.Count - 1 < dataRowIndex)
{
break;
}
if (cell != null && cell.IsMergedCell)
{
CellRangeAddress mergrRange = FindMergedRegion(sheet, i, j);
if (j == mergrRange.FirstColumn)
{
dataRow[dataRowIndex] = GetCellValue(row.GetCell(j));
dataRowIndex += 1;
}
else
{
cellCount += 1;
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));
}
}
///
/// 获取单元格值
///
///
///
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;
}
///
/// 获取合并区域
///
///
///
///
///
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; // 未找到合并区域
}
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;
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}&confirm=1";
postUrl = "{0}Api/FileUploadApi.ashx?moduleId={1}&idValue={2}&speciesno={8}&folder={3}&totsize={4}&position={5}&filename={6}&uname=false&method={7}&comfirm={9}&relPath=&encode={10}&gzip=true&uploadToken={11}&__tsp={12}";
if (!string.IsNullOrEmpty(idValue))
{
string token = "";
string loginUrl = $"{SystemInfo.Instance.OAUrl}/Api/SysUserAjaxApi.ashx";
HttpHelper.Setting("application/x-www-form-urlencoded", null, null, HttpHelper.Encode.UTF8);
Dictionary loginPmsDic = new Dictionary();
loginPmsDic.Add("method", "Login");
loginPmsDic.Add("username", System.Web.HttpUtility.UrlEncode(ERPInfo.Instance.UserName));
loginPmsDic.Add("password", System.Web.HttpUtility.UrlEncode(ERPInfo.Instance.InPassWord));
HttpWebResponse loginResponse = HttpHelper.Post(loginUrl, "", loginPmsDic, null, out string loginResult);
try
{
if (loginResponse != null && !string.IsNullOrEmpty(loginResult))
{
JObject jObject = JsonConvert.DeserializeObject(loginResult);
if (jObject.ContainsKey("success"))
{
if ((jObject["success"] + "").Equals("True"))
{
if (jObject.ContainsKey("token"))
{
token = jObject["token"] + "";
}
}
}
}
}
finally
{
loginResponse?.Close();
}
if (!string.IsNullOrEmpty(token))
{
long totalSize = fileInfo.Length;
// Web 前端上传器同样提示:经过防火墙的环境需要将分片
// 从 1MB 降到约 0.3MB。所有文件统一使用安全分片,兼容
// 内网网关、透明代理及防火墙对 multipart 请求体的限制。
int pageSize = 320 * 1024;
long position = 0;
int confirm = 1;
int encode = 4;
int failNum = 0;
bool hasFail = false;
string uploadToken = Guid.NewGuid().ToString("N").Substring(0, 24);
string uploadFileName = name;
string uploadMethod = "DoWebUploadSafe";
Dictionary headerDic = new Dictionary();
headerDic.Add("Authorization", $"Bearer {token}");
using (FileStream fs = new FileStream(File, FileMode.Open, FileAccess.Read))
{
while (position < totalSize)
{
int readSize = (int)Math.Min(pageSize, totalSize - position);
byte[] buffer = new byte[readSize];
int realRead = fs.Read(buffer, 0, readSize);
if (realRead <= 0)
{
break;
}
if (realRead != readSize)
{
byte[] tempBytes = new byte[realRead];
Array.Copy(buffer, tempBytes, realRead);
buffer = tempBytes;
readSize = realRead;
}
long tsp = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
string uploadUrl = string.Format(
postUrl,
SystemInfo.Instance.OAUrl,
"1000202-1",
System.Web.HttpUtility.UrlEncode(idValue),
"file",
totalSize,
position,
System.Web.HttpUtility.UrlEncode(uploadFileName),
uploadMethod,
System.Web.HttpUtility.UrlEncode(speciesno),
confirm,
encode,
uploadToken,
tsp
);
string result = "";
HttpWebResponse webResponse = HttpHelper.PostFileChunk(uploadUrl, buffer, uploadFileName, headerDic, out result);
bool hasResponse = webResponse != null;
webResponse?.Close();
if (hasResponse && !string.IsNullOrEmpty(result))
{
JObject jsonObject = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result);
string isSuccess = jsonObject["success"] + "";
if (isSuccess.Equals("True", StringComparison.CurrentCultureIgnoreCase))
{
failNum = 0;
if (jsonObject.ContainsKey("data") && jsonObject["data"] != null && jsonObject["data"].Type == JTokenType.Object)
{
JObject dataObject = (JObject)jsonObject["data"];
if (dataObject.ContainsKey("FileName"))
{
uploadFileName = dataObject["FileName"] + "";
}
}
if (jsonObject.ContainsKey("other"))
{
fileId = jsonObject["other"] + "";
}
position += readSize;
}
else
{
string dataCode = jsonObject.ContainsKey("data") ? jsonObject["data"] + "" : "";
if (dataCode.Equals("9") && confirm == 0)
{
confirm = 1;
fs.Position = position;
continue;
}
if (jsonObject.ContainsKey("msg"))
{
returnMsg = jsonObject["msg"] + "";
}
if (dataCode.Equals("-1"))
{
if (string.IsNullOrEmpty(returnMsg))
{
returnMsg = "上传失败,服务器未接收当前分片";
}
hasFail = true;
isUpload = false;
break;
}
failNum++;
if (failNum < 2 && returnMsg.IndexOf("权限") < 0 && returnMsg.IndexOf("禁止") < 0)
{
fs.Position = position;
continue;
}
hasFail = true;
isUpload = false;
break;
}
}
else
{
long chunkIndex = position / pageSize + 1;
long chunkCount = (totalSize + pageSize - 1) / pageSize;
returnMsg = $"上传请求失败(分片{chunkIndex}/{chunkCount},位置{position},分片大小{pageSize / 1024}KB),{result}";
hasFail = true;
isUpload = false;
break;
}
}
}
if (!hasFail && position >= totalSize)
{
isUpload = true;
if (!string.IsNullOrEmpty(fileId))
{
BaseImpl.ExecSqlValue($"update p_fm_filetab set isdisabled = 2 where fileid = '{fileId}'");
}
}
}
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;
}
///
/// 记录附件变更数据
///
///
///
public string BuildBomFileTabSql(DataTable dt, string billno)
{
if (dt == null || dt.Rows.Count == 0) return string.Empty;
var sb = new StringBuilder();
sb.AppendLine("BEGIN TRANSACTION;");
foreach (DataRow row in dt.Rows)
{
int fileId = Convert.ToInt32(row["文件ID"]);
string fileName = row["附件名称"].ToString().Replace("'", "''");// 单引号转义
string speciesNo = row["目录ID"].ToString().Replace("'", "''");// → speciesno
string dirName = row["目录名称"].ToString().Trim();// → pid
int pid = 0;
int.TryParse(dirName, out pid); //目录名称若为数字则转换,否则默认为 0
sb.AppendFormat(
@"IF NOT EXISTS (
SELECT 1 FROM bom_filetab
WHERE fileid = {0}
AND speciesno = '{1}'
AND pid = {2})
INSERT INTO bom_filetab (billno, fileid, filename, speciesno, pid)
VALUES ('{4}',{0}, N'{3}', '{1}', {2});
", fileId, speciesNo, pid, fileName, billno);
}
sb.AppendLine("COMMIT TRANSACTION;");
return sb.ToString();
}
///
/// 附件转换byte[]
///
/// 附件路径
/// 二进制
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;
}
///
/// 解析code信息
///
///
///
///
///
///
private void GetFileCodeInfo(string sourceCode, out string code, out string name, out string bb, out int bc, bool withoutExtension)
{
string namepattern = @"^(.*-S[A-Z]\d*)(.*)$";
string pattern = @"^(.*?)(\d+)?$";
string childcode = "";
string childname = "";
string childsourceCode = "";
string childsourceBB = "";
int childsourceBC = 0;
Match namematch;
if (withoutExtension)
{
namematch = Regex.Match(sourceCode.Trim(), namepattern);
}
else
{
namematch = Regex.Match(Path.GetFileNameWithoutExtension(sourceCode).Trim(), namepattern);
}
if (namematch.Success)
{
childcode = namematch.Groups[1].Value.Trim();
childname = namematch.Groups[2].Value.Trim();
}
Match match = Regex.Match(childcode, pattern);
if (match.Success)
{
childsourceCode = match.Groups[1].Value;
int.TryParse(match.Groups[2].Value, out childsourceBC);//版次
Match bbMatch = Regex.Match(childsourceCode, @"^.*?([A-Za-z]+)(\d*)$");
if (bbMatch.Success)
{
childsourceBB = bbMatch.Groups[1].Value.Trim();
}
}
code = childsourceCode;
name = childname;
bb = childsourceBB;
bc = childsourceBC;
}
///
/// 解析code信息
///
///
///
///
///
///
private bool GetOtherFileCodeInfo(string fileName, out string code, out string spec, out string name, out string extension, out string bb, out int bc)
{
string namepattern = @"^(\S+)\s+(\S*-S[A-Z][0-9]*)\s+(.+)(\.[^.]+)$";
string pattern = @"^(.*?)(\d+)?$";
var match = Regex.Match(fileName, namepattern);
code = "";
spec = "";
name = "";
extension = "";
bb = "";
bc = 0;
if (match.Success)
{
code = match.Groups[1].Value.Trim();
spec = match.Groups[2].Value.Trim();
name = match.Groups[3].Value.Trim();
extension = match.Groups[4].Value.Trim();
match = Regex.Match(spec, pattern);
if (match.Success)
{
string childsourceCode = match.Groups[1].Value;
int.TryParse(match.Groups[2].Value, out bc);//版次
Match bbMatch = Regex.Match(childsourceCode, @"^.*?([A-Za-z]+)(\d*)$");
if (bbMatch.Success)
{
bb = bbMatch.Groups[1].Value.Trim();
}
}
return true;
}
else
{
return false;
}
}
private void CopyZZQDToCopy(string topProductId)
{
string zzqdCode = SqlHelper.ExecuteScalar($" SELECT bak FROM bom_BillListTab WHERE Billdocument_Id = (select top 1 billdocument_id from bom_BillTab where productid = '{topProductId}') and bak like 'ZZQD%';") + "";
DataTable copyTable = SqlHelper.ExecuteDataTable($"select top 1 billdocument_id from bom_billTab_copy where productid = '{zzqdCode}'");
if ((copyTable != null && copyTable.Rows.Count > 0) || string.IsNullOrEmpty(zzqdCode))
{
return;
}
string sql = $@"INSERT INTO bom_billTab_copy
(
ProductId, Builder, Auditor, Operatedate, Remark, TechnicsCode, TechnicsName, ProductPeriod,
Stuff_cost, Worker_cost, Billdocument_Id, stepOverName, stepOverId, stepOverTime, stepOver, endTime,
stepTime, happenTime, stepDirection, nextStepCode, stepCode, billType, Rtagid, OperatorId, Affirmer,
AffirmDate, ban, bom_appellation, bom_spec, bom_model, bom_ProductDescrip, waste_flag, waste_time,
waste_oper, pStepCode, printCount, printLastTime, printLastOper, previewCount, previewLastTime,
previewLastOper, cancelFlag, cancelTime, cancelOper, wasteoper, wastetime, enableflag, mappellation,
mspec, mmodel, clientid, BillModuleID, taoshu, Productunitname, productidbak, yfitemname, JYBJ,
str2, lskjimport_errorFlag, version, xn_tig, bak, bombb, bombc
)
SELECT top 1
'{zzqdCode}', Builder, Auditor, Operatedate, Remark, TechnicsCode, TechnicsName, ProductPeriod,
Stuff_cost, Worker_cost, Billdocument_Id, stepOverName, stepOverId, stepOverTime, stepOver, endTime,
stepTime, happenTime, stepDirection, nextStepCode, stepCode, billType, Rtagid, OperatorId, Affirmer,
AffirmDate, ban, bom_appellation, bom_spec, bom_model, bom_ProductDescrip, waste_flag, waste_time,
waste_oper, pStepCode, printCount, printLastTime, printLastOper, previewCount, previewLastTime,
previewLastOper, cancelFlag, cancelTime, cancelOper, wasteoper, wastetime, enableflag, mappellation,
mspec, mmodel, clientid, BillModuleID, taoshu, Productunitname, productidbak, yfitemname, JYBJ,
str2, lskjimport_errorFlag, version, xn_tig, bak, bombb, bombc
FROM bom_billTab where productid = '{topProductId}';
INSERT INTO bom_BillListTab_copy
(
ProductId, Famount, Amount, ParentProduct, amountx, ProcedureID, WorkingProcedure, Bak, Ver,
SoureMode, SoureObj, autoPick, Billdocument_Id, custom_ProductDescrip, bomFlag, encapsulation, serialnumber,
lsidx_id, workorderid, providerid, mx_ProductId, amountLoss, ProductSx, lstr1, lstr2, productidbak,
cltype, parentbillno, lskjimport_errorFlag, clProductId, bom_workordername, bom_workordernameTm, isbcp,
tamount, xn_tig, historyVer, bombb, bombc
)
SELECT
ProductId, Famount, Amount, '{zzqdCode}', amountx, ProcedureID, WorkingProcedure, Bak, Ver,
SoureMode, SoureObj, autoPick, Billdocument_Id, custom_ProductDescrip, bomFlag, encapsulation, serialnumber,
lsidx_id, workorderid, providerid, mx_ProductId, amountLoss, ProductSx, lstr1, lstr2, productidbak,
cltype, parentbillno, lskjimport_errorFlag, clProductId, bom_workordername, bom_workordernameTm, isbcp,
tamount, xn_tig, historyVer, bombb, bombc
FROM bom_BillListTab WHERE Billdocument_Id = (select top 1 billdocument_id from bom_BillTab where productid = '{topProductId}') and bak like 'ZZQD%';";
SqlHelper.ExecuteNonQuery(sql);
}
}
}