using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using DevExpress.XtraEditors; using DeviceRepair.Models.Enum; using DevExpress.XtraGrid.Views.Grid; using System.Reflection; using DevExpress.XtraGrid.Columns; using DeviceRepair.Models.Attr; using System.Linq; using DeviceRepair.Models.OperationHistory; namespace TsSFCDevice.Client.Launch.History { public partial class frmBaseHistory : DevExpress.XtraEditors.XtraForm { HistoryType HisType; public Type CurrentHistoryItemType; private Type ReposType; Object CurrentRepos = null; public frmBaseHistory(HistoryType hisType, Type vType, string vTitle = "历史数据查询") { InitializeComponent(); HisType = hisType; CurrentHistoryItemType = vType; this.Text = vTitle; ReposType = typeof(Biz.Impl.HisRepository<>); ; ReposType = ReposType.MakeGenericType(CurrentHistoryItemType); CurrentRepos = Activator.CreateInstance(ReposType); dvDatas.CustomDrawRowIndicator += DvDatas_CustomDrawRowIndicator; dvDatas.RowCellStyle += dvDatas_RowCellStyle; lcgTimeFilter.CustomHeaderButtons[0].Properties.CheckedChanged += Properties_CheckedChanged; #region 设置默认时间(一周内) dtStart.EditValue = System.DateTime.Now.AddDays(-7); dtEnd.EditValue = System.DateTime.Now; #endregion SetTimeFormat(); #region 设置默认值 dvDatas.CustomColumnDisplayText += DvDatas_CustomColumnDisplayText; dvDatas.CustomDrawEmptyForeground += DvDatas_CustomDrawEmptyForeground; dvDatas.MouseMove += DvDatas_MouseMove; dvDatas.MouseDown += DvDatas_MouseDown; InitEmptyFont(); dvDatas.OptionsPrint.AutoWidth = false; #endregion splashScreenManager1.ShowWaitForm(); } private void btnExport_Click(object sender, EventArgs e) { try { if (dvDatas.DataRowCount == 0) { throw new Exception("当前没有数据可供操作!"); } SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Title = "导出Excel"; saveFileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx"; DialogResult dialogResult = saveFileDialog.ShowDialog(this); if (dialogResult == DialogResult.OK) { DevExpress.XtraPrinting.XlsxExportOptionsEx options = new DevExpress.XtraPrinting.XlsxExportOptionsEx(); options.ExportType = DevExpress.Export.ExportType.WYSIWYG; dvDatas.ExportToXlsx(saveFileDialog.FileName.ToString(), options); XtraMessageBoxHelper.Info("导出成功!"); } } catch (Exception ex) { XtraMessageBoxHelper.Error(ex.Message); } } private void btnSearch_Click(object sender, EventArgs e) { try { if (lcgTimeFilter.CustomHeaderButtons[0].Properties.Checked) { if (dtStart.EditValue == null || dtEnd.EditValue == null) { throw new Exception("请选择时间!"); } if (dtStart.Time > dtEnd.Time) { throw new Exception("开始时间不能大于结束时间!"); } if (dtStart.Time < DateTime.Now.AddYears(-2)) { throw new Exception("开始时间超出时间范围!"); } if (dtEnd.Time > DateTime.Now.AddYears(2)) { throw new Exception("结束时间超出时间范围!"); } } #region 动态控件的 splashScreenManager1.ShowWaitForm(); splashScreenManager1.SetWaitFormDescription("正在组织查询参数..."); var vParams = GetQueryParams(); #endregion SetParams(vParams); splashScreenManager1.SetWaitFormDescription("正在向服务器请求查询结果..."); var vRtm = ReposType.InvokeMember("HistoryGet", System.Reflection.BindingFlags.Default | BindingFlags.InvokeMethod, null, CurrentRepos, null); splashScreenManager1.SetWaitFormDescription("服务器返回查询结果..."); if (vRtm == null) { gdvData.DataSource = null; throw new Exception("没有查询到内容!"); } gdvData.DataSource = vRtm; dvDatas.BestFitColumns(); CloseWait(); } catch (Exception ex) { CloseWait(); if (ex.InnerException != null) { XtraMessageBoxHelper.Error(ex.InnerException.Message); } else { XtraMessageBoxHelper.Error(ex.Message); } } } private void frmBaseHistory_Load(object sender, EventArgs e) { try { Cursor.Current = Cursors.WaitCursor; InitQueryCtls(dvDatas, GetQueryItems(CurrentHistoryItemType)); InitGrid(dvDatas, GetGridColumns(CurrentHistoryItemType)); } catch (Exception ex) { Cursor.Current = Cursors.Default; CloseWait(); XtraMessageBoxHelper.Error(ex.Message); } finally { CloseWait(); Cursor.Current = Cursors.Default; } } private void bbiPrint_Click(object sender, EventArgs e) { } void CloseWait() { if (splashScreenManager1.IsSplashFormVisible) { splashScreenManager1.CloseWaitForm(); } } #region 参数相关 private IDictionary GetQueryParams() { IDictionary vParams = new Dictionary(); foreach (Control eachCtl in lcMain.Controls) { if (eachCtl.Tag == null) { continue; } HistoryQueryParam vQuery = eachCtl.Tag as HistoryQueryParam; if (vQuery == null) { continue; } if (vQuery.CtlType == HistoryFilterCtlType.TextBox) { var vTextEdit = (TextEdit)eachCtl; var vTextValue = vTextEdit.Text.Trim(); vParams.Add(vQuery.QueryCode, vTextValue); } else if (vQuery.CtlType == HistoryFilterCtlType.ComboBox) { var vComboBoxEdit = (ComboBoxEdit)eachCtl; if (!string.IsNullOrEmpty(vComboBoxEdit.Text)) { if (!vComboBoxEdit.Text.Equals("--请选择--")) { vParams.Add(vQuery.QueryCode, vQuery[vComboBoxEdit.Text]); } else { vParams.Add(vQuery.QueryCode, string.Empty); } } else { vParams.Add(vQuery.QueryCode, string.Empty); } } else { //暂时就弄了文本框和选择框,其他的以后用到再说 Myl20210528 //妈的,是真心累! } } vParams.Add("LogStartDateTime", lcgTimeFilter.CustomHeaderButtons[0].Properties.Checked ? dtStart.Time.ToString("yyyy-MM-dd HH:mm:ss") : string.Empty); vParams.Add("LogEndDateTime", lcgTimeFilter.CustomHeaderButtons[0].Properties.Checked ? dtEnd.Time.ToString("yyyy-MM-dd HH:mm:ss") : string.Empty); return vParams; } private void SetParams(IDictionary vParamsDic) { ReposType.GetProperty("ApiParameters").SetValue(CurrentRepos, vParamsDic); ReposType.GetProperty("HisType").SetValue(CurrentRepos, HisType); } #endregion #region Gv 控件相关 private void DeleteGridColumns(GridView dvGrid, params string[] colmns) { dvGrid.Columns.Clear(); } private void DeleteQueryCtls() { Root.Remove(lcciUserCode); Root.Remove(lcciOpType); Root.Remove(lcciClientName); } private void InitGrid(GridView dvGrid, IList vColumns) { DeleteGridColumns(dvGrid); int iColumnIndex = 0; foreach (var eachColumn in vColumns) { GridColumn bgColumn = new GridColumn(); bgColumn.OptionsColumn.FixedWidth = false; bgColumn.OptionsColumn.AllowShowHide = false; bgColumn.OptionsColumn.AllowSize = true; bgColumn.OptionsColumn.AllowMove = false; bgColumn.OptionsColumn.AllowFocus = true; bgColumn.OptionsColumn.AllowEdit = false; bgColumn.OptionsColumn.ReadOnly = true; bgColumn.OptionsColumn.AllowSort = DevExpress.Utils.DefaultBoolean.True; bgColumn.OptionsColumn.AllowGroup = DevExpress.Utils.DefaultBoolean.True; bgColumn.OptionsColumn.AllowIncrementalSearch = false; bgColumn.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False; bgColumn.Visible = true; bgColumn.OptionsColumn.Printable = eachColumn.AllowPrint ? DevExpress.Utils.DefaultBoolean.True : DevExpress.Utils.DefaultBoolean.False; #region 列头如果特性描述中有换行存在的情况 //这样不一定有用,后面再说 bgColumn.AppearanceHeader.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap; #endregion bgColumn.Caption = eachColumn.ColumnDescription; bgColumn.FieldName = eachColumn.ColumnCode; bgColumn.Name = $"colColumnItem{iColumnIndex++}"; bgColumn.AppearanceHeader.Options.UseBackColor = true; bgColumn.AppearanceHeader.Options.UseFont = true; bgColumn.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; bgColumn.AppearanceCell.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center; bgColumn.Tag = eachColumn; if (eachColumn.ColumnType.Name == "DateTime") { bgColumn.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime; bgColumn.DisplayFormat.FormatString = eachColumn.FormatString; } if (iColumnIndex == 1) { #region 添加汇总页脚 bgColumn.Summary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridColumnSummaryItem(DevExpress.Data.SummaryItemType.Count, eachColumn.ColumnCode, "合计:{0} 条历史记录")}); #endregion } dvGrid.Columns.Add(bgColumn); } gdvData.MainView = dvGrid; } private void InitQueryCtls(GridView dvGrid, IList vQuerys) { DeleteQueryCtls(); int iCtlIndex = 0; foreach (var eachQuery in vQuerys) { DevExpress.XtraLayout.LayoutControlItem lccQueryParam = new DevExpress.XtraLayout.LayoutControlItem(); lccQueryParam.Name = $"lcciQuery{iCtlIndex}"; lccQueryParam.AppearanceItemCaption.Font = new System.Drawing.Font("Tahoma", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); lccQueryParam.AppearanceItemCaption.Options.UseFont = true; lccQueryParam.AppearanceItemCaption.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; lccQueryParam.AppearanceItemCaption.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center; lccQueryParam.ContentHorzAlignment = DevExpress.Utils.HorzAlignment.Center; lccQueryParam.ContentVertAlignment = DevExpress.Utils.VertAlignment.Center; if (eachQuery.CtlType == HistoryFilterCtlType.TextBox) { #region 文本框 DevExpress.XtraEditors.TextEdit vTxtEdit = new DevExpress.XtraEditors.TextEdit(); vTxtEdit.Name = $"txtQuery{iCtlIndex}"; vTxtEdit.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); vTxtEdit.Properties.Appearance.Options.UseFont = true; vTxtEdit.Size = new System.Drawing.Size(379, 26); vTxtEdit.StyleController = this.lcMain; vTxtEdit.TabIndex = iCtlIndex; vTxtEdit.Tag = eachQuery; lccQueryParam.Control = vTxtEdit; #region 控制默认内容值-Myl20210625 if (!string.IsNullOrEmpty(eachQuery.DefaultNotShowQueryParamValue)) { vTxtEdit.Text = eachQuery.DefaultNotShowQueryParamValue; vTxtEdit.Enabled = false; } #endregion this.lcMain.Controls.Add(this.txtUserCode); #endregion } else if (eachQuery.CtlType == HistoryFilterCtlType.ComboBox) { #region 复选框 DevExpress.XtraEditors.ComboBoxEdit vComboBox = new DevExpress.XtraEditors.ComboBoxEdit(); vComboBox.Name = $"cmbQuery{iCtlIndex}"; vComboBox.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); vComboBox.Properties.Appearance.Options.UseFont = true; vComboBox.Properties.Items.AddRange(new object[] { "--请选择--" }); vComboBox.Properties.Items.AddRange(eachQuery.ComboBoxQueryDisplays.Split(',')); vComboBox.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor; vComboBox.Size = new System.Drawing.Size(343, 26); vComboBox.StyleController = this.lcMain; vComboBox.TabIndex = iCtlIndex; vComboBox.Tag = eachQuery; lccQueryParam.Control = vComboBox; #region 控制默认内容值-Myl20210625 if (!string.IsNullOrEmpty(eachQuery.DefaultNotShowQueryParamValue)) { vComboBox.Text = eachQuery.DefaultNotShowQueryParamValue; vComboBox.Enabled = false; } #endregion this.lcMain.Controls.Add(vComboBox); #endregion } lccQueryParam.Size = new System.Drawing.Size(475, 30); lccQueryParam.Text = eachQuery.QueryDescription; lccQueryParam.TextSize = new System.Drawing.Size(80, 19); this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { lccQueryParam }); iCtlIndex++; } layoutControlGroup1.BestFit(); } private void dvDatas_RowCellStyle(object sender, RowCellStyleEventArgs e) { } private void Properties_CheckedChanged(object sender, EventArgs e) { lcStartTime.Enabled = lcEndTime.Enabled = lcgTimeFilter.CustomHeaderButtons[0].Properties.Checked; } private void DvDatas_MouseDown(object sender, MouseEventArgs e) { if (trySearchingAgainBoundsContainCursor) { btnSearch.PerformClick(); } } private void DvDatas_MouseMove(object sender, MouseEventArgs e) { trySearchingAgainBoundsContainCursor = trySearchingAgainBounds.Contains(e.Location); gdvData.Cursor = trySearchingAgainBoundsContainCursor ? Cursors.Hand : Cursors.Default; dvDatas.InvalidateRect(trySearchingAgainBounds); } private void DvDatas_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e) { if (e.Info.IsRowIndicator && e.RowHandle >= 0) { e.Info.DisplayText = (e.RowHandle + 1).ToString(); e.Info.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; e.Info.Appearance.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center; } } private void DvDatas_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e) { try { var vColumn = e.Column.Tag as HistoryGridColumn; if (vColumn != null) { if (vColumn.ColumnType.Name == "DateTime" || vColumn.ColumnDescription.Contains("时间")) { var vValue = e.Value?.ToString()?.Trim(); if (string.IsNullOrEmpty(vValue)) { e.DisplayText = "N/A"; } } } } catch { } } private void DvDatas_CustomDrawEmptyForeground(object sender, DevExpress.XtraGrid.Views.Base.CustomDrawEventArgs e) { e.DefaultDraw(); e.Appearance.Options.UseFont = true; e.Appearance.Font = noMatchesFoundTextFont; Size size = e.Appearance.CalcTextSize(e.Cache, noMatchesFoundText, e.Bounds.Width).ToSize(); int x = (e.Bounds.Width - size.Width) / 2; int y = e.Bounds.Y + offset; noMatchesFoundBounds = new Rectangle(new Point(x, y), size); e.Appearance.DrawString(e.Cache, noMatchesFoundText, noMatchesFoundBounds); e.Appearance.Font = trySearchingAgainBoundsContainCursor ? trySearchingAgainTextFontBold : trySearchingAgainTextFont; size = e.Appearance.CalcTextSize(e.Cache, trySearchingAgainText, e.Bounds.Width).ToSize(); x = noMatchesFoundBounds.X - (size.Width - noMatchesFoundBounds.Width) / 2; y = noMatchesFoundBounds.Bottom + offset; size.Width += offset; trySearchingAgainBounds = new Rectangle(new Point(x, y), size); e.Appearance.DrawString(e.Cache, trySearchingAgainText, trySearchingAgainBounds, linkBrush); } void SetTimeFormat() { this.dtStart.Properties.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss"; this.dtStart.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dtStart.Properties.EditFormat.FormatString = "yyyy-MM-dd HH:mm:ss"; this.dtStart.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dtStart.Properties.Mask.EditMask = "yyyy-MM-dd HH:mm:ss"; this.dtEnd.Properties.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss"; this.dtEnd.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dtEnd.Properties.EditFormat.FormatString = "yyyy-MM-dd HH:mm:ss"; this.dtEnd.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dtEnd.Properties.Mask.EditMask = "yyyy-MM-dd HH:mm:ss"; } #region 无查询内容时的窗体Grid刷新 void InitEmptyFont() { noMatchesFoundTextFont = new Font("Tahoma", 10); trySearchingAgainTextFont = new Font("Tahoma", 15, FontStyle.Underline); trySearchingAgainTextFontBold = new Font(trySearchingAgainTextFont, FontStyle.Underline | FontStyle.Bold); } private string searchName = string.Empty; private Font noMatchesFoundTextFont = null; private Font trySearchingAgainTextFont = null; private Font trySearchingAgainTextFontBold = null; private SolidBrush linkBrush = new SolidBrush(DevExpress.Skins.EditorsSkins.GetSkin(DevExpress.LookAndFeel.UserLookAndFeel.Default.ActiveLookAndFeel).Colors["HyperLinkTextColor"]); private string noMatchesFoundText = "没有内容"; private string trySearchingAgainText = "Try searching again"; private Rectangle noMatchesFoundBounds = Rectangle.Empty; private Rectangle trySearchingAgainBounds = Rectangle.Empty; private bool trySearchingAgainBoundsContainCursor = false; private int offset = 10; #endregion #endregion #region 方法 IList GetQueryItems(Type vHisType) { IList hisGridColumns = new List(); PropertyInfo[] domProperties = vHisType.GetProperties(); IEnumerable domGridFields = domProperties.Where((A) => { return A.GetCustomAttributes(typeof(HistoryFilterFieldAttribute), true).Length > 0; }); if ((domGridFields?.Count() ?? 0) == 0) { throw new ArgumentNullException("实体类中字段均未指定相应的历史查询条件字段属性!"); } foreach (PropertyInfo pi in domGridFields) { Type colType = pi.PropertyType; object[] objConverter = pi.GetCustomAttributes(typeof(HistoryFilterFieldAttribute), true); var vCode = ((HistoryFilterFieldAttribute)objConverter[0]).Code; var vDescription = ((HistoryFilterFieldAttribute)objConverter[0]).Description; var vCtlType = ((HistoryFilterFieldAttribute)objConverter[0]).CtlType; var vDefaultValue = ((HistoryFilterFieldAttribute)objConverter[0]).DefaultValue; var vFuzzy = ((HistoryFilterFieldAttribute)objConverter[0]).Fuzzy; var vQueryItems = ((HistoryFilterFieldAttribute)objConverter[0]).QueryItems; var vShowSequence = ((HistoryFilterFieldAttribute)objConverter[0]).ShowSequence; var vQueryComBox = ((HistoryFilterFieldAttribute)objConverter[0]).QueryItemDisplayList; var vDefaultNotShowQueryParamValue = ((HistoryFilterFieldAttribute)objConverter[0]).DefaultNotShowQueryParamValue; hisGridColumns.Add(new HistoryQueryParam() { QueryCode = string.IsNullOrEmpty(vCode) ? pi.Name : vCode, ShowSequence = vShowSequence, QueryItems = vQueryComBox, DefaultValue = vDefaultValue, CtlType = vCtlType, bFuzzy = vFuzzy, QueryDescription = vDescription, QueryType = colType, DefaultNotShowQueryParamValue = vDefaultNotShowQueryParamValue }); } var vSequenceColumns = hisGridColumns.OrderBy(O => { return O.ShowSequence; }); return vSequenceColumns.ToList(); } public static IList GetGridColumns(Type vHisType) { IList hisGridColumns = new List(); PropertyInfo[] domProperties = vHisType.GetProperties(); IEnumerable domGridFields = domProperties.Where((A) => { return A.GetCustomAttributes(typeof(HistoryGridFieldAttribute), true).Length > 0; }); if ((domGridFields?.Count() ?? 0) == 0) { throw new ArgumentNullException("实体类中字段均未指定相应的表格字段属性!"); } foreach (PropertyInfo pi in domGridFields) { Type colType = pi.PropertyType; object[] objConverter = pi.GetCustomAttributes(typeof(HistoryGridFieldAttribute), true); if (objConverter.Length == 0) { continue; } var vCode = ((HistoryGridFieldAttribute)objConverter[0]).Code; var vDescription = ((HistoryGridFieldAttribute)objConverter[0]).Description; var vFormatString = ((HistoryGridFieldAttribute)objConverter[0]).FormatString; hisGridColumns.Add(new HistoryGridColumn() { ColumnCode = string.IsNullOrEmpty(vCode) ? pi.Name : vCode, ColumnDescription = vDescription, ColumnType = colType, FormatString = vFormatString, AllowExport = ((HistoryGridFieldAttribute)objConverter[0]).AllowExport, AllowPrint = ((HistoryGridFieldAttribute)objConverter[0]).AllowPrint, CtlType = ((HistoryGridFieldAttribute)objConverter[0]).CtlType, ShowSequence = ((HistoryGridFieldAttribute)objConverter[0]).ShowSequence }); } var vSequenceColumns = hisGridColumns.OrderBy(O => { return O.ShowSequence; }); return vSequenceColumns.ToList(); } #endregion } }