年度变更建库软件5.0版本
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1241 lines
56 KiB

6 months ago
using Aspose.Cells;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using KGIS.Framework.AE;
using KGIS.Framework.AE.ExtensionMethod;
using KGIS.Framework.DBOperator;
using KGIS.Framework.Maps;
using KGIS.Framework.Platform;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.ExtensionMethod;
using KGIS.Framework.Utils.Helper;
using Kingo.PluginServiceInterface;
using KUI.Windows;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
namespace Kingo.Plugin.ProofManager.View
{
/// <summary>
/// UCDBCheckSetting.xaml 的交互逻辑
/// </summary>
public partial class UCDBSetting : BaseWindow
{
ConfigModel cfg = null;
ProjectInfo prj = null;
IFeatureClass jctbFc = null;
IFeatureLayer jctbLayer = null;
List<LoadFile> loadFiles_yjz = null;
List<LoadFile> loadFiles_djz = null;
IWorkCatalog _workCatalog = null;
public UCDBSetting()
{
InitializeComponent();
prj = (ProjectInfo)MapsManager.Instance.CurrProjectInfo;
if (_workCatalog == null)
{
_workCatalog = UIShell.OSGi.BundleRuntime.Instance.GetFirstOrDefaultService<IWorkCatalog>();
}
if (prj != null)
{
//FindJZCGDBFile(prj.DBPath);
FindJZCGDBFile(System.IO.Path.Combine(_workCatalog.SaveWorkSapcePath, prj.ProWorkDir, "举证成果"));
}
//this.Radio_relation.IsChecked = true;
}
public void FindJZCGDBFile(string dirPath)
{
if (!Directory.Exists(dirPath))
MessageHelper.ShowWarning("不存在该路径:" + dirPath);
DirectoryInfo FileDir = new DirectoryInfo(dirPath);
List<FileInfo> listFile = new List<FileInfo>();
loadFiles_yjz = new List<LoadFile>();
loadFiles_djz = new List<LoadFile>();
DataTable DbPathdataTab = null;
LoadFile LoadFile = null;
string sqlwhere = string.Empty;
try
{
listFile.AddRange(FileDir.GetFiles("*.db", SearchOption.AllDirectories));
string dbPath = $"{(MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).ProjDir}\\BGTJ.sqlite";
IRDBHelper rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
DbPathdataTab = rdbHelper.ExecuteDatatable("DbPath", "select * from DBFILEINFO ", true);
if (DbPathdataTab != null && DbPathdataTab.Rows.Count > 0)
{
foreach (DataRow dtrow in DbPathdataTab.Rows)
{
LoadFile = new LoadFile()
{
FileName = dtrow["FileName"].ToString(),
FileSize = dtrow["FileSize"].ToString(),
IsChecked = (bool)dtrow["IsChecked"],
ParengFolder = dtrow["ParengFolder"].ToString(),
Extension = dtrow["Extension"].ToString(),
TBName = dtrow["TBName"].ToString(),
};
loadFiles_yjz.Add(LoadFile);
}
this.dgFileData_yjz.ItemsSource = loadFiles_yjz;
}
foreach (var file in listFile)
{
DbPathdataTab = SQLiteDBOperate.Instance.ExceDataTable(file.FullName, $"select name from sqlite_master where type = 'table' and name in ('DCHSXX','TBJBXX','FJ') ");
if (DbPathdataTab != null && DbPathdataTab.Rows.Count == 3)
{
var existfile = loadFiles_yjz.Where(x => x.FileName == file.Name).ToList();
if (existfile != null && existfile.Count > 0)
continue;
LoadFile = new LoadFile()
{
FileName = file.Name,
FileSize = $"{Math.Round(((decimal)file.Length) / 1024 / 1024 / 1024, 2)}G",
IsChecked = false,
ParengFolder = file.DirectoryName,
Extension = file.Extension,
TBName = string.Join(", ", DbPathdataTab.Rows.OfType<DataRow>().Select(r => r[0].ToString()))
};
loadFiles_djz.Add(LoadFile);
}
}
this.dgFileData_djz.ItemsSource = loadFiles_djz;
}
catch (Exception ex)
{
throw ex;
}
}
private void BtnSelectExcelFile_Click(object sender, RoutedEventArgs e)
{
try
{
string Filter = "";
Filter = "外业核实记录列表|*.xlsx";
KGIS.Framework.Utils.Dialog.OpenFileDialog openFileDialog = new KGIS.Framework.Utils.Dialog.OpenFileDialog();
openFileDialog.Title = "选择外业核实记录文件";
openFileDialog.Filter = Filter;
openFileDialog.FileName = string.Empty;
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
openFileDialog.DefaultExt = "xlsx";
if (openFileDialog.ShowDialog())
{
txtExcelPath.Text = openFileDialog.FileName;
}
}
catch (Exception ex)
{
LogAPI.Debug(ex.Message);
}
}
private void BtnOK_Click(object sender, RoutedEventArgs e)
{
try
{
if (loadFiles_djz.Count == 0)
{
MessageHelper.Show("未检测到可加载的数据,请先确认文件是否存在...");
return;
}
var selectfile = loadFiles_djz.Where(x => x.IsChecked == true).ToList();
if (selectfile.Count == 0)
{
MessageHelper.Show("请选择要加载的文件...");
return;
}
IFeatureLayer bgtblayer = MapsManager.Instance.MapService.GetFeatureLayerByName("DLTBBG");
if (bgtblayer == null)
{
MessageHelper.Show("未找到变更图斑范围,请确认图层是否存在!");
return;
}
this.ShowLoading("正在加载数据...", 0, 0);
string dbPath = $"{(MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).ProjDir}\\BGTJ.sqlite";
IRDBHelper rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
IWorkspace workspace = (bgtblayer.FeatureClass as FeatureClass).Workspace;
IWorkspace pOutWork = new SqlWorkspaceFactoryClass().OpenFromFile(dbPath, 0);
rdbHelper.ExecuteSQL(" drop table DLTBBG ");
TableToTable(workspace as IFeatureWorkspace, pOutWork, "DLTBBG");
var BGTBData = rdbHelper.ExecuteDatatable("tab", " select distinct TBYBH from DLTBBG ", true);
var bgtbcount = BGTBData.Rows.OfType<DataRow>().Select(r => $"{r["TBYBH"].ToString()}").ToList();
if (loadFiles_djz.Count > 0)
{
List<string> listSQL = new List<string>();
DataTable Mergedt = null;
string tableName = string.Empty;
string DbPath = string.Empty;
DataTable dt = null;
#region .db文件
listSQL.Clear();
Mergedt = null;
var selectdb = loadFiles_djz.Where(x => x.IsChecked == true).ToList();
foreach (var file in selectdb)
{
DbPath = $"{file.ParengFolder}\\{file.FileName}";
rdbHelper.ExecuteSQL($" delete from hcdb_relation WHERE DbPath='{DbPath}' ");
dt = SQLiteDBOperate.Instance.ExceDataTable(DbPath, $"select BSM,'{DbPath}' as DbPath,a.KZXX as KZXX, b.KZXX as bKZXX,TBFW,TBLX,XZQDM,XMC,TBBH,TBMC,BZ,TBMJ,XZB,YZB,WYHSQK,SDDLDM,DCSJ from TBJBXX a ,DCHSXX b on a.BSM=b.TBBSM");
if (dt != null && dt.Rows.Count > 0)
{
SQLiteDBOperate.Instance.OnlySQL($"alter table FJ add column 'isSelected' bool default true", DbPath);//添加isSelected 是否选择照片字段
foreach (DataRow row in dt.Rows)
{
listSQL.Add($"insert into hcdb_relation (TBBH,DbPath) values('{row["TBBH"]}','{row["DbPath"]}');");
}
if (Mergedt == null)
Mergedt = dt.Clone();
Mergedt.Merge(dt);
rdbHelper.ExecuteSQL($" delete from DBFILEINFO WHERE FileName='{file.FileName}' ");
listSQL.Add($"insert into DBFILEINFO (FileName,FileSize,IsChecked,ParengFolder,Extension,TBName) values('{file.FileName}','{file.FileSize}','{file.IsChecked}','{file.ParengFolder}','{file.Extension}','{file.TBName}')");
}
}
if (Mergedt != null && Mergedt.Rows.Count > 0)
{
DataView dv = new DataView(Mergedt);
if (dv.Count != dv.ToTable(true, "TBBH").Rows.Count)//判断是否存在TBBH重复数据
{
if (MessageHelper.ShowYesNoAndTips("当前数据中存在图斑编号重复数据,是否仅保留最新数据。") == System.Windows.Forms.DialogResult.Yes)
{
Mergedt = GetDistinctSelf(Mergedt, "TBBH");
}
}
IFeatureCursor InsertCursor = null;
IFeatureBuffer buffer = null;
var rowcount = Mergedt.Rows.Count;
var num = 0;
List<DataDicTionary> dic = Platform.Instance.DicHelper.GetNoGroupDic(DicTypeEnum.DLBM);
IFeatureLayer jctblayer = MapsManager.Instance.MapService.GetFeatureLayerByName("JCTB");
IFields fields_jc = jctblayer.FeatureClass.Fields;
IQueryFilter queryFilter = new QueryFilterClass();
Dictionary<int, string> dicMatchFields = new Dictionary<int, string>();
GetMatchFieldsDirectory(jctblayer, fields_jc, Mergedt, ref dicMatchFields);
Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
CEsadk(jctblayer, ref keyValuePairs);
foreach (DataRow row in Mergedt.Rows)
{
num++;
queryFilter.WhereClause = "";
if (num % 100 == 0 || num == rowcount)
this.UpdateMsg($"举证成果设置中...【{num}/{rowcount}】");
IGeometry geo = GetPolygonFromWkt(row["TBFW"].ToTrim());
if (geo == null || geo.IsEmpty) continue;
//var count = BGTBData.Rows.OfType<DataRow>().Select(r => $"{r["TBYBH"].ToString()}").ToList();
if (bgtbcount.Contains(row["TBBH"].ToString())) continue;//存在监测编号 不处理
#region 加载外业信息To监测图斑 IsUpDataJC是否要把DB中的信息更新到监测图斑中
if (jctblayer != null && !string.IsNullOrWhiteSpace(row["TBBH"].ToTrim()) && IsUpDataJC.IsChecked == true)
{
queryFilter.WhereClause = string.Format("JCBH='{0}'", row["TBBH"].ToTrim());//默认JCBH是唯一值
IFeatureCursor cursor_jc = jctblayer.FeatureClass.Update(queryFilter, true);
IFeature feature_jc = null;
if ((feature_jc = cursor_jc.NextFeature()) != null)
{ //监测图斑匹配上的,则修改
for (int i = 0; i < fields_jc.FieldCount; i++)
{
IField field_jc = fields_jc.get_Field(i);
if (field_jc.Name == "TBFW") continue;
if (field_jc.Name == "WYHSXX")
{
feature_jc.Value[jctblayer.FeatureClass.FindField("WYHSXX")] = row["WYHSQK"].ToTrim();
continue;
}
if (field_jc.Name == "BGDL")
{
feature_jc.Value[jctblayer.FeatureClass.FindField("BGDL")] = row["SDDLDM"].ToTrim();
continue;
}
if ("TBMJ,XZB,YZB".Contains(field_jc.Name))
{
if (string.IsNullOrWhiteSpace(row[field_jc.Name].ToTrim())) continue;
feature_jc.Value[i] = Convert.ToDouble(row[field_jc.Name].ToTrim());
continue;
}
if (field_jc.Name == "KZXX" || field_jc.Name == "HSX" || field_jc.Name == "DDTC" || field_jc.Name == "TZ" || field_jc.Name == "SJLY")
{
Dictionary<string, object> dicJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(row["KZXX"].ToTrim());
if (dicJson != null)
{
if (field_jc.Name == "SJLY")
feature_jc.Value[jctblayer.FeatureClass.FindField("SJLY")] = dicJson.FirstOrDefault(q => q.Key == field_jc.Name).Value.ToString() == "1" ? "GJJC" : "ZZBG";
else if (field_jc.Name == "KZXX")
feature_jc.Value[jctblayer.FeatureClass.FindField(field_jc.Name)] = row["KZXX"].ToTrim();
else
{
feature_jc.Value[jctblayer.FeatureClass.FindField(field_jc.Name)] = dicJson.FirstOrDefault(q => q.Key == field_jc.Name).Value?.ToString();
}
}
continue;
}
if (field_jc.Name == "BGFW" || field_jc.Name == "WBGLX" || field_jc.Name == "LJBZ")
{
Dictionary<string, object> dicJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(row["bKZXX"].ToTrim());
if (dicJson != null)
{
feature_jc.Value[jctblayer.FeatureClass.FindField(field_jc.Name)] = dicJson.FirstOrDefault(q => q.Key == field_jc.Name).Value?.ToString();
}
continue;
}
if (Mergedt.Columns.Contains(field_jc.Name))
feature_jc.Value[i] = row[field_jc.Name].ToTrim();//字段直接匹配上的
}
cursor_jc.UpdateFeature(feature_jc);
cursor_jc.Flush();
}
else
{ //匹配不上则添加
IFeatureBuffer bufferJC = jctblayer.FeatureClass.CreateFeatureBuffer();
IFeatureCursor T_Cursor = jctblayer.FeatureClass.Insert(true);
bufferJC.Shape = geo;
for (int i = 0; i < fields_jc.FieldCount; i++)
{
IField field_jc = fields_jc.get_Field(i);
if (field_jc.Name == "TBFW") continue;
if (field_jc.Name == "TBBH" || field_jc.Name == "JCBH")
{
bufferJC.Value[jctblayer.FeatureClass.FindField(field_jc.Name)] = row["TBBH"].ToTrim();//测试项
continue;
}
if (field_jc.Name == "WYHSXX")
{
bufferJC.Value[jctblayer.FeatureClass.FindField("WYHSXX")] = row["WYHSQK"].ToTrim();
continue;
}
if (field_jc.Name == "BGDL")
{
if (row["SDDLDM"].ToTrim().Length > field_jc.Length) continue;
bufferJC.Value[jctblayer.FeatureClass.FindField("BGDL")] = row["SDDLDM"].ToTrim();
continue;
}
if ("TBMJ,XZB,YZB".Contains(field_jc.Name))
{
if (string.IsNullOrWhiteSpace(row[field_jc.Name].ToTrim())) continue;
bufferJC.Value[i] = Convert.ToDouble(row[field_jc.Name].ToTrim());
continue;
}
if (field_jc.Name == "KZXX" || field_jc.Name == "HSX" || field_jc.Name == "DDTC" || field_jc.Name == "TZ" || field_jc.Name == "SJLY")
{
Dictionary<string, object> dicJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(row["KZXX"].ToTrim());
if (dicJson != null)
{
if (field_jc.Name == "SJLY")
bufferJC.Value[jctblayer.FeatureClass.FindField("SJLY")] = dicJson.FirstOrDefault(q => q.Key == field_jc.Name).Value.ToString() == "1" ? "GJJC" : "ZZBG";
else if (field_jc.Name == "KZXX")
bufferJC.Value[jctblayer.FeatureClass.FindField(field_jc.Name)] = row["KZXX"].ToTrim();
else
{
bufferJC.Value[jctblayer.FeatureClass.FindField(field_jc.Name)] = dicJson.FirstOrDefault(q => q.Key == field_jc.Name).Value?.ToString();
}
}
continue;
}
if (field_jc.Name == "BGFW" || field_jc.Name == "WBGLX" || field_jc.Name == "LJBZ")
{
Dictionary<string, object> dicJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(row["bKZXX"].ToTrim());
if (dicJson != null)
{
bufferJC.Value[jctblayer.FeatureClass.FindField(field_jc.Name)] = dicJson.FirstOrDefault(q => q.Key == field_jc.Name).Value?.ToString();
}
continue;
}
if (Mergedt.Columns.Contains(field_jc.Name))
bufferJC.Value[i] = row[field_jc.Name].ToTrim();//字段直接匹配上的
}
T_Cursor.InsertFeature(bufferJC);
T_Cursor.Flush();
Marshal.ReleaseComObject(T_Cursor);
Marshal.ReleaseComObject(bufferJC);
}
}
#endregion
try
{
List<IFeature> features = FeatureAPI.Identify2(geo, bgtblayer);
if (features.Count > 0)//1.存在空间关系
{
foreach (var f in features)
{
int iTBYBH = f.Fields.FindField("TBYBH");
if (iTBYBH != -1)
{
f.Value[iTBYBH] = row["TBBH"].ToString();
f.Store();
}
}
}
else if (IsLoadGeo.IsChecked == true) //2.不存在空间关系
{
if (InsertCursor == null)
InsertCursor = bgtblayer.FeatureClass.Insert(true);
if (buffer == null)
buffer = bgtblayer.FeatureClass.CreateFeatureBuffer();
buffer.Shape = geo;
Dictionary<string, object> dicJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(row["KZXX"].ToTrim());
if (dicJson != null)
{
int fieldIndex = bgtblayer.FeatureClass.FindField("DLBM");
if (dicJson.ContainsKey("DLBM"))
{
if (fieldIndex != -1)
{
buffer.Value[fieldIndex] = dicJson["DLBM"].ToTrim();
}
fieldIndex = bgtblayer.FeatureClass.FindField("DLMC");
if (fieldIndex != -1)
{
var dlmc = dic.FirstOrDefault(x => x.CODE == dicJson["DLBM"].ToTrim());
if (dlmc != null)
buffer.Value[fieldIndex] = dlmc.NAME;
}
}
fieldIndex = bgtblayer.FeatureClass.FindField("TBYBH");
if (fieldIndex != -1 && Mergedt.Columns.Contains("TBBH"))
{
buffer.Value[fieldIndex] = row["TBBH"].ToTrim();
}
}
InsertCursor.InsertFeature(buffer);
Marshal.ReleaseComObject(geo);
}
}
catch
{
LogAPI.Debug($"转换失败:{row["TBBH"].ToString()}");
continue;
}
}
if (IsLoadGeo.IsChecked == true && InsertCursor != null)
{
InsertCursor.Flush();
//修复逆时针图形
KGIS.Framework.AE.GPHelper.GeoprocessorHelper.RepairGeo(bgtblayer.FeatureClass, true);
}
InsertDB(listSQL, dbPath);
//修复要素,防止SHAPE_AREA为负数
KGIS.Framework.AE.GPHelper.GeoprocessorHelper.RepairGeo(jctblayer.FeatureClass, true);
}
#endregion
}
if (File.Exists(txtExcelPath.Text))
{
//return;
Workbook wb = new Workbook(txtExcelPath.Text);
Worksheet ws = wb.Worksheets[0];
if (ws.Cells.Rows.Count == 0)
return;
string jcbhArr = string.Empty;
Dictionary<string, string> wyhsjlDic = new Dictionary<string, string>();
for (int i = 3; i < ws.Cells.Rows.Count; i++)//跳过标题与列头
{
string jcbh = ws.Cells[i, 6].Value.ToString();//监测编号
string wyhsjl = string.Empty;
if (ws.Cells[i, 22].Value != null)
{
wyhsjl = ws.Cells[i, 22].Value.ToString();
}
wyhsjlDic.Add(jcbh, wyhsjl);
jcbhArr += string.Format("'{0}',", jcbh);
}
if (!string.IsNullOrWhiteSpace(jcbhArr))
{
jcbhArr = jcbhArr.Substring(0, jcbhArr.Length - 1);
}
if (wyhsjlDic.Count != 0)
{
IFeatureClass jcFC = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBBG");
if (jcFC != null)
{
IQueryFilter queryfiler = new QueryFilterClass();
queryfiler.WhereClause = string.Format("BSM in ({0})", jcbhArr);
IFeatureCursor pCursour = jcFC.Search(queryfiler, false);
IFeature pFeature = null;
int wyhsjlIndex = jcFC.FindField("WYHSJL");
int jcbhIndex = jcFC.FindField("TBBH");
if (wyhsjlIndex > -1 && jcbhIndex > -1)
{
while ((pFeature = pCursour.NextFeature()) != null)
{
string jcbh = pFeature.Value[jcbhIndex].ToString();
string wyhsjl = wyhsjlDic.FirstOrDefault(x => x.Key == jcbh).Value;
pFeature.Value[wyhsjlIndex] = wyhsjl;
pFeature.Store();
}
}
}
}
}
this.CloseLoading();
Marshal.ReleaseComObject(bgtblayer);
Marshal.ReleaseComObject(workspace);
MessageHelper.Show("举证包设置完成");
this.Close();
}
catch (Exception ex)
{
this.CloseLoading();
LogAPI.Debug(ex);
MessageHelper.Show(ex.Message);
}
}
#region 根据DHSJ 删除重复TBBH的数据
public DataTable GetDistinctSelf(DataTable SourceDt, string filedName)
{
for (int i = SourceDt.Rows.Count - 2; i > 0; i--)
{
DataRow[] rows = SourceDt.Select($"{filedName}='{SourceDt.Rows[i][filedName]}'");
if (rows.Length > 1)
{
List<DataRow> rows1 = rows.OrderByDescending(x => x["DCSJ"]).ToList();
for (int j = 0; j < rows1.Count; j++)
{
if (j == 0) continue;
SourceDt.Rows.Remove(rows1[j]);
}
}
}
return SourceDt;
}
private void InsertDB(List<string> listSQL, string dbPath)
{
try
{
using (BlockingCollection<string> blockingCollection = new BlockingCollection<string>())
{
listSQL.ForEach(x => blockingCollection.Add(x));
blockingCollection.CompleteAdding();
int taskNum = 5;
Task[] tasks = new Task[taskNum];
for (int i = 0; i < taskNum; i++)
{
tasks[i] = Task.Factory.StartNew(() =>
{
ExcuteThead(blockingCollection, dbPath);
});
}
Task.WaitAll(tasks);
for (int i = 0; i < taskNum; i++)
{
tasks[i].Dispose();
}
}
}
catch (Exception ex)
{
throw ex;
}
}
private void ExcuteThead(BlockingCollection<string> blockingCollection, string dbPath)
{
IRDBHelper rdbHelper = null;
string sqlDe = string.Empty;
try
{
rdbHelper = RDBFactory.CreateDbHelper(string.Format("Data Source={0};Initial Catalog=sqlite;Integrated Security=True;Max Pool Size=10;", dbPath), DatabaseType.SQLite);
if (rdbHelper == null)
{
throw new Exception("执行成果接收时打开数据库连接字符串失败!");
}
rdbHelper.BeginTransaction();
foreach (string sql in blockingCollection.GetConsumingEnumerable())
{
sqlDe = sql;
rdbHelper.ExecuteNonQueryWithException(sql, CommandType.Text);
}
rdbHelper.Commit();
}
catch (Exception ex)
{
if (rdbHelper != null)
{
rdbHelper.Rollback();
}
LogAPI.Debug(sqlDe);
LogAPI.Debug(ex);
throw ex;
}
finally
{
if (rdbHelper != null)
{
rdbHelper.DisConnect();
}
}
}
#endregion
/// <summary>
/// 加载外业信息To监测图斑 IsUpDataJC是否要把DB中的信息更新到监测图斑中
/// </summary>
/// <param name="jctblayer"></param>
/// <param name="queryFilter"></param>
/// <param name="dicMatchFields"></param>
/// <param name="row"></param>
/// <param name="Mergedt"></param>
/// <param name="geo"></param>
private void UpdateDataToJCTB(IFeatureLayer jctblayer, IQueryFilter queryFilter, Dictionary<int, string> dicMatchFields, DataRow row, DataTable Mergedt, IGeometry geo, Dictionary<string, string> keyValuePairs)
{
try
{
if (!string.IsNullOrWhiteSpace(row["TBBH"].ToTrim()) && IsUpDataJC.IsChecked == true)
{
if (keyValuePairs.Keys.Contains(row["TBBH"].ToTrim()))
{
IRow feature_jc = (jctblayer.FeatureClass as ITable).GetRow(Convert.ToInt32(keyValuePairs[row["TBBH"].ToTrim()]));
foreach (int key in dicMatchFields.Keys)
{
if ("TBMJ,XZB,YZB".Contains(dicMatchFields[key]))
{
if (string.IsNullOrWhiteSpace(row[dicMatchFields[key]].ToTrim())) continue;
feature_jc.Value[key] = Convert.ToDouble(row[dicMatchFields[key]].ToTrim());
continue;
}
if (dicMatchFields[key] == "SDDLDM")
{
feature_jc.Value[jctblayer.FeatureClass.FindField("BGDL")] = row["SDDLDM"].ToTrim();
}
else
feature_jc.Value[key] = row[dicMatchFields[key]];
}
if (!string.IsNullOrWhiteSpace(row["KZXX"].ToTrim()))
{
Dictionary<string, object> dicJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(row["KZXX"].ToTrim());
if (dicJson != null)
{
foreach (var item in dicJson)
{
if (/*item.Key == "TBLX" || */item.Value == null || jctblayer.FeatureClass.FindField(item.Key) == -1) continue;
if (item.Key == "SJLY")
{
feature_jc.Value[jctblayer.FeatureClass.FindField(item.Key)] = item.Value.ToString() == "1" ? "GJJC" : "ZZBG";
continue;
}
if (jctblayer.FeatureClass.FindField(item.Key) != -1)
feature_jc.Value[jctblayer.FeatureClass.FindField(item.Key)] = item.Value.ToString();
}
}
}
feature_jc.Store();
Marshal.ReleaseComObject(feature_jc);
}
else
{ //匹配不上则添加
IFeatureBuffer bufferJC = jctblayer.FeatureClass.CreateFeatureBuffer();
IFeatureCursor T_Cursor = jctblayer.FeatureClass.Insert(true);
bufferJC.Shape = geo;
foreach (int key in dicMatchFields.Keys)
{
if ("TBMJ,XZB,YZB".Contains(dicMatchFields[key]))
{
if (string.IsNullOrWhiteSpace(row[dicMatchFields[key]].ToTrim())) continue;
bufferJC.Value[key] = Convert.ToDouble(row[dicMatchFields[key]].ToTrim());
continue;
}
if (dicMatchFields[key] == "SDDLDM")
{
bufferJC.Value[jctblayer.FeatureClass.FindField("BGDL")] = row["SDDLDM"].ToTrim();
}
else
bufferJC.Value[key] = row[dicMatchFields[key]];
}
if (!string.IsNullOrWhiteSpace(row["KZXX"].ToTrim()))
{
Dictionary<string, object> dicJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(row["KZXX"].ToTrim());
if (dicJson != null)
{
foreach (var item in dicJson)
{
if (/*item.Key == "TBLX" || */item.Value == null || jctblayer.FeatureClass.FindField(item.Key) == -1) continue;
if (item.Key == "SJLY")
{
bufferJC.Value[jctblayer.FeatureClass.FindField(item.Key)] = item.Value.ToString() == "1" ? "GJJC" : "ZZBG";
continue;
}
if (jctblayer.FeatureClass.FindField(item.Key) != -1)
bufferJC.Value[jctblayer.FeatureClass.FindField(item.Key)] = item.Value.ToString();
}
}
}
//try
//{
// T_Cursor.InsertFeature(bufferJC);
//}
//catch (Exception eee)
//{
//}
T_Cursor.InsertFeature(bufferJC);
T_Cursor.Flush();
Marshal.ReleaseComObject(T_Cursor);
Marshal.ReleaseComObject(bufferJC);
}
}
}
catch (Exception ee)
{
return;
}
}
private void CEsadk(IFeatureLayer jctblayer, ref Dictionary<string, string> keyValuePairs)
{
ICursor pCur = null;
IRow pRow = null;
IQueryDef pQDef = ((jctblayer.FeatureClass as FeatureClass).Workspace as IFeatureWorkspace).CreateQueryDef();
pQDef.Tables = "JCTB";
pQDef.WhereClause = " 1=1 AND JCBH<>'' ";
pQDef.SubFields = "OBJECTID,JCBH,BSM,TBBH";//NYRDDL替换当前基础图斑地类
pCur = pQDef.Evaluate();
while ((pRow = pCur.NextRow()) != null)
{
if (!string.IsNullOrWhiteSpace(pRow.get_Value(1).ToString()))
{
keyValuePairs[pRow.get_Value(1).ToString()] = pRow.get_Value(0).ToString();
}
Marshal.ReleaseComObject(pRow);
}
}
private static void GetMatchFieldsDirectory(IFeatureLayer jctblayer, IFields fields_jc, DataTable Mergedt, ref Dictionary<int, string> dicMatchFields)
{
for (int i = 0; i < fields_jc.FieldCount; i++)
{
IField field_jc = fields_jc.get_Field(i);
if (field_jc.Required == false && field_jc.Editable == true)
{
if ("TBLX,TBFW".Contains(field_jc.Name)) continue;
if (field_jc.Name == "JCBH")
{
dicMatchFields.Add(i, "TBBH");
continue;
}
if (field_jc.Name == "WYHSXX")
{
dicMatchFields.Add(i, "WYHSQK");
continue;
}
if (field_jc.Name == "BGDL")
{
dicMatchFields.Add(i, "SDDLDM");
continue;
}
if (Mergedt.Columns.Contains(field_jc.Name))
dicMatchFields.Add(i, field_jc.Name);
}
}
}
public bool TableToTable(IFeatureWorkspace pInWork, IWorkspace pOutWork, string tableName, IQueryFilter queryFilter = null)
{
try
{
if (pInWork == null || pOutWork == null || string.IsNullOrEmpty(tableName)) return false;
IWorkspace2 workspace2 = pInWork as IWorkspace2;
if (workspace2 != null)
{
if (!workspace2.get_NameExists(esriDatasetType.esriDTFeatureClass, tableName))
{
return false;
}
}
ITable pInTable = pInWork.OpenTable(tableName);
if (pInTable == null) return false;
IDataset pIndataset = (IDataset)pInTable;
IDatasetName pInDatasetName = (IDatasetName)pIndataset.FullName;
IEnumDataset enumDataset = pOutWork.get_Datasets(esriDatasetType.esriDTTable);
IDataset dataset;
enumDataset.Reset();
while ((dataset = enumDataset.Next()) != null)
{
string[] names = dataset.Name.Split('.');
if (string.Equals(names[names.Length - 1], tableName, StringComparison.CurrentCultureIgnoreCase))
{
dataset.Delete();
break;
}
}
IDataset pOutDataset = (IDataset)pOutWork;
IDatasetName pOutDatasetName = new TableNameClass();
pOutDatasetName.WorkspaceName = (IWorkspaceName)pOutDataset.FullName;
pOutDatasetName.Name = tableName;
IFieldChecker fieldChecker = new FieldCheckerClass();
IFields targetFeatureClassFields = pInTable.Fields;
IFields sourceFeatureClassFields = pInTable.Fields;
IEnumFieldError enumFieldError;
fieldChecker.InputWorkspace = pInWork as IWorkspace;
fieldChecker.ValidateWorkspace = pOutWork;
fieldChecker.Validate(sourceFeatureClassFields, out enumFieldError, out targetFeatureClassFields);
IFeatureDataConverter one2another = new FeatureDataConverterClass();
try
{
one2another.ConvertTable(pInDatasetName, queryFilter, pOutDatasetName, targetFeatureClassFields, "", 1000, 0);
}
finally
{
Marshal.ReleaseComObject(one2another);
}
return true;
}
catch (Exception ex)
{
LogAPI.Debug(ex);
throw ex;
}
}
private void InherentAttribute(IFeatureBuffer feature, IGeometry pGeo)
{
try
{
if (jctbLayer == null)
jctbLayer = MapsManager.Instance.MapService.GetFeatureLayerByName("JC_DLTB");
if (jctbLayer == null) return;
string fields = "QSXZ,ZLDWDM,ZLDWMC,QSDWDM,QSDWMC,GDDB,FRDBS,MSSM,HDMC";
List<IFeature> jcfeatures = FeatureAPI.Identify(pGeo, jctbLayer);
IFeature f = null;
double area = 0;
foreach (var item in jcfeatures)
{
try
{
IArea topo = FeatureAPI.InterSect(item.ShapeCopy, feature.Shape) as IArea;
if (f == null)
{
f = item;
if (topo != null)
area = topo.Area;
continue;
}
if (topo != null)
{
if (area < topo.Area)
{
f = item;
area = topo.Area;
}
}
}
catch (Exception ex)
{
LogAPI.Debug(ex);
}
}
if (f == null) return;
for (int i = 0; i < feature.Fields.FieldCount; i++)
{
IField field = feature.Fields.Field[i];
if (fields.Contains(field.Name))
{
int idx = f.Fields.FindField(field.Name);
feature.Value[i] = f.Value[idx];
}
}
}
catch (Exception ex)
{
LogAPI.Debug(ex);
}
}
private IGeometry GetPolygonFromWkt(string pointsStr)
{
//OSGeo.OGR.Ogr.RegisterAll();
IGeometry geometry = new PolygonClass();
OSGeo.OGR.Geometry rstGeometry = OSGeo.OGR.Geometry.CreateFromWkt(pointsStr);
byte[] geometryBytes = new byte[rstGeometry.WkbSize()];
rstGeometry.ExportToWkb(geometryBytes);
IGeometryFactory3 factory = new GeometryEnvironment() as IGeometryFactory3;
int bytesLen = geometryBytes.Length;
factory.CreateGeometryFromWkbVariant(geometryBytes, out geometry, out bytesLen);
IPolygon polygon = geometry as IPolygon;
polygon.Close();
ITopologicalOperator pBoundaryTop = polygon as ITopologicalOperator;
pBoundaryTop.Simplify();
return geometry;
}
private void BtnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void chkSelectedAll_EditValueChanged(object sender, DevExpress.Xpf.Editors.EditValueChangedEventArgs e)
{
try
{
if (this.loadFiles_djz != null && this.loadFiles_djz.Count > 0)
{
bool check = (sender as DevExpress.Xpf.Editors.CheckEdit).IsChecked == null ? false : bool.Parse((sender as DevExpress.Xpf.Editors.CheckEdit).IsChecked.Value.ToString());
this.loadFiles_djz.ForEach(x => x.IsChecked = check);
this.dgFileData_djz.ItemsSource = loadFiles_djz;
this.dgFileData_djz.RefreshData();
}
}
catch (Exception ex)
{
MessageHelper.ShowError("全选发生异常:" + ex.Message);
}
}
#region 删除当前行
private void Txt_Delete_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
try
{
var del = sender as System.Windows.Controls.TextBlock;
if (del != null)
{
string dbPath = $"{(MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).ProjDir}\\BGTJ.sqlite";
IRDBHelper rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
rdbHelper.ExecuteSQL($" delete from DBFILEINFO WHERE FileName='{del.Tag}' ");
var delfile = loadFiles_yjz.FirstOrDefault(x => x.FileName == del.Tag.ToString());
if (delfile != null)
loadFiles_yjz.Remove(delfile);
FindJZCGDBFile(System.IO.Path.Combine(_workCatalog.SaveWorkSapcePath, prj.ProWorkDir, "举证成果"));
this.dgFileData_djz.RefreshData();
this.dgFileData_yjz.RefreshData();
}
}
catch (Exception ex)
{
LogAPI.Debug("删除举证包设置信息失败:" + ex.Message);
}
}
#endregion
}
public class BCFSToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
BCFS s = (BCFS)value;
return s == (BCFS)int.Parse(parameter.ToString());
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool isChecked = (bool)value;
if (!isChecked)
{
return null;
}
return (BCFS)int.Parse(parameter.ToString());
}
}
public enum BCFS
{
Cover,
Add
}
public class ConfigModel : INotifyPropertyChanged
{
private string _DbPath;
private string _shpPath;
private string _yXFWPath;
private string _zPFWPath;
private bool _isExtractVectorFromDB;
private bool _isExtractVectorFromFile;
private bool _isExtractVectorFromExcelFile;
private bool _isInherentAttribute;
private BCFS _bcfs;
public int ShowIndex { get; set; }
public string DbPath
{
get
{
return _DbPath;
}
set
{
_DbPath = value;
OnPropertyChanged("DbPath");
}
}
public string ShpPath
{
get
{
return _shpPath;
}
set
{
_shpPath = value;
OnPropertyChanged("ShpPath");
}
}
private string _excelPath;
public string ExcelPath
{
get
{
return _excelPath;
}
set
{
_excelPath = value;
OnPropertyChanged("ExcelPath");
}
}
public string YXFWPath
{
get
{
return _yXFWPath;
}
set
{
_yXFWPath = value;
OnPropertyChanged("YXFWPath");
}
}
public string ZPFWPath
{
get
{
return _zPFWPath;
}
set
{
_zPFWPath = value;
OnPropertyChanged("ZPFWPath");
}
}
public bool IsExtractVectorFromDB
{
get
{
return _isExtractVectorFromDB;
}
set
{
if (value)
IsExtractVectorFromFile = !value;
_isExtractVectorFromDB = value;
OnPropertyChanged("IsExtractVectorFromDB");
}
}
public bool IsExtractVectorFromFile
{
get
{
return _isExtractVectorFromFile;
}
set
{
if (value)
IsExtractVectorFromDB = !value;
_isExtractVectorFromFile = value;
OnPropertyChanged("IsExtractVectorFromFile");
}
}
public bool IsExtractVectorFromExcelFile
{
get
{
return _isExtractVectorFromExcelFile;
}
set
{
if (value)
IsExtractVectorFromDB = !value;
_isExtractVectorFromExcelFile = value;
OnPropertyChanged("IsExtractVectorFromExcelFile");
}
}
public BCFS bcfs
{
get
{
return _bcfs;
}
set
{
_bcfs = value;
OnPropertyChanged("bcfs");
}
}
public bool IsInherentAttribute
{
get
{
return _isInherentAttribute;
}
set
{
_isInherentAttribute = value;
OnPropertyChanged("IsInherentAttribute");
}
}
public int CacheNum { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public bool Save(ProjectInfo prj)
{
try
{
if (prj == null) return false;
if (string.IsNullOrWhiteSpace(prj.ProjDir))
{
return false;
}
//将对象序列化成字符串
string Str = SerializeAPI.SerializeToXML<ConfigModel>(this);
Byte[] bytearr = Encoding.UTF8.GetBytes(Str);
//对字符串进行加密
//Byte[] resultArray = AesEncrypt(Str, "58ef12f9891a4cd89fa7bdd181ef13a7");
//修改人:李进营 修改时间 增加using引用
using (Stream stream = new System.IO.FileStream(prj.ProjDir + "\\" + "DbSetting.cfg", FileMode.Create, FileAccess.Write, FileShare.None))
{
stream.Write(bytearr, 0, bytearr.Length);
stream.Close();
}
return true;
}
catch (Exception ex)
{
LogAPI.Debug(ex);
return false;
}
}
}
public partial class LoadFile : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private int _id;
public int ID
{
get { return _id; }
set
{
_id = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("ID"));
}
}
}
private string _fileName;
public string FileName
{
get { return _fileName; }
set
{
_fileName = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("FileName"));
}
}
}
private string _fileSize;
/// <summary>
/// 文件大小
/// </summary>
public string FileSize
{
get { return _fileSize; }
set
{
_fileSize = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("FileSize"));
}
}
}
private bool _isChecked = false;
public bool IsChecked
{
set
{
_isChecked = value;
if (PropertyChanged != null)//有改变
{
PropertyChanged(this, new PropertyChangedEventArgs("IsChecked"));//对Name进行监听
}
}
get
{
return _isChecked;
}
}
private string _parengFolder;
public string ParengFolder
{
get { return _parengFolder; }
set
{
_parengFolder = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("ParengFolder"));
}
}
}
private string _extension;
/// <summary>
/// 文件扩展名
/// </summary>
public string Extension
{
get { return _extension; }
set
{
_extension = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Extension"));
}
}
}
private string _TBName;
/// <summary>
/// 数据表名称
/// </summary>
public string TBName
{
get { return _TBName; }
set
{
_TBName = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("TBName"));
}
}
}
}
}