CNCEC_SUBQHSE_WUHUAN/SGGL/BLL/DataShare/APIDataShareSyncService.cs

574 lines
21 KiB
C#
Raw Normal View History

using System.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace BLL
{
/// <summary>
/// 数据共享互通辅助服务
/// </summary>
public class APIDataShareSyncService
{
#region
/// <summary>
/// 获取班组Id
/// </summary>
/// <param name="TeamGroupName"></param>
/// <param name="projectId"></param>
/// <param name="unitId"></param>
/// <returns></returns>
public static string GetTeamGroupId(string TeamGroupName, string projectId, string unitId)
{
string TeamGroupId = null;
if (!string.IsNullOrEmpty(TeamGroupName))
{
var tg = Funs.DB.ProjectData_TeamGroup.Where(x => x.TeamGroupName == TeamGroupName && x.ProjectId == projectId && x.UnitId == unitId).ToList();
if (tg.Count == 0)
{
Model.ProjectData_TeamGroup newTeamGroup = new Model.ProjectData_TeamGroup
{
TeamGroupId = SQLHelper.GetNewID(typeof(Model.ProjectData_TeamGroup)),
ProjectId = projectId,
UnitId = unitId,
TeamGroupName = TeamGroupName,
Remark = "导入"
};
TeamGroupService.AddTeamGroup(newTeamGroup);
TeamGroupId = newTeamGroup.TeamGroupId;
}
else
{
TeamGroupId = tg.FirstOrDefault().TeamGroupId;
}
}
return TeamGroupId;
}
#endregion
#region
/// <summary>
/// 作业区域
/// </summary>
/// <param name="UnitWorkName"></param>
/// <param name="projectId"></param>
/// <returns></returns>
public static string getUnitWorkId(string UnitWorkName, string projectId)
{
string UnitWorkId = null;
if (!string.IsNullOrEmpty(UnitWorkName))
{
var uw = Funs.DB.WBS_UnitWork.Where(x =>
x.UnitWorkName == UnitWorkName && x.ProjectId == projectId && x.SuperUnitWork == null).ToList();
if (uw.Count == 0)
{
Model.WBS_UnitWork newUnitWork = new Model.WBS_UnitWork
{
UnitWorkId = SQLHelper.GetNewID(typeof(Model.WBS_UnitWork)),
ProjectId = projectId,
UnitWorkName = UnitWorkName,
};
UnitWorkService.AddUnitWork(newUnitWork);
UnitWorkId = newUnitWork.UnitWorkId;
}
else
{
UnitWorkId = uw.FirstOrDefault().UnitWorkId;
}
}
return UnitWorkId;
}
#endregion
#region
/// <summary>
/// 获取系统用户
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static string getUserId(string userName)
{
string UserId = null;
if (!string.IsNullOrEmpty(userName))
{
var u = Funs.DB.Sys_User.Where(x =>
x.UserName == userName).ToList();
if (u.Count == 0)
{
Model.Sys_User newUser = new Model.Sys_User
{
UserId = SQLHelper.GetNewID(typeof(Model.Sys_User)),
UserName = userName,
// Remark = "导入",
};
UserService.AddUser(newUser);
UserId = newUser.UserId;
}
else
{
UserId = u.FirstOrDefault().UserId;
}
}
return UserId;
}
#endregion
#region
/// <summary>
/// 获取检查类别
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static string getCheckItemSetId(string checkItemName)
{
string CheckItemSetId = null;
if (!string.IsNullOrEmpty(checkItemName))
{
var cis = Funs.DB.Technique_CheckItemSet.Where(x =>
x.CheckItemName == checkItemName && x.CheckType == "2").ToList();
if (cis.Count == 0)
{
Model.Technique_CheckItemSet newCheckItemSet = new Model.Technique_CheckItemSet
{
CheckItemSetId = SQLHelper.GetNewID(typeof(Model.Technique_CheckItemSet)),
CheckItemName = checkItemName,
SupCheckItem = "0",
CheckType = "2",
};
Technique_CheckItemSetService.AddCheckItemSet(newCheckItemSet);
CheckItemSetId = newCheckItemSet.CheckItemSetId;
}
else
{
CheckItemSetId = cis.FirstOrDefault().CheckItemSetId;
}
}
return CheckItemSetId;
}
#endregion
#region
/// <summary>
/// 获取巡检问题类型
/// </summary>
/// <param name="RegisterTypesName"></param>
/// <returns></returns>
public static string getRegisterTypesId(string RegisterTypesName)
{
string RegisterTypesId = null;
if (!string.IsNullOrEmpty(RegisterTypesName))
{
var ht = Funs.DB.HSSE_Hazard_HazardRegisterTypes.Where(x =>
x.RegisterTypesName == RegisterTypesName && x.HazardRegisterType == "1").ToList();
if (ht.Count == 0)
{
Model.HSSE_Hazard_HazardRegisterTypes newHazardRegisterTypes = new Model.HSSE_Hazard_HazardRegisterTypes
{
RegisterTypesId = SQLHelper.GetNewID(typeof(Model.HSSE_Hazard_HazardRegisterTypes)),
RegisterTypesName = RegisterTypesName,
HazardRegisterType = "1",
Remark = "导入",
};
HSSE_Hazard_HazardRegisterTypesService.AddHazardRegisterTypes(newHazardRegisterTypes);
RegisterTypesId = newHazardRegisterTypes.RegisterTypesId;
}
else
{
RegisterTypesId = ht.FirstOrDefault().RegisterTypesId;
}
}
return RegisterTypesId;
}
#endregion
#region
/// <summary>
/// 特岗证书
/// </summary>
/// <param name="CertificateName"></param>
/// <returns></returns>
public static Model.CertificateItem GetPersonQualityByPersonId(string personId)
{
Model.CertificateItem item = new Model.CertificateItem();
var personQuality = PersonQualityService.GetPersonQualityByPersonId(personId);
if (personQuality != null)
{
item.PersonQualityId = personQuality.PersonQualityId;//主键
item.CertificateId = personQuality.CertificateId;
item.CertificateName = personQuality.CertificateName;
item.CertificateNo = personQuality.CertificateNo;
item.CertificateLimitDate = personQuality.LimitDate;
}
return item;
}
#endregion
#region
public static void ProcessPersonQualityData(Model.CertificateItem item, string personId)
{
using (Model.SGGLDB db = new Model.SGGLDB(Funs.ConnString))
{
if (item == null)
{
return;
}
if (!string.IsNullOrEmpty(item.CertificateId))
{
var personQuality = BLL.PersonQualityService.GetPersonQualityByPersonId(personId);
var certificate =
db.Base_Certificate.FirstOrDefault(e => e.CertificateId == item.CertificateId);
var CertificateId = string.Empty;
if (certificate != null)
{
CertificateId = certificate.CertificateId;
}
else
{
Model.Base_Certificate newCertificate = new Model.Base_Certificate
{
CertificateId = SQLHelper.GetNewID(typeof(Model.Base_Certificate)),
CertificateName = item.CertificateName,
Remark = "导入"
};
db.Base_Certificate.InsertOnSubmit(newCertificate);
db.SubmitChanges();
// BLL.CertificateService.AddCertificate(newCertificate);
CertificateId = newCertificate.CertificateId;
}
if (personQuality != null)
{
personQuality.CertificateId = CertificateId;
personQuality.CertificateName = item.CertificateName;
personQuality.CertificateNo = item.CertificateNo;
personQuality.LimitDate = item.CertificateLimitDate;
BLL.PersonQualityService.UpdatePersonQuality(personQuality);
}
else
{
Model.QualityAudit_PersonQuality newPersonQuality = new Model.QualityAudit_PersonQuality
{
PersonQualityId = SQLHelper.GetNewID(typeof(Model.QualityAudit_PersonQuality)),
PersonId = personId,
};
newPersonQuality.CertificateId = CertificateId;
newPersonQuality.CertificateName = item.CertificateName;
newPersonQuality.CertificateNo = item.CertificateNo;
newPersonQuality.LimitDate = item.CertificateLimitDate;
BLL.PersonQualityService.AddPersonQuality(newPersonQuality);
}
}
}
}
#endregion
#region
/// <summary>
/// 岗位
/// </summary>
/// <param name="WorkPostName"></param>
/// <returns></returns>
public static string getWorkPostId(string WorkPostName, string PostType, string IsHsse, string IsCQMS)
{
string WorkPostId = null;
if (!string.IsNullOrEmpty(WorkPostName))
{
var wp = Funs.DB.Base_WorkPost.Where(x => x.WorkPostName == WorkPostName).ToList();
if (wp.Count == 0)
{
Model.Base_WorkPost newWorkPost = new Model.Base_WorkPost
{
WorkPostId = SQLHelper.GetNewID(typeof(Model.Base_WorkPost)),
WorkPostName = WorkPostName,
PostType = PostType,
IsHsse = Convert.ToBoolean(IsHsse),
IsCQMS = Convert.ToBoolean(IsCQMS),
Remark = "导入"
};
WorkPostService.AddWorkPost(newWorkPost);
WorkPostId = newWorkPost.WorkPostId;
}
else
{
WorkPostId = wp.FirstOrDefault().WorkPostId;
}
}
return WorkPostId;
}
#endregion
#region
/// <summary>
/// 单位工程
/// </summary>
/// <param name="WorkAreaName"></param>
/// <param name="projectId"></param>
/// <returns></returns>
public static string getWorkAreaId(string WorkAreaName, string projectId)
{
string WorkAreaId = null;
if (!string.IsNullOrEmpty(WorkAreaName))
{
var names = WorkAreaName.Split(',');
List<string> workAreaIdList = new List<string>();
foreach (var name in names)
{
var uw = Funs.DB.WBS_UnitWork.Where(x =>
x.UnitWorkName == name && x.ProjectId == projectId).ToList();
if (uw.Count == 0)
{
Model.WBS_UnitWork newUnitWork = new Model.WBS_UnitWork
{
UnitWorkId = SQLHelper.GetNewID(typeof(Model.WBS_UnitWork)),
ProjectId = projectId,
UnitWorkName = name,
};
UnitWorkService.AddUnitWork(newUnitWork);
workAreaIdList.Add(newUnitWork.UnitWorkId);
}
else
{
workAreaIdList.Add(uw.FirstOrDefault().UnitWorkId);
}
}
WorkAreaId = string.Join(",", workAreaIdList);
}
return WorkAreaId;
}
#endregion
#region id获取单位工程名称
/// <summary>
/// 获取根据id获取单位工程名称
/// </summary>
/// <param name="WorkAreaId"></param>
/// <param name="projectId"></param>
/// <returns></returns>
public static string GetWorkAreaNames(string WorkAreaId, string projectId)
{
string WorkAreaNames = string.Empty;
if (!string.IsNullOrEmpty(WorkAreaId))
{
var workAreas = WorkAreaId.Split(',');
//创建一个数组集合
List<string> workAreaNameList = new List<string>();
foreach (var workArea in workAreas)
{
var WorkAreaName = Funs.DB.WBS_UnitWork
.First(x => x.UnitWorkId == workArea && x.ProjectId == projectId)
.UnitWorkName;
workAreaNameList.Add(WorkAreaName);
}
WorkAreaNames = string.Join(",", workAreaNameList);
}
return WorkAreaNames;
}
#endregion
#region base64的文件
public static async Task<byte[]> DownloadHeadImageAsync(string webUrl, string photoUrl)
{
byte[] b = null;
try
{
if (!string.IsNullOrEmpty(photoUrl))
{
string localRoot = ConfigurationManager.AppSettings["localRoot"]; // 物理路径
// 先下载到本地(异步等待完成)
DownloadAndSaveFileWithRetryAsync(webUrl, photoUrl, localRoot);
b = AttachFileService.SetImageToByteArray(localRoot + photoUrl.Split(',')[0]);
}
}
catch (Exception ex)
{
throw ex;
}
return b;
}
#endregion
#region AttachFile文件表中添加或修改数据
public static async Task OperationAttachFile(string webUrl, string tokeyId, string menuId, string attachFileUrl)
{
using (Model.SGGLDB db = new Model.SGGLDB(Funs.ConnString))
{
if (!string.IsNullOrEmpty(attachFileUrl))
{
string localRoot = ConfigurationManager.AppSettings["localRoot"]; //物理路径
//attachFileUrl可能是多个
string[] attachFileUrls = attachFileUrl.Split(',');
var attachFile = db.AttachFile.FirstOrDefault(x => x.ToKeyId == tokeyId && x.MenuId == menuId);
if (attachFile != null)
{
if (attachFile.AttachUrl != attachFileUrl)
{
string[] oldAttachFileUrls = attachFile.AttachUrl.Split(',');
foreach (var oldFileUrl in oldAttachFileUrls)
{
//删除之前的
UploadFileService.DeleteFile(localRoot, oldFileUrl);
}
foreach (var fileUrl in attachFileUrls)
{
DownloadAndSaveFileWithRetryAsync(webUrl, fileUrl, localRoot);
}
UploadFileService.SaveAttachUrl(
UploadFileService.GetSourceByAttachUrl(attachFileUrl, 10, null),
attachFileUrl, menuId, tokeyId);
}
}
else
{
foreach (var fileUrl in attachFileUrls)
{
DownloadAndSaveFileWithRetryAsync(webUrl, fileUrl, localRoot);
}
UploadFileService.SaveAttachUrl(
UploadFileService.GetSourceByAttachUrl(attachFileUrl, 10, null),
attachFileUrl, menuId, tokeyId);
}
}
}
}
public static async Task DownloadAndSaveFileAsync(string webUrl, string attachFileUrl, string localPath)
{
// 验证输入参数
if (string.IsNullOrEmpty(webUrl) || string.IsNullOrEmpty(attachFileUrl) || string.IsNullOrEmpty(localPath))
{
BLL.ErrLogInfo.WriteLog(
$"下载文件参数无效: webUrl={webUrl}, attachFileUrl={attachFileUrl}, localPath={localPath}");
return;
}
try
{
// 构造完整的远程文件 URL
string fullRemoteUrl = $"{webUrl.TrimEnd('/')}/{attachFileUrl.TrimStart('/')}";
// 构造本地文件路径
string localFilePath = Path.Combine(localPath, attachFileUrl);
// 确保本地目录存在
string directoryPath = Path.GetDirectoryName(localFilePath);
if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
// 使用独立的HttpClient实例并配置不捕获同步上下文
using (var httpClient = new HttpClient())
{
// 设置合理的超时时间
httpClient.Timeout = TimeSpan.FromMinutes(3);
// 下载文件字节使用ConfigureAwait(false)避免上下文问题)
byte[] fileBytes = await httpClient.GetByteArrayAsync(fullRemoteUrl).ConfigureAwait(false);
// 写入文件同样使用ConfigureAwait(false)
await Task.Run(() => File.WriteAllBytes(localFilePath, fileBytes)).ConfigureAwait(false);
}
}
catch (HttpRequestException httpEx)
{
BLL.ErrLogInfo.WriteLog($"HTTP请求失败 - URL: {webUrl}/{attachFileUrl}", httpEx);
// 不抛出异常,让调用方继续处理
}
catch (DirectoryNotFoundException dirEx)
{
BLL.ErrLogInfo.WriteLog($"目录创建失败 - 路径: {localPath}", dirEx);
}
catch (UnauthorizedAccessException authEx)
{
BLL.ErrLogInfo.WriteLog($"文件访问权限不足 - 路径: {Path.Combine(localPath, attachFileUrl)}", authEx);
}
catch (Exception ex)
{
BLL.ErrLogInfo.WriteLog($"下载文件失败 - URL: {webUrl}/{attachFileUrl}", ex);
// 不重新抛出异常,避免中断整个流程
}
}
// 添加重试机制的下载方法
public static async Task<bool> DownloadAndSaveFileWithRetryAsync(string webUrl, string attachFileUrl,
string localPath, int maxRetries = 3)
{
for (int attempt = 0; attempt < maxRetries; attempt++)
{
try
{
await DownloadAndSaveFileAsync(webUrl, attachFileUrl, localPath);
return true; // 成功下载
}
catch (HttpRequestException)
{
if (attempt == maxRetries - 1)
{
BLL.ErrLogInfo.WriteLog($"下载失败,已重试{maxRetries}次 - URL: {webUrl}/{attachFileUrl}");
return false;
}
// 等待后重试
await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt)));
}
}
return false;
}
#endregion
}
}