DeviceManager/TsSFCDevice.Client.Launch/Maintain/pageMaintainView.cs
2024-11-09 12:25:57 +08:00

1171 lines
48 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using DevExpress.XtraBars.ToolbarForm;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DeviceRepair.Models;
using DeviceRepair.Models.Common;
using DeviceRepair.Models.DeviceRepair.ExportView;
using DeviceRepair.Utils;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using TsSFCDevice.Client.Biz.Base.Utils;
using TsSFCDevice.Client.Biz.Impl;
namespace TsSFCDevice.Client.Launch.Maintain
{
public partial class pageMaintainView : ToolbarForm
{
/// <summary>
/// 设备编号
/// </summary>
string Filter_DeviceID
{
get { return txt_DeviceID.EditValue.ToString().Trim(); }
}
DeviceWarrantyRequestFormFilter _filter;
DeviceWarrantyRequestFormFilter FilterInfo
{
get
{
if (_filter == null)
_filter = new DeviceWarrantyRequestFormFilter();
_filter.EquipmentID = EquipmentID;
if (Filter_Start_Date == DateTime.MinValue)
de_StartDate.EditValue = DateTime.Today.AddMonths(-1);
_filter.StartTime = Filter_Start_Date;
if (Filter_End_Date == DateTime.MinValue)
de_EndDate.EditValue = DateTime.Today.AddDays(1).AddMilliseconds(-1);
_filter.EndTime = Filter_End_Date.AddDays(1).AddMilliseconds(-1);
_filter.Status = Filter_Status;
_filter.DownStatus = Filter_DownStatus;
return _filter;
}
}
string EquipmentID
{
get { return txt_DeviceID.Text.Trim(); }
}
/// <summary>
/// 设备状态
/// </summary>
DeviceWarrantyRequestFormStatus Filter_Status
{
get { return (DeviceWarrantyRequestFormStatus)((int)(cb_Status.EditValue)); }
}
/// <summary>
/// 设备停机状态
/// </summary>
DeviceRunningStatus Filter_DownStatus
{
get { return (DeviceRunningStatus)cbbIsDown.SelectedIndex; }
}
/// <summary>
/// 开始时间
/// </summary>
DateTime Filter_Start_Date
{
get { return Convert.ToDateTime(de_StartDate.EditValue); }
}
/// <summary>
/// 结束时间
/// </summary>
DateTime Filter_End_Date
{
get { return Convert.ToDateTime(de_EndDate.EditValue); }
}
List<LookUpItemModel> lookupMaintenanceStatus;
int m_SelectedCurrentRowIndex = 0;
DeviceWarrantyRequestFormView CurrentObjectInfo = null;
Dictionary<int, string> _UserMapping;
Dictionary<int, string> UserMapping
{
get
{
if (_UserMapping == null)
{
try
{
_UserMapping = Utility.SystemRuntimeInfo.CurrentUsersCaches?.ToList().ToDictionary(x => x.Id, x => x.UserName);
}
catch (Exception ex)
{
XtraMessageBoxHelper.Error(ex.Message);
}
}
return _UserMapping;
}
}
public pageMaintainView()
{
InitializeComponent();
this.Load += PageMaintainView_Load;
}
/// <summary>
/// 程序加载
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PageMaintainView_Load(object sender, EventArgs e)
{
//ToDescription
if (lookupMaintenanceStatus == null)
lookupMaintenanceStatus = new List<LookUpItemModel>();
foreach (DeviceWarrantyRequestFormStatus item in Enum.GetValues(typeof(DeviceWarrantyRequestFormStatus)))
{
lookupMaintenanceStatus.Add(new LookUpItemModel
{
ValueMember = (int)item,
DisplayMember = item.ToDescription()
});
}
cbbIsDown.Properties.Items.BeginUpdate();
foreach (DeviceRunningStatus item in Enum.GetValues(typeof(DeviceRunningStatus)))
{
cbbIsDown.Properties.Items.Add(item.ToDescription());
}
cbbIsDown.Properties.Items.EndUpdate();
cbbIsDown.SelectedIndex = 0;
// 设置显示成员和值成员
layoutControlGroup4.ViewInfo.OwnerILayoutControl.AllowCustomizationMenu = false;
Root.ViewInfo.OwnerILayoutControl.AllowCustomizationMenu = false;
GridViewInitialize(gridView1);
cb_Status.Properties.DataSource = lookupMaintenanceStatus;
cb_Status.Properties.DisplayMember = "DisplayMember";
cb_Status.Properties.ValueMember = "ValueMember";
cb_Status.Properties.BestFitMode = DevExpress.XtraEditors.Controls.BestFitMode.BestFitResizePopup;
cb_Status.EditValue = (int)DeviceWarrantyRequestFormStatus.All;
de_StartDate.EditValue = DateTime.Today.AddMonths(-1);
de_EndDate.EditValue = DateTime.Today;
}
List<DeviceWarrantyRequestFormView> DataSource;
/// <summary>
/// 数据加载
/// </summary>
void LoadingGridviewDatas()
{
try
{
splashScreenManager1.ShowWaitForm();
DataSource = MaintenanceRepository.Instance.GetDatas(FilterInfo)?.ToList();
foreach (DeviceWarrantyRequestFormView item in DataSource)
{
if (string.IsNullOrWhiteSpace(item.CreatorName))
{
item.CreatorName = UserMapping.ContainsKey(item.CreatBy.Value) ? UserMapping[item.CreatBy.Value] : "";
}
}
SizeF size = this.CreateGraphics().MeasureString((DataSource.Count).ToString(), gridView1.Appearance.ViewCaption.Font);
gridView1.IndicatorWidth = Convert.ToInt32(size.Width) + 25;
gridControl1.DataSource = null;
gridControl1.DataSource = DataSource.ToDataTable();
//gridView1.BestFitColumns();
splashScreenManager1.TryCloseWait();
}
catch (Exception ex)
{
gridControl1.DataSource = null;
splashScreenManager1.TryCloseWait();
XtraMessageBoxHelper.Error(ex.Message);
}
}
/// <summary>
/// 行选择模式,且全部只读
/// </summary>
/// <param name="view"></param>
void GridViewInitialize(GridView view)
{
gridView1.OptionsMenu.EnableColumnMenu = false;
view.OptionsSelection.EnableAppearanceFocusedCell = false;
view.OptionsScrollAnnotations.ShowSelectedRows = DevExpress.Utils.DefaultBoolean.False;
foreach (DevExpress.XtraGrid.Columns.GridColumn item in view.Columns)
{
item.OptionsColumn.AllowEdit = false;
item.OptionsColumn.AllowGroup = DevExpress.Utils.DefaultBoolean.True;
item.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
item.OptionsColumn.AllowShowHide = false;
}
view.BestFitColumns();
}
/// <summary>
/// 表格行号
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void gridView1_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
{
if (e.Info.IsRowIndicator && e.RowHandle >= 0)
{
e.Info.DisplayText = (e.RowHandle + 1).ToString();
e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
e.Appearance.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center;
SizeF size = e.Graphics.MeasureString((e.RowHandle + 1).ToString(), e.Appearance.Font);
}
}
/// <summary>
/// 多选框标题修改
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void gridView1_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e)
{
if (e.Column != null && (e.Column.Caption == "Selection" || e.Column.FieldName == "DX$CheckboxSelectorColumn"))
{
e.Info.Caption = "选择";
e.Appearance.Font = new System.Drawing.Font("Tahoma", 12F);
}
}
/// <summary>
/// 单元格点击
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void gridView1_RowCellClick(object sender, RowCellClickEventArgs e)
{
}
/// <summary>
/// 选择行改变
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
{
bool WaitIsShowBefore = splashScreenManager1.IsSplashFormVisible;
try
{
if (!WaitIsShowBefore)
splashScreenManager1.ShowWaitForm();
if (e.FocusedRowHandle >= 0)
{
m_SelectedCurrentRowIndex = e.FocusedRowHandle;
DataRowView drv = gridView1.GetRow(e.FocusedRowHandle) as DataRowView;
string AutoID = drv.Row["AutoID"]?.ToString();
int intAutoID = 0;
if (!int.TryParse(AutoID, out intAutoID) && intAutoID <= 0)
{
throw new Exception("获取行数据出错,请重试!");
}
CurrentObjectInfo = DataSource.FirstOrDefault(x => x.AutoID == intAutoID);
if (CurrentObjectInfo == null)
{
throw new Exception("获取行数据出错,请重试!");
}
btn_Maintain.Enabled = CurrentObjectInfo.MaintaionItems == null || CurrentObjectInfo.MaintaionItems.SubmitBy == 0 ? true : false;
btn_ChangeDownStatus.Enabled = CurrentObjectInfo.MaintaionItems == null || CurrentObjectInfo.MaintaionItems?.SubmitBy == 0 ? true : false;
// 双重确认
btn_Validate.Enabled = false;
if (CurrentObjectInfo.MaintaionItems != null && CurrentObjectInfo.MaintaionItems.SubmitBy > 0)
{
// 技术人员确认
if ((Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.Device_REPAIRRECORD_Echnician) || Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.Device_REPAIRRECORD_Engineer)) && CurrentObjectInfo.MaintaionItems.ValidateBy == 0)
{
btn_Validate.Enabled = true;
btn_Validate.Tag = "1";
}
else if (CurrentObjectInfo.MaintaionItems.ValidateBy > 0 && CurrentObjectInfo.MaintaionItems.ValidateBy != Utility.SystemRuntimeInfo.CurrentUser.Id && (Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.Device_REPAIRRECORD_Engineer) || Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.Device_REPAIRRECORD_Manager)))
{
if (CurrentObjectInfo.MaintaionItems.Validate2By == 0)
{
btn_Validate.Enabled = true;
btn_Validate.Tag = "2";
}
}
}
barBtn_Print.Enabled = CurrentObjectInfo.RestorationConfirmationBy > 0;
barBtn_ExportPdf.Enabled = CurrentObjectInfo.RestorationConfirmationBy > 0;
barBtn_Print.Refresh();
barBtn_ExportPdf.Refresh();
#region
ucMaintenance view = new ucMaintenance(CurrentObjectInfo);
if (CurrentObjectInfo.MaintaionItems != null)
{
IList<DeviceWarrantyRequestAccessoriesInfo> Accs = MaintenanceRepository.Instance.GetFormAccessories(CurrentObjectInfo.MaintaionItems.AutoID);
CurrentObjectInfo.MaintaionItems.AccessoriesItems = Accs?.ToList();
}
this.splitContainerControl1.Panel2.Controls.Clear();
this.splitContainerControl1.Panel2.Controls.Add(view);
view.Show();
this.splitContainerControl1.Panel2.Refresh();
#endregion
#region
this.gridView1.SelectRow(e.FocusedRowHandle);
#endregion
}
else
{
CurrentObjectInfo = null;
}
if (!WaitIsShowBefore)
splashScreenManager1.CloseWaitForm();
}
catch (Exception ex)
{
if (!WaitIsShowBefore)
splashScreenManager1.CloseWaitForm();
//gridView1.FocusedRowChanged += gridView1_FocusedRowChanged;
XtraMessageBoxHelper.Error(ex.Message);
}
}
private void gridView1_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
{
GridView view = sender as GridView;
view.BeginSelection();
if (e.Action == CollectionChangeAction.Add && view.GetSelectedRows().Length > 1)
view.ClearSelection();
if (e.Action == CollectionChangeAction.Refresh)
view.SelectRow(view.FocusedRowHandle);
if (e.Action == CollectionChangeAction.Remove & view.GetSelectedRows().Length == 0)
view.SelectRow(view.FocusedRowHandle);
//
view.EndSelection();
}
/// <summary>
/// 查询数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_Query_Click(object sender, EventArgs e)
{
if (!Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.Device_REPAIRRECORD_Watch))
{
XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
return;
}
LoadingGridviewDatas();
}
private void splitContainerControl1_SplitterMoved(object sender, EventArgs e)
{
this.splitContainerControl1.Panel2.Refresh();
this.splitContainerControl1.Panel1.Refresh();
}
private void pageMaintainView_SizeChanged(object sender, EventArgs e)
{
this.Refresh();
}
/// <summary>
/// 维修
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_Maintain_Click(object sender, EventArgs e)
{
try
{
if (!Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.Device_REPAIRRECORD_Edit))
{
XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
return;
}
if (CurrentObjectInfo == null)
{
throw new Exception($"请选择要维修的停机单!");
}
using (pageMaintainEdit view = new pageMaintainEdit(CurrentObjectInfo))
{
if (view.ShowDialog(this) == DialogResult.OK)
{
XtraMessageBoxHelper.Info("操作成功!");
}
LoadingGridviewDatas();
}
}
catch (Exception ex)
{
XtraMessageBoxHelper.Error(ex.Message);
}
}
/// <summary>
/// 双重恢复验证
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_Validate_Click(object sender, EventArgs e)
{
try
{
if (!Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.Device_REPAIRRECORD_Engineer) && !Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.Device_REPAIRRECORD_Echnician) && !Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.Device_REPAIRRECORD_Manager))
{
XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
return;
}
if (CurrentObjectInfo == null)
{
throw new Exception($"请选择要操作的停机单!");
}
if (XtraMessageBoxHelper.Ask($"是否确认当前设备已恢复!") == DialogResult.OK)
{
int t = 0;
if (!int.TryParse(btn_Validate.Tag + "", out t) && (t != 1 && t != 2))
{
throw new Exception($"当前操作员类型获取出错,请重试!");
}
APIResponseData apiResponseData = MaintenanceRepository.Instance.ValidateMaintenance(CurrentObjectInfo.AutoID, t);
if (!apiResponseData.IsSuccess)
throw new Exception(apiResponseData.Message);
XtraMessageBoxHelper.Info("操作成功!");
LoadingGridviewDatas();
}
}
catch (Exception ex)
{
XtraMessageBoxHelper.Error(ex.Message);
}
}
/// <summary>
/// 修改停机状态
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_ChangeDownStatus_Click(object sender, EventArgs e)
{
try
{
if (!Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.Device_REPAIRRECORD_Edit))
{
XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
return;
}
if (CurrentObjectInfo == null)
{
throw new Exception($"请选择要维修的停机单!");
}
if (XtraMessageBoxHelper.Ask($"是否确认将维修单:<color=red>{CurrentObjectInfo.AutoID}</color>的停机状态修改为:<color=blue>{(CurrentObjectInfo.IsDown ? "" : "")}</color>状态!") == DialogResult.OK)
{
APIResponseData apiResponseData = MaintenanceRepository.Instance.Update_Maintenance_Status(CurrentObjectInfo.AutoID, !CurrentObjectInfo.IsDown);
if (!apiResponseData.IsSuccess)
throw new Exception(apiResponseData.Message);
XtraMessageBoxHelper.Info("操作成功!");
LoadingGridviewDatas();
}
}
catch (Exception ex)
{
XtraMessageBoxHelper.Error(ex.Message);
}
}
/// <summary>
/// 打印
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void simpleButton1_Click(object sender, EventArgs e)
{
try
{
if (CurrentObjectInfo == null)
{
throw new Exception("获取对象失败,请重试!");
}
DataTable table = SubassembliesCurrentData();
FastReport.Report report = new FastReport.Report();
var vLabelDir = System.IO.Path.Combine(Application.StartupPath, "Labels");
//判断文件夹是否存在
if (!System.IO.Directory.Exists(vLabelDir))
{
throw new Exception("缺少待打印的标签模板目录!");
}
//路径拼接模板文件名
var vFileName = System.IO.Path.Combine(vLabelDir, "DeviceMaintenance.frx");
//判断模板文件是否存在
if (!System.IO.File.Exists(vFileName))
{
throw new Exception("缺少待打印的标签模板文件!");
}
report.Load(vFileName);
report.DoublePass = true;
DataSet dsDatas = new DataSet();
dsDatas.Tables.Add(table);
report.RegisterData(dsDatas, "MaintenanceInfo");
//report.Design();
if (report.Prepare(true))
{
report.ShowPrepared();
}
report.Dispose();
}
catch (Exception ex)
{
XtraMessageBoxHelper.Error(ex.Message);
}
}
private DataTable SubassembliesCurrentData()
{
DataTable table = new DataTable("MaintenanceInfo");
table.Columns.Add("申请部门", typeof(string));
table.Columns.Add("名称", typeof(string));
table.Columns.Add("设备编号", typeof(string));
table.Columns.Add("接收部门", typeof(string));
table.Columns.Add("现象区分", typeof(string));
table.Columns.Add("故障发生地点", typeof(string));
table.Columns.Add("故障发生时间", typeof(string));
table.Columns.Add("维修方式", typeof(string));
table.Columns.Add("产品批号", typeof(string));
table.Columns.Add("修理开始日期", typeof(string));
table.Columns.Add("修理结束日期", typeof(string));
table.Columns.Add("质量部评估", typeof(string));
table.Columns.Add("工程部评估", typeof(string));
table.Columns.Add("总修复时间", typeof(string));
table.Columns.Add("总停机时间", typeof(string));
table.Columns.Add("故障现象", typeof(string));
table.Columns.Add("故障原因", typeof(string));
table.Columns.Add("维修内容", typeof(string));
table.Columns.Add("配件", typeof(string));
table.Columns.Add("人员", typeof(string));
table.Columns.Add("是否需要再验证", typeof(string));
table.Columns.Add("验证编号", typeof(string));
table.Columns.Add("设备恢复确认", typeof(string));
table.Columns.Add("申请部门确认/日期", typeof(string));
//string[] fieldCodes = new string[] { "SymptomlDistinction", "Maintenance", "Accessories" };
//IList<FieldsInfo> SelectionDatas = CustomFieldRepository.Instance.GetDatas(fieldCodes);
//Dictionary<int, FieldsInfo> keyValuePairs = SelectionDatas.ToDictionary(x => x.AutoID, x => x);
DataRow dr = table.NewRow();
dr["申请部门"] = $"生产部 - {CurrentObjectInfo.CreatorName}";
dr["名称"] = CurrentObjectInfo.EquipmentName;
dr["设备编号"] = CurrentObjectInfo.EquipmentID;
dr["接收部门"] = "设备实施部";
dr["现象区分"] = CurrentObjectInfo.MaintaionItems.SymptomlDistinctionText; //keyValuePairs.ContainsKey(CurrentObjectInfo.MaintaionItems.SymptomlDistinction) ? keyValuePairs[CurrentObjectInfo.MaintaionItems.SymptomlDistinction].FieldText : "";
dr["故障发生地点"] = CurrentObjectInfo.LocationName;
dr["故障发生时间"] = CurrentObjectInfo.CreatOn.Value.ToString("yyyy-MM-dd HH:mm:ss");
dr["维修方式"] = CurrentObjectInfo.MaintaionItems.MaintenanceText; //keyValuePairs.ContainsKey(CurrentObjectInfo.MaintaionItems.Maintenance) ? keyValuePairs[CurrentObjectInfo.MaintaionItems.Maintenance].FieldText : "";
dr["产品批号"] = CurrentObjectInfo.InProduction ? $@"Yes, Product Lot/Testing Order产品批号/检测任务号{Environment.NewLine}{CurrentObjectInfo.Batch}" : "No";
dr["修理开始日期"] = CurrentObjectInfo.MaintaionItems.MaintainStartTime.ToString("yyyy-MM-dd HH:mm:ss");
dr["修理结束日期"] = CurrentObjectInfo.MaintaionItems.MaintainEndTime.ToString("yyyy-MM-dd HH:mm:ss");
if (CurrentObjectInfo.EvaluatorItems != null && CurrentObjectInfo.EvaluatorItems.Count > 0)
{
var PEItem = CurrentObjectInfo.EvaluatorItems.Where(x => x.EvaluatorCode == "PE").FirstOrDefault();
if (PEItem != null)
{
dr["质量部评估"] = $"{PEItem.Description} - {PEItem.CreatorName}";
}
var QEItem = CurrentObjectInfo.EvaluatorItems.Where(x => x.EvaluatorCode == "QE").FirstOrDefault();
if (QEItem != null)
{
dr["工程部评估"] = $"{QEItem.Description} - {QEItem.CreatorName}";
}
}
else
{
dr["质量部评估"] = "N/A";
dr["工程部评估"] = "N/A";
}
DateTime FormSubDate = CurrentObjectInfo.CreatOn.Value;
TimeSpan timeDifference = CurrentObjectInfo.MaintaionItems.MaintainEndTime - CurrentObjectInfo.MaintaionItems.MaintainStartTime;
dr["总修复时间"] = $"{timeDifference.Days}天/{(timeDifference.Hours)}小时/{(timeDifference.Minutes)}分钟/{timeDifference.Seconds}秒";
timeDifference = CurrentObjectInfo.MaintaionItems.MaintainEndTime - FormSubDate;
dr["总停机时间"] = $"{timeDifference.Days}天/{(timeDifference.Hours)}小时/{(timeDifference.Minutes)}分钟/{timeDifference.Seconds}秒";
dr["故障现象"] = CurrentObjectInfo.FaultSymptoms;
dr["故障原因"] = CurrentObjectInfo.MaintaionItems.MaintainCause;
dr["维修内容"] = CurrentObjectInfo.MaintaionItems.MaintainContent;
//配件
if (CurrentObjectInfo.MaintaionItems.AccessoriesItems != null && CurrentObjectInfo.MaintaionItems.AccessoriesItems.Count > 0)
{
System.Text.StringBuilder builder = new System.Text.StringBuilder();
foreach (DeviceWarrantyRequestAccessoriesInfo item in CurrentObjectInfo.MaintaionItems.AccessoriesItems)
{
builder.Append($"{item.FieldName} x {item.AccessoriesCount};");
}
dr["配件"] = builder.ToString();
}
dr["人员"] = UserMapping[CurrentObjectInfo.MaintaionItems.SubmitBy];
if (CurrentObjectInfo.MaintaionItems.BeValidate)
{
dr["是否需要再验证"] = $"Yes 需要Validation ID验证编号{CurrentObjectInfo.MaintaionItems.ValidateNo}";
}
else
{
dr["是否需要再验证"] = $"No 不需要, Rational理由{CurrentObjectInfo.MaintaionItems.Reason}";
}
dr["验证编号"] = "";
string doubleValidate = "";
if (CurrentObjectInfo.MaintaionItems.ValidateBy == 0)
{
doubleValidate = "N/A";
}
else
{
doubleValidate = $"{UserMapping[CurrentObjectInfo.MaintaionItems.ValidateBy]} / {CurrentObjectInfo.MaintaionItems.ValidateOn.ToString("yyyy-MM-dd HH:mm:ss")}";
if (CurrentObjectInfo.MaintaionItems.Validate2By == 0)
{
doubleValidate += " N/A";
}
else
{
doubleValidate += $" {UserMapping[CurrentObjectInfo.MaintaionItems.Validate2By]} / {CurrentObjectInfo.MaintaionItems.Validate2On.ToString("yyyy-MM-dd HH:mm:ss")}";
}
}
dr["设备恢复确认"] = doubleValidate;
dr["申请部门确认/日期"] = $"{CurrentObjectInfo.RestorationConfirmationOnName} / {CurrentObjectInfo.RestorationConfirmationOn.Value.ToString("yyyy-MM-dd HH:mm:ss")}";
table.Rows.Add(dr);
return table;
}
/// <summary>
/// 打印
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void barBtn_Print_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
this.barBtn_Print.Enabled = false;
try
{
if (CurrentObjectInfo == null)
{
barBtn_Print.Enabled = false;
barBtn_Print.Refresh();
throw new Exception("请选择要打印的维修单!");
}
var template = Utility.SystemRuntimeInfo.DeviceWarrantyFormVerCaches.FirstOrDefault(x => { return x.AutoID == CurrentObjectInfo.FormVer; });
if (template == null)
{
throw new Exception("没有获取到表单模板信息,请联系管理员!");
}
if (string.IsNullOrWhiteSpace(template.FormVerCode))
{
throw new Exception("表单模板信息中的表单编码为空,请联系管理员!");
}
if (string.IsNullOrWhiteSpace(template.FormVerName))
{
throw new Exception("表单模板信息中的表单名称为空,请联系管理员!");
}
if (string.IsNullOrWhiteSpace(template.PrintTemplateFileName))
{
throw new Exception("表单模板信息中的打印文件名为空,请联系管理员!");
}
DataTable table = SubassembliesCurrentData();
table.Columns.Add("表单版本名称", typeof(string));
table.Columns.Add("表单版本编码", typeof(string));
table.Rows[0]["表单版本名称"] = template.FormVerName;
table.Rows[0]["表单版本编码"] = template.FormVerCode;
FastReport.Report report = new FastReport.Report();
var vLabelDir = System.IO.Path.Combine(Application.StartupPath, "Labels");
//判断文件夹是否存在
if (!System.IO.Directory.Exists(vLabelDir))
{
throw new Exception("缺少待打印的标签模板目录!");
}
//路径拼接模板文件名
var vFileName = System.IO.Path.Combine(vLabelDir, template.PrintTemplateFileName);
//判断模板文件是否存在
if (!System.IO.File.Exists(vFileName))
{
throw new Exception("缺少待打印的标签模板文件!");
}
report.Load(vFileName);
report.DoublePass = true;
DataSet dsDatas = new DataSet();
dsDatas.Tables.Add(table);
report.RegisterData(dsDatas, "MaintenanceInfo");
//report.Design();
if (report.Prepare(true))
{
report.ShowPrepared();
}
report.Dispose();
}
catch (Exception ex)
{
XtraMessageBoxHelper.Error(ex.Message);
}
this.barBtn_Print.Enabled = true;
}
/// <summary>
/// 导出word
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void barBtn_ExportWord_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
try
{
if (CurrentObjectInfo == null)
{
barBtn_ExportWord.Enabled = false;
barBtn_ExportWord.Refresh();
throw new Exception("请选择要导出的维修单!");
}
using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
{
folderDialog.Description = "请选择保存文件的路径:";
folderDialog.ShowNewFolderButton = true;
DialogResult result = folderDialog.ShowDialog(this);
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(folderDialog.SelectedPath))
{
string selectedPath = folderDialog.SelectedPath;
DataTable table = SubassembliesCurrentData();
FastReport.Report report = new FastReport.Report();
var vLabelDir = Path.Combine(Application.StartupPath, "Labels");
//判断文件夹是否存在
if (!Directory.Exists(vLabelDir))
{
throw new Exception("缺少待打印的标签模板目录!");
}
//路径拼接模板文件名
var vFileName = Path.Combine(vLabelDir, "DeviceMaintenance.frx");
//判断模板文件是否存在
if (!File.Exists(vFileName))
{
throw new Exception("缺少待打印的标签模板文件!");
}
report.Load(vFileName);
report.DoublePass = true;
DataSet dsDatas = new DataSet();
dsDatas.Tables.Add(table);
report.RegisterData(dsDatas, "MaintenanceInfo");
string filePath = Path.Combine(selectedPath, ("维修单" + CurrentObjectInfo.AutoID + ".docx"));
if (report.Prepare())
{
FastReport.Export.OoXML.Word2007Export export = new FastReport.Export.OoXML.Word2007Export();
report.MaxPages = 1;
export.CurPage = 1;
report.Export(export, filePath);
}
report.Dispose();
XtraMessageBoxHelper.Info($"导出成功!");
}
}
}
catch (Exception ex)
{
XtraMessageBoxHelper.Error(ex.Message);
}
}
private void barBtnExcel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
try
{
splashScreenManager1.ShowWaitForm();
IList<MaintainOrderView> views = MaintenanceRepository.Instance.Get_Maintenance_Xlsx_Datas(FilterInfo); ;// MaintenanceManager.Instance.GetXlsxData(FilterInfo);
if (views == null || views.Count == 0)
{
throw new Exception("没有查询到数据!");
}
DataTable dataTable = views?.ToList()?.ToDataTable();
dataTable.TableName = "设备维修台账";
System.Reflection.PropertyInfo[] prop = typeof(MaintainOrderView).GetProperties();
foreach (System.Reflection.PropertyInfo item in prop)
{
if (dataTable.Columns.Contains(item.Name))
{
DataColumn dc = dataTable.Columns[item.Name];
object[] attrs = item.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (null != attrs && attrs.Length > 0)
{
DescriptionAttribute description = (DescriptionAttribute)attrs[0];
dc.ColumnName = description.Description;
}
}
}
splashScreenManager1.TryCloseWait();
XtraSaveFileDialog xofd = new XtraSaveFileDialog()
{
Filter = "xlsx file*.xlsx|*.xlsx"
};
SelectPath:
if (xofd.ShowDialog(this) == DialogResult.OK)
{
if (File.Exists(xofd.FileName))
{
XtraMessageBoxHelper.Error("当前文件已存在,请重新命名!");
goto SelectPath;
}
byte[] btRtn = Export(dataTable);
Common.dlgProgressBar view = new Common.dlgProgressBar(btRtn, xofd.FileName);
view.ShowDialog(this);
splashScreenManager1.TryCloseWait();
XtraMessageBoxHelper.Info("操作成功!");
}
}
catch (Exception ex)
{
splashScreenManager1.TryCloseWait();
XtraMessageBoxHelper.Error(ex.Message);
}
}
byte[] Export(DataTable dataTable)
{
try
{
IWorkbook workbook = new XSSFWorkbook();
string sheetName = string.IsNullOrEmpty(dataTable.TableName) ? "Sheet1" : dataTable.TableName;
ISheet sheet = workbook.CreateSheet(sheetName);
// 创建表头
IRow headerRow = sheet.CreateRow(0);
// 表头样式
#region
ICellStyle style = workbook.CreateCellStyle();
style.WrapText = true;//设置换行这个要先设置
style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;//居中
style.VerticalAlignment = VerticalAlignment.Center;//水平居中
//HSSFPalette palette = new HSSFPalette();
//palette.SetColorAtIndex((short)1, 217, 217, 217);
//var v1 = palette.FindColor(217, 217, 217);
//colorStyle.FillForegroundColor = v1.GetIndex();
style.FillPattern = FillPattern.SolidForeground;
style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
ICellStyle cellStyle = workbook.CreateCellStyle();
cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;//居中
cellStyle.VerticalAlignment = VerticalAlignment.Center;//水平居中
cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
////设置字体
//IFont font = workbook.CreateFont();
//font.FontHeightInPoints = 10;
//font.FontName = "黑体";
//style.SetFont(font);
#endregion
for (int i = 0; i < dataTable.Columns.Count; i++)
{
headerRow.CreateCell(i).SetCellValue(dataTable.Columns[i].ColumnName);
headerRow.GetCell(i).CellStyle = style;
headerRow.GetCell(i).CellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Medium;
headerRow.GetCell(i).CellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Medium;
headerRow.GetCell(i).CellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Medium;
headerRow.GetCell(i).CellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;
}
// 填充数据
for (int i = 0; i < dataTable.Rows.Count; i++)
{
IRow dataRow = sheet.CreateRow(i + 1);
for (int j = 0; j < dataTable.Columns.Count; j++)
{
dataRow.CreateCell(j).SetCellValue(dataTable.Rows[i][j].ToString());
ICellStyle styleContent = workbook.CreateCellStyle();
styleContent.CloneStyleFrom(cellStyle);
dataRow.GetCell(j).CellStyle = styleContent;
// 第一列
if (j == 0)
dataRow.GetCell(j).CellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Medium;
else if (j == dataTable.Columns.Count - 1)
{
// 最后一列
dataRow.GetCell(j).CellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Medium;
}
if (i == dataTable.Rows.Count - 1)
dataRow.GetCell(j).CellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;
}
}
for (int i = 0; i < dataTable.Columns.Count; i++)
{
sheet.AutoSizeColumn(i);
}
// 转换为byte[]
using (MemoryStream stream = new MemoryStream())
{
workbook.Write(stream);
return stream.ToArray();
}
}
catch (Exception ex)
{
throw new Exception($"生成EXCEL出错{ex.Message}");
}
}
private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
try
{
if (CurrentObjectInfo == null)
{
barBtn_ExportPdf.Enabled = false;
barBtn_ExportPdf.Refresh();
throw new Exception("请选择要导出的维修单!");
}
using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
{
folderDialog.Description = "请选择保存文件的路径:";
folderDialog.ShowNewFolderButton = true;
DialogResult result = folderDialog.ShowDialog(this);
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(folderDialog.SelectedPath))
{
string selectedPath = folderDialog.SelectedPath;
DataTable table = SubassembliesCurrentData();
FastReport.Report report = new FastReport.Report();
var vLabelDir = Path.Combine(Application.StartupPath, "Labels");
//判断文件夹是否存在
if (!Directory.Exists(vLabelDir))
{
throw new Exception("缺少待打印的标签模板目录!");
}
//路径拼接模板文件名
var vFileName = Path.Combine(vLabelDir, "DeviceMaintenance.frx");
//判断模板文件是否存在
if (!File.Exists(vFileName))
{
throw new Exception("缺少待打印的标签模板文件!");
}
report.Load(vFileName);
report.DoublePass = true;
DataSet dsDatas = new DataSet();
dsDatas.Tables.Add(table);
report.RegisterData(dsDatas, "MaintenanceInfo");
string filePath = Path.Combine(selectedPath, ("维修单" + CurrentObjectInfo.AutoID + ".docx"));
if (report.Prepare())
{
FastReport.Export.OoXML.Word2007Export export = new FastReport.Export.OoXML.Word2007Export();
report.MaxPages = 1;
export.CurPage = 1;
report.Export(export, filePath);
}
report.Dispose();
XtraMessageBoxHelper.Info($"导出成功!");
}
}
}
catch (Exception ex)
{
XtraMessageBoxHelper.Error(ex.Message);
}
}
private void barBtn_ExportPdf_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
try
{
if (CurrentObjectInfo == null)
{
barBtn_ExportPdf.Enabled = false;
barBtn_ExportPdf.Refresh();
throw new Exception("请选择要导出的维修单!");
}
var template = Utility.SystemRuntimeInfo.DeviceWarrantyFormVerCaches.FirstOrDefault(x => { return x.AutoID == CurrentObjectInfo.FormVer; });
if (template == null)
{
throw new Exception("没有获取到表单模板信息,请联系管理员!");
}
if (string.IsNullOrWhiteSpace(template.FormVerCode))
{
throw new Exception("表单模板信息中的表单编码为空,请联系管理员!");
}
if (string.IsNullOrWhiteSpace(template.FormVerName))
{
throw new Exception("表单模板信息中的表单名称为空,请联系管理员!");
}
if (string.IsNullOrWhiteSpace(template.PrintTemplateFileName))
{
throw new Exception("表单模板信息中的打印文件名为空,请联系管理员!");
}
using (XtraSaveFileDialog saveFileDialog = new XtraSaveFileDialog()
{
Filter = "pdf*.pdf|*.pdf",
Title = "导出pdf"
})
{
DialogResult dialogResult = saveFileDialog.ShowDialog(this);
if (dialogResult == DialogResult.OK)
{
string selectedPath = saveFileDialog.FileName;
DataTable table = SubassembliesCurrentData();
table.Columns.Add("表单版本名称", typeof(string));
table.Columns.Add("表单版本编码", typeof(string));
table.Rows[0]["表单版本名称"] = template.FormVerName;
table.Rows[0]["表单版本编码"] = template.FormVerCode;
FastReport.Report report = new FastReport.Report();
var vLabelDir = Path.Combine(Application.StartupPath, "Labels");
//判断文件夹是否存在
if (!Directory.Exists(vLabelDir))
{
throw new Exception("缺少待打印的标签模板目录!");
}
//路径拼接模板文件名
var vFileName = Path.Combine(vLabelDir, template.PrintTemplateFileName);
//判断模板文件是否存在
if (!File.Exists(vFileName))
{
throw new Exception("缺少待打印的标签模板文件!");
}
report.Load(vFileName);
report.DoublePass = true;
DataSet dsDatas = new DataSet();
dsDatas.Tables.Add(table);
report.RegisterData(dsDatas, "MaintenanceInfo");
if (report.Prepare())
{
FastReport.Export.Pdf.PDFExport pdfExport = new FastReport.Export.Pdf.PDFExport();
report.Export(pdfExport, selectedPath);
}
report.Dispose();
XtraMessageBoxHelper.Info($"导出成功!");
}
}
}
catch (Exception ex)
{
XtraMessageBoxHelper.Error(ex.Message);
}
}
}
}