You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1814 lines
72 KiB
C#

1 month ago
// ***********************************************************************
// Assembly : Construction
// Author : flythink
// Created : 06-05-2020
//
// Last Modified By : flythink
// Last Modified On : 09-01-2020
// ***********************************************************************
// <copyright file="FrmDataViewer.cs" company="jindongfang">
// Copyright (c) jindongfang. All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
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
{
/// <summary>
/// 数据查看控件
/// </summary>
public partial class FrmDataViewer : Form
{
/// <summary>
/// The k page count.
/// </summary>
private const int KPageCount = 10000;
private string dataName;
private string property;
private string property2;
private List<TableInfo> listColumnNames;
private List<SysDictionary> listDictionary;
private SlowDownTimer timer = new SlowDownTimer(1000);
private Type type;
private int maxId = -1;
private List<DuplicateData> duplicate = new List<DuplicateData>();
private Random randomGen = new Random();
public event EventHandler DataSaved;
/// <summary>
/// Initializes a new instance of the <see cref="FrmDataViewer" /> class.
/// </summary>
public FrmDataViewer()
{
this.InitializeComponent();
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the <see cref="FrmDataViewer"/> class.
/// </summary>
/// <param name="dataName">Name of the data.</param>
/// <param name="property">The property.</param>
/// <param name="property2">The property2.</param>
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<IReservoirData>()*/)
{
this.btn_formula.Visible = true;
}
this.toolStrip1.Enabled = enableToolbar;
}
/// <summary>
/// Gets a value indicating whether this instance is need save.
/// </summary>
/// <value><c>true</c> if this instance is need save; otherwise, <c>false</c>.</value>
public bool IsNeedSave => this.btnSave.Enabled;
/// <summary>
/// Saves the data.
/// </summary>
public void SaveData()
{
this.btnSave.PerformClick();
}
/// <summary>
/// Shows the data if.
/// </summary>
/// <param name="expression">The expression.</param>
/// <param name="order">The order.</param>
/// <returns>A Task.</returns>
private async Task ShowDataIf<T>(Expression<Func<T, bool>> expression, List<OrderByModel> orders = null)
{
if (this.type == typeof(T) || (this.type == typeof(WellCurve) && typeof(T) == typeof(WellCurveFile)))
{
ISugarQueryable<T> query = DBHelp.NewDb.Queryable<T>();
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<T>(
Expression<Func<T, bool>> expression,
Expression<Func<T, object>> orderExpression = null)
{
if (this.type == typeof(T))
{
ISugarQueryable<T> query = DBHelp.NewDb.Queryable<T>();
if (!string.IsNullOrWhiteSpace(this.property))
{
query = query.Where(expression);
}
if (orderExpression != null)
{
query = query.OrderBy(orderExpression);
}
await this.LoadDataAsync(query, KPageCount);
}
}
/// <summary>
/// Shows the data.
/// </summary>
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<OrderByModel> orderList = OrderByModel.Create(new OrderByModel() { FieldName = "xhid" });
await this.ShowDataIf<WellBase>(o => o.JH == this.property, OrderByModel.Create(new OrderByModel() { FieldName = "JH" }));
await this.ShowDataIf<WellCapacityOilMonth>(o => o.Block == this.property, orderList);
await this.ShowDataIf<WellCapacityOilYear>(o => o.Block == this.property, orderList);
await this.ShowDataIf<WellCapacityWaterMonth>(o => o.Block == this.property, orderList);
await this.ShowDataIf<WellCapacityWaterYear>(o => o.Block == this.property, orderList);
await this.ShowDataIf<WellCapacityWaterDay>(o => o.Block == this.property, orderList);
await this.ShowDataIf<WellCapacityOilDay>(o => o.Block == this.property, orderList);
await this.ShowDataIf<WellTestResult>(o => o.Block == this.property, orderList);
await this.ShowDataIf<WellTestTotal>(o => o.Block == this.property, orderList);
await this.ShowDataIf<LssxCjx>(o => o.JH == this.property);
await this.ShowDataIf<LssxSt>(o => o.JH == this.property);
await this.ShowDataIf<LssxYlsy>(o => o.JH == this.property);
await this.ShowDataIf<LssxYxsy>(o => o.JH == this.property);
await this.ShowDataIf<WellDeflection>(o => o.JH == this.property, orderList);
//await this.ShowDataIf<HoriWellFracturParameter>(o => o.JH == this.property, OrderByModel.Create(new OrderByModel() { FieldName = "XHID" }));
await this.ShowParamData<HoriWellFracturParameter>(o => o.JH == this.property, o => SqlFunc.ToInt32(o.XHID));
await this.ShowDataIf<HoriWellFracturCoord>(o => o.JH == this.property);
await this.ShowDataIf<WellCasingDamage>(o => o.GROUP == this.property, OrderByModel.Create(new OrderByModel() { FieldName = "jh" }));
//测井曲线
await this.ShowDataIf<WellCurveFile>(o => o.JH == this.property, OrderByModel.Create(new OrderByModel() { FieldName = "JH" }));
List<OrderByModel> orderList1 = OrderByModel.Create(new OrderByModel() { FieldName = "ID" });
await this.ShowDataIf<WellReservesLayer>(o => o.Well == this.property, orderList1);
await this.ShowDataIf<CycleShortterm>(o => o.Well == this.property, orderList1);
await this.ShowDataIf<CycleMediumterm>(o => o.Well == this.property, orderList1);
await this.ShowDataIf<CycleLongterm>(o => o.Well == this.property, orderList1);
await this.ShowDataIf<WellLithology>(o => o.Well == this.property, orderList1);
await this.ShowDataIf<WellInnerLayer>(o => o.Well == this.property, orderList1);
await this.ShowDataIf<WellCoring>(o => o.Well == this.property, orderList1);
await this.ShowDataIf<WellSideWallCoring>(o => o.Well == this.property, orderList1);
await this.ShowDataIf<WellWaterInjection>(o => o.Well == this.property, orderList1);
await this.ShowDataIf<WellFluidProducingProfile>(o => o.Well == this.property, orderList1);
await this.ShowDataIf<WellLithologicalAnalysis>(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<CcsjBhd>(o => o.CW == this.property, cc_orderList);
await this.ShowDataIf<CcsjKxd>(o => o.CW == this.property, cc_orderList);
await this.ShowDataIf<CcsjStl>(o => o.CW == this.property, cc_orderList);
await this.ShowDataIf<CcsjSyhd>(o => o.CW == this.property, cc_orderList);
await this.ShowDataIf<CcsjYxhd>(o => o.CW == this.property, cc_orderList);
}
else
{
if (int.TryParse(this.property2, out var level))
{
var cws = DBHelp.NewDb.Queryable<GeologicalStratification>()
.Where(o => o.Level == level)
.Select(o => o.Code)
.ToList();
await this.ShowDataIf<CcsjBhd>(o => o.JH == this.property && cws.Contains(o.CW), cc_orderList);
await this.ShowDataIf<CcsjKxd>(o => o.JH == this.property && cws.Contains(o.CW), cc_orderList);
await this.ShowDataIf<CcsjStl>(o => o.JH == this.property && cws.Contains(o.CW), cc_orderList);
await this.ShowDataIf<CcsjSyhd>(o => o.JH == this.property && cws.Contains(o.CW), cc_orderList);
await this.ShowDataIf<CcsjYxhd>(o => o.JH == this.property && cws.Contains(o.CW), cc_orderList);
}
else
{
cc_orderList = OrderByModel.Create(new OrderByModel() { FieldName = "ID" });
await this.ShowDataIf<CcsjBhd>(o => o.JH == this.property, cc_orderList);
await this.ShowDataIf<CcsjKxd>(o => o.JH == this.property, cc_orderList);
await this.ShowDataIf<CcsjStl>(o => o.JH == this.property, cc_orderList);
await this.ShowDataIf<CcsjSyhd>(o => o.JH == this.property, cc_orderList);
await this.ShowDataIf<CcsjYxhd>(o => o.JH == this.property, cc_orderList);
}
}
//if (DataHelp.IsDrillwelllayeredGroupByLayer)
//{
// //查询所有下级
// List<string> lstCw = WellDistribute.GetReservoirChildLayers(this.property);
// await this.ShowDataIf<InterpretDrillWellLayered>(o => lstCw.Contains(SqlFunc.ToUpper(o.CW)), orderList);
//}
//else
{
await this.ShowDataIf<InterpretDrillWellLayered>(o => o.JH == this.property, orderList);
}
//await this.ShowDataIf<InterpretFault>(o => o.CW == this.property, orderList);
//await this.ShowDataIf<InterpretTimeLayer>(o => o.CW == this.property, orderList);
//await this.ShowDataIf<InterpretDepthLayer>(o => o.CW == this.property, orderList);
//await this.ShowDataIf<InterpretVaildThickness>(o => o.CW == this.property, orderList);
//await this.ShowDataIf<InterpretSandThickness>(o => o.CW == this.property, orderList);
//await this.ShowDataIf<InterpretPorosity>(o => o.CW == this.property, orderList);
//await this.ShowDataIf<InterpretPenetration>(o => o.CW == this.property, orderList);
//await this.ShowDataIf<InterpretSaturation>(o => o.CW == this.property, orderList);
//await this.ShowDataIf<InterpretBoundary>(o => o.CW == this.property, orderList);
//await this.ShowDataIf<Surveyline2d>(o => true);
string[] array = this.property.Split('@');
if (array.Length > 1)
{
string arr0 = array[0];
string arr1 = array[1];
await this.ShowDataIf<InterpretAttribute>(r => r.CW == arr0 && r.Attribute == arr1, orderList);
}
if (array.Length > 0)
{
string arr0 = array[0];
await this.ShowDataIf<WellPerforation>(r => r.JH == arr0, orderList);
await this.ShowDataIf<WellBreakPoint>(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 = "合计:{0n2}";
}
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<WellBase>(DataHelp.SyncSearchWellName);
await this.SaveDataAsyncIf<InterpretDrillWellLayered>();
await this.SaveDataAsyncIf<WellDeflection>();
await this.SaveDataAsyncIf<HoriWellFracturParameter>();
await this.SaveDataAsyncIf<HoriWellFracturCoord>();
await this.SaveDataAsyncIf<WellCasingDamage>();
await this.SaveDataAsyncIf<CcsjKxd>();
await this.SaveDataAsyncIf<CcsjStl>();
await this.SaveDataAsyncIf<CcsjBhd>();
await this.SaveDataAsyncIf<CcsjSyhd>();
await this.SaveDataAsyncIf<CcsjYxhd>();
//await this.SaveDataAsyncIf<InterpretFault>();
//await this.SaveDataAsyncIf<InterpretTimeLayer>();
//await this.SaveDataAsyncIf<InterpretDepthLayer>();
//await this.SaveDataAsyncIf<InterpretSandThickness>();
//await this.SaveDataAsyncIf<InterpretVaildThickness>();
//await this.SaveDataAsyncIf<InterpretPorosity>();
//await this.SaveDataAsyncIf<InterpretPenetration>();
//await this.SaveDataAsyncIf<InterpretSaturation>();
await this.SaveDataAsyncIf<InterpretBoundary>();
await this.SaveDataAsyncIf<InterpretAttribute>();
await this.SaveDataAsyncIf<WellCurve>();
await this.SaveDataAsyncIf<WellPerforation>();
await this.SaveDataAsyncIf<WellBreakPoint>();
await this.SaveDataAsyncIf<WellCapacityOilMonth>();
await this.SaveDataAsyncIf<WellCapacityOilYear>();
await this.SaveDataAsyncIf<WellCapacityWaterMonth>();
await this.SaveDataAsyncIf<WellCapacityWaterYear>();
await this.SaveDataAsyncIf<WellCapacityWaterDay>();
await this.SaveDataAsyncIf<WellCapacityOilDay>();
await this.SaveDataAsyncIf<WellTestResult>();
await this.SaveDataAsyncIf<WellTestTotal>();
// await this.SaveDataAsyncIf<Surveyline2d>();
await this.SaveDataAsyncIf<WellReservesLayer>();
await this.SaveDataAsyncIf<CycleLongterm>();
await this.SaveDataAsyncIf<CycleShortterm>();
await this.SaveDataAsyncIf<CycleMediumterm>();
await this.SaveDataAsyncIf<WellLithology>();
await this.SaveDataAsyncIf<WellInnerLayer>();
await this.SaveDataAsyncIf<WellCoring>();
await this.SaveDataAsyncIf<WellSideWallCoring>();
await this.SaveDataAsyncIf<WellWaterInjection>();
await this.SaveDataAsyncIf<WellFluidProducingProfile>();
await this.SaveDataAsyncIf<WellLithologicalAnalysis>();
}
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<int>("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<IOrderEntity>().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<IUniqueEntity> list = collection.OfType<IUniqueEntity>()
.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<IUniqueEntity> list = collection.OfType<IUniqueEntity>()
.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<WellCapacity> 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<string>> list = new List<List<string>>();
string txt = Clipboard.GetText(TextDataFormat.Text);
string[] rows = txt.Split(
Constants.StringSplit.LineSeparator,
StringSplitOptions.RemoveEmptyEntries);
foreach (string item in rows)
{
List<string> list_row = new List<string>();
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<string, string> rowValues = new Dictionary<string, string>();
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<string, string> rowValues = new Dictionary<string, string>();
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<T> SetFieldSortValue<T>(List<T> 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;
}
// 异步分页加载数据
/// <summary>
/// Loads the data async.
/// </summary>
/// <param name="query">The query.</param>
/// <param name="pageCount">The page count.</param>
/// <returns>A Task.</returns>
private async Task LoadDataAsync<T>(ISugarQueryable<T> query, int pageCount)
{
this.gridViewMain.Columns.Clear();
if (this.type == typeof(WellCurve))
{
string tableName = DBHelp.GetTableName(this.type);
this.UpdateCustomColumnInfo(tableName);
//读取文件
List<T> 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<T> list = await query.ToListAsync();
this.gridViewMain.PopulateColumns();
this.gridControl1.DataSource = DataHelp.ResTableByList(list);
}
else if (DataHelp.IsDrillwelllayeredGroupByLayer && this.type == typeof(InterpretDrillWellLayered))
{
this.UpdateColumnInfo();
//这里有错 ,应该先去层位数据结构
AsyncBindingList<InterpretDrillWellLayered> bindinglist = new AsyncBindingList<InterpretDrillWellLayered>();
int pageIndex = 1;
List<T> 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<InterpretDrillWellLayered>();
//分层计算
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<CcsjWellSetting> listSettings = DBHelp.NewDb.Queryable<CcsjWellSetting>().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<CcsjWellSetting>().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<CcsjWellSetting>()
.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<T> bindinglist = new AsyncBindingList<T>();
List<T> list = new List<T>();
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<T> bindinglist = new AsyncBindingList<T>();
List<T> list = new List<T>();
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<T> wds = MessagePackSerializer.Deserialize<List<T>>(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<T> bindinglist = new AsyncBindingList<T>();
//List<T> list = new List<T>();
//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);
}
}
/// <summary>
/// Saves the data async if.
/// </summary>
/// <param name="action">The action.</param>
/// <returns>A Task.</returns>
private async Task SaveDataAsyncIf<T>(Action action = null)
where T : class, new()
{
if (this.type == typeof(T))
{
await this.SaveDataImplAsync<T>();
action?.Invoke();
}
if (typeof(T) == typeof(WellBase))
{
this.DataSaved?.Invoke(this, EventArgs.Empty);
}
KEPDataManager.NotifyChange<T>();
}
private async Task SaveDataImplAsync<T>()
where T : class, new()
{
if (this.gridViewMain.DataSource is IHistoryList history)
{
await DBHelp.NewDb.UseTranAsync(async db =>
{
// 插入
{
List<T> 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<T>()).ExecuteCommandAsync();
}
}
}
// 删除
{
List<T> 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<T>()).ExecuteCommandAsync();
}
}
}
// 更新
{
List<T> 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<T>()).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);
}
}
/// <summary>
/// Updates the column info.
/// </summary>
/// <param name="array">The array.</param>
private void UpdateColumnInfo()
{
List<ColumnData> 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<ColumnData> tmp = new List<ColumnData>();
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;
}
}
}
/// <summary>
/// 自定义列
/// </summary>
private void UpdateCustomColumnInfo(string tableName)
{
List<ColumnData> columns = DBHelp.NewDb.Queryable<TableInfo>().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<ColumnData> tmp = new List<ColumnData>();
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<ColumnData> 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<ColumnData> 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<Color>();
using (SplashHelper splash = SplashHelper.Create())
{
if (this.gridViewMain.DataSource is IList list)
{
var lookup = list.OfType<object>()
.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();
}
/// <summary>
/// 计算数据
/// </summary>
/// <param name="target">目标</param>
/// <param name="formula">公式</param>
/// <param name="listColumn">列信息数组</param>
private void CalcFormula(ColumnData target, string formula, List<ColumnData> listColumn)
{
if (this.gridViewMain.DataSource is IList list)
{
var processor = new Processor();
var exp = processor.Parse(formula);
var edited = new Dictionary<int, object>();
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();
}
}
}
/// <summary>
/// Class ColumnData.
/// </summary>
public class ColumnData
{
/// <summary>
/// Gets or sets the caption.
/// </summary>
/// <value>The caption.</value>
public string Caption { get; set; }
/// <summary>
/// Gets or sets the name of the field.
/// </summary>
/// <value>The name of the field.</value>
public string FieldName { get; set; }
/// <summary>
/// Gets or sets the name of the Variable.
/// </summary>
public string Variable { get; set; }
/// <summary>
/// Info
/// </summary>
internal EntityColumnInfo Info { get; set; }
}
/// <summary>
/// class FormulaData
/// </summary>
public class FormulaData
{
/// <summary>
/// ColumnData
/// </summary>
public List<ColumnData> ColumnList { get; } = new List<ColumnData>();
/// <summary>
/// 数据运算回调, 参数1是目标列, 参数2是公式, 参数3是列数组
/// </summary>
public Action<ColumnData, string, List<ColumnData>> CalcFormula { get; set; }
/// <summary>
/// 刷新界面
/// </summary>
public Action RefreshView { get; set; }
}
/// <summary>
/// Class Operation.
/// </summary>
private class Operation
{
/// <summary>
/// Gets or sets the data.
/// </summary>
/// <value>The data.</value>
public object Data { get; set; }
/// <summary>
/// Gets or sets the type.
/// </summary>
/// <value>The type.</value>
public ListChangedType Type { get; set; }
}
private class DuplicateData
{
/// <summary>
/// Key
/// </summary>
public string Key { get; set; }
/// <summary>
/// Color
/// </summary>
public Color Color { get; set; }
/// <summary>
/// Rows
/// </summary>
public List<object> Rows { get; set; }
}
}
}