// *********************************************************************** // Assembly : Construction // Author : flythink // Created : 06-05-2020 // // Last Modified By : flythink // Last Modified On : 09-01-2020 // *********************************************************************** // // Copyright (c) jindongfang. All rights reserved. // // // *********************************************************************** using DevExpress.Utils; //using xFunc.Maths.Expressions.Collections; using DevExpress.XtraEditors; using DevExpress.XtraEditors.Repository; using DevExpress.XtraGrid.Columns; using DevExpress.XtraGrid.Views.Base; using DevExpress.XtraGrid.Views.Grid; using DevExpress.XtraGrid.Views.Grid.ViewInfo; //using DQ.Construction.NewLook.CustomControls; using Fasterflect; using Fk.Utils; using Mapster; using MessagePack; using Newtonsoft.Json; using SqlSugar; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using WorkData; using WorkData.Entity; using WorkData.EntityBase; using xFunc.Maths; using xFunc.Maths.Expressions; using xFunc.Maths.Expressions.Parameters; using System.IO; namespace WellWorkDataUI { /// /// 数据查看控件 /// public partial class FrmDataViewer : Form { /// /// The k page count. /// private const int KPageCount = 10000; private string dataName; private string property; private string property2; private List listColumnNames; private List listDictionary; private SlowDownTimer timer = new SlowDownTimer(1000); private Type type; private int maxId = -1; private List duplicate = new List(); private Random randomGen = new Random(); public event EventHandler DataSaved; /// /// Initializes a new instance of the class. /// public FrmDataViewer() { this.InitializeComponent(); this.Initialize(); } /// /// Initializes a new instance of the class. /// /// Name of the data. /// The property. /// The property2. public FrmDataViewer(string dataName, string property, string property2 = "", bool enableToolbar = true) : this() { this.type = EntityHelp.GetEntityTypeByDesc(dataName); this.dataName = dataName; this.property = property; this.property2 = property2; this.btn_find_duplicate.Visible = dataName != "测井曲线"; if (this.type == typeof(WellBase) || this.type == typeof(InterpretDrillWellLayered) /*|| this.type.IsType()*/) { this.btn_formula.Visible = true; } this.toolStrip1.Enabled = enableToolbar; } /// /// Gets a value indicating whether this instance is need save. /// /// true if this instance is need save; otherwise, false. public bool IsNeedSave => this.btnSave.Enabled; /// /// Saves the data. /// public void SaveData() { this.btnSave.PerformClick(); } /// /// Shows the data if. /// /// The expression. /// The order. /// A Task. private async Task ShowDataIf(Expression> expression, List orders = null) { if (this.type == typeof(T) || (this.type == typeof(WellCurve) && typeof(T) == typeof(WellCurveFile))) { ISugarQueryable query = DBHelp.NewDb.Queryable(); if (orders != null) { query = query.OrderBy(orders); } if (!string.IsNullOrWhiteSpace(this.property)) { query = query.Where(expression); } await this.LoadDataAsync(query, KPageCount); } } private async Task ShowParamData( Expression> expression, Expression> orderExpression = null) { if (this.type == typeof(T)) { ISugarQueryable query = DBHelp.NewDb.Queryable(); if (!string.IsNullOrWhiteSpace(this.property)) { query = query.Where(expression); } if (orderExpression != null) { query = query.OrderBy(orderExpression); } await this.LoadDataAsync(query, KPageCount); } } /// /// Shows the data. /// public async void ShowData() { using (SplashHelper.Create()) { Type type = this.type; string tablename = DBHelp.GetTableName(this.type); this.listDictionary = DataHelp.ListSysDictionary .Where(o => string.Equals(o.TableName, tablename, StringComparison.CurrentCultureIgnoreCase)) .ToList(); this.listColumnNames = DataHelp.ListTableInfo .Where(o => string.Equals(o.TableName, tablename, StringComparison.CurrentCultureIgnoreCase)) .OrderBy(r => r.OrderBy) .ToList(); List orderList = OrderByModel.Create(new OrderByModel() { FieldName = "xhid" }); await this.ShowDataIf(o => o.JH == this.property, OrderByModel.Create(new OrderByModel() { FieldName = "JH" })); await this.ShowDataIf(o => o.Block == this.property, orderList); await this.ShowDataIf(o => o.Block == this.property, orderList); await this.ShowDataIf(o => o.Block == this.property, orderList); await this.ShowDataIf(o => o.Block == this.property, orderList); await this.ShowDataIf(o => o.Block == this.property, orderList); await this.ShowDataIf(o => o.Block == this.property, orderList); await this.ShowDataIf(o => o.Block == this.property, orderList); await this.ShowDataIf(o => o.Block == this.property, orderList); await this.ShowDataIf(o => o.JH == this.property); await this.ShowDataIf(o => o.JH == this.property); await this.ShowDataIf(o => o.JH == this.property); await this.ShowDataIf(o => o.JH == this.property); await this.ShowDataIf(o => o.JH == this.property, orderList); //await this.ShowDataIf(o => o.JH == this.property, OrderByModel.Create(new OrderByModel() { FieldName = "XHID" })); await this.ShowParamData(o => o.JH == this.property, o => SqlFunc.ToInt32(o.XHID)); await this.ShowDataIf(o => o.JH == this.property); await this.ShowDataIf(o => o.GROUP == this.property, OrderByModel.Create(new OrderByModel() { FieldName = "jh" })); //测井曲线 await this.ShowDataIf(o => o.JH == this.property, OrderByModel.Create(new OrderByModel() { FieldName = "JH" })); List orderList1 = OrderByModel.Create(new OrderByModel() { FieldName = "ID" }); await this.ShowDataIf(o => o.Well == this.property, orderList1); await this.ShowDataIf(o => o.Well == this.property, orderList1); await this.ShowDataIf(o => o.Well == this.property, orderList1); await this.ShowDataIf(o => o.Well == this.property, orderList1); await this.ShowDataIf(o => o.Well == this.property, orderList1); await this.ShowDataIf(o => o.Well == this.property, orderList1); await this.ShowDataIf(o => o.Well == this.property, orderList1); await this.ShowDataIf(o => o.Well == this.property, orderList1); await this.ShowDataIf(o => o.Well == this.property, orderList1); await this.ShowDataIf(o => o.Well == this.property, orderList1); await this.ShowDataIf(o => o.Well == this.property, orderList1); var cc_orderList = OrderByModel.Create(new OrderByModel() { FieldName = "CW" }, new OrderByModel() { FieldName = "JH" }, new OrderByModel() { FieldName = "ID" }); if (DataHelp.IsReservoirDataGroupByLayer) { await this.ShowDataIf(o => o.CW == this.property, cc_orderList); await this.ShowDataIf(o => o.CW == this.property, cc_orderList); await this.ShowDataIf(o => o.CW == this.property, cc_orderList); await this.ShowDataIf(o => o.CW == this.property, cc_orderList); await this.ShowDataIf(o => o.CW == this.property, cc_orderList); } else { if (int.TryParse(this.property2, out var level)) { var cws = DBHelp.NewDb.Queryable() .Where(o => o.Level == level) .Select(o => o.Code) .ToList(); await this.ShowDataIf(o => o.JH == this.property && cws.Contains(o.CW), cc_orderList); await this.ShowDataIf(o => o.JH == this.property && cws.Contains(o.CW), cc_orderList); await this.ShowDataIf(o => o.JH == this.property && cws.Contains(o.CW), cc_orderList); await this.ShowDataIf(o => o.JH == this.property && cws.Contains(o.CW), cc_orderList); await this.ShowDataIf(o => o.JH == this.property && cws.Contains(o.CW), cc_orderList); } else { cc_orderList = OrderByModel.Create(new OrderByModel() { FieldName = "ID" }); await this.ShowDataIf(o => o.JH == this.property, cc_orderList); await this.ShowDataIf(o => o.JH == this.property, cc_orderList); await this.ShowDataIf(o => o.JH == this.property, cc_orderList); await this.ShowDataIf(o => o.JH == this.property, cc_orderList); await this.ShowDataIf(o => o.JH == this.property, cc_orderList); } } //if (DataHelp.IsDrillwelllayeredGroupByLayer) //{ // //查询所有下级 // List lstCw = WellDistribute.GetReservoirChildLayers(this.property); // await this.ShowDataIf(o => lstCw.Contains(SqlFunc.ToUpper(o.CW)), orderList); //} //else { await this.ShowDataIf(o => o.JH == this.property, orderList); } //await this.ShowDataIf(o => o.CW == this.property, orderList); //await this.ShowDataIf(o => o.CW == this.property, orderList); //await this.ShowDataIf(o => o.CW == this.property, orderList); //await this.ShowDataIf(o => o.CW == this.property, orderList); //await this.ShowDataIf(o => o.CW == this.property, orderList); //await this.ShowDataIf(o => o.CW == this.property, orderList); //await this.ShowDataIf(o => o.CW == this.property, orderList); //await this.ShowDataIf(o => o.CW == this.property, orderList); //await this.ShowDataIf(o => o.CW == this.property, orderList); //await this.ShowDataIf(o => true); string[] array = this.property.Split('@'); if (array.Length > 1) { string arr0 = array[0]; string arr1 = array[1]; await this.ShowDataIf(r => r.CW == arr0 && r.Attribute == arr1, orderList); } if (array.Length > 0) { string arr0 = array[0]; await this.ShowDataIf(r => r.JH == arr0, orderList); await this.ShowDataIf(r => r.JH == arr0, orderList); } } if (this.gridViewMain.Columns.Count > 0) { GridColumn column0 = this.gridViewMain.Columns[0]; column0.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count; column0.SummaryItem.DisplayFormat = "合计:{0:n2}"; } foreach (GridColumn col in this.gridViewMain.Columns) { if (col.FieldName.Equals("ID", StringComparison.CurrentCultureIgnoreCase) || col.FieldName.Equals("Unique", StringComparison.CurrentCultureIgnoreCase) || col.FieldName.Equals("GQID", StringComparison.CurrentCultureIgnoreCase) || col.FieldName.Equals("CWID", StringComparison.CurrentCultureIgnoreCase) || col.FieldName.Equals("Data", StringComparison.CurrentCultureIgnoreCase)) { col.Visible = false; } if (DataHelp.IsDrillwelllayeredGroupByLayer && col.FieldName.Equals("XHID", StringComparison.CurrentCultureIgnoreCase)) { col.Visible = false; } } } private async Task SaveDataAsync() { await this.SaveDataAsyncIf(DataHelp.SyncSearchWellName); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); //await this.SaveDataAsyncIf(); //await this.SaveDataAsyncIf(); //await this.SaveDataAsyncIf(); //await this.SaveDataAsyncIf(); //await this.SaveDataAsyncIf(); //await this.SaveDataAsyncIf(); //await this.SaveDataAsyncIf(); //await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); // await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); await this.SaveDataAsyncIf(); } private void Initialize() { this.UpdateToolState(); this.gridViewMain.OptionsMenu.EnableColumnMenu = false; this.gridViewMain.OptionsCustomization.AllowSort = true; this.gridViewMain.OptionsCustomization.AllowFilter = false; this.gridViewMain.ActiveFilterEnabled = true; this.gridViewMain.OptionsView.ShowFilterPanelMode = ShowFilterPanelMode.Never; } private int GetNextId() { if (this.maxId < 0) { this.maxId = DBHelp.NewDb.Queryable(DBHelp.GetTableName(this.type), null).Max("ID"); } return ++this.maxId; } private void BtnAddRow_Click(object sender, EventArgs e) { if (this.gridViewMain.DataSource is IList collection) { object obj = Activator.CreateInstance(this.type); if (obj is IOrderEntity ioe && collection.Count > 0) { ioe.ID = this.GetNextId(); ioe.XHID = collection.OfType().Max(r => r.XHID) + 1; } collection.Add(obj); this.MakeLastRowVisible(); this.UpdateToolState(); } } private void BtnDeleteRow_Click(object sender, EventArgs e) { int focusedIndex = this.gridViewMain.GetDataSourceRowIndex(this.gridViewMain.FocusedRowHandle); object[] rowObjects = this.gridViewMain.GetSelectedRows().Select(i => this.gridViewMain.GetRow(i)).ToArray(); if (rowObjects.Length > 0 && this.gridViewMain.DataSource is IList collection) { foreach (object obj in rowObjects) { int index = collection.IndexOf(obj); collection.RemoveAt(index); if (obj is IUniqueEntity iue) { string unique = iue.Unique; List list = collection.OfType() .Where(o => o.Unique == unique) .Where(o => o.XHID >= iue.XHID) .ToList(); foreach (IUniqueEntity item in list) { item.XHID--; collection[collection.IndexOf(item)] = item; } } } this.UpdateToolState(); if (focusedIndex == collection.Count) { focusedIndex--; } } this.gridViewMain.SelectRow(this.gridViewMain.GetRowHandle(focusedIndex)); } // 空列后置 private void BtnEmpty_Click(object sender, EventArgs e) { this.btn_empty.Checked = !this.btn_empty.Checked; if (this.btn_empty.Checked) { IList bindinglist = this.gridControl1.DataSource as IList; //if (bindinglist == null) //{ // return; //} int index = this.gridViewMain.Columns.Count; foreach (GridColumn col in this.gridViewMain.Columns) { bool empty = true; for (int i = 0; i < this.gridViewMain.RowCount; i++) { int rowHandle = this.gridViewMain.GetRowHandle(i); object value = this.gridViewMain.GetRowCellValue(rowHandle, col.FieldName); if (!string.IsNullOrWhiteSpace(value?.ToString())) { empty = false; break; } } if (empty) { col.VisibleIndex = index++; } } } else { this.gridViewMain.Columns.Clear(); if (this.type == typeof(WellCurve) || this.type == typeof(HoriWellFracturParameter)) { string tableName = DBHelp.GetTableName(this.type); this.UpdateCustomColumnInfo(tableName); } else { this.UpdateColumnInfo(); } } } private void BtnInsertRow_Click(object sender, EventArgs e) { if (this.gridViewMain.FocusedRowHandle >= 0) { int index = this.gridViewMain.GetDataSourceRowIndex(this.gridViewMain.FocusedRowHandle); if (this.gridViewMain.DataSource is IList collection) { if (index <= collection.Count) { object origin = collection[index]; Type type = origin.GetType(); object obj = origin.Adapt(type, type); foreach (System.Reflection.PropertyInfo prop in type.GetProperties()) { if (prop.CanRead && prop.CanWrite) { if (prop.Name == "ID") { prop.SetValue(obj, this.GetNextId()); } else if (prop.PropertyType == typeof(double)) { prop.SetValue(obj, 0d); } else if (prop.PropertyType == typeof(double?)) { prop.SetValue(obj, null); } } } if (obj is IUniqueEntity iue) { string unique = iue.Unique; List list = collection.OfType() .Where(o => o.Unique == unique) .Where(o => o.XHID >= iue.XHID) .ToList(); foreach (IUniqueEntity item in list) { item.XHID++; collection[collection.IndexOf(item)] = item; } } collection.Insert(index, obj); } } this.UpdateToolState(); } } private void BtnPaste_Click(object sender, EventArgs e) { DataTable dt = this.ClipToDataTable("auto"); if (dt != null) { //FrmImportData frm_import = new FrmImportData(DBHelp.GetTableName(this.type), string.Empty, dt); //frm_import.ImportFromTable = true; //if (frm_import.ShowDialog() == DialogResult.OK) //{ // this.ShowData(); //} } } private void BtnRedo_Click(object sender, EventArgs e) { //if (this.gridViewMain.DataSource is IHistoryList history && history.RedoCount > 0) //{ // history.Redo(); // this.UpdateToolState(); //} } private void BtnSave_Click(object sender, EventArgs e) { if (MessageBox.Show("确定要保存数据吗?", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK) { if (this.CheckData()) { this.SaveDataAsync().Wait(); } } } private bool CheckData() { Type type = this.type; if (typeof(WellCapacity).IsAssignableFrom(type)) { if (this.gridViewMain.DataSource is IHistoryList history) { List list = history.History.Where(r => r.ChangedType == ListChangedType.ItemAdded) .Select(r => r.New as WellCapacity).ToList(); foreach (WellCapacity item in list) { if (string.IsNullOrWhiteSpace(item.JH)) { ShowFieldEmptyMessage("井号", GetRowIndex(history, item)); return false; } if (string.IsNullOrWhiteSpace(item.Block)) { ShowFieldEmptyMessage("区块", GetRowIndex(history, item)); return false; } } } } return true; int GetRowIndex(object history, object item) { if (history is IList list) { int index = list.IndexOf(item); return this.gridViewMain.GetRowHandle(index); } return -1; } void ShowFieldEmptyMessage(string field, int rowHandle) { MessageBox.Show($"列'{field}'不能为空, 请填写!"); this.gridViewMain.MakeRowVisible(rowHandle); this.gridViewMain.FocusedRowHandle = rowHandle; } } private void BtnUndo_Click(object sender, EventArgs e) { if (this.gridViewMain.DataSource is IHistoryList history && history.UndoCount > 0) { history.Undo(); this.UpdateToolState(); } } private DataTable ClipToDataTable(string type) { try { if (Clipboard.ContainsText(TextDataFormat.Text)) { DataTable dt = new DataTable(); List> list = new List>(); string txt = Clipboard.GetText(TextDataFormat.Text); string[] rows = txt.Split( Constants.StringSplit.LineSeparator, StringSplitOptions.RemoveEmptyEntries); foreach (string item in rows) { List list_row = new List(); string[] array = item.Split( Constants.StringSplit.Separator, StringSplitOptions.RemoveEmptyEntries); list_row.AddRange(array); list.Add(list_row); } if (list.Count > 0) { for (int i = 0; i < list[0].Count; i++) { string colname = "列" + (i + 1); dt.Columns.Add(colname); } for (int i = 0; i < list.Count; i++) { DataRow dr = dt.NewRow(); for (int j = 0; j < list[i].Count; j++) { dr[j] = list[i][j]; } dt.Rows.Add(dr); } } return dt; } MessageBox.Show("无可粘贴的数据", "提示"); return null; } catch (Exception) { MessageBox.Show("数据无法解析", "提示"); return null; } } private void ComboColumn_DrawItem(object sender, DrawItemEventArgs e) { if (e.Index < 0) { return; } System.Windows.Forms.ComboBox combo = sender as System.Windows.Forms.ComboBox; // 当前的ComboBox控件 e.DrawBackground(); e.DrawFocusRectangle(); e.Graphics.DrawString( combo.GetItemText(combo.Items[e.Index]), e.Font, new SolidBrush(e.ForeColor), e.Bounds.X, e.Bounds.Y + 5); SolidBrush myBrush = new SolidBrush(combo.ForeColor); // 字体颜色 Font ft = combo.Font; // 获取在属性中设置的字体 // 选项的文本 string itemText = combo.GetItemText(combo.Items[e.Index]); // 计算字符串尺寸(以像素为单位) SizeF ss = e.Graphics.MeasureString(itemText, combo.Font); // 水平居中 float left = 0; if (left < 0) { left = 0f; } // 垂直居中 float top = (float)(e.Bounds.Height - ss.Height) / 2; if (top <= 0) { top = 0f; } // 输出 e.DrawBackground(); e.Graphics.DrawString( itemText, ft, myBrush, new RectangleF( e.Bounds.X + left, // 设置X坐标偏移量 e.Bounds.Y + top, // 设置Y坐标偏移量 e.Bounds.Width, e.Bounds.Height), StringFormat.GenericDefault); // e.Graphics.DrawString(cmb.GetItemText(cmb.Items[e.Index]), ft, myBrush, e.Bounds, StringFormat.GenericDefault); e.DrawFocusRectangle(); } private void ComboColumn_SelectedIndexChanged(object sender, EventArgs e) { this.SearchDataOnce(); } private void gridViewMain_CellValueChanging(object sender, CellValueChangedEventArgs e) { if (e.RowHandle >= 0) { int index = this.gridViewMain.GetDataSourceRowIndex(e.RowHandle); if (this.gridViewMain.DataSource is DataView dataTable) { //dataTable.Table.Rows[index][e.Column.AbsoluteIndex] = dataTable.Table.Rows[index][e.Column.AbsoluteIndex].DeepClone(); } else if (this.gridViewMain.DataSource is IList collection) { if (index <= collection.Count) { collection[index] = collection[index].DeepClone(); } } } } private void GridViewMain_CellValueChanged(object sender, CellValueChangedEventArgs e) { foreach (GridColumn col in this.gridViewMain.Columns) { col.OptionsColumn.AllowEdit = false; } if (e.RowHandle >= 0) { if (this.gridViewMain.DataSource is DataView dataView) { if (this.type == typeof(WellCurve)) { DataRow dr = dataView.Table.Rows[e.RowHandle]; if (dr["JH"] != null && dr["RowID"] != null && dr["DEPTH"] != null) { WellCurve wellCurve = new WellCurve(); Dictionary rowValues = new Dictionary(); foreach (DataColumn column in dataView.Table.Columns) { if (column.ColumnName == "JH") { wellCurve.JH = dr["JH"].ToString(); } else if (column.ColumnName == "RowID") { wellCurve.RowID = Convert.ToInt32(dr["RowID"].ToString()); } else if (column.ColumnName == "DEPTH") { wellCurve.DEPTH = Convert.ToDouble(dr["DEPTH"].ToString()); } else { rowValues[column.ColumnName] = dr[column].ToString(); } } wellCurve.ColumnValue = JsonConvert.SerializeObject(rowValues); DBHelp.NewDb.Updateable(wellCurve).IgnoreColumns(x => new { x.JH, x.RowID }).Where(x => x.RowID == wellCurve.RowID && x.JH == wellCurve.JH).ExecuteCommand(); } } else if (this.type == typeof(HoriWellFracturParameter)) { DataRow dr = dataView.Table.Rows[e.RowHandle]; if (dr["JH"] != null && dr["RowID"] != null) { HoriWellFracturParameter wellCurve = new HoriWellFracturParameter(); Dictionary rowValues = new Dictionary(); foreach (DataColumn column in dataView.Table.Columns) { if (column.ColumnName == "JH") { wellCurve.JH = dr["JH"].ToString(); } else if (column.ColumnName == "RowID") { wellCurve.RowID = Convert.ToInt32(dr["RowID"].ToString()); } else if (column.ColumnName == "SYWZ1") { wellCurve.SYWZ1 = Convert.ToDouble(dr["SYWZ1"].ToString()); } else if (column.ColumnName == "SYWZ2") { wellCurve.SYWZ2 = Convert.ToDouble(dr["SYWZ2"].ToString()); } else { rowValues[column.ColumnName] = dr[column].ToString(); } } wellCurve.ColumnValue = JsonConvert.SerializeObject(rowValues); DBHelp.NewDb.Updateable(wellCurve).IgnoreColumns(x => new { x.JH, x.RowID, x.XHID }).Where(x => x.RowID == wellCurve.RowID && x.JH == wellCurve.JH).ExecuteCommand(); } } } this.UpdateToolState(); } } private void GridViewMain_DoubleClick(object sender, EventArgs e) { //Point pt = this.gridControl1.PointToClient(Cursor.Position); //GridHitInfo info = this.gridViewMain.CalcHitInfo(pt); //if (info.Column != null) //{ // this.gridViewMain.FocusedRowHandle = info.RowHandle; // info.Column.OptionsColumn.AllowEdit = true; // this.gridViewMain.ShowEditor(); //} } private void GridViewMain_MouseDown(object sender, MouseEventArgs e) { GridView view = sender as GridView; GridHitInfo hitInfo = view.CalcHitInfo(e.Location); if (hitInfo.InRowCell) { hitInfo.Column.OptionsColumn.AllowEdit = true; view.ClearSelection(); view.SelectRow(hitInfo.RowHandle); view.FocusedRowHandle = hitInfo.RowHandle; view.FocusedColumn = hitInfo.Column; DXMouseEventArgs.GetMouseArgs(e).Handled = true; if (e.Clicks == 2 && e.Button == MouseButtons.Left) { view.ShowEditor(); view.ActiveEditor.SelectAll(); } else if (hitInfo.Column.FieldName == "Setting") { view.ShowEditor(); } } } private void GridViewMain_FocusedColumnChanged(object sender, FocusedColumnChangedEventArgs e) { GridView view = sender as GridView; foreach (GridColumn col in view.Columns) { if (col.FieldName != "Setting") { col.OptionsColumn.AllowEdit = false; } } } private List SetFieldSortValue(List list, string fieldName, int start = 0) { foreach (var item in list) { start++; Type type = item.GetType(); PropertyInfo propertyInfo = type.GetProperty(fieldName); if (propertyInfo != null && propertyInfo.PropertyType.IsAssignableFrom(start.GetType())) { propertyInfo.SetValue(item, start); } } return list; } // 异步分页加载数据 /// /// Loads the data async. /// /// The query. /// The page count. /// A Task. private async Task LoadDataAsync(ISugarQueryable query, int pageCount) { this.gridViewMain.Columns.Clear(); if (this.type == typeof(WellCurve)) { string tableName = DBHelp.GetTableName(this.type); this.UpdateCustomColumnInfo(tableName); //读取文件 List list = await query.ToListAsync(); //获取 WellCurveFile wellCurveFile = list.First() as WellCurveFile; string filename = FileHelp.Convert2AbsolutePath(wellCurveFile.FilePath); DataTable dataTable = new DataTable(); LasHelper.LasFileToDataTable(ref dataTable, filename, EncodingType.GetType(filename)?.BodyName, 0); foreach (GridColumn col in this.gridViewMain.Columns) { if (!dataTable.Columns.Contains(col.FieldName)) { dataTable.Columns.Add(col.FieldName, col.ColumnType ?? typeof(string)); } } this.gridControl1.DataSource = dataTable; } else if (this.type == typeof(HoriWellFracturParameter)) { string tableName = DBHelp.GetTableName(this.type); this.UpdateCustomColumnInfo(tableName); List list = await query.ToListAsync(); this.gridViewMain.PopulateColumns(); this.gridControl1.DataSource = DataHelp.ResTableByList(list); } else if (DataHelp.IsDrillwelllayeredGroupByLayer && this.type == typeof(InterpretDrillWellLayered)) { this.UpdateColumnInfo(); //这里有错 ,应该先去层位数据结构 AsyncBindingList bindinglist = new AsyncBindingList(); int pageIndex = 1; List list = await query.ToPageListAsync(pageIndex++, pageCount); if (list == null) { return; } foreach (GridColumn col in this.gridViewMain.Columns) { col.OptionsColumn.AllowEdit = false; } var wellLayers = list.OfType(); //分层计算 var lst = wellLayers.GroupBy(x => x.JH).Select(x => new InterpretDrillWellLayered() { JH = x.Key, CW = this.property, X = x.First().X, Y = x.First().Y, DJSD = x.Max(c => c.DJSD), SD = x.Min(c => c.SD), CWID = x.Min(c => c.CWID), CS_T = x.Min(c => c.CS_T), CS_B = x.Max(c => c.CS_B), HD = getHD(x.Max(c => c.DJSD), x.Min(c => c.SD)), V_HD = getHD(x.Max(c => c.CS_B), x.Min(c => c.CS_T)), HBSD1 = x.Max(c => c.HBSD1), HBSD2 = x.Min(c => c.HBSD2), //HBHD = getHD(x.Max(c => c.HBSD2), x.Min(c => c.HBSD1)), }); bindinglist.AddRange(lst, false); string lx = "井位分层"; List listSettings = DBHelp.NewDb.Queryable().Where(o => o.SJLX == lx).ToList(); RepositoryItemCheckEdit repositoryItemCheckEdit1 = new RepositoryItemCheckEdit(); repositoryItemCheckEdit1.CheckedChanged += (a, b) => { //this.gridViewMain.PostEditor(); }; this.gridViewMain.CustomUnboundColumnData += (a, e) => { if (e.Column.FieldName == "Setting") { if (e.Row is InterpretDrillWellLayered row) { string jh = row.JH; string cw = row.CW; int level = 0; if (e.IsGetData) { var obj = listSettings.FirstOrDefault(o => o.SJLX == lx && o.JH == jh && o.CW == cw); e.Value = obj == null; } else if (e.IsSetData) { if (e.Value is bool bCheck) { if (!bCheck) { var maxID = DBHelp.NewDb.Queryable().Max(x => x.ID); var obj = new CcsjWellSetting { ID = maxID + 1, SJLX = lx, JH = jh, CW = cw, CWJB = level, YSBS = true, }; DBHelp.NewDb.Insertable(obj).ExecuteCommand(); listSettings.Add(obj); } else { var obj = listSettings.FirstOrDefault(o => o.SJLX == lx && o.JH == jh && o.CW == cw && o.CWJB == level); if (obj != null) { listSettings.Remove(obj); } DBHelp.NewDb.Deleteable() .Where(o => o.SJLX == lx && o.JH == jh && o.CW == cw && o.CWJB == level) .ExecuteCommand(); } } } } } }; var colCheck = new GridColumn { UnboundType = DevExpress.Data.UnboundColumnType.Boolean, Caption = "选择", FieldName = "Setting", ColumnEdit = repositoryItemCheckEdit1, Visible = true, }; this.gridViewMain.Columns.Add(colCheck); // 添加表头复选框列 colCheck.OptionsColumn.AllowEdit = true; colCheck.VisibleIndex = 0; this.gridControl1.DataSource = bindinglist; double? getHD(double? a, double? b) { if (a.HasValue && b.HasValue) { return Math.Abs(Math.Round(a.Value - b.Value, 2)); } return default(double?); } } else if (this.type == typeof(WellTestTotal)) { this.UpdateColumnInfo(); AsyncBindingList bindinglist = new AsyncBindingList(); List list = new List(); query.ForEach(x => { list.Add(x); }, KPageCount); bindinglist.AddRange(list, false); this.gridControl1.DataSource = bindinglist; string[] columnsToHide = { "X", "Y", "BlockName", "XHID", "Block" }; foreach (string colName in columnsToHide) { var column = this.gridViewMain.Columns[colName]; if (column != null) { column.Visible = false; } } } else { AsyncBindingList bindinglist = new AsyncBindingList(); List list = new List(); if (this.type == typeof(WellDeflection)) { string tableName = DBHelp.GetTableName(this.type); this.UpdateCustomColumnInfo(tableName); //因为查询条件是单口井 WellDeflection wd = query.First() as WellDeflection; if (wd != null && !string.IsNullOrWhiteSpace(wd.FileName)) { string filePath = Path.Combine(EntityHelp.WellDeflectionPath, wd.FileName); if (File.Exists(filePath)) { byte[] datas = File.ReadAllBytes(filePath); List wds = MessagePackSerializer.Deserialize>(datas); var showDatas = wds.Take(KPageCount); list.AddRange(showDatas); this.SetFieldSortValue(list, "XHID", 0); } foreach (GridColumn col in this.gridViewMain.Columns) { col.Visible = true; } //string[] columnsToHide = { "X", "Y", "BlockName", "XHID", "Block" }; //foreach (string colName in columnsToHide) //{ // var column = this.gridViewMain.Columns[colName]; // if (column != null) // { // column.Visible = false; // } //} } } else { this.UpdateColumnInfo(); query.ForEach(x => { list.Add(x); }, KPageCount); } bindinglist.AddRange(list, false); this.gridControl1.DataSource = bindinglist; //this.UpdateColumnInfo(); //AsyncBindingList bindinglist = new AsyncBindingList(); //List list = new List(); //query.ForEach(x => //{ // list.Add(x); //}, KPageCount); //if (this.type == typeof(WellDeflection)) //{ // //因为查询条件是单口井 // this.SetFieldSortValue(list, "XHID", 0); //} //bindinglist.AddRange(list, false); //this.gridControl1.DataSource = bindinglist; } } private void MakeLastRowVisible() { GridViewInfo viewInfo = this.gridViewMain.GetViewInfo() as GridViewInfo; if (viewInfo.RowsInfo.Count > 0) { this.gridViewMain.MakeRowVisible(viewInfo.RowsInfo.Last().RowHandle); } } /// /// Saves the data async if. /// /// The action. /// A Task. private async Task SaveDataAsyncIf(Action action = null) where T : class, new() { if (this.type == typeof(T)) { await this.SaveDataImplAsync(); action?.Invoke(); } if (typeof(T) == typeof(WellBase)) { this.DataSaved?.Invoke(this, EventArgs.Empty); } KEPDataManager.NotifyChange(); } private async Task SaveDataImplAsync() where T : class, new() { if (this.gridViewMain.DataSource is IHistoryList history) { await DBHelp.NewDb.UseTranAsync(async db => { // 插入 { List list = history.History.Where(r => r.ChangedType == ListChangedType.ItemAdded) .Select(r => r.New as T).ToList(); if (list.Count > 0) { await db.Insertable(list).ExecuteCommandAsync(); if (typeof(T) == typeof(InterpretDrillWellLayered) || typeof(T).IsSubclassOf(typeof(ReservoirDataBase))) { await db.Insertable(list).AS(DBHelp.GetTableOriginName()).ExecuteCommandAsync(); } } } // 删除 { List list = history.History.Where(r => r.ChangedType == ListChangedType.ItemDeleted) .Select(r => r.Old as T).ToList(); if (list.Count > 0) { await db.Deleteable(list).ExecuteCommandAsync(); //同时删除原始数据 if (typeof(T) == typeof(InterpretDrillWellLayered) || typeof(T).IsSubclassOf(typeof(ReservoirDataBase))) { await db.Deleteable(list).AS(DBHelp.GetTableOriginName()).ExecuteCommandAsync(); } } } // 更新 { List list = history.History.Where(r => r.ChangedType == ListChangedType.ItemChanged) .Select(r => r.New as T).ToList(); if (list.Count > 0) { await db.Updateable(list).ExecuteCommandAsync(); if (typeof(T) == typeof(InterpretDrillWellLayered) || typeof(T).IsSubclassOf(typeof(ReservoirDataBase))) { await db.Updateable(list).AS(DBHelp.GetTableOriginName()).ExecuteCommandAsync(); } } } }); history.ClearHistory(); this.UpdateToolState(); } } private void SearchDataOnce() { void SearchData() { using (SplashHelper.Create()) { string key = this.combo_column.ComboBox.SelectedValue.ToString(); string value = this.txt_select.Text; if (string.IsNullOrWhiteSpace(value)) { this.gridViewMain.ActiveFilterString = null; } else { if (key != "全部") { this.gridViewMain.ActiveFilterString = string.Format( "Contains([{0}],'{1}')", key, value); } else { StringBuilder sb = new StringBuilder(); foreach (GridColumn col in this.gridViewMain.Columns) { sb.AppendFormat("Contains([{0}],'{1}')", col.FieldName, value); sb.Append(" or "); } if (sb.Length > 4) { sb.Length -= 4; } this.gridViewMain.ActiveFilterString = sb.ToString(); } } } } this.timer.Invoke(SearchData); } private void TbSearch_TextChanged(object sender, EventArgs e) { this.SearchDataOnce(); } private void ToolStrip1_Paint(object sender, PaintEventArgs e) { if ((sender as ToolStrip).RenderMode == ToolStripRenderMode.System) { Rectangle rect = new Rectangle(0, 0, this.toolStrip1.Width, this.toolStrip1.Height - 2); e.Graphics.SetClip(rect); } } /// /// Updates the column info. /// /// The array. private void UpdateColumnInfo() { List columns = DBHelp.GetEntityColumnInfo(this.type).Where(x => x.IsIgnore == false) .Select(r => new ColumnData { Caption = r.DbColumnName, FieldName = r.PropertyInfo.Name }).ToList(); foreach (ColumnData col in columns) { TableInfo caption = this.listColumnNames.FirstOrDefault( r => r.ColumnName.Equals(col.FieldName, StringComparison.OrdinalIgnoreCase)); if (caption != null) { col.Caption = caption.ChineseName; } } this.combo_column.ComboBox.DisplayMember = "Caption"; this.combo_column.ComboBox.ValueMember = "FieldName"; List tmp = new List(); tmp.Add(new ColumnData { Caption = "全部", FieldName = "全部" }); tmp.AddRange(columns); this.combo_column.ComboBox.DataSource = tmp; foreach (ColumnData col in columns.OrderByList(this.listColumnNames, (a, b) => a.Caption == b.ChineseName)) { TableInfo tableinfo = this.listColumnNames.FirstOrDefault(o => o.ChineseName == col.Caption); GridColumn gc = new GridColumn { Caption = col.Caption, FieldName = col.FieldName, Visible = !(tableinfo?.Show == "否"), }; gc.OptionsColumn.AllowEdit = false; this.gridViewMain.Columns.Add(gc); } foreach (GridColumn col in this.gridViewMain.Columns) { if (col.FieldName.Equals("ID", StringComparison.CurrentCultureIgnoreCase) || col.FieldName.Equals("Unique", StringComparison.CurrentCultureIgnoreCase) || col.FieldName.Equals("GQID", StringComparison.CurrentCultureIgnoreCase) || col.FieldName.Equals("CWID", StringComparison.CurrentCultureIgnoreCase) || col.FieldName.Equals("Data", StringComparison.CurrentCultureIgnoreCase)) { col.Visible = false; } if (DataHelp.IsDrillwelllayeredGroupByLayer && col.FieldName.Equals("XHID", StringComparison.CurrentCultureIgnoreCase)) { col.Visible = false; } } } /// /// 自定义列 /// private void UpdateCustomColumnInfo(string tableName) { List columns = DBHelp.NewDb.Queryable().Where(x => x.TableName == tableName).Select(r => new ColumnData { Caption = r.ChineseName, FieldName = r.ColumnName, }).ToList(); foreach (ColumnData col in columns) { TableInfo caption = this.listColumnNames.FirstOrDefault( r => r.ColumnName.Equals(col.FieldName, StringComparison.OrdinalIgnoreCase)); if (caption != null) { col.Caption = caption.ChineseName; } } this.combo_column.ComboBox.DisplayMember = "Caption"; this.combo_column.ComboBox.ValueMember = "FieldName"; List tmp = new List(); tmp.Add(new ColumnData { Caption = "全部", FieldName = "全部" }); tmp.AddRange(columns); this.combo_column.ComboBox.DataSource = tmp; foreach (ColumnData col in columns.OrderByList(this.listColumnNames, (a, b) => a.Caption == b.ChineseName)) { try { TableInfo tableinfo = this.listColumnNames.FirstOrDefault(o => o.ChineseName == col.Caption); GridColumn gc = new GridColumn { Caption = col.Caption, FieldName = col.FieldName, Visible = !(tableinfo?.Show == "否"), }; if (tableinfo.ColumnType == "浮点" || tableinfo.ColumnType == "整数") { gc.SortMode = DevExpress.XtraGrid.ColumnSortMode.Custom; } gc.OptionsColumn.AllowEdit = false; this.gridViewMain.Columns.Add(gc); } catch (Exception) { } } this.gridViewMain.CustomColumnSort += (sender, e) => { // 自定义排序逻辑,例如将字符串转换为数字后排序 try { if (e.Value1 != DBNull.Value && e.Value2 != DBNull.Value) { if (double.TryParse(e.Value1.ToString(), out double val1) && double.TryParse(e.Value2.ToString(), out double val2)) { e.Result = Comparer.Default.Compare(val1, val2); e.Handled = true; } } } catch (Exception) { } }; foreach (GridColumn col in this.gridViewMain.Columns) { col.Visible = true; if (col.FieldName.Equals("ID", StringComparison.CurrentCultureIgnoreCase) || col.FieldName.Equals("Unique", StringComparison.CurrentCultureIgnoreCase) || col.FieldName.Equals("GQID", StringComparison.CurrentCultureIgnoreCase) || col.FieldName.Equals("CWID", StringComparison.CurrentCultureIgnoreCase) || col.FieldName.Equals("Data", StringComparison.CurrentCultureIgnoreCase)) { col.Visible = false; } } } private void UpdateToolState() { if (this.gridViewMain.DataSource is IHistoryList history) { this.btnSave.Enabled = history.UndoCount > 0; this.btnUndo.Enabled = history.UndoCount > 0; this.btnRedo.Enabled = history.RedoCount > 0; } else { this.btnSave.Enabled = false; this.btnUndo.Enabled = false; this.btnRedo.Enabled = false; } } private void gridViewMain_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e) { if (e.Info.IsRowIndicator && e.RowHandle >= 0) { e.Info.DisplayText = (e.RowHandle + 1).ToString(); } else { e.Info.DisplayText = $"行号"; } } private void gridViewMain_CustomColumnDisplayText(object sender, CustomColumnDisplayTextEventArgs e) { if (this.listDictionary != null && this.listDictionary.Any(r => r.ColumnName == e.Column.FieldName)) { SysDictionary obj = this.listDictionary.FirstOrDefault(r => r.ColumnName == e.Column.FieldName && r.Key.Equals(e.Value)); if (obj != null) { e.DisplayText = obj.Value; } } } // 重复数据样式 private void gridViewMain_RowStyle(object sender, RowStyleEventArgs e) { var obj = this.gridViewMain.GetRow(e.RowHandle); if (obj != null) { foreach (var item in this.duplicate) { if (item.Rows.Contains(obj)) { e.Appearance.BackColor = item.Color; break; } } } } // 重复数据筛选 private void gridViewMain_CustomRowFilter(object sender, RowFilterEventArgs e) { if (this.duplicate.Count > 0 && this.gridViewMain.DataSource is IList list) { var obj = list[e.ListSourceRow]; e.Handled = true; e.Visible = false; foreach (var item in this.duplicate) { if (item.Rows.Contains(obj)) { e.Visible = true; break; } } } } private void btn_formula_Click(object sender, EventArgs e) { FormulaData fd = new FormulaData() { CalcFormula = this.CalcFormula, RefreshView = this.RefreshView, }; List columns = DBHelp.GetEntityColumnInfo(this.type) .Select(r => new ColumnData { Caption = r.DbColumnName, FieldName = r.PropertyInfo.Name, Info = r }) .ToList(); int index = 0; foreach (ColumnData col in columns) { TableInfo ti = this.listColumnNames.FirstOrDefault( r => r.ColumnName.Equals(col.FieldName, StringComparison.OrdinalIgnoreCase)); if (ti != null && ti.ColumnType == "浮点") { col.Caption = ti.ChineseName; col.Variable = $"{Convert.ToChar('a' + index++)}"; fd.ColumnList.Add(col); } else if (col.FieldName == "X" || col.FieldName == "Y") { col.Variable = $"{Convert.ToChar('a' + index++)}"; fd.ColumnList.Add(col); } } var frm = new FrmDataFormula(fd); frm.Show(this); } private void btn_find_duplicate_Click(object sender, EventArgs e) { List columns = DBHelp.GetEntityColumnInfo(this.type).Where(x => x.PropertyInfo.Name != "Unique") .Select(r => new ColumnData { Caption = r.DbColumnName, FieldName = r.PropertyInfo.Name, Info = r }) .ToList(); foreach (ColumnData col in columns) { TableInfo ti = this.listColumnNames.FirstOrDefault( r => r.ColumnName.Equals(col.FieldName, StringComparison.OrdinalIgnoreCase)); if (ti != null && !string.IsNullOrWhiteSpace(ti.ChineseName)) { col.Caption = ti.ChineseName; } } var frm = new FrmSelectColumn(columns); if (frm.ShowDialog() == DialogResult.OK) { var selectedColumns = frm.SelectedColumns; if (selectedColumns.Count > 0) { var listColors = new List(); using (SplashHelper splash = SplashHelper.Create()) { if (this.gridViewMain.DataSource is IList list) { var lookup = list.OfType() .ToLookup(o => string.Join(",", selectedColumns.Select(k => o.GetPropertyValue(k.FieldName)))); this.duplicate.Clear(); foreach (var item in lookup) { var listRow = item.ToList(); if (listRow.Count < 2) { continue; } Color color; do { color = Color.FromArgb(this.randomGen.Next(22, 222), this.randomGen.Next(22, 222), this.randomGen.Next(22, 222)); } while (listColors.Contains(color) || color.GetBrightness() < 0.4); listColors.Add(color); this.duplicate.Add(new DuplicateData { Key = item.Key, Color = color, Rows = listRow, }); } if (this.duplicate.Count > 0) { this.RefreshView(); } } } } else { this.duplicate.Clear(); this.RefreshView(); } } } private void RefreshView() { this.gridViewMain.RefreshData(); } /// /// 计算数据 /// /// 目标 /// 公式 /// 列信息数组 private void CalcFormula(ColumnData target, string formula, List listColumn) { if (this.gridViewMain.DataSource is IList list) { var processor = new Processor(); var exp = processor.Parse(formula); var edited = new Dictionary(); foreach (var item in list) { var parameters = new ExpressionParameters(); foreach (var cd in listColumn) { parameters.Add(new Parameter(cd.Variable, cd.FieldName)); } var value = exp.Execute(parameters); if (value is NumberValue nv) { var newItem = item.DeepClone(); newItem.SetPropertyValue(target.FieldName, nv.Number); edited[list.IndexOf(item)] = newItem; } } if (edited.Count > 0) { foreach (var kv in edited) { list[kv.Key] = kv.Value; } this.UpdateToolState(); } } } /// /// Class ColumnData. /// public class ColumnData { /// /// Gets or sets the caption. /// /// The caption. public string Caption { get; set; } /// /// Gets or sets the name of the field. /// /// The name of the field. public string FieldName { get; set; } /// /// Gets or sets the name of the Variable. /// public string Variable { get; set; } /// /// Info /// internal EntityColumnInfo Info { get; set; } } /// /// class FormulaData /// public class FormulaData { /// /// ColumnData /// public List ColumnList { get; } = new List(); /// /// 数据运算回调, 参数1是目标列, 参数2是公式, 参数3是列数组 /// public Action> CalcFormula { get; set; } /// /// 刷新界面 /// public Action RefreshView { get; set; } } /// /// Class Operation. /// private class Operation { /// /// Gets or sets the data. /// /// The data. public object Data { get; set; } /// /// Gets or sets the type. /// /// The type. public ListChangedType Type { get; set; } } private class DuplicateData { /// /// Key /// public string Key { get; set; } /// /// Color /// public Color Color { get; set; } /// /// Rows /// public List Rows { get; set; } } } }