feixian_weifajianguan/OpenAuth.App/BaseApp/Shape/ShpLayerSourceApp.cs

2432 lines
96 KiB
C#
Raw Permalink Normal View History

2026-02-03 16:00:02 +08:00
using System;
using System.Data;
using System.Dynamic;
using System.IO.Compression;
using System.Text;
using DocumentFormat.OpenXml.Bibliography;
using DocumentFormat.OpenXml.EMMA;
using DocumentFormat.OpenXml.Office.CustomUI;
using Infrastructure;
using Infrastructure.Extensions;
using Microsoft.Extensions.Options;
using NetTopologySuite.Geometries;
using NetTopologySuite.IO;
using NetTopologySuite.IO.Esri;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.BaseApp.Shape.Request;
using OpenAuth.App.BasicQueryService;
using OpenAuth.App.FormScheme;
using OpenAuth.App.FormScheme.FormHelpers;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.ServiceApp.ShpGeo.Request;
using OpenAuth.App.Shape.Request;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using Org.BouncyCastle.Ocsp;
using SqlSugar;
using Shapefile = NetTopologySuite.IO.Esri.Shapefile;
namespace OpenAuth.App.BaseApp.Shape;
public class ShpLayerSourceApp : SqlSugarBaseApp<ShpLayerSource, SugarDbContext>
{
private readonly string _filePath;
private readonly FormSchemeApp _formSchemeApp;
private readonly ISqlSugarClient _client;
CommonDataManager _commonDataManager;
public ShpLayerSourceApp(ISugarUnitOfWork<SugarDbContext> unitWork,
ISimpleClient<ShpLayerSource> repository, IAuth auth, FormSchemeApp formSchemeApp,
IOptions<AppSetting> setOptions, ISqlSugarClient client, CommonDataManager commonDataManager) : base(unitWork, repository, auth)
{
_filePath = setOptions.Value.UploadPath;
if (string.IsNullOrEmpty(_filePath))
{
_filePath = AppContext.BaseDirectory;
}
_formSchemeApp = formSchemeApp;
_client = client;
_commonDataManager = commonDataManager;
}
public async Task<Response<bool>> Add(ShpLayerSource obj)
{
var loginContext = _auth.GetCurrentUser();
if (loginContext == null)
{
throw new CommonException("登录已过期", Define.INVALID_TOKEN);
}
ShpLayerSource source = obj;
source.CreateTime = DateTime.Now;
source.Id = Guid.NewGuid().ToString();
source.CreateId = loginContext.User.Id.ToString();
var flag = await base.Repository.InsertAsync(source);
return new Response<bool>
{
Result = flag,
Message = flag == true ? "success" : "error"
};
}
public async Task<Response<PageInfo<List<ShpLayerSource>>>> LoadPage(ShpLayerSourceReq req)
{
RefAsync<int> totalCount = 0;
var sources = await base.Repository.AsQueryable()
.Where(c => c.Status.Equals(1))
.WhereIF(!string.IsNullOrEmpty(req.name), a => a.Name.Contains(req.name))
.ToPageListAsync(req.page, req.limit, totalCount);
return new Response<PageInfo<List<ShpLayerSource>>>
{
Result = new PageInfo<List<ShpLayerSource>>
{
Items = sources,
Total = totalCount
}
};
}
public ShpLayerSource Get(string id)
{
return base.Repository.GetById(id);
}
public Response<bool> CreateTable(string tableName)
{
//using (var db = this.CodeClient("", _configuration))
using (var db = base.Repository.AsSugarClient())
{
// 原生SQL建表语句
/* string createTableSql = @"
CREATE TABLE demo_demo_haha (
id varchar(64) NOT NULL,
enterprise_id varchar(255) ,
geom geometry(GEOMETRY),
CONSTRAINT demo_haha_pkey_hahah PRIMARY KEY (id)
);";
// 执行建表语句
db.Db.Ado.ExecuteCommand(createTableSql);
db.Commit();*/
db.Ado.BeginTran();
// todo 校验表名存不存,若存在重新生成表名
// db.DbMaintenance.IsAnyTable(tableName,false);
var typeBuilder = db.DynamicBuilder()
.CreateClass(tableName, new SugarTable() { TableName = tableName, TableDescription = "测试动态类型建表" });
List<DbColumnInput> dbColumnInfoList = new List<DbColumnInput>();
DbColumnInput col = new DbColumnInput();
// 添加主键
col.DbColumnName = "id";
col.DataType = "varchar";
col.Length = 36;
col.IsNullable = 0;
col.IsPrimarykey = 1;
col.ColumnDescription = "主键";
dbColumnInfoList.Add(col);
// 添加几何字段
col = new DbColumnInput();
col.DbColumnName = "geom";
col.DataType = "geometry(GEOMETRY, 4326)";
col.IsNullable = 1;
col.ColumnDescription = "几何图形";
dbColumnInfoList.Add(col);
dbColumnInfoList.ForEach(u =>
{
typeBuilder.CreateProperty(u.DbColumnName, typeof(string), new SugarColumn()
{
IsPrimaryKey = u.IsPrimarykey == 1,
IsIdentity = u.IsIdentity == 1,
ColumnDataType = u.DataType,
Length = u.Length,
IsNullable = u.IsNullable == 1,
DecimalDigits = u.DecimalDigits,
ColumnDescription = u.ColumnDescription,
});
});
db.CodeFirst.InitTables(typeBuilder.BuilderType());
db.Ado.CommitTran();
Console.WriteLine("Table created successfully.");
return new Response<bool>()
{
Code = 200,
Result = true,
Message = "创建成功"
};
}
}
public byte[] QueryMapbox(QueryMapboxReq req)
{
QueryVectorTileByTableReq reqCopy = new QueryVectorTileByTableReq();
reqCopy.x = req.x;
reqCopy.y = req.y;
reqCopy.z = req.z;
string serviceId = req.serviceId;
// todo 根据serviceId
// todo 查询表名
//reqCopy.table = "";
// throw new Exception("未查询到表名");
return _formSchemeApp.QueryVectorTileByTable(reqCopy);
}
[Obsolete("不再使用")]
public async Task<string> CreateGISLayer(string zipFilePath, string tableName, string srid, string serverName)
{
// _filePath 调试时路径D:\vs\project\基础框架后端svn\OpenAuth.WebApi\bin\Debug\net6.0
Console.WriteLine("项目基本目录:" + _filePath);
//zipFilePath = "C:\\Users\\Admin\\Desktop\\4490.zip";
zipFilePath = Path.Combine(_filePath, zipFilePath);
// 确保ZIP文件存在
if (!File.Exists(zipFilePath))
{
throw new FileNotFoundException("ZIP文件未找到。");
}
// 打开ZIP存档 取除后缀之前的字符串
var extractPath = zipFilePath.Substring(0, zipFilePath.LastIndexOf(".")) + "extract";
Console.WriteLine("解压根目录:" + extractPath);
await UnZip(zipFilePath, extractPath);
var searchPattern = "*.shp"; // 设置你想要遍历的文件后缀名
var fileName = Directory.GetFiles(extractPath, searchPattern, SearchOption.AllDirectories);
if (fileName.IsEmpty())
{
throw new Exception("压缩文件中无shp文件");
}
string shpFileName = fileName[0];
//Console.WriteLine($"{shpFileName}");
// shpFile 文件路径
string shpFile = Path.Combine(extractPath, shpFileName);
//Console.WriteLine($"{shpFile}");
// 动态类型插入
using (var db = Repository.AsSugarClient())
{
if (db.DbMaintenance.IsAnyTable(tableName, false))
{
throw new Exception(tableName + "已存在");
}
// 开启事务
await db.Ado.BeginTranAsync(IsolationLevel.ReadCommitted);
var typeBuilder = db.DynamicBuilder().CreateClass(tableName,
new SugarTable() { TableName = tableName, TableDescription = serverName + "图斑" });
List<DbColumnInput> dbColumnInfoList = new List<DbColumnInput>();
DbColumnInput col = new DbColumnInput();
// 添加主键
col.DbColumnName = "id";
col.DataType = "varchar";
col.Length = 36;
col.IsNullable = 0;
col.IsPrimarykey = 1;
col.ColumnDescription = "主键";
dbColumnInfoList.Add(col);
// 添加几何字段
col = new DbColumnInput();
col.DbColumnName = "geom";
col.DataType = "geometry(GEOMETRY, " + srid + ")";
col.IsNullable = 1;
col.ColumnDescription = "几何图形";
dbColumnInfoList.Add(col);
// 外键
col = new DbColumnInput();
col.DbColumnName = "relation_id";
col.Length = 36;
col.DataType = "varchar";
col.IsNullable = 1;
col.ColumnDescription = "关联图层表字段";
dbColumnInfoList.Add(col);
dbColumnInfoList.ForEach(u =>
{
typeBuilder.CreateProperty(u.DbColumnName, typeof(string), new SugarColumn()
{
IsPrimaryKey = u.IsPrimarykey == 1,
IsIdentity = u.IsIdentity == 1,
ColumnDataType = u.DataType,
Length = u.Length,
IsNullable = u.IsNullable == 1,
DecimalDigits = u.DecimalDigits,
ColumnDescription = u.ColumnDescription,
});
});
db.CodeFirst.InitTables(typeBuilder.BuilderType());
// end createTable
var loginContext = _auth.GetCurrentUser();
// 新建图层表记录
string layerId = Guid.NewGuid().ToString();
ShpLayerSource layerSource = new ShpLayerSource()
{
Id = layerId,
Name = serverName, // 图层名称
RelationTable = tableName, // 数据表表名
Srid = srid, // 空间参考
CreateTime = DateTime.Now,
CreateId = loginContext.User.Id.ToString()
};
db.Insertable(layerSource).AS("shp_layer_source")
.InsertColumns("Id", "Name", "RelationTable", "Srid", "CreateTime", "CreateId").ExecuteCommand();
foreach (var geometry in Shapefile.ReadAllGeometries(shpFile))
{
var insertObj = new Dictionary<string, object>
{
{ "id", Guid.NewGuid().ToString() },
{ "geom", geometry.AsBinary() },
{ "relation_id", layerId }
};
int insertCount = db.Insertable(insertObj)
.AS(tableName) // 指定目标表名
.InsertColumns("id", "geom", "relation_id") // 指定要插入的列
.ExecuteCommand();
}
// 提交事务
db.Ado.CommitTran();
}
Console.WriteLine("shp录入完成");
// 刪除解压文件
DeleteFile(extractPath);
return "ok";
}
private static async Task UnZip(string zipFilePath, string extractPath)
{
await Task.Run(() =>
{
Directory.CreateDirectory(extractPath);
// 设置字符编码
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var gbk = Encoding.GetEncoding("utf-8");
using (var archive = ZipFile.OpenRead(zipFilePath))
{
// 列举ZIP文件中的条目
foreach (var entry in archive.Entries)
{
var xxx = gbk.GetString(Encoding.Default.GetBytes(entry.FullName));
Console.WriteLine(xxx);
}
// 提取ZIP文件中的所有文件到指定目录
foreach (var entry in archive.Entries)
{
if (entry.Name != string.Empty)
{
// 确保完整路径存在 entry.FullName 是否可以编码
var fixedEntryName = entry.FullName.Replace("/", "");
var destinationPath = Path.GetFullPath(Path.Combine(extractPath, fixedEntryName));
Console.WriteLine("解压文件路径:" + destinationPath);
if (!destinationPath.StartsWith(Path.GetFullPath(extractPath) + Path.DirectorySeparatorChar))
{
throw new UnauthorizedAccessException("试图提取的文件超出了目标文件夹的路径边界。");
}
// 提取条目到目标路径
entry.ExtractToFile(destinationPath, overwrite: true);
}
}
}
// 遍历解压目录是否有shp后缀的文件
if (!Directory.Exists(extractPath))
{
throw new Exception("文件解压失败");
}
});
}
private static void DeleteFile(string extractPath)
{
try
{
// 递归删除目录和其内容
Directory.Delete(extractPath, true);
Console.WriteLine("解压目录删除成功");
}
catch (IOException ex)
{
Console.WriteLine("解压目录不能删除: " + ex.Message);
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine("没有权限删除解压目录: " + ex.Message);
}
}
[Obsolete("测试方法是可行,已无用")]
public async Task<string> TestReadShpFeature(string filePath)
{
filePath = Path.Combine(_filePath, filePath);
// 确保ZIP文件存在
if (!File.Exists(filePath))
{
throw new FileNotFoundException("ZIP文件未找到。");
}
// 打开ZIP存档 取除后缀之前的字符串
var extractPath = filePath.Substring(0, filePath.LastIndexOf(".")) + "extract";
await UnZip(filePath, extractPath);
var searchPattern = "*.shp"; // 设置你想要遍历的文件后缀名
string[] fileName = Directory.GetFiles(extractPath, searchPattern, SearchOption.AllDirectories);
if (fileName.IsEmpty())
{
throw new Exception("压缩文件中无shp文件");
}
var shpFileName = fileName[0];
var shpFile = Path.Combine(extractPath, shpFileName);
// 使用ShapefileDataReader读取.shp文件
using (var dataReader = new ShapefileDataReader(shpFile, GeometryFactory.Default))
{
while (dataReader.Read())
{
/*
for (var i = 0; i < dataReader.FieldCount; i++)
{
Console.WriteLine(dataReader.GetName(i));
Console.WriteLine(dataReader.GetValue(i));
}
*/
// 获取DbfDataReader用于读取属性信息
var dbfReader = dataReader.DbaseHeader;
for (var i = 0; i < dbfReader.Fields.Length; i++)
{
Console.Write(dbfReader.Fields[i].Name + " ");
Console.Write(dbfReader.Fields[i].Type + " ");
Console.Write(" " + dbfReader.Fields[i].Length);
Console.WriteLine();
}
break;
}
}
Console.WriteLine("结束运行");
/*var shpReader = Shapefile.OpenRead(shpFile);
foreach (var field in shpReader.Fields)
{
Console.Write(field.Name + " ");
Console.Write(field.FieldType);
Console.Write(" " + field.Length);
Console.WriteLine(" " + field.Value);
}*/
/*var y = Shapefile.ReadAllFeatures(shpFile);
foreach (var feature in y)
{
}*/
return "ok";
}
private static string MapDbaseTypeToPostgresString(char dbaseType)
{
return dbaseType switch
{
'C' => "varchar",
'N' => "numeric",
'L' => "boolean",
'D' => "date",
'M' => "text",
_ => "unknown"
};
}
public async Task<Response<ShpInfo>> ParseShpInfo(string zipFilePath, string serviceName, string tableName,
string srid)
{
using var db = Repository.AsSugarClient();
// 开启事务
if (db.DbMaintenance.IsAnyTable(tableName))
{
throw new Exception("表名已存在");
}
// 取得文件完全路径
zipFilePath = Path.Combine(_filePath, zipFilePath);
// 确保ZIP文件存在
if (!File.Exists(zipFilePath))
{
throw new FileNotFoundException("ZIP文件未找到。");
}
var exist = await db.Queryable<ShpLayerSource>()
.Where(c => c.RelationTable.Equals(tableName))
.Where(c => c.Status.Equals(1)) // 已发布
.CountAsync();
if (exist > 0)
{
throw new Exception(tableName + "关联图层已发布");
}
// 打开ZIP存档 取除后缀之前的字符串
var extractPath = zipFilePath.Substring(0, zipFilePath.LastIndexOf(".", StringComparison.Ordinal)) +
"extract";
// 解压文件
await UnZip(zipFilePath, extractPath);
var searchPattern = "*.shp"; // 设置你想要遍历的文件后缀名
string[] fileName = Directory.GetFiles(extractPath, searchPattern, SearchOption.AllDirectories);
if (fileName.IsEmpty())
{
throw new Exception("压缩文件中无shp文件");
}
var shpFileName = fileName[0];
var shpFile = Path.Combine(extractPath, shpFileName);
var shapeType = Shapefile.GetShapeType(shpFile);
var shpInfo = new ShpInfo();
switch (shapeType)
{
case ShapeType.Point:
shpInfo.DataType = "点";
break;
case ShapeType.Polygon:
shpInfo.DataType = "面";
break;
case ShapeType.PolyLine:
shpInfo.DataType = "线";
break;
default:
throw new Exception("不支持的shp类型: " + shapeType);
}
List<DataTableAttr> attrs = new List<DataTableAttr>();
// 添加自定义字段
var geom = new DataTableAttr
{
Name = "Geometry",
Type = string.Concat("geometry(GEOMETRY, ",
srid.AsSpan(srid.LastIndexOf(":", StringComparison.Ordinal) + 1),
")")
};
attrs.Add(geom);
using (var reader = new ShapefileDataReader(shpFile, GeometryFactory.Default))
{
// 获取DbfDataReader用于读取属性信息
var dbfReader = reader.DbaseHeader;
foreach (var dbaseFieldDescriptor in dbfReader.Fields)
{
DataTableAttr attr = new DataTableAttr();
attr.Name = dbaseFieldDescriptor.Name;
attr.Length = dbaseFieldDescriptor.Length;
attr.Type = MapDbaseTypeToPostgresString(dbaseFieldDescriptor.DbaseType);
attrs.Add(attr);
}
}
shpInfo.Headers = attrs;
// 创建图层记录
var loginContext = _auth.GetCurrentUser();
var layerId = Guid.NewGuid().ToString();
var layerSource = new ShpLayerSource()
{
Id = layerId, // guid主键
Name = serviceName, // 图层名称
RelationTable = tableName, // 数据表表名
ShpPath = zipFilePath,
Srid = srid, // 空间参考
CreateTime = DateTime.Now,
CreateId = loginContext.User.Id.ToString()
};
await db.Ado.BeginTranAsync(IsolationLevel.ReadCommitted);
// 插入图层记录
await db.Insertable(layerSource).AS("shp_layer_source")
.InsertColumns("Id", "Name", "RelationTable", "ShpPath", "Srid", "CreateTime", "CreateId")
.ExecuteCommandAsync();
await db.Ado.CommitTranAsync();
shpInfo.TableName = tableName;
return new Response<ShpInfo>()
{
Result = shpInfo,
Message = "ok"
};
}
public async Task<Response<bool>> CreateDataTable(ShpInfo shpInfo)
{
using var db = Repository.AsSugarClient();
var tableName = shpInfo.TableName;
// 校验 表是否存在
var exist = await db.Queryable<ShpLayerSource>()
.Where(c => c.RelationTable.Equals(tableName))
.Where(c => c.Status.Equals(1)) // 已发布
.CountAsync();
if (exist > 0)
{
throw new Exception(tableName + "关联图层已发布");
}
// 查询未发布图层
var shpLayerSource = await db.Queryable<ShpLayerSource>()
.Where(c => c.Name.Equals(shpInfo.serviceName))
.Where(c => c.Status.Equals(0))
.FirstAsync();
if (shpLayerSource.IsNullOrEmpty())
{
throw new Exception("未执行shp解析");
}
// 创建数据表
var typeBuilder = db.DynamicBuilder().CreateClass(tableName,
new SugarTable() { TableName = tableName, TableDescription = shpInfo.serviceName + "图斑" });
//添加主键
typeBuilder.CreateProperty("geom_id", typeof(string), new SugarColumn()
{
IsPrimaryKey = true,
IsIdentity = false,
ColumnDataType = "varchar",
Length = 36,
ColumnDescription = "主键",
});
shpInfo.Headers.ForEach(u =>
{
typeBuilder.CreateProperty(u.RefName, typeof(string), new SugarColumn()
{
IsPrimaryKey = false,
IsIdentity = false,
ColumnDataType = u.Type,
IsNullable = true,
Length = u.Length,
ColumnDescription = u.InitName,
});
});
// 开启事务
await db.Ado.BeginTranAsync(IsolationLevel.ReadCommitted);
// 创建表
db.CodeFirst.InitTables(typeBuilder.BuilderType());
// 插入图斑数据
var shpPath = shpLayerSource.ShpPath;
var extractPath = shpPath.Substring(0, shpPath.LastIndexOf(".", StringComparison.Ordinal)) + "extract";
var searchPattern = "*.shp"; // 设置你想要遍历的文件后缀名
var fileName = Directory.GetFiles(extractPath, searchPattern, SearchOption.AllDirectories);
if (fileName.IsEmpty())
{
throw new Exception("未找到shp文件");
}
string shpFileName = fileName[0];
// shpFile 文件路径
string shpFile = Path.Combine(extractPath, shpFileName);
var rows = new List<Dictionary<string, object>>();
using (var dataReader = new ShapefileDataReader(shpFile, GeometryFactory.Default))
{
while (dataReader.Read())
{
var insertObj = new Dictionary<string, object>
{
{ "geom_id", Guid.NewGuid().ToString() }
};
for (int i = 0, j = 0; i < dataReader.FieldCount; i++)
{
if (shpInfo.Headers[j].Name.Equals(dataReader.GetName(i)))
{
insertObj.Add(shpInfo.Headers[j++].RefName, dataReader.GetValue(i));
}
}
rows.Add(insertObj);
}
}
// 批量插入
var cols = new string[shpInfo.Headers.Count + 1];
for (var i = 0; i < shpInfo.Headers.Count; i++)
{
cols[i] = shpInfo.Headers[i].RefName;
}
cols[^1] = "geom_id";
await db.Insertable(rows)
.AS(tableName) // 指定目标表名
.InsertColumns(cols) // 指定要插入的列
.ExecuteCommandAsync();
// 更新图层记录
var shpLayerSourceRecord = new ShpLayerSource
{
// 设置主键
Id = shpLayerSource.Id,
// 设置图层发布状态
Status = 1
};
await db.Updateable(shpLayerSourceRecord).IgnoreNullColumns().ExecuteCommandAsync();
await db.Ado.CommitTranAsync();
return new Response<bool>()
{
Result = true,
Message = "ok"
};
}
/// <summary>
/// 发布图层
/// </summary>
/// <param name="publishLayerReq"></param>
/// <returns></returns>
public async Task<Response<bool>> PublishLayer(PublishLayerReq publishLayerReq)
{
var shpLayerSource = publishLayerReq.MapTo<ShpLayerSource>();
// 设置主键
shpLayerSource.Id = Guid.NewGuid().ToString();
// 设置发布状态
shpLayerSource.Status = 1;
var loginContext = _auth.GetCurrentUser();
shpLayerSource.CreateId = loginContext.User.Id.ToString();
shpLayerSource.CreateTime = DateTime.Now;
using var db = Repository.AsSugarClient();
await db.Ado.BeginTranAsync();
await db.Insertable(shpLayerSource).ExecuteCommandAsync();
await db.Ado.CommitTranAsync();
return new Response<bool>()
{
Result = true,
Message = "发布成功"
};
}
/// <summary>
/// 图层更新
/// </summary>
/// <param name="updateLayerReq"></param>
/// <returns></returns>
public async Task<Response<bool>> UpdateLayer(UpdateLayerReq updateLayerReq)
{
var db = Repository.AsSugarClient();
await db.Ado.BeginTranAsync();
var record = updateLayerReq.MapTo<ShpLayerSource>();
await db.Updateable(record).IgnoreNullColumns().ExecuteCommandAsync();
await db.Ado.CommitTranAsync();
return new Response<bool>()
{
Result = true,
Message = "更新成功"
};
}
/// <summary>
/// 删除图层
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<Response<bool>> DeleteLayer(string id)
{
var db = Repository.AsSugarClient();
await db.Ado.BeginTranAsync();
await db.Deleteable<ShpLayerSource>().Where(c => c.Id.Equals(id)).ExecuteCommandAsync();
await db.Ado.CommitTranAsync();
return new Response<bool>()
{
Result = true,
Message = "删除成功"
};
}
public async Task<Response<PageInfo<List<NoEntityGeom>>>> GetShapeData(ShapePageReq req)
{
var whereSql = "";
if (!req.FieldName.IsNullOrEmpty())
{
whereSql += "where " + req.FieldName + " in (";
whereSql = req.FieldValue.Aggregate(whereSql, (current, item) => current + ("'" + item + "',"));
whereSql = string.Concat(whereSql.AsSpan(0, whereSql.Length - 1), ")");
}
using var db = Repository.AsSugarClient();
/*
var sql = $"SELECT gid,ST_AsText(geom) as geom " +
$"FROM {req.TableName} {whereSql} LIMIT {req.limit} OFFSET ({req.limit} * ({req.page} - 1))";
*/
var sql = $"SELECT gid,ST_AsText(geom) as geom " +
$"FROM {req.TableName} {whereSql} LIMIT {req.limit} OFFSET ({req.limit} * ({req.page} - 1))";
var result = await db.Ado.SqlQueryAsync<NoEntityGeom>(sql);
return new Response<PageInfo<List<NoEntityGeom>>>
{
Result = new PageInfo<List<NoEntityGeom>>
{
Items = result,
Total = result.Count
}
};
}
public async Task<Response<List<string>>> SaveShapeData(ShapeDataForm req)
{
var wktReader = new WKTReader();
var rows = new List<Dictionary<string, object>>();
var ids = new List<string>();
foreach (var wkt in req.Data)
{
var geometry = wktReader.Read(wkt);
var id = Guid.NewGuid().ToString();
ids.Add(id);
var insertObj = new Dictionary<string, object>
{
{ req.GuidFieldName, id },
{ req.GeometryFieldName, geometry.AsBinary() }
};
rows.Add(insertObj);
}
using (var db = Repository.AsSugarClient())
{
await db.Ado.BeginTranAsync();
await db.Insertable(rows).AS(req.TableName).ExecuteCommandAsync();
await db.Ado.CommitTranAsync();
}
return new Response<List<string>>()
{
Result = ids,
Message = "ok"
};
}
#region 前端地图配置
/// <summary>
/// 查询配置
/// </summary>
public async Task<Response<FrontendSettingConfig>> LoadSettingConfig(string code)
{
var info = await base.Repository.ChangeRepository<SugarRepositiry<FrontendSettingConfig>>().AsQueryable()
.Where(r => r.Code == code)
.FirstAsync();
return new Response<FrontendSettingConfig>
{
Result = info
};
}
/// <summary>
/// 添加配置
/// </summary>
public async Task<Response<bool>> AddSettingConfig(FrontendSettingConfig obj)
{
var flag = await base.Repository.ChangeRepository<SugarRepositiry<FrontendSettingConfig>>().InsertAsync(obj);
return new Response<bool>
{
Result = flag,
Message = flag == true ? "success" : "error"
};
}
/// <summary>
/// 更新配置
/// </summary>
/// <param name="obj"></param>
public async Task<Response<bool>> UpdateSettingConfig(FrontendSettingConfig obj)
{
bool flag = await base.Repository.ChangeRepository<SugarRepositiry<FrontendSettingConfig>>().UpdateAsync(u =>
new FrontendSettingConfig
{
CodeValue = obj.CodeValue,
}, u => u.Code == obj.Code);
return new Response<bool>
{
Result = flag,
Message = flag == true ? "success" : "error"
};
}
/// <summary>
/// 删除配置
/// </summary>
/// <param name="ids"></param>
public async Task<Response<bool>> DeleteSettingConfig(string code)
{
var flag = await base.Repository.ChangeRepository<SugarRepositiry<FrontendSettingConfig>>()
.DeleteAsync(r => r.Code == code);
return new Response<bool>
{
Result = flag,
Message = flag == true ? "success" : "error"
};
}
#endregion
public async Task<Response<List<dynamic>>> GetIllegalShapeData(string caseid, string category)
{
// 违法用地 非法采矿 耕地非粮化 重点问题 巡察审计
var tableName = "drone_caseinfo_single";
var caseNo = "case_no";
switch (category)
{
case "非法采矿卫片下发":
tableName = "drone_caseinfo_wpxf";
break;
case "非法采矿工作管理":
tableName = "drone_caseinfo_minerals";
caseNo = "tubannum_base";
break;
case "耕地非粮化":
tableName = "drone_caseinfo_gdflh";
break;
case "重点问题\u2160类":
tableName = "drone_caseinfo_zdwt1";
break;
case "重点问题\u2161类":
tableName = "drone_caseinfo_zdwt2";
break;
case "巡察审计":
tableName = "drone_caseinfo_xcsj";
break;
case "生态保护红线监管":
tableName = "drone_caseinfo_sthx";
break;
case "生态修复":
tableName = "drone_caseinfo_stxf";
break;
case "设施农用地":
tableName = "drone_ssnyd";
caseNo = "xiangmu_no";
break;
}
using var db = Repository.AsSugarClient();
var sql =
$"SELECT s.gid,ST_AsText(geom) as geom,c.{caseNo} as caseno FROM drone_shp_data s left join {tableName} c on s.relid = c.\"Id\" where c.\"Id\" = '{caseid}'";
var result = await db.Ado.SqlQueryAsync<dynamic>(sql);
return new Response<List<dynamic>>()
{
Result = result,
Message = "ok"
};
}
#region 案件审核上传shp
/// <summary>
/// 违法用地
/// </summary>
/// <param name="zipFilePath"></param>
/// <param name="srid"></param>
/// <returns></returns>
/// <exception cref="FileNotFoundException"></exception>
/// <exception cref="Exception"></exception>
public async Task<Response<bool>> UpdateCaseInfoShpData(string zipFilePath,string srid)
{
var _user = _auth.GetCurrentUser().User;
using var db = Repository.AsSugarClient();
// 开启事务
await db.Ado.BeginTranAsync(IsolationLevel.ReadCommitted);
// 取得文件完全路径
zipFilePath = Path.Combine(_filePath, zipFilePath);
// 确保ZIP文件存在
if (!File.Exists(zipFilePath))
{
throw new FileNotFoundException("ZIP文件未找到。");
}
// 打开ZIP存档 取除后缀之前的字符串
var extractPath = zipFilePath.Substring(0, zipFilePath.LastIndexOf(".", StringComparison.Ordinal)) +
"extract";
// 解压文件
await UnZip(zipFilePath, extractPath);
var searchPattern = "*.shp"; // 设置你想要遍历的文件后缀名
var fileName = Directory.GetFiles(extractPath, searchPattern, SearchOption.AllDirectories);
if (fileName.IsEmpty())
{
throw new Exception("压缩文件中无shp文件");
}
var shpFileName = fileName[0];
var shpFile = Path.Combine(extractPath, shpFileName);
List<DroneCaseInfoSingle> datalist = new List<DroneCaseInfoSingle>();
List<DroneShpData> shplist = new List<DroneShpData>();
StringBuilder geomSql = new StringBuilder();
//批量更新面积
StringBuilder sql = new StringBuilder();
using (var dataReader = new ShapefileDataReader(shpFile, GeometryFactory.Default))
{
int i = 0;
while (dataReader.Read())
{
DroneCaseInfoSingle cinfo = new DroneCaseInfoSingle();
cinfo.Id = Guid.NewGuid().ToString();
cinfo.createtime = DateTime.Now;
cinfo.createuser = _user.Id.ToString();
cinfo.createusername = _user.Name.ToString();
cinfo.is_illegal = 1;
cinfo.is_intact = 1;
cinfo.synchronoustime = DateTime.Now;
cinfo.handle_status_id = 0;
cinfo.handle_status_name = "待接收";
cinfo.is_jieshou = 0;
cinfo.is_closed = 0;
cinfo.is_delete = 0;
cinfo.case_description = dataReader.GetValue(2).ToString();
if (dataReader.IsDBNull(6))
{
throw new Exception("图斑面积不能为空");
}
else
{
cinfo.area = dataReader.GetValue(6).ToString();
}
if (dataReader.IsDBNull(7))
{
throw new Exception("图斑来源不能为空");
}
else
{
cinfo.tubanlaiyuan = dataReader.GetValue(7).ToString();
}
cinfo.typename = dataReader.GetValue(5).ToString();
//类型id
var type = db.Queryable<SysDataItemDetail>().Where(r => r.ItemName == cinfo.typename && r.ItemCode == "DRONE_CASE_TYPE").First();
if (type != null)
{
cinfo.typeid = type.ItemDetailId;
}
//坐标及行政区划
if (dataReader.IsDBNull(3) || dataReader.IsDBNull(4))
{
throw new Exception("坐标不能为空");
}
else
{
var aa = dataReader.GetValue(2).ToString();
var bb= dataReader.GetValue(0).ToString();
decimal lng = Convert.ToDecimal(dataReader.GetValue(3).ToString());
decimal lat = Convert.ToDecimal(dataReader.GetValue(4).ToString());
cinfo.lng = lng;
cinfo.lat = lat;
JObject xzqh = GetOrgAreaByPoint(lng, lat);
var cc = (string)xzqh["countyid"];
cinfo.countyid = xzqh["countyid"].ToString();
cinfo.countyname = xzqh["countyname"].ToString();
cinfo.streetid = xzqh["streetid"].ToString();
cinfo.streetname = xzqh["streetname"].ToString();
cinfo.communityid = xzqh["communityid"].ToString();
cinfo.communityname = xzqh["communityname"].ToString();
cinfo.address = cinfo.countyname+" " + cinfo.streetname+" " + cinfo.communityname;
}
//案件编号
if (!dataReader.IsDBNull(1))
{
var caseinfo = _client.Queryable<DroneCaseInfoSingle>().Where(r => r.case_no == dataReader.GetValue(1).ToString()).ToList();
if (caseinfo.Count > 0)
{
throw new Exception("图斑编号" + dataReader.GetValue(1).ToString() + "已存在,请重新整理数据");
}
else
{
cinfo.case_no = dataReader.GetValue(1).ToString();
}
}
else
{
Random random = new Random();
bool isUnique;
var prefix = type?.Prefix;
do
{
var caseno = prefix + cinfo.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
var count = db.Queryable<DroneCaseInfoSingle>().Where(c => c.case_no == caseno).Count();
isUnique = count == 0;
} while (!isUnique);
}
//图斑数据drone_shp_data
DroneShpData model = new DroneShpData();
model.relid = cinfo.Id;
model.createtime = DateTime.Now;
model.createuser = _user.Name;
//获取主键
string _gid = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
model.gid = int.Parse(_gid)+i;//转为数字类型
i++;
cinfo.geomid = model.gid.ToString();
//geom
if (!dataReader.IsDBNull(0))
{
var geometry = (Geometry)dataReader.GetValue(0);
if (!geometry.IsValid)
{
throw new Exception("图斑" + cinfo.case_no + "未闭合,请重新整理数据");
}
var geometryForWgs84 = GeometryFactory.Default.WithSRID(int.Parse(srid))
.CreateGeometry(geometry);
geomSql.AppendFormat($" update drone_shp_data set geom = '{geometryForWgs84.AsText()}' where gid = '{model.gid}';");
}
model.geom = null;
sql.AppendFormat($" update drone_shp_data set area = st_area(st_transform(ST_SetSRID(geom,4326), 4527)) where gid = '{model.gid}';");
shplist.Add(model);
datalist.Add(cinfo);
}
}
using (var uow = base.UnitWork.CreateContext())
{
await uow.DroneCaseInfoSingle.InsertRangeAsync(datalist);
await uow.DroneShpData.InsertRangeAsync(shplist);
await uow.Db.Ado.ExecuteCommandAsync(geomSql.ToString());
await uow.Db.Ado.ExecuteCommandAsync(sql.ToString());
var flag = uow.Commit();
return new Response<bool>()
{
Result = flag,
Message = "ok"
};
}
}
/// <summary>
/// 非粮化
/// </summary>
/// <param name="zipFilePath"></param>
/// <param name="srid"></param>
/// <returns></returns>
/// <exception cref="FileNotFoundException"></exception>
/// <exception cref="Exception"></exception>
public async Task<Response<bool>> UpdateCaseInfoShpDataFLH(string zipFilePath, string srid)
{
var _user = _auth.GetCurrentUser().User;
using var db = Repository.AsSugarClient();
// 开启事务
await db.Ado.BeginTranAsync(IsolationLevel.ReadCommitted);
// 取得文件完全路径
zipFilePath = Path.Combine(_filePath, zipFilePath);
// 确保ZIP文件存在
if (!File.Exists(zipFilePath))
{
throw new FileNotFoundException("ZIP文件未找到。");
}
// 打开ZIP存档 取除后缀之前的字符串
var extractPath = zipFilePath.Substring(0, zipFilePath.LastIndexOf(".", StringComparison.Ordinal)) +
"extract";
// 解压文件
await UnZip(zipFilePath, extractPath);
var searchPattern = "*.shp"; // 设置你想要遍历的文件后缀名
var fileName = Directory.GetFiles(extractPath, searchPattern, SearchOption.AllDirectories);
if (fileName.IsEmpty())
{
throw new Exception("压缩文件中无shp文件");
}
var shpFileName = fileName[0];
var shpFile = Path.Combine(extractPath, shpFileName);
List<DroneCaseInfoFLH> datalist = new List<DroneCaseInfoFLH>();
List<DroneShpData> shplist = new List<DroneShpData>();
StringBuilder geomSql = new StringBuilder();
//批量更新面积
StringBuilder sql = new StringBuilder();
using (var dataReader = new ShapefileDataReader(shpFile, GeometryFactory.Default))
{
int i = 0;
while (dataReader.Read())
{
DroneCaseInfoFLH cinfo = new DroneCaseInfoFLH();
cinfo.Id = Guid.NewGuid().ToString();
cinfo.createtime = DateTime.Now;
cinfo.createuser = _user.Id.ToString();
cinfo.createusername = _user.Name.ToString();
cinfo.is_illegal = 1;
cinfo.is_intact = 1;
cinfo.synchronoustime = DateTime.Now;
cinfo.handle_status_id = 0;
cinfo.handle_status_name = "待接收";
cinfo.is_jieshou = 0;
cinfo.is_closed = 0;
cinfo.is_delete = 0;
cinfo.case_description = dataReader.GetValue(2).ToString();
if (dataReader.IsDBNull(6))
{
throw new Exception("图斑面积不能为空");
}
else
{
cinfo.area = dataReader.GetValue(6).ToString();
}
if (dataReader.IsDBNull(7))
{
throw new Exception("图斑来源不能为空");
}
else
{
cinfo.tubanlaiyuan = dataReader.GetValue(7).ToString();
}
cinfo.typename = dataReader.GetValue(5).ToString();
//类型id
var type = db.Queryable<SysDataItemDetail>().Where(r => r.ItemName == cinfo.typename && r.ItemCode == "DRONE_CASE_TYPE").First();
if (type != null)
{
cinfo.typeid = type.ItemDetailId;
}
//坐标及行政区划
if (dataReader.IsDBNull(3) || dataReader.IsDBNull(4))
{
throw new Exception("坐标不能为空");
}
else
{
var aa = dataReader.GetValue(2).ToString();
var bb = dataReader.GetValue(0).ToString();
decimal lng = Convert.ToDecimal(dataReader.GetValue(3).ToString());
decimal lat = Convert.ToDecimal(dataReader.GetValue(4).ToString());
cinfo.lng = lng;
cinfo.lat = lat;
JObject xzqh = GetOrgAreaByPoint(lng, lat);
var cc = (string)xzqh["countyid"];
cinfo.countyid = xzqh["countyid"].ToString();
cinfo.countyname = xzqh["countyname"].ToString();
cinfo.streetid = xzqh["streetid"].ToString();
cinfo.streetname = xzqh["streetname"].ToString();
cinfo.communityid = xzqh["communityid"].ToString();
cinfo.communityname = xzqh["communityname"].ToString();
cinfo.address = cinfo.countyname + " " + cinfo.streetname + " " + cinfo.communityname;
}
//案件编号
if (!dataReader.IsDBNull(1))
{
var caseinfo = _client.Queryable<DroneCaseInfoFLH>().Where(r => r.case_no == dataReader.GetValue(1).ToString()).ToList();
if (caseinfo.Count > 0)
{
throw new Exception("图斑编号" + dataReader.GetValue(1).ToString() + "已存在,请重新整理数据");
}
else
{
cinfo.case_no = dataReader.GetValue(1).ToString();
}
}
else
{
Random random = new Random();
bool isUnique;
var prefix = type?.Prefix;
do
{
var caseno = prefix + cinfo.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
var count = db.Queryable<DroneCaseInfoSingle>().Where(c => c.case_no == caseno).Count();
isUnique = count == 0;
} while (!isUnique);
}
//图斑数据drone_shp_data
DroneShpData model = new DroneShpData();
model.relid = cinfo.Id;
model.createtime = DateTime.Now;
model.createuser = _user.Name;
//获取主键
string _gid = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
model.gid = int.Parse(_gid) + i;//转为数字类型
i++;
cinfo.geomid = model.gid.ToString();
//geom
if (!dataReader.IsDBNull(0))
{
var geometry = (Geometry)dataReader.GetValue(0);
if (!geometry.IsValid)
{
throw new Exception("图斑" + cinfo.case_no + "未闭合,请重新整理数据");
}
var geometryForWgs84 = GeometryFactory.Default.WithSRID(int.Parse(srid))
.CreateGeometry(geometry);
geomSql.AppendFormat($" update drone_shp_data set geom = '{geometryForWgs84.AsText()}' where gid = '{model.gid}';");
}
model.geom = null;
sql.AppendFormat($" update drone_shp_data set area = st_area(st_transform(ST_SetSRID(geom,4326), 4527)) where gid = '{model.gid}';");
shplist.Add(model);
datalist.Add(cinfo);
}
}
using (var uow = base.UnitWork.CreateContext())
{
await uow.DroneCaseInfoFLH.InsertRangeAsync(datalist);
await uow.DroneShpData.InsertRangeAsync(shplist);
await uow.Db.Ado.ExecuteCommandAsync(geomSql.ToString());
await uow.Db.Ado.ExecuteCommandAsync(sql.ToString());
var flag = uow.Commit();
return new Response<bool>()
{
Result = flag,
Message = "ok"
};
}
}
/// <summary>
/// 重点问题1
/// </summary>
/// <param name="zipFilePath"></param>
/// <param name="srid"></param>
/// <returns></returns>
/// <exception cref="FileNotFoundException"></exception>
/// <exception cref="Exception"></exception>
public async Task<Response<bool>> UpdateCaseInfoShpDataZDWT1(string zipFilePath, string srid)
{
var _user = _auth.GetCurrentUser().User;
using var db = Repository.AsSugarClient();
// 开启事务
await db.Ado.BeginTranAsync(IsolationLevel.ReadCommitted);
// 取得文件完全路径
zipFilePath = Path.Combine(_filePath, zipFilePath);
// 确保ZIP文件存在
if (!File.Exists(zipFilePath))
{
throw new FileNotFoundException("ZIP文件未找到。");
}
// 打开ZIP存档 取除后缀之前的字符串
var extractPath = zipFilePath.Substring(0, zipFilePath.LastIndexOf(".", StringComparison.Ordinal)) +
"extract";
// 解压文件
await UnZip(zipFilePath, extractPath);
var searchPattern = "*.shp"; // 设置你想要遍历的文件后缀名
var fileName = Directory.GetFiles(extractPath, searchPattern, SearchOption.AllDirectories);
if (fileName.IsEmpty())
{
throw new Exception("压缩文件中无shp文件");
}
var shpFileName = fileName[0];
var shpFile = Path.Combine(extractPath, shpFileName);
List<DroneCaseInfoZdwt1> datalist = new List<DroneCaseInfoZdwt1>();
List<DroneShpData> shplist = new List<DroneShpData>();
StringBuilder geomSql = new StringBuilder();
//批量更新面积
StringBuilder sql = new StringBuilder();
using (var dataReader = new ShapefileDataReader(shpFile, GeometryFactory.Default))
{
int i = 0;
while (dataReader.Read())
{
DroneCaseInfoZdwt1 cinfo = new DroneCaseInfoZdwt1();
cinfo.Id = Guid.NewGuid().ToString();
cinfo.createtime = DateTime.Now;
cinfo.createuser = _user.Id.ToString();
cinfo.createusername = _user.Name.ToString();
cinfo.is_illegal = 1;
cinfo.is_intact = 1;
cinfo.synchronoustime = DateTime.Now;
cinfo.handle_status_id = 0;
cinfo.handle_status_name = "待接收";
cinfo.is_jieshou = 0;
cinfo.is_closed = 0;
cinfo.is_delete = 0;
cinfo.case_description = dataReader.GetValue(2).ToString();
if (dataReader.IsDBNull(6))
{
throw new Exception("图斑面积不能为空");
}
else
{
cinfo.area = dataReader.GetValue(6).ToString();
}
if (dataReader.IsDBNull(7))
{
throw new Exception("图斑来源不能为空");
}
else
{
cinfo.tubanlaiyuan = dataReader.GetValue(7).ToString();
}
cinfo.typename = dataReader.GetValue(5).ToString();
//类型id
var type = db.Queryable<SysDataItemDetail>().Where(r => r.ItemName == cinfo.typename && r.ItemCode == "DRONE_CASE_TYPE").First();
if (type != null)
{
cinfo.typeid = type.ItemDetailId;
}
//坐标及行政区划
if (dataReader.IsDBNull(3) || dataReader.IsDBNull(4))
{
throw new Exception("坐标不能为空");
}
else
{
var aa = dataReader.GetValue(2).ToString();
var bb = dataReader.GetValue(0).ToString();
decimal lng = Convert.ToDecimal(dataReader.GetValue(3).ToString());
decimal lat = Convert.ToDecimal(dataReader.GetValue(4).ToString());
cinfo.lng = lng;
cinfo.lat = lat;
JObject xzqh = GetOrgAreaByPoint(lng, lat);
var cc = (string)xzqh["countyid"];
cinfo.countyid = xzqh["countyid"].ToString();
cinfo.countyname = xzqh["countyname"].ToString();
cinfo.streetid = xzqh["streetid"].ToString();
cinfo.streetname = xzqh["streetname"].ToString();
cinfo.communityid = xzqh["communityid"].ToString();
cinfo.communityname = xzqh["communityname"].ToString();
cinfo.address = cinfo.countyname + " " + cinfo.streetname + " " + cinfo.communityname;
}
//案件编号
if (!dataReader.IsDBNull(1))
{
var caseinfo = _client.Queryable<DroneCaseInfoZdwt1>().Where(r => r.case_no == dataReader.GetValue(1).ToString()).ToList();
if (caseinfo.Count > 0)
{
throw new Exception("图斑编号" + dataReader.GetValue(1).ToString() + "已存在,请重新整理数据");
}
else
{
cinfo.case_no = dataReader.GetValue(1).ToString();
}
}
else
{
Random random = new Random();
bool isUnique;
var prefix = type?.Prefix;
do
{
var caseno = prefix + cinfo.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
var count = db.Queryable<DroneCaseInfoSingle>().Where(c => c.case_no == caseno).Count();
isUnique = count == 0;
} while (!isUnique);
}
//图斑数据drone_shp_data
DroneShpData model = new DroneShpData();
model.relid = cinfo.Id;
model.createtime = DateTime.Now;
model.createuser = _user.Name;
//获取主键
string _gid = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
model.gid = int.Parse(_gid) + i;//转为数字类型
i++;
cinfo.geomid = model.gid.ToString();
//geom
if (!dataReader.IsDBNull(0))
{
var geometry = (Geometry)dataReader.GetValue(0);
if (!geometry.IsValid)
{
throw new Exception("图斑" + cinfo.case_no + "未闭合,请重新整理数据");
}
var geometryForWgs84 = GeometryFactory.Default.WithSRID(int.Parse(srid))
.CreateGeometry(geometry);
geomSql.AppendFormat($" update drone_shp_data set geom = '{geometryForWgs84.AsText()}' where gid = '{model.gid}';");
}
model.geom = null;
sql.AppendFormat($" update drone_shp_data set area = st_area(st_transform(ST_SetSRID(geom,4326), 4527)) where gid = '{model.gid}';");
shplist.Add(model);
datalist.Add(cinfo);
}
}
using (var uow = base.UnitWork.CreateContext())
{
await uow.DroneCaseInfoZdwt1.InsertRangeAsync(datalist);
await uow.DroneShpData.InsertRangeAsync(shplist);
await uow.Db.Ado.ExecuteCommandAsync(geomSql.ToString());
await uow.Db.Ado.ExecuteCommandAsync(sql.ToString());
var flag = uow.Commit();
return new Response<bool>()
{
Result = flag,
Message = "ok"
};
}
}
/// <summary>
/// 重点问题2
/// </summary>
/// <param name="zipFilePath"></param>
/// <param name="srid"></param>
/// <returns></returns>
/// <exception cref="FileNotFoundException"></exception>
/// <exception cref="Exception"></exception>
public async Task<Response<bool>> UpdateCaseInfoShpDataZDWT2(string zipFilePath, string srid)
{
var _user = _auth.GetCurrentUser().User;
using var db = Repository.AsSugarClient();
// 开启事务
await db.Ado.BeginTranAsync(IsolationLevel.ReadCommitted);
// 取得文件完全路径
zipFilePath = Path.Combine(_filePath, zipFilePath);
// 确保ZIP文件存在
if (!File.Exists(zipFilePath))
{
throw new FileNotFoundException("ZIP文件未找到。");
}
// 打开ZIP存档 取除后缀之前的字符串
var extractPath = zipFilePath.Substring(0, zipFilePath.LastIndexOf(".", StringComparison.Ordinal)) +
"extract";
// 解压文件
await UnZip(zipFilePath, extractPath);
var searchPattern = "*.shp"; // 设置你想要遍历的文件后缀名
var fileName = Directory.GetFiles(extractPath, searchPattern, SearchOption.AllDirectories);
if (fileName.IsEmpty())
{
throw new Exception("压缩文件中无shp文件");
}
var shpFileName = fileName[0];
var shpFile = Path.Combine(extractPath, shpFileName);
List<DroneCaseInfoZdwt2> datalist = new List<DroneCaseInfoZdwt2>();
List<DroneShpData> shplist = new List<DroneShpData>();
StringBuilder geomSql = new StringBuilder();
//批量更新面积
StringBuilder sql = new StringBuilder();
using (var dataReader = new ShapefileDataReader(shpFile, GeometryFactory.Default))
{
int i = 0;
while (dataReader.Read())
{
DroneCaseInfoZdwt2 cinfo = new DroneCaseInfoZdwt2();
cinfo.Id = Guid.NewGuid().ToString();
cinfo.createtime = DateTime.Now;
cinfo.createuser = _user.Id.ToString();
cinfo.createusername = _user.Name.ToString();
cinfo.is_illegal = 1;
cinfo.is_intact = 1;
cinfo.synchronoustime = DateTime.Now;
cinfo.handle_status_id = 0;
cinfo.handle_status_name = "待接收";
cinfo.is_jieshou = 0;
cinfo.is_closed = 0;
cinfo.is_delete = 0;
cinfo.case_description = dataReader.GetValue(2).ToString();
if (dataReader.IsDBNull(6))
{
throw new Exception("图斑面积不能为空");
}
else
{
cinfo.area = dataReader.GetValue(6).ToString();
}
if (dataReader.IsDBNull(7))
{
throw new Exception("图斑来源不能为空");
}
else
{
cinfo.tubanlaiyuan = dataReader.GetValue(7).ToString();
}
cinfo.typename = dataReader.GetValue(5).ToString();
//类型id
var type = db.Queryable<SysDataItemDetail>().Where(r => r.ItemName == cinfo.typename && r.ItemCode == "DRONE_CASE_TYPE").First();
if (type != null)
{
cinfo.typeid = type.ItemDetailId;
}
//坐标及行政区划
if (dataReader.IsDBNull(3) || dataReader.IsDBNull(4))
{
throw new Exception("坐标不能为空");
}
else
{
var aa = dataReader.GetValue(2).ToString();
var bb = dataReader.GetValue(0).ToString();
decimal lng = Convert.ToDecimal(dataReader.GetValue(3).ToString());
decimal lat = Convert.ToDecimal(dataReader.GetValue(4).ToString());
cinfo.lng = lng;
cinfo.lat = lat;
JObject xzqh = GetOrgAreaByPoint(lng, lat);
var cc = (string)xzqh["countyid"];
cinfo.countyid = xzqh["countyid"].ToString();
cinfo.countyname = xzqh["countyname"].ToString();
cinfo.streetid = xzqh["streetid"].ToString();
cinfo.streetname = xzqh["streetname"].ToString();
cinfo.communityid = xzqh["communityid"].ToString();
cinfo.communityname = xzqh["communityname"].ToString();
cinfo.address = cinfo.countyname + " " + cinfo.streetname + " " + cinfo.communityname;
}
//案件编号
if (!dataReader.IsDBNull(1))
{
var caseinfo = _client.Queryable<DroneCaseInfoZdwt2>().Where(r => r.case_no == dataReader.GetValue(1).ToString()).ToList();
if (caseinfo.Count > 0)
{
throw new Exception("图斑编号" + dataReader.GetValue(1).ToString() + "已存在,请重新整理数据");
}
else
{
cinfo.case_no = dataReader.GetValue(1).ToString();
}
}
else
{
Random random = new Random();
bool isUnique;
var prefix = type?.Prefix;
do
{
var caseno = prefix + cinfo.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
var count = db.Queryable<DroneCaseInfoSingle>().Where(c => c.case_no == caseno).Count();
isUnique = count == 0;
} while (!isUnique);
}
//图斑数据drone_shp_data
DroneShpData model = new DroneShpData();
model.relid = cinfo.Id;
model.createtime = DateTime.Now;
model.createuser = _user.Name;
//获取主键
string _gid = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
model.gid = int.Parse(_gid) + i;//转为数字类型
i++;
cinfo.geomid = model.gid.ToString();
//geom
if (!dataReader.IsDBNull(0))
{
var geometry = (Geometry)dataReader.GetValue(0);
if (!geometry.IsValid)
{
throw new Exception("图斑" + cinfo.case_no + "未闭合,请重新整理数据");
}
var geometryForWgs84 = GeometryFactory.Default.WithSRID(int.Parse(srid))
.CreateGeometry(geometry);
geomSql.AppendFormat($" update drone_shp_data set geom = '{geometryForWgs84.AsText()}' where gid = '{model.gid}';");
}
model.geom = null;
sql.AppendFormat($" update drone_shp_data set area = st_area(st_transform(ST_SetSRID(geom,4326), 4527)) where gid = '{model.gid}';");
shplist.Add(model);
datalist.Add(cinfo);
}
}
using (var uow = base.UnitWork.CreateContext())
{
await uow.DroneCaseInfoZdwt2.InsertRangeAsync(datalist);
await uow.DroneShpData.InsertRangeAsync(shplist);
await uow.Db.Ado.ExecuteCommandAsync(geomSql.ToString());
await uow.Db.Ado.ExecuteCommandAsync(sql.ToString());
var flag = uow.Commit();
return new Response<bool>()
{
Result = flag,
Message = "ok"
};
}
}
/// <summary>
/// 巡查审计
/// </summary>
/// <param name="zipFilePath"></param>
/// <param name="srid"></param>
/// <returns></returns>
/// <exception cref="FileNotFoundException"></exception>
/// <exception cref="Exception"></exception>
public async Task<Response<bool>> UpdateCaseInfoShpDataXCSJ(string zipFilePath, string srid)
{
var _user = _auth.GetCurrentUser().User;
using var db = Repository.AsSugarClient();
// 开启事务
await db.Ado.BeginTranAsync(IsolationLevel.ReadCommitted);
// 取得文件完全路径
zipFilePath = Path.Combine(_filePath, zipFilePath);
// 确保ZIP文件存在
if (!File.Exists(zipFilePath))
{
throw new FileNotFoundException("ZIP文件未找到。");
}
// 打开ZIP存档 取除后缀之前的字符串
var extractPath = zipFilePath.Substring(0, zipFilePath.LastIndexOf(".", StringComparison.Ordinal)) +
"extract";
// 解压文件
await UnZip(zipFilePath, extractPath);
var searchPattern = "*.shp"; // 设置你想要遍历的文件后缀名
var fileName = Directory.GetFiles(extractPath, searchPattern, SearchOption.AllDirectories);
if (fileName.IsEmpty())
{
throw new Exception("压缩文件中无shp文件");
}
var shpFileName = fileName[0];
var shpFile = Path.Combine(extractPath, shpFileName);
List<DroneCaseInfoXcsj> datalist = new List<DroneCaseInfoXcsj>();
List<DroneShpData> shplist = new List<DroneShpData>();
StringBuilder geomSql = new StringBuilder();
//批量更新面积
StringBuilder sql = new StringBuilder();
using (var dataReader = new ShapefileDataReader(shpFile, GeometryFactory.Default))
{
int i = 0;
while (dataReader.Read())
{
DroneCaseInfoXcsj cinfo = new DroneCaseInfoXcsj();
cinfo.Id = Guid.NewGuid().ToString();
cinfo.createtime = DateTime.Now;
cinfo.createuser = _user.Id.ToString();
cinfo.createusername = _user.Name.ToString();
cinfo.is_illegal = 1;
cinfo.is_intact = 1;
cinfo.synchronoustime = DateTime.Now;
cinfo.handle_status_id = 0;
cinfo.handle_status_name = "待接收";
cinfo.is_jieshou = 0;
cinfo.is_closed = 0;
cinfo.is_delete = 0;
cinfo.case_description = dataReader.GetValue(2).ToString();
if (dataReader.IsDBNull(6))
{
throw new Exception("图斑面积不能为空");
}
else
{
cinfo.area = dataReader.GetValue(6).ToString();
}
if (dataReader.IsDBNull(7))
{
throw new Exception("图斑来源不能为空");
}
else
{
cinfo.tubanlaiyuan = dataReader.GetValue(7).ToString();
}
cinfo.typename = dataReader.GetValue(5).ToString();
//类型id
var type = db.Queryable<SysDataItemDetail>().Where(r => r.ItemName == cinfo.typename && r.ItemCode == "DRONE_CASE_TYPE").First();
if (type != null)
{
cinfo.typeid = type.ItemDetailId;
}
//坐标及行政区划
if (dataReader.IsDBNull(3) || dataReader.IsDBNull(4))
{
throw new Exception("坐标不能为空");
}
else
{
var aa = dataReader.GetValue(2).ToString();
var bb = dataReader.GetValue(0).ToString();
decimal lng = Convert.ToDecimal(dataReader.GetValue(3).ToString());
decimal lat = Convert.ToDecimal(dataReader.GetValue(4).ToString());
cinfo.lng = lng;
cinfo.lat = lat;
JObject xzqh = GetOrgAreaByPoint(lng, lat);
var cc = (string)xzqh["countyid"];
cinfo.countyid = xzqh["countyid"].ToString();
cinfo.countyname = xzqh["countyname"].ToString();
cinfo.streetid = xzqh["streetid"].ToString();
cinfo.streetname = xzqh["streetname"].ToString();
cinfo.communityid = xzqh["communityid"].ToString();
cinfo.communityname = xzqh["communityname"].ToString();
cinfo.address = cinfo.countyname + " " + cinfo.streetname + " " + cinfo.communityname;
}
//案件编号
if (!dataReader.IsDBNull(1))
{
var caseinfo = _client.Queryable<DroneCaseInfoXcsj>().Where(r => r.case_no == dataReader.GetValue(1).ToString()).ToList();
if (caseinfo.Count > 0)
{
throw new Exception("图斑编号" + dataReader.GetValue(1).ToString() + "已存在,请重新整理数据");
}
else
{
cinfo.case_no = dataReader.GetValue(1).ToString();
}
}
else
{
Random random = new Random();
bool isUnique;
var prefix = type?.Prefix;
do
{
var caseno = prefix + cinfo.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
var count = db.Queryable<DroneCaseInfoSingle>().Where(c => c.case_no == caseno).Count();
isUnique = count == 0;
} while (!isUnique);
}
//图斑数据drone_shp_data
DroneShpData model = new DroneShpData();
model.relid = cinfo.Id;
model.createtime = DateTime.Now;
model.createuser = _user.Name;
//获取主键
string _gid = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
model.gid = int.Parse(_gid) + i;//转为数字类型
i++;
cinfo.geomid = model.gid.ToString();
//geom
if (!dataReader.IsDBNull(0))
{
var geometry = (Geometry)dataReader.GetValue(0);
if (!geometry.IsValid)
{
throw new Exception("图斑" + cinfo.case_no + "未闭合,请重新整理数据");
}
var geometryForWgs84 = GeometryFactory.Default.WithSRID(int.Parse(srid))
.CreateGeometry(geometry);
geomSql.AppendFormat($" update drone_shp_data set geom = '{geometryForWgs84.AsText()}' where gid = '{model.gid}';");
}
model.geom = null;
sql.AppendFormat($" update drone_shp_data set area = st_area(st_transform(ST_SetSRID(geom,4326), 4527)) where gid = '{model.gid}';");
shplist.Add(model);
datalist.Add(cinfo);
}
}
using (var uow = base.UnitWork.CreateContext())
{
await uow.DroneCaseInfoXcsj.InsertRangeAsync(datalist);
await uow.DroneShpData.InsertRangeAsync(shplist);
await uow.Db.Ado.ExecuteCommandAsync(geomSql.ToString());
await uow.Db.Ado.ExecuteCommandAsync(sql.ToString());
var flag = uow.Commit();
return new Response<bool>()
{
Result = flag,
Message = "ok"
};
}
}
/// <summary>
/// 卫片下发
/// </summary>
/// <param name="zipFilePath"></param>
/// <param name="srid"></param>
/// <returns></returns>
/// <exception cref="FileNotFoundException"></exception>
/// <exception cref="Exception"></exception>
public async Task<Response<bool>> UpdateCaseInfoShpDataWPXF(string zipFilePath, string srid)
{
var _user = _auth.GetCurrentUser().User;
using var db = Repository.AsSugarClient();
// 开启事务
await db.Ado.BeginTranAsync(IsolationLevel.ReadCommitted);
// 取得文件完全路径
zipFilePath = Path.Combine(_filePath, zipFilePath);
// 确保ZIP文件存在
if (!File.Exists(zipFilePath))
{
throw new FileNotFoundException("ZIP文件未找到。");
}
// 打开ZIP存档 取除后缀之前的字符串
var extractPath = zipFilePath.Substring(0, zipFilePath.LastIndexOf(".", StringComparison.Ordinal)) +
"extract";
// 解压文件
await UnZip(zipFilePath, extractPath);
var searchPattern = "*.shp"; // 设置你想要遍历的文件后缀名
var fileName = Directory.GetFiles(extractPath, searchPattern, SearchOption.AllDirectories);
if (fileName.IsEmpty())
{
throw new Exception("压缩文件中无shp文件");
}
var shpFileName = fileName[0];
var shpFile = Path.Combine(extractPath, shpFileName);
List<DroneCaseInfoSatellite> datalist = new List<DroneCaseInfoSatellite>();
List<DroneShpData> shplist = new List<DroneShpData>();
StringBuilder geomSql = new StringBuilder();
//批量更新面积
StringBuilder sql = new StringBuilder();
using (var dataReader = new ShapefileDataReader(shpFile, GeometryFactory.Default))
{
int i = 0;
while (dataReader.Read())
{
DroneCaseInfoSatellite cinfo = new DroneCaseInfoSatellite();
cinfo.Id = Guid.NewGuid().ToString();
cinfo.createtime = DateTime.Now;
cinfo.createuser = _user.Id.ToString();
cinfo.createusername = _user.Name.ToString();
cinfo.is_illegal = 1;
cinfo.is_intact = 1;
cinfo.synchronoustime = DateTime.Now;
cinfo.handle_status_id = 0;
cinfo.handle_status_name = "待接收";
cinfo.is_jieshou = 0;
cinfo.is_closed = 0;
cinfo.is_delete = 0;
cinfo.case_description = dataReader.GetValue(2).ToString();
if (dataReader.IsDBNull(6))
{
throw new Exception("图斑面积不能为空");
}
else
{
cinfo.area = dataReader.GetValue(6).ToString();
}
if (dataReader.IsDBNull(7))
{
throw new Exception("图斑来源不能为空");
}
else
{
cinfo.tubanlaiyuan = dataReader.GetValue(7).ToString();
}
cinfo.typename = dataReader.GetValue(5).ToString();
//类型id
var type = db.Queryable<SysDataItemDetail>().Where(r => r.ItemName == cinfo.typename && r.ItemCode == "DRONE_CASE_TYPE").First();
if (type != null)
{
cinfo.typeid = type.ItemDetailId;
}
//坐标及行政区划
if (dataReader.IsDBNull(3) || dataReader.IsDBNull(4))
{
throw new Exception("坐标不能为空");
}
else
{
var aa = dataReader.GetValue(2).ToString();
var bb = dataReader.GetValue(0).ToString();
decimal lng = Convert.ToDecimal(dataReader.GetValue(3).ToString());
decimal lat = Convert.ToDecimal(dataReader.GetValue(4).ToString());
cinfo.lng = lng;
cinfo.lat = lat;
JObject xzqh = GetOrgAreaByPoint(lng, lat);
var cc = (string)xzqh["countyid"];
cinfo.countyid = xzqh["countyid"].ToString();
cinfo.countyname = xzqh["countyname"].ToString();
cinfo.streetid = xzqh["streetid"].ToString();
cinfo.streetname = xzqh["streetname"].ToString();
cinfo.communityid = xzqh["communityid"].ToString();
cinfo.communityname = xzqh["communityname"].ToString();
cinfo.address = cinfo.countyname + " " + cinfo.streetname + " " + cinfo.communityname;
}
//案件编号
if (!dataReader.IsDBNull(1))
{
var caseinfo = _client.Queryable<DroneCaseInfoSatellite>().Where(r => r.case_no == dataReader.GetValue(1).ToString()).ToList();
if (caseinfo.Count > 0)
{
throw new Exception("图斑编号" + dataReader.GetValue(1).ToString() + "已存在,请重新整理数据");
}
else
{
cinfo.case_no = dataReader.GetValue(1).ToString();
}
}
else
{
Random random = new Random();
bool isUnique;
var prefix = type?.Prefix;
do
{
var caseno = prefix + cinfo.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
var count = db.Queryable<DroneCaseInfoSingle>().Where(c => c.case_no == caseno).Count();
isUnique = count == 0;
} while (!isUnique);
}
//图斑数据drone_shp_data
DroneShpData model = new DroneShpData();
model.relid = cinfo.Id;
model.createtime = DateTime.Now;
model.createuser = _user.Name;
//获取主键
string _gid = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
model.gid = int.Parse(_gid) + i;//转为数字类型
i++;
cinfo.geomid = model.gid.ToString();
//geom
if (!dataReader.IsDBNull(0))
{
var geometry = (Geometry)dataReader.GetValue(0);
if (!geometry.IsValid)
{
throw new Exception("图斑" + cinfo.case_no + "未闭合,请重新整理数据");
}
var geometryForWgs84 = GeometryFactory.Default.WithSRID(int.Parse(srid))
.CreateGeometry(geometry);
geomSql.AppendFormat($" update drone_shp_data set geom = '{geometryForWgs84.AsText()}' where gid = '{model.gid}';");
}
model.geom = null;
sql.AppendFormat($" update drone_shp_data set area = st_area(st_transform(ST_SetSRID(geom,4326), 4527)) where gid = '{model.gid}';");
shplist.Add(model);
datalist.Add(cinfo);
}
}
using (var uow = base.UnitWork.CreateContext())
{
await uow.DroneCaseInfoSatellite.InsertRangeAsync(datalist);
await uow.DroneShpData.InsertRangeAsync(shplist);
await uow.Db.Ado.ExecuteCommandAsync(geomSql.ToString());
await uow.Db.Ado.ExecuteCommandAsync(sql.ToString());
var flag = uow.Commit();
return new Response<bool>()
{
Result = flag,
Message = "ok"
};
}
}
/// <summary>
/// 矿产
/// </summary>
/// <param name="zipFilePath"></param>
/// <param name="srid"></param>
/// <returns></returns>
/// <exception cref="FileNotFoundException"></exception>
/// <exception cref="Exception"></exception>
public async Task<Response<bool>> UpdateCaseInfoShpDataMinerals(string zipFilePath, string srid)
{
var _user = _auth.GetCurrentUser().User;
using var db = Repository.AsSugarClient();
// 开启事务
await db.Ado.BeginTranAsync(IsolationLevel.ReadCommitted);
// 取得文件完全路径
zipFilePath = Path.Combine(_filePath, zipFilePath);
// 确保ZIP文件存在
if (!File.Exists(zipFilePath))
{
throw new FileNotFoundException("ZIP文件未找到。");
}
// 打开ZIP存档 取除后缀之前的字符串
var extractPath = zipFilePath.Substring(0, zipFilePath.LastIndexOf(".", StringComparison.Ordinal)) +
"extract";
// 解压文件
await UnZip(zipFilePath, extractPath);
var searchPattern = "*.shp"; // 设置你想要遍历的文件后缀名
var fileName = Directory.GetFiles(extractPath, searchPattern, SearchOption.AllDirectories);
if (fileName.IsEmpty())
{
throw new Exception("压缩文件中无shp文件");
}
var shpFileName = fileName[0];
var shpFile = Path.Combine(extractPath, shpFileName);
List<DroneCaseInfoMinerals> datalist = new List<DroneCaseInfoMinerals>();
List<DroneShpData> shplist = new List<DroneShpData>();
StringBuilder geomSql = new StringBuilder();
//批量更新面积
StringBuilder sql = new StringBuilder();
using (var dataReader = new ShapefileDataReader(shpFile, GeometryFactory.Default))
{
int i = 0;
while (dataReader.Read())
{
DroneCaseInfoMinerals cinfo = new DroneCaseInfoMinerals();
cinfo.Id = Guid.NewGuid().ToString();
cinfo.createtime = DateTime.Now;
cinfo.createuser = _user.Id.ToString();
//cinfo.createusername = _user.Name.ToString();
cinfo.is_illegal = 1;
cinfo.xiafatime_base = DateTime.Now;
cinfo.handle_status_id = 1;
cinfo.is_closed = 0;
cinfo.case_description = dataReader.GetValue(2).ToString();
if (dataReader.IsDBNull(6))
{
throw new Exception("图斑面积不能为空");
}
else
{
cinfo.weifaarea_base = dataReader.GetValue(6).ToString();
}
if (dataReader.IsDBNull(7))
{
throw new Exception("图斑来源不能为空");
}
else
{
cinfo.tubanlaiyuan = dataReader.GetValue(7).ToString();
}
cinfo.typename = dataReader.GetValue(5).ToString();
//坐标及行政区划
if (dataReader.IsDBNull(3) || dataReader.IsDBNull(4))
{
throw new Exception("坐标不能为空");
}
else
{
decimal lng = Convert.ToDecimal(dataReader.GetValue(3).ToString());
decimal lat = Convert.ToDecimal(dataReader.GetValue(4).ToString());
cinfo.centerlng_base = dataReader.GetValue(3).ToString();
cinfo.centerlat_base = dataReader.GetValue(4).ToString();
JObject xzqh = GetOrgAreaByPoint(lng, lat);
var cc = (string)xzqh["countyid"];
cinfo.countyid = xzqh["countyid"].ToString();
cinfo.countyname = xzqh["countyname"].ToString();
cinfo.streetid = xzqh["streetid"].ToString();
cinfo.streetname = xzqh["streetname"].ToString();
cinfo.communityid = xzqh["communityid"].ToString();
cinfo.communityname = xzqh["communityname"].ToString();
}
//案件编号
if (!dataReader.IsDBNull(1))
{
var caseinfo = _client.Queryable<DroneCaseInfoMinerals>().Where(r => r.case_no == dataReader.GetValue(1).ToString()).ToList();
if (caseinfo.Count > 0)
{
throw new Exception("图斑编号" + dataReader.GetValue(1).ToString() + "已存在,请重新整理数据");
}
else
{
cinfo.case_no = dataReader.GetValue(1).ToString();
}
}
else
{
Random random = new Random();
bool isUnique;
var prefix = "KC";
do
{
var caseno = prefix + cinfo.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
var count = db.Queryable<DroneCaseInfoSingle>().Where(c => c.case_no == caseno).Count();
isUnique = count == 0;
} while (!isUnique);
}
//图斑数据drone_shp_data
DroneShpData model = new DroneShpData();
model.relid = cinfo.Id;
model.createtime = DateTime.Now;
model.createuser = _user.Name;
//获取主键
string _gid = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
model.gid = int.Parse(_gid) + i;//转为数字类型
i++;
cinfo.geomid = model.gid.ToString();
//geom
if (!dataReader.IsDBNull(0))
{
var geometry = (Geometry)dataReader.GetValue(0);
if (!geometry.IsValid)
{
throw new Exception("图斑" + cinfo.case_no + "未闭合,请重新整理数据");
}
var geometryForWgs84 = GeometryFactory.Default.WithSRID(int.Parse(srid))
.CreateGeometry(geometry);
geomSql.AppendFormat($" update drone_shp_data set geom = '{geometryForWgs84.AsText()}' where gid = '{model.gid}';");
}
model.geom = null;
sql.AppendFormat($" update drone_shp_data set area = st_area(st_transform(ST_SetSRID(geom,4326), 4527)) where gid = '{model.gid}';");
shplist.Add(model);
datalist.Add(cinfo);
}
}
using (var uow = base.UnitWork.CreateContext())
{
await uow.DroneCaseInfoMinerals.InsertRangeAsync(datalist);
await uow.DroneShpData.InsertRangeAsync(shplist);
await uow.Db.Ado.ExecuteCommandAsync(geomSql.ToString());
await uow.Db.Ado.ExecuteCommandAsync(sql.ToString());
var flag = uow.Commit();
return new Response<bool>()
{
Result = flag,
Message = "ok"
};
}
}
/// <summary>
/// 根据经纬度获取组织机构
/// </summary>
/// <param name="lng"></param>
/// <param name="lat"></param>
/// <returns></returns>
public JObject GetOrgAreaByPoint(decimal lng, decimal lat)
{
//县id
string countyid = "";
string countyname = "";
//镇id
string streetid = "";
string streetname = "";
//村id
string communityid = "";
string communityname = "";
//SqlSugar实例
using (var db = Repository.AsSugarClient())
{
//查询坐标属于哪个县
StringBuilder sql = new StringBuilder();
sql.AppendFormat($" SELECT xzqdm,xzqmc FROM \"shp_drone_county\" where ST_Within(st_geomfromtext('POINT({lng} {lat})',4326), ST_SetSRID(geom,4326))");
var countyList = db.SqlQueryable<dynamic>(sql.ToString()).ToList();
if (countyList.Count > 0)
{
//县名称
countyname = countyList[0].xzqmc;
//县id
countyid= countyList[0].xzqdm;
}
//查询坐标属于哪个镇
sql = new StringBuilder();
sql.AppendFormat($" SELECT xzqdm,xzqmc FROM \"shp_drone_town\" where ST_Within(st_geomfromtext('POINT({lng} {lat})',4326), ST_SetSRID(geom,4326))");
var streetList = db.SqlQueryable<dynamic>(sql.ToString()).ToList();
if (streetList.Count > 0)
{
//镇名称
streetname = streetList[0].xzqmc;
//镇id
streetid= streetList[0].xzqdm;
}
if (!string.IsNullOrEmpty(streetid))
{
//查询组织机构属于哪个村
sql = new StringBuilder();
sql.AppendFormat($" SELECT zldwdm,zldwmc FROM \"shp_drone_community\" where ST_Within(st_geomfromtext('POINT({lng} {lat})',4326), ST_SetSRID(geom,4326))");
var communityidList = db.SqlQueryable<dynamic>(sql.ToString()).ToList();
if (communityidList.Count > 0)
{
//村名称
communityname = communityidList[0].zldwmc;
//村id
communityid= communityidList[0].zldwdm;
}
}
//拼接json数据返回到前台
JObject obj = new JObject();
obj.Add("countyid", countyid);
obj.Add("countyname", countyname);
obj.Add("streetid", streetid);
obj.Add("streetname", streetname);
obj.Add("communityid", communityid);
obj.Add("communityname", communityname);
return obj;
}
}
#endregion
#region 导入shp数据新版
/// <summary>
/// 违法用地
/// </summary>
/// <param name="zipFilePath"></param>
/// <param name="srid"></param>
/// <returns></returns>
/// <exception cref="FileNotFoundException"></exception>
/// <exception cref="Exception"></exception>
public async Task<Response<bool>> importCaseInfoShpData(string zipFilePath, string srid,string subjectname)
{
var _user = _auth.GetCurrentUser().User;
using var db = Repository.AsSugarClient();
// 开启事务
await db.Ado.BeginTranAsync(IsolationLevel.ReadCommitted);
// 取得文件完全路径
zipFilePath = Path.Combine(_filePath, zipFilePath);
// 确保ZIP文件存在
if (!File.Exists(zipFilePath))
{
throw new FileNotFoundException("ZIP文件未找到。");
}
// 打开ZIP存档 取除后缀之前的字符串
var extractPath = zipFilePath.Substring(0, zipFilePath.LastIndexOf(".", StringComparison.Ordinal)) +
"extract";
// 解压文件
await UnZip(zipFilePath, extractPath);
var searchPattern = "*.shp"; // 设置你想要遍历的文件后缀名
var fileName = Directory.GetFiles(extractPath, searchPattern, SearchOption.AllDirectories);
if (fileName.IsEmpty())
{
throw new Exception("压缩文件中无shp文件");
}
var shpFileName = fileName[0];
var shpFile = Path.Combine(extractPath, shpFileName);
List<DroneCaseInfoImport> datalist = new List<DroneCaseInfoImport>();
List<DroneShpData> shplist = new List<DroneShpData>();
StringBuilder geomSql = new StringBuilder();
//批量更新面积
StringBuilder sql = new StringBuilder();
Random random = new Random();
//批次号
var pici = DateTime.Now.ToString("yyyyMMssHHmmss") + random.Next(1000, 9999).ToString();
//
string countyid = "";
using (var dataReader = new ShapefileDataReader(shpFile, GeometryFactory.Default))
{
while (dataReader.Read())
{
DroneCaseInfoImport cinfo = new DroneCaseInfoImport();
cinfo.Id = Guid.NewGuid().ToString();
cinfo.createtime = DateTime.Now;
cinfo.createuser = _user.Id.ToString();
cinfo.createusername = _user.Name.ToString();
cinfo.case_description = dataReader.GetValue(2).ToString();
cinfo.subjectname = subjectname;
cinfo.picihao = pici;
if (dataReader.IsDBNull(6))
{
throw new Exception("图斑面积不能为空");
}
else
{
cinfo.area = dataReader.GetValue(6).ToString();
}
if (dataReader.IsDBNull(7))
{
throw new Exception("图斑来源不能为空");
}
else
{
cinfo.tubanlaiyuan = dataReader.GetValue(7).ToString();
}
cinfo.typename = dataReader.GetValue(5).ToString();
//类型id
var type = db.Queryable<SysDataItemDetail>().Where(r => r.ItemName == cinfo.typename && r.ItemCode == "DRONE_CASE_TYPE").First();
//坐标及行政区划
if (dataReader.IsDBNull(3) || dataReader.IsDBNull(4))
{
throw new Exception("坐标不能为空");
}
else
{
decimal lng = Convert.ToDecimal(dataReader.GetValue(3).ToString());
decimal lat = Convert.ToDecimal(dataReader.GetValue(4).ToString());
cinfo.lng = lng;
cinfo.lat = lat;
JObject xzqh = GetOrgAreaByPoint(lng, lat);
countyid = xzqh["countyid"].ToString();
}
//案件编号
if (!dataReader.IsDBNull(1))
{
var caseinfo = _client.Queryable<DroneCaseInfoSingle>().Where(r => r.case_no == dataReader.GetValue(1).ToString()).ToList();
if (caseinfo.Count > 0)
{
throw new Exception("图斑编号" + dataReader.GetValue(1).ToString() + "已存在,请重新整理数据");
}
else
{
cinfo.case_no = dataReader.GetValue(1).ToString();
}
}
else
{
bool isUnique;
var prefix = type?.Prefix;
do
{
var caseno = prefix + countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
var count = db.Queryable<DroneCaseInfoSingle>().Where(c => c.case_no == caseno).Count();
isUnique = count == 0;
} while (!isUnique);
}
//geom
if (!dataReader.IsDBNull(0))
{
var geometry = (Geometry)dataReader.GetValue(0);
if (!geometry.IsValid)
{
throw new Exception("图斑" + cinfo.case_no + "未闭合,请重新整理数据");
}
var geometryForWgs84 = GeometryFactory.Default.WithSRID(int.Parse(srid))
.CreateGeometry(geometry);
geomSql.AppendFormat($" update drone_caseinfo_import set geom = '{geometryForWgs84.AsText()}' where \"Id\" = '{cinfo.Id}';");
}
datalist.Add(cinfo);
}
}
using (var uow = base.UnitWork.CreateContext())
{
//await uow.DroneCaseInfoSingle.InsertRangeAsync(datalist);
await uow.DroneShpData.InsertRangeAsync(shplist);
await uow.Db.Ado.ExecuteCommandAsync(geomSql.ToString());
//await uow.Db.Ado.ExecuteCommandAsync(sql.ToString());
var flag = uow.Commit();
return new Response<bool>()
{
Result = flag,
Message = "ok"
};
}
}
#endregion
}