diff --git a/src/Shentun.Peis.Application/CCTJExportDatas/CCTJExportDataOldAppService.cs b/src/Shentun.Peis.Application/CCTJExportDatas/CCTJExportDataOldAppService.cs new file mode 100644 index 0000000..bf174ed --- /dev/null +++ b/src/Shentun.Peis.Application/CCTJExportDatas/CCTJExportDataOldAppService.cs @@ -0,0 +1,3933 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Shentun.Peis.ColumnReferences; +using Shentun.Peis.CustomerOrgs; +using Shentun.Peis.DataMigrations; +using Shentun.Peis.Enums; +using Shentun.Peis.ItemTypes; +using Shentun.Peis.Models; +using Shentun.Peis.MyUser; +using Shentun.Peis.PatientRegisters; +using Shentun.Peis.RegisterCheckItems; +using Shentun.Utilities; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Data; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Volo.Abp; +using Volo.Abp.Application.Services; +using Volo.Abp.Domain.Entities; +using Volo.Abp.Domain.Repositories; +using Volo.Abp.Identity; +using Volo.Abp.Uow; + +namespace Shentun.Peis.CCTJExportDatas +{ + /// + /// 长城体检中心 老系统数据导入2 + /// + [Authorize] + public class CCTJExportDataOldAppService : ApplicationService + { + //默认指引类别ID + private readonly char defaultGuidTypeId = '0'; + //默认体检报告类别ID + private readonly char defaultMedicalReportTypeId = '0'; + //默认体检结论类别 + private readonly string defaultMedicalConclusionType = "01"; + //默认体检中心 + private readonly Guid defaultMedicalCenterId = Guid.Parse("8beda924-3925-4525-be49-d28bbb3618c4"); + //默认容器ID + private readonly Guid defaultSampleContainerId = Guid.Parse("3a126a07-eb42-a369-99e4-114a2629d714"); + //默认单位性质ID + private readonly Guid defaultOrgTypeId = Guid.Parse("3a126a08-9607-fe40-e5da-6daa01712468"); + + //老系统数据库配置 + private readonly SqlSugarClient oldDb = new SqlSugarClient(new ConnectionConfig() + { + ConnectionString = "server=192.168.0.3;uid=sa;pwd=132****6302;database=oldPeis;Encrypt=false;", + DbType = SqlSugar.DbType.SqlServer, + IsAutoCloseConnection = true + }); + + //新系统配置 + private readonly SqlSugarClient newDb = new SqlSugarClient(new ConnectionConfig() + { + ConnectionString = "Host=localhost;Port=5432;Database=ShentunPeis;User ID=postgres;Password=St123456;", + DbType = SqlSugar.DbType.PostgreSQL, + IsAutoCloseConnection = true + }); + + private readonly UnitOfWorkManager _unitOfWorkManager; + private readonly IRepository _deviceTypeRepository; + private readonly IRepository _itemTypeRepository; + private readonly ItemTypeManager _itemTypeManager; + private readonly IRepository _unitRepository; + private readonly IRepository _medicalTypeRepository; + private readonly IRepository _personnelTypeRepository; + private readonly IRepository _invoiceItemTypeRepository; + private readonly IRepository _fieldComparisonRepository; + private readonly IRepository _sampleTypeRepository; + private readonly IRepository _itemRepository; + private readonly IRepository _referenceRangeRepository; + private readonly IRepository _asbitemRepository; + private readonly IRepository _asbitemDetailRepository; + private readonly IRepository _medicalPackageRepository; + private readonly IRepository _medicalPackageDetailRepository; + private readonly IRepository _diagnosisRepository; + private readonly IRepository _suggestionRepository; + private readonly IRepository _itemResultTemplateRepository; + private readonly IRepository _ItemResultMatchRepository; + private readonly IRepository _menuInfoRepository; + private readonly IRepository _customerOrgRepository; + private readonly CustomerOrgManager _customerOrgManager; + private readonly IRepository _customerOrgRegisterRepository; + private readonly IRepository _customerOrgGroupRepository; + private readonly IRepository _customerOrgGroupDetailRepository; + private readonly IRepository _nationRepository; + private readonly ILogger _logger; + private readonly IRepository _identityUserRepository; + private readonly IRepository _medicalConclusionRepository; + private readonly IRepository _sampleGroupRepository; + private readonly IRepository _sampleGroupDetailRepository; + private readonly IRepository _sysParmTypeRepository; + private readonly IRepository _sysParmRepository; + private readonly IRepository _sysParmValueRepository; + private readonly IRepository _collectItemTypeRepository; + private readonly IRepository _asbitemGuideRepository; + //业务 + private readonly IRepository _patientRepository; + private readonly IRepository _patientRegisterRepository; + private readonly IRepository _registerCheckRepository; + private readonly IRepository _registerCheckAsbitemRepository; + private readonly IRepository _registerCheckItemRepository; + private readonly IRepository _registerCheckSummaryRepository; + private readonly RegisterCheckItemManager _registerCheckItemManager; + private readonly IRepository _sumSuggestionHeaderRepository; + private readonly IRepository _sumSuggestionContentRepository; + private readonly IRepository _sumSummaryHeaderRepository; + private readonly IRepository _sumSummaryContentRepository; + private readonly IRepository _sumDiagnosisRepository; + private readonly IConfiguration _configuration; + private readonly MyUserAppService _myUserAppService; + private readonly ColumnReferenceAppService _columnReferenceAppService; + private readonly IRepository _cardTypeRepository; + private readonly IRepository _cardRegisterRepository; + + private static List fieldComparisonTempList = new List(); + public CCTJExportDataOldAppService( + UnitOfWorkManager unitOfWorkManager, + IRepository deviceTypeRepository, + IRepository itemTypeRepository, + ItemTypeManager itemTypeManager, + IRepository unitRepository, + IRepository medicalTypeRepository, + IRepository personnelTypeRepository, + IRepository invoiceItemTypeRepository, + IRepository fieldComparisonRepository, + IRepository sampleTypeRepository, + IRepository itemRepository, + IRepository referenceRangeRepository, + IRepository asbitemRepository, + IRepository asbitemDetailRepository, + IRepository medicalPackageRepository, + IRepository medicalPackageDetailRepository, + IRepository diagnosisRepository, + IRepository suggestionRepository, + IRepository itemResultTemplateRepository, + IRepository itemResultMatchRepository, + IRepository menuInfoRepository, + IRepository customerOrgRepository, + CustomerOrgManager customerOrgManager, + IRepository customerOrgRegisterRepository, + IRepository customerOrgGroupRepository, + IRepository customerOrgGroupDetailRepository, + IRepository nationRepository, + ILogger logger, + IRepository identityUserRepository, + IRepository medicalConclusionRepository, + IRepository sampleGroupRepository, + IRepository sampleGroupDetailRepository, + IRepository sysParmTypeRepository, + IRepository sysParmRepository, + IRepository sysParmValueRepository, + IRepository collectItemTypeRepository, + IRepository asbitemGuideRepository, + IRepository patientRepository, + IRepository patientRegisterRepository, + IRepository registerCheckRepository, + IRepository registerCheckAsbitemRepository, + IRepository registerCheckItemRepository, + IRepository registerCheckSummaryRepository, + RegisterCheckItemManager registerCheckItemManager, + IRepository sumSuggestionHeaderRepository, + IRepository sumSuggestionContentRepository, + IRepository sumSummaryHeaderRepository, + IRepository sumSummaryContentRepository, + IRepository sumDiagnosisRepository, + IConfiguration configuration, + MyUserAppService myUserAppService, + ColumnReferenceAppService columnReferenceAppService, + IRepository cardTypeRepository, + IRepository cardRegisterRepository) + { + _unitOfWorkManager = unitOfWorkManager; + _deviceTypeRepository = deviceTypeRepository; + _itemTypeRepository = itemTypeRepository; + _itemTypeManager = itemTypeManager; + _unitRepository = unitRepository; + _medicalTypeRepository = medicalTypeRepository; + _personnelTypeRepository = personnelTypeRepository; + _invoiceItemTypeRepository = invoiceItemTypeRepository; + _fieldComparisonRepository = fieldComparisonRepository; + _sampleTypeRepository = sampleTypeRepository; + _itemRepository = itemRepository; + _referenceRangeRepository = referenceRangeRepository; + _asbitemRepository = asbitemRepository; + _asbitemDetailRepository = asbitemDetailRepository; + _medicalPackageRepository = medicalPackageRepository; + _medicalPackageDetailRepository = medicalPackageDetailRepository; + _diagnosisRepository = diagnosisRepository; + _suggestionRepository = suggestionRepository; + _itemResultTemplateRepository = itemResultTemplateRepository; + _ItemResultMatchRepository = itemResultMatchRepository; + _menuInfoRepository = menuInfoRepository; + _customerOrgRepository = customerOrgRepository; + _customerOrgManager = customerOrgManager; + _customerOrgRegisterRepository = customerOrgRegisterRepository; + _customerOrgGroupRepository = customerOrgGroupRepository; + _customerOrgGroupDetailRepository = customerOrgGroupDetailRepository; + _nationRepository = nationRepository; + _logger = logger; + _identityUserRepository = identityUserRepository; + _medicalConclusionRepository = medicalConclusionRepository; + _sampleGroupRepository = sampleGroupRepository; + _sampleGroupDetailRepository = sampleGroupDetailRepository; + _sysParmTypeRepository = sysParmTypeRepository; + _sysParmRepository = sysParmRepository; + _sysParmValueRepository = sysParmValueRepository; + _collectItemTypeRepository = collectItemTypeRepository; + _asbitemGuideRepository = asbitemGuideRepository; + _patientRepository = patientRepository; + _patientRegisterRepository = patientRegisterRepository; + _registerCheckRepository = registerCheckRepository; + _registerCheckAsbitemRepository = registerCheckAsbitemRepository; + _registerCheckItemRepository = registerCheckItemRepository; + _registerCheckSummaryRepository = registerCheckSummaryRepository; + _registerCheckItemManager = registerCheckItemManager; + _sumSuggestionHeaderRepository = sumSuggestionHeaderRepository; + _sumSuggestionContentRepository = sumSuggestionContentRepository; + _sumSummaryHeaderRepository = sumSummaryHeaderRepository; + _sumSummaryContentRepository = sumSummaryContentRepository; + _sumDiagnosisRepository = sumDiagnosisRepository; + _configuration = configuration; + _myUserAppService = myUserAppService; + _columnReferenceAppService = columnReferenceAppService; + _cardTypeRepository = cardTypeRepository; + _cardRegisterRepository = cardRegisterRepository; + } + + + /// + /// 处理基础数据 + /// + /// + [AllowAnonymous] + [HttpPost("api/app/CCTJExportDataOldOld/HandBaseData")] + public async Task HandBaseData() + { + await TransferDeviceTypeData(); + await TransferUnitData(); + await TransferMedicalTypeData(); + await TransferPersonnelTypeData(); + await TransferInvoiceItemTypeData(); + await TransferCollectItemTypeData(); + await TransferItemTypeData(); + await TransferSampleTypeData(); + await TransferNationData(); + await TransferMedicalConclusionData(); + await TransferUserData(); + } + + + /// + /// 处理基础项目相关数据 + /// + /// + [AllowAnonymous] + [HttpPost("api/app/CCTJExportDataOld/HandBaseItemData")] + public async Task HandBaseItemData() + { + await TransferItemData(); + await TransferAsbitemData(); + await TransferAsbitemDetailData(); + await TransferMedicalPackageData(); + await TransferMedicalPackageDetailData(); + await TransferDiagnosisData(); + await TransferSuggestionData(); + await TransferItemResultTemplateData(); + await TransferItemResultMatchData(); + await TransferReferenceRangeData(); + await TransferSampleGroupData(); + await TransferSampleGroupDetailData(); + await TransferTopCustomerOrgData(); + await TransferTwoCustomerOrgData(); + await TransferThreeCustomerOrgData(); + await TransferFourCustomerOrgData(); + await TransferCustomerOrgRegisterData(); + await TransferCustomerOrgGroupData(); + await TransferCustomerOrgGroupDetailData(); + } + + + + #region 基础数据 + + /// + /// 迁移仪器类别数据 + /// + /// + [RemoteService(false)] + public async Task TransferDeviceTypeData() + { + var count = await _deviceTypeRepository.GetCountAsync(); + if (count == 0) + { + var oldDeviceTypeList = await oldDb.Ado.GetDataTableAsync("select device_type_id,device_type_name from device_type order by display_order asc"); + if (oldDeviceTypeList.Rows.Count > 0) + { + foreach (DataRow row in oldDeviceTypeList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + Guid deviceTypeId = GuidGenerator.Create(); + + var data = new DeviceType(deviceTypeId) + { + CheckTypeFlag = '0', + DisplayName = row["device_type_name"].ToString(), + DisplayOrder = oldDeviceTypeList.Rows.IndexOf(row) + 1, + SimpleCode = LanguageConverter.GetPYSimpleCode(row["device_type_name"].ToString()) + }; + + await _deviceTypeRepository.InsertAsync(data); + + var fieldComparison = new FieldComparison + { + TableName = "device_type", + FieldName = "id", + NewKeyValue = deviceTypeId.ToString(), + OldKeyValue = row["device_type_id"].ToString() + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + } + } + + _logger.LogInformation($"仪器类别数据处理完毕,处理数量{oldDeviceTypeList.Rows.Count}"); + } + else + { + _logger.LogInformation("仪器类别数据已存在,未处理"); + } + } + + + /// + /// 迁移数值单位数据 + /// + /// + [RemoteService(false)] + public async Task TransferUnitData() + { + var count = await _unitRepository.GetCountAsync(); + if (count == 0) + { + var oldUnitList = await oldDb.Ado.GetDataTableAsync("select unit_id,unit_name from unit order by display_order asc"); + if (oldUnitList.Rows.Count > 0) + { + foreach (DataRow row in oldUnitList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + Guid unitId = GuidGenerator.Create(); + var data = new Unit(unitId) + { + DisplayName = row["unit_name"].ToString(), + DisplayOrder = oldUnitList.Rows.IndexOf(row) + 1, + SimpleCode = LanguageConverter.GetPYSimpleCode(row["unit_name"].ToString()) + }; + + await _unitRepository.InsertAsync(data); + + var fieldComparison = new FieldComparison + { + TableName = "unit", + FieldName = "id", + NewKeyValue = unitId.ToString(), + OldKeyValue = row["unit_id"].ToString() + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + + } + + _logger.LogInformation($"数值单位数据处理完毕,处理数量{oldUnitList.Rows.Count}"); + + } + else + { + _logger.LogInformation($"数值单位数据已存在,未处理"); + } + } + } + + /// + /// 迁移体检类别数据 + /// + /// + [RemoteService(false)] + public async Task TransferMedicalTypeData() + { + var count = await _medicalTypeRepository.GetCountAsync(); + if (count == 0) + { + + var oldMedicalTypeList = await oldDb.Ado.GetDataTableAsync("select medical_type_id,medical_type_name from medical_type order by display_order asc"); + if (oldMedicalTypeList.Rows.Count > 0) + { + foreach (DataRow row in oldMedicalTypeList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + Guid medicalTypeId = GuidGenerator.Create(); + var data = new MedicalType(medicalTypeId) + { + DisplayName = row["medical_type_name"].ToString(), + DisplayOrder = oldMedicalTypeList.Rows.IndexOf(row) + 1, + SimpleCode = LanguageConverter.GetPYSimpleCode(row["medical_type_name"].ToString()) + }; + + await _medicalTypeRepository.InsertAsync(data); + + var fieldComparison = new FieldComparison + { + TableName = "medical_type", + FieldName = "id", + NewKeyValue = medicalTypeId.ToString(), + OldKeyValue = row["medical_type_id"].ToString() + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + + } + + _logger.LogInformation($"体检类别数据处理完毕,处理数量{oldMedicalTypeList.Rows.Count}"); + + } + else + { + _logger.LogInformation($"体检类别数据已存在,未处理"); + } + } + } + + + /// + /// 迁移人员类别数据 + /// + /// + [RemoteService(false)] + public async Task TransferPersonnelTypeData() + { + var count = await _personnelTypeRepository.GetCountAsync(); + if (count == 0) + { + + var oldPersonnelTypeList = await oldDb.Ado.GetDataTableAsync("select personnel_type_id,personnel_type_name from personnel_type order by display_order asc"); + if (oldPersonnelTypeList.Rows.Count > 0) + { + + + foreach (DataRow row in oldPersonnelTypeList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + Guid personnelTypeId = GuidGenerator.Create(); + + var data = new PersonnelType(personnelTypeId) + { + DisplayName = row["personnel_type_name"].ToString(), + DisplayOrder = oldPersonnelTypeList.Rows.IndexOf(row) + 1, + SimpleCode = LanguageConverter.GetPYSimpleCode(row["personnel_type_name"].ToString()) + }; + + await _personnelTypeRepository.InsertAsync(data); + + var fieldComparison = new FieldComparison + { + TableName = "personnel_type", + FieldName = "id", + NewKeyValue = personnelTypeId.ToString(), + OldKeyValue = row["personnel_type_id"].ToString() + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + + + } + + + } + _logger.LogInformation($"人员类别数据处理完毕,处理数量{oldPersonnelTypeList.Rows.Count}"); + } + else + { + _logger.LogInformation($"人员类别数据已存在,未处理"); + } + } + + + + /// + /// 迁移发票项目类别数据 + /// + /// + [RemoteService(false)] + public async Task TransferInvoiceItemTypeData() + { + var count = await _invoiceItemTypeRepository.GetCountAsync(); + if (count == 0) + { + var oldInvoiceItemTypeList = await oldDb.Ado.GetDataTableAsync("select invoice_item_type_id,invoice_item_type_name from invoice_item_type order by display_order asc"); + if (oldInvoiceItemTypeList.Rows.Count > 0) + { + foreach (DataRow row in oldInvoiceItemTypeList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + Guid invoiceItemTypeId = GuidGenerator.Create(); + + var data = new InvoiceItemType(invoiceItemTypeId) + { + DisplayName = row["invoice_item_type_name"].ToString(), + DisplayOrder = oldInvoiceItemTypeList.Rows.IndexOf(row) + 1, + SimpleCode = LanguageConverter.GetPYSimpleCode(row["invoice_item_type_name"].ToString()) + }; + + await _invoiceItemTypeRepository.InsertAsync(data); + + var fieldComparison = new FieldComparison + { + TableName = "invoice_item_type", + FieldName = "id", + NewKeyValue = invoiceItemTypeId.ToString(), + OldKeyValue = row["invoice_item_type_id"].ToString() + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + } + + + } + _logger.LogInformation($"发票项目类别数据处理完毕,处理数量{oldInvoiceItemTypeList.Rows.Count}"); + } + else + { + _logger.LogInformation($"发票项目类别数据已存在,未处理"); + } + } + + + + /// + /// 迁移汇总项目类别数据 + /// + /// + [RemoteService(false)] + public async Task TransferCollectItemTypeData() + { + var count = await _collectItemTypeRepository.GetCountAsync(); + if (count == 0) + { + var oldCollectItemTypeList = await oldDb.Ado.GetDataTableAsync("select collect_item_type_id,collect_item_type_name,invoice_item_type_id from collect_item_type order by display_order asc"); + if (oldCollectItemTypeList.Rows.Count > 0) + { + foreach (DataRow row in oldCollectItemTypeList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + Guid collectItemTypeId = GuidGenerator.Create(); + + + Guid invoiceItemTypeId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "invoice_item_type" && m.OldKeyValue == row["invoice_item_type_id"].ToString()).FirstOrDefault().NewKeyValue); + + var data = new CollectItemType(collectItemTypeId) + { + DisplayName = row["collect_item_type_name"].ToString(), + DisplayOrder = oldCollectItemTypeList.Rows.IndexOf(row) + 1, + SimpleCode = LanguageConverter.GetPYSimpleCode(row["collect_item_type_name"].ToString()), + InvoiceItemTypeId = invoiceItemTypeId + }; + + await _collectItemTypeRepository.InsertAsync(data); + + var fieldComparison = new FieldComparison + { + TableName = "collect_item_type", + FieldName = "id", + NewKeyValue = collectItemTypeId.ToString(), + OldKeyValue = row["collect_item_type_id"].ToString() + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + } + + _logger.LogInformation($"汇总项目类别数据处理完毕,处理数量{oldCollectItemTypeList.Rows.Count}"); + } + else + { + _logger.LogInformation($"汇总项目类别数据已存在,未处理"); + } + } + } + + + /// + /// 迁移项目类别-科室数据 + /// + /// + [RemoteService(false)] + public async Task TransferItemTypeData() + { + var count = await _itemTypeRepository.GetCountAsync(); + if (count == 0) + { + + var oldItemTypeList = await oldDb.Ado.GetDataTableAsync("select department_id,department_type,department_name,merge_asbitem_flag,print_pacs_barcode_flag from department order by display_order asc"); + if (oldItemTypeList.Rows.Count > 0) + { + foreach (DataRow row in oldItemTypeList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + Guid itemTypeId = GuidGenerator.Create(); + + var data = new ItemType(itemTypeId) + { + DisplayName = row["department_name"].ToString(), + DisplayOrder = oldItemTypeList.Rows.IndexOf(row) + 1, + SimpleCode = LanguageConverter.GetPYSimpleCode(row["department_name"].ToString()), + CheckTypeFlag = Convert.ToChar(row["department_type"]), + GuidTypeId = defaultGuidTypeId, + IsMergeAsbitem = Convert.ToChar(row["merge_asbitem_flag"]), + IsWrap = 'N', + MedicalReportTypeId = defaultMedicalReportTypeId, + ParentId = null, + PathCode = _itemTypeManager.CreatePathCode(null).Result, + IsCheckRequest = Convert.ToChar(row["print_pacs_barcode_flag"]) + }; + + await _itemTypeRepository.InsertAsync(data); + + var fieldComparison = new FieldComparison + { + TableName = "item_type", + FieldName = "id", + NewKeyValue = itemTypeId.ToString(), + OldKeyValue = row["department_id"].ToString() + }; + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + } + + + } + _logger.LogInformation($"项目类别数据处理完毕,处理数量{oldItemTypeList.Rows.Count}"); + } + else + { + _logger.LogInformation($"项目类别数据已存在,未处理"); + } + } + + + /// + /// 迁移标本类型数据 + /// + /// + [RemoteService(false)] + public async Task TransferSampleTypeData() + { + var count = await _sampleTypeRepository.GetCountAsync(); + if (count == 0) + { + var oldSampleTypeList = await oldDb.Ado.GetDataTableAsync("select specimen_type_id,specimen_type_name from specimen_type order by display_order asc"); + if (oldSampleTypeList.Rows.Count > 0) + { + + foreach (DataRow row in oldSampleTypeList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + Guid sampleTypeId = GuidGenerator.Create(); + + var data = new SampleType(sampleTypeId) + { + DisplayName = row["specimen_type_name"].ToString(), + DisplayOrder = oldSampleTypeList.Rows.IndexOf(row) + 1, + SimpleCode = LanguageConverter.GetPYSimpleCode(row["specimen_type_name"].ToString()) + }; + + await _sampleTypeRepository.InsertAsync(data); + + var fieldComparison = new FieldComparison + { + TableName = "sample_type", + FieldName = "id", + NewKeyValue = sampleTypeId.ToString(), + OldKeyValue = row["specimen_type_id"].ToString() + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + } + + } + _logger.LogInformation($"标本类型数据处理完毕,处理数量{oldSampleTypeList.Rows.Count}"); + } + else + { + _logger.LogInformation($"标本类型数据已存在,未处理"); + } + } + + + /// + /// 民族数据对照 + /// + /// + [RemoteService(false)] + public async Task TransferNationData() + { + var newNationList = await _nationRepository.GetListAsync(); + var oldNationList = await oldDb.Ado.GetDataTableAsync("select * from nation"); + + if (oldNationList.Rows.Count > 0) + { + + foreach (DataRow row in oldNationList.Rows) + { + string oldName = row["nation_name"].ToString(); //老系统名称 + var newNationEnt = newNationList.Where(m => m.DisplayName.Contains(oldName)).FirstOrDefault(); + if (newNationEnt != null) + { + var fieldComparison = new FieldComparison + { + FieldName = "id", + NewKeyValue = newNationEnt.Id.ToString(), + OldKeyValue = row["nation_id"].ToString(), + TableName = "nation" + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + } + + } + + _logger.LogInformation($"民族数据处理完毕,处理数量{oldNationList.Rows.Count}"); + } + else + { + _logger.LogInformation($"民族数据无需处理"); + } + } + + /// + /// 迁移体检结论数据 + /// + /// + [RemoteService(false)] + public async Task TransferMedicalConclusionData() + { + var count = await _medicalConclusionRepository.GetCountAsync(); + if (count == 0) + { + var oldMedicalConclusionList = await oldDb.Ado.GetDataTableAsync("select medical_conclusion_id,medical_conclusion_name from medical_conclusion order by display_order asc"); + if (oldMedicalConclusionList.Rows.Count > 0) + { + foreach (DataRow row in oldMedicalConclusionList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + Guid medicalConclusionId = GuidGenerator.Create(); + + var data = new MedicalConclusion(medicalConclusionId) + { + DisplayName = row["medical_conclusion_name"].ToString(), + DisplayOrder = oldMedicalConclusionList.Rows.IndexOf(row) + 1, + SimpleCode = LanguageConverter.GetPYSimpleCode(row["medical_conclusion_name"].ToString()), + MedicalConclusionTypeId = defaultMedicalConclusionType + }; + + await _medicalConclusionRepository.InsertAsync(data); + + var fieldComparison = new FieldComparison + { + TableName = "medical_conclusion", + FieldName = "id", + NewKeyValue = medicalConclusionId.ToString(), + OldKeyValue = row["medical_conclusion_id"].ToString() + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + } + } + _logger.LogInformation($"体检结论数据处理完毕,处理数量{oldMedicalConclusionList.Rows.Count}"); + } + else + { + _logger.LogInformation("体检结论数据已存在,未处理"); + } + } + + #endregion + + + + #region 基础项目相关数据 + + /// + /// 迁移项目数据 + /// + /// + [RemoteService(false)] + public async Task TransferItemData() + { + var count = await _itemRepository.GetCountAsync(); + if (count == 0) + { + + var oldItemList = await oldDb.Ado.GetDataTableAsync("select a.* from item as a left join department as b on a.department_id=b.department_id order by b.display_order,a.display_order"); + if (oldItemList.Rows.Count > 0) + { + + foreach (DataRow row in oldItemList.Rows) + { + + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + + #region 根据仪器类别生成二级科室 + + var itemTypeId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "item_type" && m.OldKeyValue == row["department_id"].ToString()).FirstOrDefault().NewKeyValue); + + Guid? deviceTypeId = null; + + if (!string.IsNullOrWhiteSpace(row["device_type_id"].ToString())) + { + deviceTypeId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "device_type" && m.OldKeyValue == row["device_type_id"].ToString()).FirstOrDefault().NewKeyValue); + + var itemTypeEnt = await _itemTypeRepository.GetAsync(itemTypeId); + var deviceTypeEnt = await _deviceTypeRepository.GetAsync(deviceTypeId.Value); + + + var itemTypeChildEnt = await _itemTypeRepository.FirstOrDefaultAsync(m => m.ParentId == itemTypeEnt.Id && m.DisplayName == deviceTypeEnt.DisplayName); + if (itemTypeChildEnt == null) + { + Guid autoItemTypeId = GuidGenerator.Create(); + + #region 排序值 + + int displayOrder = (await _itemTypeRepository.CountAsync(m => m.ParentId == itemTypeEnt.Id)) + 1; + + #endregion + + var item_type_data = new ItemType(autoItemTypeId) + { + DisplayName = deviceTypeEnt.DisplayName, + DisplayOrder = displayOrder, + SimpleCode = LanguageConverter.GetPYSimpleCode(deviceTypeEnt.DisplayName), + CheckTypeFlag = itemTypeEnt.CheckTypeFlag, + GuidTypeId = itemTypeEnt.GuidTypeId, + IsMergeAsbitem = itemTypeEnt.IsMergeAsbitem, + IsWrap = itemTypeEnt.IsWrap, + MedicalReportTypeId = itemTypeEnt.MedicalReportTypeId, + ParentId = itemTypeEnt.Id, + PathCode = _itemTypeManager.CreatePathCode(itemTypeEnt.Id).Result, + IsCheckRequest = itemTypeEnt.IsCheckRequest + }; + + await _itemTypeRepository.InsertAsync(item_type_data); + itemTypeId = autoItemTypeId; + } + else + { + itemTypeId = itemTypeChildEnt.Id; + } + + } + + #endregion + + + + Guid? unitId = null; + if (!string.IsNullOrWhiteSpace(row["unit_id"].ToString())) + unitId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "unit" && m.OldKeyValue == row["unit_id"].ToString()).FirstOrDefault().NewKeyValue); + + Guid itemId = GuidGenerator.Create(); + + var data = new Item(itemId) + { + DisplayName = row["item_name"].ToString(), + DisplayOrder = oldItemList.Rows.IndexOf(row) + 1, + SimpleCode = LanguageConverter.GetPYSimpleCode(row["item_name"].ToString()), + CalculationFunction = "", + DefaultResult = row["default_result"].ToString(), + DiagnosisFunction = "", + EnglishShortName = row["english_abbreviation"].ToString(), + InputCheck = row["input_check"].ToString(), + IsActive = Convert.ToChar(row["valid_flag"].ToString()), + IsCalculationItem = 'N', + IsContinueProcess = 'N', + IsDiagnosisFunction = 'N', + IsNameIntoSummary = Convert.ToChar(row["name_into_summary_flag"]), + IsProduceSummary = Convert.ToChar(row["produce_summary_flag"]), + ItemTypeId = itemTypeId, + LineModeFlag = '0', + Price = Convert.ToDecimal(row["price"]), + PriceItemId = null, + ReferenceRangeTypeFlag = Convert.ToChar(row["reference_range_type"]), + ResultTemplateTypeFlag = '0', + UnitId = unitId, + DeviceTypeId = deviceTypeId + }; + + await _itemRepository.InsertAsync(data); + + if (row["reference_range_type"].ToString() == "2" && !string.IsNullOrWhiteSpace(row["reference_range_value"].ToString())) + { + //增加字符型参考范围到参考范围表 + + Guid referenceRangeId = GuidGenerator.Create(); + + var referenceRange = new ReferenceRange(referenceRangeId) + { + AgeLowerLimit = 0, + AgeUpperLimit = 200, + CriticalRangeValue = "", + ItemId = itemId, + ForSexId = ForSexFlag.All, + LowerDiagnosisId = null, + ReferenceRangeTypeFlag = ItemReferenceRangeTypeFlag.Character, + UpperDiagnosisId = null, + ReferenceRangeValue = row["reference_range_value"].ToString() + }; + + //referenceRanges.Add(referenceRange); + await _referenceRangeRepository.InsertAsync(referenceRange); + } + + + var fieldComparison = new FieldComparison + { + TableName = "item", + FieldName = "id", + NewKeyValue = itemId.ToString(), + OldKeyValue = row["item_id"].ToString() + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + } + + + + + } + _logger.LogInformation($"项目数据处理完毕,处理数量{oldItemList.Rows.Count}"); + } + else + { + _logger.LogInformation("项目数据已存在,未处理"); + } + } + + /// + /// 迁移组合项目数据 + /// + /// + [RemoteService(false)] + public async Task TransferAsbitemData() + { + var count = await _asbitemRepository.GetCountAsync(); + + if (count == 0) + { + var oldAsbitemList = await oldDb.Ado.GetDataTableAsync("select a.* from asbitem as a left join department as b on a.department_id=b.department_id order by b.display_order,a.display_order "); + if (oldAsbitemList.Rows.Count > 0) + { + foreach (DataRow row in oldAsbitemList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + + #region 根据仪器类别生成二级科室 + + var itemTypeId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "item_type" && m.OldKeyValue == row["department_id"].ToString()).FirstOrDefault().NewKeyValue); + + Guid? deviceTypeId = null; + + if (!string.IsNullOrWhiteSpace(row["device_type_id"].ToString())) + { + deviceTypeId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "device_type" && m.OldKeyValue == row["device_type_id"].ToString()).FirstOrDefault().NewKeyValue); + + var itemTypeEnt = await _itemTypeRepository.GetAsync(itemTypeId); + var deviceTypeEnt = await _deviceTypeRepository.GetAsync(deviceTypeId.Value); + + + var itemTypeChildEnt = await _itemTypeRepository.FirstOrDefaultAsync(m => m.ParentId == itemTypeEnt.Id && m.DisplayName == deviceTypeEnt.DisplayName); + if (itemTypeChildEnt == null) + { + Guid autoItemTypeId = GuidGenerator.Create(); + + #region 排序值 + + int displayOrder = (await _itemTypeRepository.CountAsync(m => m.ParentId == itemTypeEnt.Id)) + 1; + + #endregion + + var item_type_data = new ItemType(autoItemTypeId) + { + DisplayName = deviceTypeEnt.DisplayName, + DisplayOrder = displayOrder, + SimpleCode = LanguageConverter.GetPYSimpleCode(deviceTypeEnt.DisplayName), + CheckTypeFlag = itemTypeEnt.CheckTypeFlag, + GuidTypeId = itemTypeEnt.GuidTypeId, + IsMergeAsbitem = itemTypeEnt.IsMergeAsbitem, + IsWrap = itemTypeEnt.IsWrap, + MedicalReportTypeId = itemTypeEnt.MedicalReportTypeId, + ParentId = itemTypeEnt.Id, + PathCode = _itemTypeManager.CreatePathCode(itemTypeEnt.Id).Result, + IsCheckRequest = itemTypeEnt.IsCheckRequest + }; + + await _itemTypeRepository.InsertAsync(item_type_data); + itemTypeId = autoItemTypeId; + } + else + { + itemTypeId = itemTypeChildEnt.Id; + } + + } + + #endregion + + Guid collectItemTypeId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "collect_item_type" && m.OldKeyValue == row["collect_item_type_id"].ToString()).FirstOrDefault().NewKeyValue); + + Guid asbitemId = GuidGenerator.Create(); + + + var data = new Asbitem(asbitemId) + { + DisplayName = row["asbitem_name"].ToString(), + DisplayOrder = oldAsbitemList.Rows.IndexOf(row) + 1, + SimpleCode = LanguageConverter.GetPYSimpleCode(row["asbitem_name"].ToString()), + DefaultResult = row["default_result"].ToString(), + DiagnosisFunction = "", + IsActive = Convert.ToChar(row["valid_flag"].ToString()), + IsContinueProcess = 'N', + IsDiagnosisFunction = 'N', + ItemTypeId = itemTypeId, + Price = Convert.ToDecimal(row["price"]), + DeviceTypeId = deviceTypeId, + ClinicalMeaning = row["clinical_meaning"].ToString(), + ForSexId = ConvertForSex(row["for_sex_id"].ToString()), + CollectItemTypeId = collectItemTypeId, + //InvoiceItemTypeId = InvoiceItemTypeId, + IsBeforeEat = Convert.ToChar(row["before_eat_flag"].ToString()), + IsCheck = Convert.ToChar(row["check_flag"].ToString()), + IsItemResultMerger = Convert.ToChar(row["item_result_merger_flag"].ToString()), + IsPictureRotate = Convert.ToChar(row["picture_rotate_flag"].ToString()), + QueueTime = string.IsNullOrEmpty(row["queue_time"].ToString()) ? 0 : Convert.ToDecimal(row["queue_time"].ToString()), + ShortName = row["short_name"].ToString(), + BarcodeMode = '0', + DiseaseScreeningTypeId = null, + ForPregnantFlag = 'A', + IsWebAppoint = 'N', + MaritalStatusId = 'A', + Warn = "" + }; + + await _asbitemRepository.InsertAsync(data); + + + #region 指引信息 + + if (!string.IsNullOrWhiteSpace(row["prompt"].ToString())) + { + var asbitemGuideData = new AsbitemGuide + { + AsbitemId = asbitemId, + ForSexId = ForSexFlag.All, + Guide = row["prompt"].ToString(), + MedicalCenterId = defaultMedicalCenterId + }; + + await _asbitemGuideRepository.InsertAsync(asbitemGuideData); + } + + #endregion + + var fieldComparison = new FieldComparison + { + TableName = "asbitem", + FieldName = "id", + NewKeyValue = asbitemId.ToString(), + OldKeyValue = row["asbitem_id"].ToString() + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + } + + + + + } + _logger.LogInformation($"组合项目数据处理完毕,处理数量{oldAsbitemList.Rows.Count}"); + } + else + { + _logger.LogInformation("组合项目数据已存在,未处理"); + } + + + } + + + /// + /// 迁移组合项目明细数据 无字典 + /// + /// + [RemoteService(false)] + public async Task TransferAsbitemDetailData() + { + var count = await _asbitemDetailRepository.GetCountAsync(); + + if (count == 0) + { + var oldAsbitemDetailList = await oldDb.Ado.GetDataTableAsync("select * from asbitem_detail "); + if (oldAsbitemDetailList.Rows.Count > 0) + { + foreach (DataRow row in oldAsbitemDetailList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + Guid asbitemId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "asbitem" && m.OldKeyValue == row["asbitem_id"].ToString()).FirstOrDefault().NewKeyValue); + Guid itemId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "item" && m.OldKeyValue == row["item_id"].ToString()).FirstOrDefault().NewKeyValue); + var data = new AsbitemDetail + { + AsbitemId = asbitemId, + ItemId = itemId + }; + + await _asbitemDetailRepository.InsertAsync(data); + + await uow.CompleteAsync(); + } + } + } + _logger.LogInformation($"组合项目明细数据处理完毕,处理数量{oldAsbitemDetailList.Rows.Count}"); + } + else + { + _logger.LogInformation("组合项目明细数据已存在,未处理"); + } + + + } + + + /// + /// 迁移体检套餐数据 + /// + /// + [RemoteService(false)] + public async Task TransferMedicalPackageData() + { + var count = await _medicalPackageRepository.GetCountAsync(); + + if (count == 0) + { + var oldMedicalPackageList = await oldDb.Ado.GetDataTableAsync("select * from medical_package order by display_order"); + if (oldMedicalPackageList.Rows.Count > 0) + { + foreach (DataRow row in oldMedicalPackageList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + Guid medicalPackageId = GuidGenerator.Create(); + + var data = new MedicalPackage(medicalPackageId) + { + DisplayName = row["medical_package_name"].ToString(), + DisplayOrder = oldMedicalPackageList.Rows.IndexOf(row) + 1, + SimpleCode = LanguageConverter.GetPYSimpleCode(row["medical_package_name"].ToString()), + ForSexId = ConvertForSex(row["for_sex_id"].ToString()), + IsActive = Convert.ToChar(row["valid_flag"].ToString()), + Price = Convert.ToDecimal(row["price"].ToString()), + Remark = row["remark"].ToString(), + AgeLowerLimit = 0, + AgeUpperLimit = 200, + IsBasicRecommend = 'N', + IsWebAppoint = 'N', + MaritalStatusId = 'A' + }; + + await _medicalPackageRepository.InsertAsync(data); + + + var fieldComparison = new FieldComparison + { + TableName = "medical_package", + FieldName = "id", + NewKeyValue = medicalPackageId.ToString(), + OldKeyValue = row["medical_package_id"].ToString() + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + } + } + _logger.LogInformation($"体检套餐数据处理完毕,处理数量{oldMedicalPackageList.Rows.Count}"); + } + else + { + _logger.LogInformation("体检套餐数据已存在,未处理"); + } + + + } + + + /// + /// 迁移体检套餐明细数据 无字典 + /// + /// + [RemoteService(false)] + public async Task TransferMedicalPackageDetailData() + { + var count = await _medicalPackageDetailRepository.GetCountAsync(); + + if (count == 0) + { + var oldMedicalPackageDetailList = await oldDb.Ado.GetDataTableAsync("select * from medical_package_detail "); + if (oldMedicalPackageDetailList.Rows.Count > 0) + { + foreach (DataRow row in oldMedicalPackageDetailList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + Guid asbitemId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "asbitem" && m.OldKeyValue == row["asbitem_id"].ToString()).FirstOrDefault().NewKeyValue); + Guid MedicalPackageId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "medical_package" && m.OldKeyValue == row["medical_package_id"].ToString()).FirstOrDefault().NewKeyValue); + + var asbitemEnt = await _asbitemRepository.GetAsync(asbitemId); + + var data = new MedicalPackageDetail + { + AsbitemId = asbitemId, + Amount = 1, + MedicalPackageId = MedicalPackageId, + Price = asbitemEnt.Price + }; + + await _medicalPackageDetailRepository.InsertAsync(data); + + await uow.CompleteAsync(); + } + } + } + _logger.LogInformation($"体检套餐明细数据处理完毕,处理数量{oldMedicalPackageDetailList.Rows.Count}"); + } + else + { + _logger.LogInformation("体检套餐明细数据已存在,未处理"); + } + + } + + /// + /// 迁移诊断设置数据 + /// + /// + [RemoteService(false)] + public async Task TransferDiagnosisData() + { + var count = await _diagnosisRepository.GetCountAsync(); + if (count == 0) + { + + var oldDiagnosisList = await oldDb.Ado.GetDataTableAsync("select a.* from diagnosis as a left join department as b on a.department_id=b.department_id order by b.display_order,a.display_order "); + if (oldDiagnosisList.Rows.Count > 0) + { + foreach (DataRow row in oldDiagnosisList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + #region 根据仪器类别生成二级科室 + + var itemTypeId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "item_type" && m.OldKeyValue == row["department_id"].ToString()).FirstOrDefault().NewKeyValue); + + Guid? deviceTypeId = null; + + if (!string.IsNullOrWhiteSpace(row["device_type_id"].ToString())) + { + var fieldComparisonEnt = (await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "device_type" && m.OldKeyValue == row["device_type_id"].ToString()).FirstOrDefault(); + if (fieldComparisonEnt != null) + { + deviceTypeId = Guid.Parse(fieldComparisonEnt.NewKeyValue); + var itemTypeEnt = await _itemTypeRepository.GetAsync(itemTypeId); + var deviceTypeEnt = await _deviceTypeRepository.GetAsync(deviceTypeId.Value); + + + var itemTypeChildEnt = await _itemTypeRepository.FirstOrDefaultAsync(m => m.ParentId == itemTypeEnt.Id && m.DisplayName == deviceTypeEnt.DisplayName); + if (itemTypeChildEnt == null) + { + Guid autoItemTypeId = GuidGenerator.Create(); + + #region 排序值 + + int displayOrder = (await _itemTypeRepository.CountAsync(m => m.ParentId == itemTypeEnt.Id)) + 1; + + #endregion + + var item_type_data = new ItemType(autoItemTypeId) + { + DisplayName = deviceTypeEnt.DisplayName, + DisplayOrder = displayOrder, + SimpleCode = LanguageConverter.GetPYSimpleCode(deviceTypeEnt.DisplayName), + CheckTypeFlag = itemTypeEnt.CheckTypeFlag, + GuidTypeId = itemTypeEnt.GuidTypeId, + IsMergeAsbitem = itemTypeEnt.IsMergeAsbitem, + IsWrap = itemTypeEnt.IsWrap, + MedicalReportTypeId = itemTypeEnt.MedicalReportTypeId, + ParentId = itemTypeEnt.Id, + PathCode = _itemTypeManager.CreatePathCode(itemTypeEnt.Id).Result, + IsCheckRequest = itemTypeEnt.IsCheckRequest + }; + + await _itemTypeRepository.InsertAsync(item_type_data); + itemTypeId = autoItemTypeId; + } + else + { + itemTypeId = itemTypeChildEnt.Id; + } + } + + } + + #endregion + + + Guid diagnosisId = GuidGenerator.Create(); + + var data = new Diagnosis(diagnosisId) + { + DisplayName = row["diagnosis_name"].ToString(), + DisplayOrder = oldDiagnosisList.Rows.IndexOf(row) + 1, + SimpleCode = LanguageConverter.GetPYSimpleCode(row["diagnosis_name"].ToString()), + ItemTypeId = itemTypeId, + DiagnosisLevelId = 1, + ForSexId = 'A', + IsIll = Convert.ToChar(row["ill_flag"].ToString()), + IsSummaryTemplate = Convert.ToChar(row["template_flag"].ToString()), + SuggestionName = row["suggestion_name"].ToString() + }; + + await _diagnosisRepository.InsertAsync(data); + + + var fieldComparison = new FieldComparison + { + TableName = "diagnosis", + FieldName = "id", + NewKeyValue = diagnosisId.ToString(), + OldKeyValue = row["diagnosis_id"].ToString() + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + } + + + + + } + _logger.LogInformation($"诊断设置数据处理完毕,处理数量{oldDiagnosisList.Rows.Count}"); + } + else + { + _logger.LogInformation("诊断设置数据已存在,未处理"); + } + } + + /// + /// 迁移诊断建议数据 + /// + /// + [RemoteService(false)] + public async Task TransferSuggestionData() + { + var count = await _suggestionRepository.GetCountAsync(); + if (count == 0) + { + + var oldSuggestionList = await oldDb.Ado.GetDataTableAsync("select * from suggestion order by display_order,suggestion_id "); + if (oldSuggestionList.Rows.Count > 0) + { + + foreach (DataRow row in oldSuggestionList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + + Guid DiagnosisId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "diagnosis" && m.OldKeyValue == row["diagnosis_id"].ToString()).FirstOrDefault().NewKeyValue); + + Guid suggestionId = GuidGenerator.Create(); + + if (await _suggestionRepository.FirstOrDefaultAsync(f => f.DiagnosisId == DiagnosisId && f.SuggestionContent == row["suggestion_content"].ToString()) == null) + { + var data = new Suggestion(suggestionId) + { + DisplayOrder = oldSuggestionList.Rows.IndexOf(row) + 1, + DiagnosisId = DiagnosisId, + SuggestionType = SuggestionTypeFlag.HealthGuidance, + SuggestionContent = row["suggestion_content"].ToString() + }; + + await _suggestionRepository.InsertAsync(data); + + + var fieldComparison = new FieldComparison + { + TableName = "suggestion", + FieldName = "id", + NewKeyValue = suggestionId.ToString(), + OldKeyValue = row["suggestion_id"].ToString() + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + } + await uow.CompleteAsync(); + } + } + } + _logger.LogInformation($"诊断建议数据处理完毕,处理数量{oldSuggestionList.Rows.Count}"); + } + else + { + _logger.LogInformation("诊断建议数据已存在,未处理"); + } + } + + /// + /// 迁移项目结果模板数据 + /// + /// + [RemoteService(false)] + public async Task TransferItemResultTemplateData() + { + var count = await _itemResultTemplateRepository.GetCountAsync(); + if (count == 0) + { + var oldItemResultTemplateList = await oldDb.Ado.GetDataTableAsync("select * from item_result_template order by display_order,item_result_template_id "); + if (oldItemResultTemplateList.Rows.Count > 0) + { + foreach (DataRow row in oldItemResultTemplateList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + Guid? DiagnosisId = null; + if (!string.IsNullOrWhiteSpace(row["diagnosis_id"].ToString())) + { + var fieldComparisonDiagnosisEnt = (await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "diagnosis" && m.OldKeyValue == row["diagnosis_id"].ToString()).FirstOrDefault(); + if (fieldComparisonDiagnosisEnt != null) + { + DiagnosisId = Guid.Parse(fieldComparisonDiagnosisEnt.NewKeyValue); + } + } + + Guid ItemId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "item" && m.OldKeyValue == row["item_id"].ToString()).FirstOrDefault().NewKeyValue); + + Guid itemResultTemplateId = GuidGenerator.Create(); + + if (await _itemResultTemplateRepository.FirstOrDefaultAsync(f => f.ItemId == ItemId && f.Result == row["result"].ToString()) == null) + { + + var data = new ItemResultTemplate(itemResultTemplateId) + { + DisplayOrder = oldItemResultTemplateList.Rows.IndexOf(row) + 1, + DiagnosisId = DiagnosisId, + IsNameIntoSummary = Convert.ToChar(row["name_into_summary_flag"].ToString()), + IsResultIntoSummary = Convert.ToChar(row["result_into_summary_flag"].ToString()), + ItemId = ItemId, + Result = row["result"].ToString(), + SimpleCode = LanguageConverter.GetPYSimpleCode(row["result"].ToString()), + ResultStatusId = row["result_status_id"].ToString() + }; + + await _itemResultTemplateRepository.InsertAsync(data); + + + var fieldComparison = new FieldComparison + { + TableName = "item_result_template", + FieldName = "id", + NewKeyValue = itemResultTemplateId.ToString(), + OldKeyValue = row["item_result_template_id"].ToString() + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + } + await uow.CompleteAsync(); + + } + } + } + _logger.LogInformation($"项目结果模板数据处理完毕,处理数量{oldItemResultTemplateList.Rows.Count}"); + } + else + { + _logger.LogInformation("项目结果模板数据已存在,未处理"); + } + } + + /// + /// 迁移项目结果匹配数据 + /// + /// + [RemoteService(false)] + public async Task TransferItemResultMatchData() + { + var count = await _ItemResultMatchRepository.GetCountAsync(); + if (count == 0) + { + var oldItemResultMatchList = await oldDb.Ado.GetDataTableAsync("select * from item_result_match order by display_order,item_result_match_id "); + if (oldItemResultMatchList.Rows.Count > 0) + { + foreach (DataRow row in oldItemResultMatchList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + + var fieldComparisonDiagnosisEnt = (await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "diagnosis" && m.OldKeyValue == row["diagnosis_id"].ToString()).FirstOrDefault(); + if (fieldComparisonDiagnosisEnt != null) + { + Guid DiagnosisId = Guid.Parse(fieldComparisonDiagnosisEnt.NewKeyValue); + Guid ItemId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "item" && m.OldKeyValue == row["item_id"].ToString()).FirstOrDefault().NewKeyValue); + + Guid itemResultMatchId = GuidGenerator.Create(); + + var data = new ItemResultMatch(itemResultMatchId) + { + DisplayOrder = oldItemResultMatchList.Rows.IndexOf(row) + 1, + DiagnosisId = DiagnosisId, + ItemId = ItemId, + Result = row["result"].ToString() + }; + + var ent = await _ItemResultMatchRepository.InsertAsync(data, true); + + + var fieldComparison = new FieldComparison + { + TableName = "item_result_match", + FieldName = "id", + NewKeyValue = ent.Id.ToString(), + OldKeyValue = row["item_result_match_id"].ToString() + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + } + + await uow.CompleteAsync(); + } + + } + + + + + } + _logger.LogInformation($"项目结果匹配数据处理完毕,处理数量{oldItemResultMatchList.Rows.Count}"); + } + else + { + _logger.LogInformation("项目结果匹配数据已存在,未处理"); + } + } + + + + /// + /// 迁移项目参考范围数据 无字典 + /// + /// + [RemoteService(false)] + public async Task TransferReferenceRangeData() + { + var count = (await _referenceRangeRepository.GetQueryableAsync()).Where(m => m.ReferenceRangeTypeFlag != ItemReferenceRangeTypeFlag.Character).Count(); + if (count == 0) + { + + var oldReferenceRangeList = await oldDb.Ado.GetDataTableAsync("select * from reference_range order by reference_range_id "); + if (oldReferenceRangeList.Rows.Count > 0) + { + foreach (DataRow row in oldReferenceRangeList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + Guid? LowerDiagnosisId = null; + Guid? UpperDiagnosisId = null; + + var fieldComparisonLowerDiagnosisEnt = (await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "diagnosis" && m.OldKeyValue == row["lower_diagnosis_id"].ToString()).FirstOrDefault(); + var fieldComparisonUpperDiagnosisEnt = (await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "diagnosis" && m.OldKeyValue == row["upper_diagnosis_id"].ToString()).FirstOrDefault(); + if (fieldComparisonLowerDiagnosisEnt != null) + { + LowerDiagnosisId = Guid.Parse(fieldComparisonLowerDiagnosisEnt.NewKeyValue); + } + if (fieldComparisonUpperDiagnosisEnt != null) + { + UpperDiagnosisId = Guid.Parse(fieldComparisonUpperDiagnosisEnt.NewKeyValue); + } + + Guid ItemId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "item" && m.OldKeyValue == row["item_id"].ToString()).FirstOrDefault().NewKeyValue); + + Guid referenceRangeId = GuidGenerator.Create(); + + var data = new ReferenceRange(referenceRangeId) + { + ItemId = ItemId, + AgeLowerLimit = (short)Convert.ToInt32(row["age_lower_limit"].ToString()), + AgeUpperLimit = (short)Convert.ToInt32(row["age_upper_limit"].ToString()), + CriticalRangeValue = string.Empty, + ForSexId = ConvertForSex(row["for_sex_id"].ToString()), + LowerDiagnosisId = LowerDiagnosisId, + ReferenceRangeTypeFlag = ItemReferenceRangeTypeFlag.Number, + ReferenceRangeValue = Convert.ToDecimal(row["lower_limit"].ToString()).ToString("#0.####") + "-" + Convert.ToDecimal(row["upper_limit"].ToString()).ToString("#0.####"), + UpperDiagnosisId = UpperDiagnosisId + }; + + await _referenceRangeRepository.InsertAsync(data); + + await uow.CompleteAsync(); + } + } + + + } + _logger.LogInformation($"项目参考范围数据处理完毕,处理数量{oldReferenceRangeList.Rows.Count}"); + } + else + { + _logger.LogInformation("项目参考范围数据已存在,未处理"); + } + } + + + /// + /// 迁移条码分组数据 + /// + /// + [RemoteService(false)] + public async Task TransferSampleGroupData() + { + var count = await _sampleGroupRepository.GetCountAsync(); + if (count == 0) + { + //获取一条条码类型的数据 + Guid defaultSampleTypeId = Guid.Empty; + var sampleTypeEnt = await _sampleTypeRepository.FirstOrDefaultAsync(); + if (sampleTypeEnt != null) + { + defaultSampleTypeId = sampleTypeEnt.Id; + } + if (defaultSampleTypeId != Guid.Empty) + { + var oldSampleGroupList = await oldDb.Ado.GetDataTableAsync("select * from vessels_type order by display_order"); + if (oldSampleGroupList.Rows.Count > 0) + { + foreach (DataRow row in oldSampleGroupList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + #region 转成成新的标本类型ID + + Guid newSampleTypeId = defaultSampleTypeId; //默认取其他 ID + + if (!string.IsNullOrWhiteSpace(row["specimen_type_id"].ToString())) + { + var oldSampleType = (await _fieldComparisonRepository.GetQueryableAsync()) + .Where(m => m.TableName == "sample_type" && m.OldKeyValue == row["specimen_type_id"].ToString()).FirstOrDefault(); + if (oldSampleType != null) + { + newSampleTypeId = Guid.Parse(oldSampleType.NewKeyValue); + } + } + #endregion + + Guid sampleGroupId = GuidGenerator.Create(); + + var data = new SampleGroup(sampleGroupId) + { + DisplayName = row["vessels_type_name"].ToString(), + DisplayOrder = oldSampleGroupList.Rows.IndexOf(row) + 1, + SimpleCode = LanguageConverter.GetPYSimpleCode(row["vessels_type_name"].ToString()), + SampleContainerId = defaultSampleContainerId, + SampleTypeId = newSampleTypeId + }; + + await _sampleGroupRepository.InsertAsync(data); + + var fieldComparison = new FieldComparison + { + TableName = "sample_group", + FieldName = "id", + NewKeyValue = sampleGroupId.ToString(), + OldKeyValue = row["vessels_type_id"].ToString() + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + } + + + } + + _logger.LogInformation($"条码分组数据处理完毕,处理数量{oldSampleGroupList.Rows.Count}"); + } + else + { + _logger.LogInformation($"条码类型未获取到默认数据,跳过条码分组数据处理"); + } + } + else + { + _logger.LogInformation("条码分组数据已存在,未处理"); + } + } + + + /// + /// 迁移条码分组明细数据 + /// + /// + [RemoteService(false)] + public async Task TransferSampleGroupDetailData() + { + var count = await _sampleGroupDetailRepository.GetCountAsync(); + if (count == 0) + { + var oldSampleGroupDetailList = await oldDb.Ado.GetDataTableAsync("select * from vessels_type_detail "); + if (oldSampleGroupDetailList.Rows.Count > 0) + { + + foreach (DataRow row in oldSampleGroupDetailList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + Guid newSampleGroupId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()) + .Where(m => m.TableName == "sample_group" && m.OldKeyValue == row["vessels_type_id"].ToString()).FirstOrDefault().NewKeyValue); + + Guid newAsbitemId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()) + .Where(m => m.TableName == "asbitem" && m.OldKeyValue == row["asbitem_id"].ToString()).FirstOrDefault().NewKeyValue); + + var data = new SampleGroupDetail + { + AsbitemId = newAsbitemId, + SampleGroupId = newSampleGroupId + }; + + await _sampleGroupDetailRepository.InsertAsync(data); + + await uow.CompleteAsync(); + + } + } + + + } + _logger.LogInformation($"条码分组明细数据处理完毕,处理数量{oldSampleGroupDetailList.Rows.Count}"); + } + else + { + _logger.LogInformation("条码分组明细数据已存在,未处理"); + } + } + + /// + /// 迁移体检单位数据 一级 + /// + /// + [RemoteService(false)] + public async Task TransferTopCustomerOrgData() + { + var count = await _customerOrgRepository.GetCountAsync(); + if (count == 0) + { + var oldCustomerOrgList = await oldDb.Ado.GetDataTableAsync("select * from org where len(org_id)=5 order by display_order asc"); + if (oldCustomerOrgList.Rows.Count > 0) + { + foreach (DataRow row in oldCustomerOrgList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + Guid customerOrgId = GuidGenerator.Create(); + + if (row["org_id"].ToString() == "00000") + { + customerOrgId = Guid.Parse("00000000-0000-0000-0000-000000000001"); + } + + #region 备注 导入联系人姓名、电话 + string remark = ""; + if (!string.IsNullOrWhiteSpace(row["linkman"].ToString())) + { + remark = row["linkman"].ToString(); + } + if (!string.IsNullOrWhiteSpace(row["telephone"].ToString())) + { + if (!string.IsNullOrWhiteSpace(remark)) + { + remark += "|" + row["telephone"].ToString(); + } + else + { + remark = row["telephone"].ToString(); + } + } + #endregion + + var data = new CustomerOrg(customerOrgId) + { + Accounts = row["accounts"].ToString(), + Address = row["address"].ToString(), + Bank = row["bank"].ToString(), + DisplayName = row["org_name"].ToString(), + DisplayOrder = oldCustomerOrgList.Rows.IndexOf(row) + 1, + Fax = row["fax"].ToString(), + InvoiceName = row["org_name"].ToString(), + IsActive = 'Y', + IsLock = Convert.ToChar(row["lock_flag"].ToString()), + MedicalCenterId = defaultMedicalCenterId, + OrgTypeId = defaultOrgTypeId, //默认为私营 + ParentId = null, + PathCode = (oldCustomerOrgList.Rows.IndexOf(row) + 1).ToString().PadLeft(5, '0'), + PostalCode = row["postalcode"].ToString(), + Remark = remark, + ShortName = row["short_name"].ToString(), + SimpleCode = LanguageConverter.GetPYSimpleCode(row["org_name"].ToString()), + Telephone = row["telephone"].ToString(), + CountryOrgCode = row["org_id"].ToString(), + SalesPerson = "", + SalesPersonPhone = "" + }; + + await _customerOrgRepository.InsertAsync(data); + + var fieldComparison = new FieldComparison + { + FieldName = "id", + NewKeyValue = customerOrgId.ToString(), + OldKeyValue = row["org_id"].ToString(), + TableName = "customer_org" + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + + } + + } + } + _logger.LogInformation($"体检单位一级数据处理完毕,处理数量{oldCustomerOrgList.Rows.Count}"); + } + else + { + _logger.LogInformation("体检单位一级数据已存在,未处理"); + } + } + + + /// + /// 迁移体检单位数据 二级 + /// + /// + [RemoteService(false)] + public async Task TransferTwoCustomerOrgData() + { + var count = (await _customerOrgRepository.GetQueryableAsync()).Where(m => m.PathCode.Length > 5).Count(); + if (count == 0) + { + + var oldCustomerOrgList = await oldDb.Ado.GetDataTableAsync("select * from [dbo].[org] where len(org_id)=8 order by org_id asc"); + if (oldCustomerOrgList.Rows.Count > 0) + { + List customerOrgList = await _customerOrgRepository.GetListAsync(m => m.ParentId == null); + List fieldComparisonList = await _fieldComparisonRepository.GetListAsync(m => m.TableName == "customer_org"); + + foreach (DataRow row in oldCustomerOrgList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + #region 查找上级ID + string oldId = row["org_id"].ToString(); + string oldParentId = oldId.Substring(0, 5); + Guid parentId = Guid.Parse(fieldComparisonList.Where(m => m.OldKeyValue == oldParentId).FirstOrDefault().NewKeyValue); + #endregion + + + Guid customerOrgId = GuidGenerator.Create(); + + #region 备注 导入联系人姓名、电话 + string remark = ""; + if (!string.IsNullOrWhiteSpace(row["linkman"].ToString())) + { + remark = row["linkman"].ToString(); + } + if (!string.IsNullOrWhiteSpace(row["telephone"].ToString())) + { + if (!string.IsNullOrWhiteSpace(remark)) + { + remark += "|" + row["telephone"].ToString(); + } + else + { + remark = row["telephone"].ToString(); + } + } + #endregion + + var data = new CustomerOrg(customerOrgId) + { + Accounts = row["accounts"].ToString(), + Address = row["address"].ToString(), + Bank = row["bank"].ToString(), + DisplayName = row["org_name"].ToString(), + DisplayOrder = oldCustomerOrgList.Rows.IndexOf(row) + 1, + Fax = row["fax"].ToString(), + InvoiceName = row["org_name"].ToString(), + IsActive = 'Y', + IsLock = Convert.ToChar(row["lock_flag"].ToString()), + MedicalCenterId = defaultMedicalCenterId, + OrgTypeId = defaultOrgTypeId, //默认为私营 + ParentId = parentId, + PathCode = _customerOrgManager.CreatePathCode(parentId).Result, + PostalCode = row["postalcode"].ToString(), + Remark = remark, + ShortName = row["short_name"].ToString(), + SimpleCode = LanguageConverter.GetPYSimpleCode(row["org_name"].ToString()), + Telephone = row["telephone"].ToString(), + CountryOrgCode = row["org_id"].ToString(), + SalesPerson = "", + SalesPersonPhone = "" + }; + + await _customerOrgRepository.InsertAsync(data); + + var fieldComparison = new FieldComparison + { + FieldName = "id", + NewKeyValue = customerOrgId.ToString(), + OldKeyValue = row["org_id"].ToString(), + TableName = "customer_org" + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + + } + + } + _logger.LogInformation($"体检单位二级数据处理完毕,处理数量{oldCustomerOrgList.Rows.Count}"); + } + else + { + _logger.LogInformation("体检单位二级数据已存在,未处理"); + } + } + + /// + /// 迁移体检单位数据 三级 + /// + /// + [RemoteService(false)] + public async Task TransferThreeCustomerOrgData() + { + var count = (await _customerOrgRepository.GetQueryableAsync()).Where(m => m.PathCode.Length > 11).Count(); + if (count == 0) + { + var oldCustomerOrgList = await oldDb.Ado.GetDataTableAsync("select * from [dbo].[org] where len(org_id)=11 order by org_id asc"); + if (oldCustomerOrgList.Rows.Count > 0) + { + List customerOrgList = await _customerOrgRepository.GetListAsync(m => m.ParentId == null); + List fieldComparisonList = await _fieldComparisonRepository.GetListAsync(m => m.TableName == "customer_org"); + + foreach (DataRow row in oldCustomerOrgList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + + #region 查找上级ID + string oldId = row["org_id"].ToString(); + string oldParentId = oldId.Substring(0, 8); + Guid parentId = Guid.Parse(fieldComparisonList.Where(m => m.OldKeyValue == oldParentId).FirstOrDefault().NewKeyValue); + #endregion + + + Guid customerOrgId = GuidGenerator.Create(); + + #region 备注 导入联系人姓名、电话 + string remark = ""; + if (!string.IsNullOrWhiteSpace(row["linkman"].ToString())) + { + remark = row["linkman"].ToString(); + } + if (!string.IsNullOrWhiteSpace(row["telephone"].ToString())) + { + if (!string.IsNullOrWhiteSpace(remark)) + { + remark += "|" + row["telephone"].ToString(); + } + else + { + remark = row["telephone"].ToString(); + } + } + #endregion + + var data = new CustomerOrg(customerOrgId) + { + Accounts = row["accounts"].ToString(), + Address = row["address"].ToString(), + Bank = row["bank"].ToString(), + DisplayName = row["org_name"].ToString(), + DisplayOrder = oldCustomerOrgList.Rows.IndexOf(row) + 1, + Fax = row["fax"].ToString(), + InvoiceName = row["org_name"].ToString(), + IsActive = 'Y', + IsLock = Convert.ToChar(row["lock_flag"].ToString()), + MedicalCenterId = defaultMedicalCenterId, + OrgTypeId = defaultOrgTypeId, //默认为私营 + ParentId = parentId, + PathCode = _customerOrgManager.CreatePathCode(parentId).Result, + PostalCode = row["postalcode"].ToString(), + Remark = remark, + ShortName = row["short_name"].ToString(), + SimpleCode = LanguageConverter.GetPYSimpleCode(row["org_name"].ToString()), + Telephone = row["telephone"].ToString(), + CountryOrgCode = row["org_id"].ToString(), + SalesPerson = "", + SalesPersonPhone = "" + }; + + await _customerOrgRepository.InsertAsync(data); + + var fieldComparison = new FieldComparison + { + FieldName = "id", + NewKeyValue = customerOrgId.ToString(), + OldKeyValue = row["org_id"].ToString(), + TableName = "customer_org" + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + } + } + _logger.LogInformation($"体检单位三级数据处理完毕,处理数量{oldCustomerOrgList.Rows.Count}"); + } + else + { + _logger.LogInformation("体检单位三级数据已存在,未处理"); + } + } + + + + /// + /// 迁移体检单位数据 四级 + /// + /// + [RemoteService(false)] + public async Task TransferFourCustomerOrgData() + { + var count = (await _customerOrgRepository.GetQueryableAsync()).Where(m => m.PathCode.Length > 17).Count(); + if (count == 0) + { + var oldCustomerOrgList = await oldDb.Ado.GetDataTableAsync("select * from [dbo].[org] where len(org_id)=14 order by org_id asc"); + if (oldCustomerOrgList.Rows.Count > 0) + { + List customerOrgList = await _customerOrgRepository.GetListAsync(m => m.ParentId == null); + List fieldComparisonList = await _fieldComparisonRepository.GetListAsync(m => m.TableName == "customer_org"); + + foreach (DataRow row in oldCustomerOrgList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + + #region 查找上级ID + string oldId = row["org_id"].ToString(); + string oldParentId = oldId.Substring(0, 11); + Guid parentId = Guid.Parse(fieldComparisonList.Where(m => m.OldKeyValue == oldParentId).FirstOrDefault().NewKeyValue); + #endregion + + + Guid customerOrgId = GuidGenerator.Create(); + + #region 备注 导入联系人姓名、电话 + string remark = ""; + if (!string.IsNullOrWhiteSpace(row["linkman"].ToString())) + { + remark = row["linkman"].ToString(); + } + if (!string.IsNullOrWhiteSpace(row["telephone"].ToString())) + { + if (!string.IsNullOrWhiteSpace(remark)) + { + remark += "|" + row["telephone"].ToString(); + } + else + { + remark = row["telephone"].ToString(); + } + } + #endregion + + var data = new CustomerOrg(customerOrgId) + { + Accounts = row["accounts"].ToString(), + Address = row["address"].ToString(), + Bank = row["bank"].ToString(), + DisplayName = row["org_name"].ToString(), + DisplayOrder = oldCustomerOrgList.Rows.IndexOf(row) + 1, + Fax = row["fax"].ToString(), + InvoiceName = row["org_name"].ToString(), + IsActive = 'Y', + IsLock = Convert.ToChar(row["lock_flag"].ToString()), + MedicalCenterId = defaultMedicalCenterId, + OrgTypeId = defaultOrgTypeId, //默认为私营 + ParentId = parentId, + PathCode = _customerOrgManager.CreatePathCode(parentId).Result, + PostalCode = row["postalcode"].ToString(), + Remark = remark, + ShortName = row["short_name"].ToString(), + SimpleCode = LanguageConverter.GetPYSimpleCode(row["org_name"].ToString()), + Telephone = row["telephone"].ToString(), + CountryOrgCode = row["org_id"].ToString(), + SalesPerson = "", + SalesPersonPhone = "" + }; + + await _customerOrgRepository.InsertAsync(data); + + var fieldComparison = new FieldComparison + { + FieldName = "id", + NewKeyValue = customerOrgId.ToString(), + OldKeyValue = row["org_id"].ToString(), + TableName = "customer_org" + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + } + } + _logger.LogInformation($"体检单位四级数据处理完毕,处理数量{oldCustomerOrgList.Rows.Count}"); + } + else + { + _logger.LogInformation("体检单位四级数据已存在,未处理"); + } + } + + /// + /// 迁移单位体检次数数据 无字典 + /// + /// + [RemoteService(false)] + public async Task TransferCustomerOrgRegisterData() + { + var count = await _customerOrgRegisterRepository.GetCountAsync(); + if (count == 0) + { + var oldCustomerOrgRegisterList = await oldDb.Ado.GetDataTableAsync("select * from org_medical_register order by org_medical_times"); + if (oldCustomerOrgRegisterList.Rows.Count > 0) + { + List fieldComparisonList = await _fieldComparisonRepository.GetListAsync(m => m.TableName == "customer_org"); + + foreach (DataRow row in oldCustomerOrgRegisterList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + Guid customerOrgId = Guid.Parse(fieldComparisonList.Where(m => m.OldKeyValue == row["org_id"].ToString()).FirstOrDefault().NewKeyValue); + Guid customerOrgRegisterId = GuidGenerator.Create(); + + if (customerOrgId == GuidFlag.PersonCustomerOrgId) + customerOrgRegisterId = GuidFlag.PersonCustomerOrgRegisterId; + var data = new CustomerOrgRegister(customerOrgRegisterId) + { + BeginTime = Convert.ToDateTime(row["start_time"].ToString()), + CustomerOrgId = customerOrgId, + EndTime = !string.IsNullOrWhiteSpace(row["end_time"].ToString()) ? Convert.ToDateTime(row["end_time"].ToString()) : null, + IsComplete = Convert.ToChar(row["complete_flag"].ToString()), + MedicalTimes = (short)Convert.ToInt32(row["org_medical_times"].ToString()), + RegisterName = "", + RegisterNo = "" + }; + + await _customerOrgRegisterRepository.InsertAsync(data); + + await uow.CompleteAsync(); + } + } + } + _logger.LogInformation($"单位体检次数数据处理完毕,处理数量{oldCustomerOrgRegisterList.Rows.Count}"); + } + else + { + _logger.LogInformation("单位体检次数数据已存在,未处理"); + } + } + + /// + /// 迁移单位分组 + /// + /// + [RemoteService(false)] + public async Task TransferCustomerOrgGroupData() + { + var count = await _customerOrgGroupRepository.GetCountAsync(); + if (count == 0) + { + + var oldCustomerOrgGroupList = await oldDb.Ado.GetDataTableAsync("select * from org_group order by display_order asc"); + if (oldCustomerOrgGroupList.Rows.Count > 0) + { + List fieldComparisonList = await _fieldComparisonRepository.GetListAsync(m => m.TableName == "customer_org"); + List customerOrgRegisterList = await _customerOrgRegisterRepository.GetListAsync(); + + foreach (DataRow row in oldCustomerOrgGroupList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + //新系统单位ID + Guid customerOrgId = Guid.Parse(fieldComparisonList.Where(m => m.OldKeyValue == row["org_id"].ToString()).FirstOrDefault().NewKeyValue); + Guid customerOrgRegisterId = customerOrgRegisterList.Where(m => m.CustomerOrgId == customerOrgId + && m.MedicalTimes == (short)Convert.ToInt32(row["org_medical_times"].ToString())).FirstOrDefault().Id; + Guid customerOrgGroupId = GuidGenerator.Create(); + + var data = new CustomerOrgGroup(customerOrgGroupId) + { + AgeLowerLimit = (short)Convert.ToInt32(row["age_lower_limit"].ToString()), + AgeUpperLimit = (short)Convert.ToInt32(row["age_upper_limit"].ToString()), + CustomerOrgRegisterId = customerOrgRegisterId, + DisplayName = row["org_group_name"].ToString(), + DisplayOrder = oldCustomerOrgGroupList.Rows.IndexOf(row) + 1, + ForSexId = ConvertForSex(row["for_sex_id"].ToString()), + JobPost = row["job_post"].ToString(), + JobTitle = row["job_title"].ToString(), + MaritalStatusId = Convert.ToChar(row["marital_status_id"].ToString()), + Price = Convert.ToDecimal(row["price"].ToString()), + Remark = row["remark"].ToString(), + CanAddMoney = 0 + }; + + await _customerOrgGroupRepository.InsertAsync(data); + + var fieldComparison = new FieldComparison + { + FieldName = "id", + NewKeyValue = customerOrgGroupId.ToString(), + OldKeyValue = row["org_group_id"].ToString(), + TableName = "customer_org_group" + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + + } + + + } + _logger.LogInformation($"单位分组数据处理完毕,处理数量{oldCustomerOrgGroupList.Rows.Count}"); + } + else + { + _logger.LogInformation("单位分组数据已存在,未处理"); + } + } + + + /// + /// 迁移单位分组明细数据 + /// + /// + [RemoteService(false)] + public async Task TransferCustomerOrgGroupDetailData() + { + var count = await _customerOrgGroupDetailRepository.GetCountAsync(); + if (count == 0) + { + + int pclcount = 200; + + var oldCustomerOrgGroupList = await oldDb.Ado.GetDataTableAsync("select * from org_group_detail "); + if (oldCustomerOrgGroupList.Rows.Count > 0) + { + List tempList = new List(); + + foreach (DataRow row in oldCustomerOrgGroupList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + //新系统单位分组ID + Guid customerOrgGroupId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()) + .Where(m => m.TableName == "customer_org_group" && m.OldKeyValue == row["org_group_id"].ToString()).FirstOrDefault().NewKeyValue); + Guid asbitemId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()) + .Where(m => m.TableName == "asbitem" && m.OldKeyValue == row["asbitem_id"].ToString()).FirstOrDefault().NewKeyValue); + + decimal price = 0; + if (!decimal.TryParse(row["price"].ToString(), out price)) + { + price = 0; + } + + var data = new CustomerOrgGroupDetail + { + AsbitemId = asbitemId, + CustomerOrgGroupId = customerOrgGroupId, + Price = price, + Amount = 1 + }; + + tempList.Add(data); + + if (tempList.Count >= pclcount) + { + await _customerOrgGroupDetailRepository.InsertManyAsync(tempList); + + tempList = new List(); + + } + else + { + if (oldCustomerOrgGroupList.Rows.IndexOf(row) == oldCustomerOrgGroupList.Rows.Count - 1) + { + await _customerOrgGroupDetailRepository.InsertManyAsync(tempList); + } + } + + await uow.CompleteAsync(); + + } + + } + + + } + _logger.LogInformation($"单位分组明细数据处理完毕,处理数量{oldCustomerOrgGroupList.Rows.Count}"); + } + else + { + _logger.LogInformation("单位分组明细数据已存在,未处理"); + } + } + + #endregion + + + + + + + #region 导入业务数据 + [HttpPost("api/app/CCTJExportDataOld/InitFieldComparisonCache")] + public async Task InitFieldComparisonCache() + { + //List flist = new List(); + //flist.Add( new FieldComparison + //{ + // FieldName = "id", + // NewKeyValue = "newid", + // OldKeyValue = "oldid", + // TableName = "test" + //}); + //flist.Add(new FieldComparison + //{ + // FieldName = "id", + // NewKeyValue = "newid2", + // OldKeyValue = "oldid2", + // TableName = "test" + //}); + + fieldComparisonTempList = (await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName != "patient_register").ToList(); + } + + private int hangPatientRegisterCount = 0; + private int hangPatientRegisterErrorCount = 0; + private int hangPatientRegisterReverseCount = 0; + + /// + /// 迁移人员、检查单、登记项目、项目结果、医生小结、修改人员创建者、创建时间 + /// + /// 每次处理的人员数量 + /// 开始日期 + /// 截止日期 + /// 是否继续处理 + /// + [HttpPost("api/app/CCTJExportDataOld/TransferPatientRegisterWithDetailData")] + public async Task TransferPatientRegisterWithDetailData(int handCount, string startdate, string enddate, bool isGo = false) + { + + + //当前导入的ID + string nextKeyValue = oldDb.Ado.GetString("select keyvalue from tb_export_key where tablename='patient_register' "); + + string sqlPatientRegister = ""; + + if (!string.IsNullOrWhiteSpace(startdate) && !string.IsNullOrWhiteSpace(enddate)) + { + sqlPatientRegister = $"select top {handCount} * from patient_register where patient_register_id>'{nextKeyValue}'" + + $" and register_date>='{startdate}' and register_date<'{enddate}' order by patient_register_id asc"; + + } + else + { + sqlPatientRegister = $"select top {handCount} * from patient_register where patient_register_id>'{nextKeyValue}' order by patient_register_id asc"; + + } + + DataTable oldPatientRegisterList = await oldDb.Ado.GetDataTableAsync(sqlPatientRegister); + + if (oldPatientRegisterList.Rows.Count > 0) + { + + var userList = await _identityUserRepository.GetListAsync(); + List customerOrgRegisterList = await _customerOrgRegisterRepository.GetListAsync(); + + Stopwatch stopwatch2 = new Stopwatch(); + stopwatch2.Start(); + + foreach (DataRow row in oldPatientRegisterList.Rows) + { + hangPatientRegisterCount++; + try + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + string oldPatientRegisterId = row["patient_register_id"].ToString(); + + //检查是否已经导入 + var isDZPatientRegisterTemp = (await _fieldComparisonRepository.GetListAsync(f => f.TableName == "patient_register" + && f.OldKeyValue == oldPatientRegisterId)); + + + if (isDZPatientRegisterTemp.Count > 0) + { + continue; + } + + + + //档案ID + Guid patientId = Guid.Empty; + + #region 处理档案,未找到档案就生成 + + var patientEnt = await _patientRepository.FirstOrDefaultAsync(m => m.PatientNo == row["patient_id"].ToString()); + if (patientEnt == null) + { + string nationId = null; + if (!string.IsNullOrWhiteSpace(row["nation_id"].ToString())) + { + var nationEnt = fieldComparisonTempList.Where(m => m.TableName == "nation" && m.OldKeyValue == row["nation_id"].ToString()).FirstOrDefault(); + if (nationEnt == null) + { + nationId = row["nation_id"].ToString(); + } + else + { + nationId = nationEnt.NewKeyValue; + } + } + + Guid autoPatientId = GuidGenerator.Create(); //档案ID + + var dataPatient = new Patient(autoPatientId) + { + Address = row["address"].ToString(), + BirthDate = string.IsNullOrEmpty(row["birth_date"].ToString()) ? null : Convert.ToDateTime(row["birth_date"].ToString()), + BirthPlaceId = null, + DisplayName = row["name"].ToString(), + Email = row["email"].ToString(), + IdNo = row["id_card_no"].ToString(), + MaritalStatusId = row["marital_status_id"].ToString() == "2" ? '4' : Convert.ToChar(row["marital_status_id"].ToString()), + MedicalCenterId = defaultMedicalCenterId, + MobileTelephone = row["mobile_telephone"].ToString(), + NationId = nationId, + PatientNo = row["patient_id"].ToString(), + PatientPassword = row["patient_password"].ToString(), + PostalCode = row["postalcode"].ToString(), + SexId = ConvertSex(row["sex_id"].ToString()), + SimpleCode = LanguageConverter.GetPYSimpleCode(row["name"].ToString()), + Telephone = row["telephone"].ToString() + }; + + await _patientRepository.InsertAsync(dataPatient, true); + patientId = autoPatientId; + } + else + { + patientId = patientEnt.Id; + } + + + #endregion + + + + Guid patientRegisterId = GuidGenerator.Create(); //生成登记ID + + #region 转换审核医生ID + Guid? AuditDoctorId = null; + if (!string.IsNullOrWhiteSpace(row["audit_doctor"].ToString())) + { + var userEnt = userList.Where(m => m.Name == row["audit_doctor"].ToString().Trim()).FirstOrDefault(); + if (userEnt != null) + { + AuditDoctorId = userEnt.Id; + } + } + #endregion + + #region 转换单位分组ID + Guid? customerOrgGroupId = null; + if (!string.IsNullOrWhiteSpace(row["org_group_id"].ToString())) + { + var customerOrgGroupEnt = fieldComparisonTempList.Where(m => m.TableName == "customer_org_group" && m.OldKeyValue == row["org_group_id"].ToString()).FirstOrDefault(); + if (customerOrgGroupEnt != null) + { + customerOrgGroupId = Guid.Parse(customerOrgGroupEnt.NewKeyValue); + } + } + #endregion + + #region 转换单位ID 部门 + Guid customerOrgId = Guid.Parse(fieldComparisonTempList.Where(m => m.TableName == "customer_org" && m.OldKeyValue == row["org_id"].ToString()).FirstOrDefault().NewKeyValue); + #endregion + + #region 转换单位体检次数ID 没有增加默认值 + Guid customerOrgRegisterId = GuidFlag.PersonCustomerOrgRegisterId; + if (row["org_id"].ToString() != "00000") + { + Guid topCustomerOrgId = Guid.Parse(fieldComparisonTempList.Where(m => m.TableName == "customer_org" && m.OldKeyValue == row["org_id"].ToString().Substring(0, 5)).FirstOrDefault().NewKeyValue); + var customerOrgRegisterEnt = customerOrgRegisterList.Where(m => m.CustomerOrgId == topCustomerOrgId + && m.MedicalTimes == (short)Convert.ToInt32(row["org_medical_times"].ToString())).FirstOrDefault(); + if (customerOrgRegisterEnt != null) + { + customerOrgRegisterId = customerOrgRegisterEnt.Id; + } + } + + #endregion + + #region 转换体检结论ID + Guid? medicalConclusionId = null; + if (!string.IsNullOrWhiteSpace(row["medical_conclusion_id"].ToString())) + { + var medicalConclusionEnt = fieldComparisonTempList.Where(m => m.TableName == "medical_conclusion" + && m.OldKeyValue == row["medical_conclusion_id"].ToString()).FirstOrDefault(); + if (medicalConclusionEnt != null) + { + medicalConclusionId = Guid.Parse(medicalConclusionEnt.NewKeyValue); + } + } + #endregion + + #region 转换套餐ID + Guid? medicalPackageId = null; + if (!string.IsNullOrWhiteSpace(row["medical_package_id"].ToString())) + { + var medicalPackageEnt = fieldComparisonTempList.Where(m => m.TableName == "medical_package" && m.OldKeyValue == row["medical_package_id"].ToString()).FirstOrDefault(); + if (medicalPackageEnt != null) + { + medicalPackageId = Guid.Parse(medicalPackageEnt.NewKeyValue); + } + } + #endregion + + #region 转换体检类别ID + Guid? medicalTypeId = null; + if (!string.IsNullOrWhiteSpace(row["medical_type_id"].ToString())) + { + var medicalTypeEnt = fieldComparisonTempList.Where(m => m.TableName == "medical_type" && m.OldKeyValue == row["medical_type_id"].ToString()).FirstOrDefault(); + if (medicalTypeEnt != null) + { + medicalTypeId = Guid.Parse(medicalTypeEnt.NewKeyValue); + } + } + #endregion + + + + #region 转换人员类别ID + Guid? personnelTypeId = null; + if (!string.IsNullOrWhiteSpace(row["personnel_type_id"].ToString())) + { + var personnelTypeEnt = fieldComparisonTempList.Where(m => m.TableName == "personnel_type" && m.OldKeyValue == row["personnel_type_id"].ToString()).FirstOrDefault(); + if (personnelTypeEnt != null) + { + personnelTypeId = Guid.Parse(personnelTypeEnt.NewKeyValue); + } + } + #endregion + + #region 转换总检医生ID + Guid? summaryDoctorId = null; + if (!string.IsNullOrWhiteSpace(row["summary_doctor"].ToString())) + { + var userEnt = userList.Where(m => m.Name == row["summary_doctor"].ToString().Trim()).FirstOrDefault(); + if (userEnt != null) + { + summaryDoctorId = userEnt.Id; + } + } + #endregion + + + #region 上传图片,获取地址 + + string photo = ""; + if (!string.IsNullOrEmpty(row["photograph"].ToString())) + { + photo = UpLoadImg(patientRegisterId, Convert.ToDateTime(row["register_date"].ToString()), (byte[])row["photograph"]); + } + + #endregion + + var data = new PatientRegister(patientRegisterId) + { + BirthDate = string.IsNullOrEmpty(row["birth_date"].ToString()) ? null : Convert.ToDateTime(row["birth_date"].ToString()), + MaritalStatusId = row["marital_status_id"].ToString() == "2" ? '4' : Convert.ToChar(row["marital_status_id"].ToString()), + MedicalCenterId = defaultMedicalCenterId, + SexId = ConvertSex(row["sex_id"].ToString()), + Age = string.IsNullOrWhiteSpace(row["age"].ToString()) ? null : Convert.ToInt16(row["age"].ToString()), + AuditDate = string.IsNullOrWhiteSpace(row["audit_date"].ToString()) ? null : Convert.ToDateTime(row["audit_date"].ToString()), + AuditDoctorId = AuditDoctorId, + CompleteFlag = Convert.ToChar(row["complete_flag"].ToString()), + CustomerOrgGroupId = customerOrgGroupId, + CustomerOrgId = customerOrgId, + CustomerOrgRegisterId = customerOrgRegisterId, + GuidePrintTimes = string.IsNullOrWhiteSpace(row["instruct_print_times"].ToString()) ? (short)0 : Convert.ToInt16(row["instruct_print_times"].ToString()), + InterposeMeasure = null, + IsAudit = string.IsNullOrWhiteSpace(row["audit_flag"].ToString()) ? 'N' : Convert.ToChar(row["audit_flag"].ToString()), + IsLock = string.IsNullOrWhiteSpace(row["lock_flag"].ToString()) ? 'N' : Convert.ToChar(row["lock_flag"].ToString()), + IsMedicalStart = string.IsNullOrWhiteSpace(row["medical_start_flag"].ToString()) ? 'N' : Convert.ToChar(row["medical_start_flag"].ToString()), + IsNameHide = string.IsNullOrWhiteSpace(row["name_encrypt_flag"].ToString()) ? 'N' : Convert.ToChar(row["name_encrypt_flag"].ToString()), + IsPhoneFollow = 'N', + IsRecoverGuide = string.IsNullOrWhiteSpace(row["recover_form_flag"].ToString()) ? 'N' : Convert.ToChar(row["recover_form_flag"].ToString()), + IsUpload = string.IsNullOrWhiteSpace(row["upload_flag"].ToString()) ? 'N' : Convert.ToChar(row["upload_flag"].ToString()), + IsVip = string.IsNullOrWhiteSpace(row["vip_flag"].ToString()) ? 'N' : Convert.ToChar(row["vip_flag"].ToString()), + JobCardNo = row["job_card_no"].ToString(), + JobPost = row["job_post"].ToString(), + JobTitle = row["job_title"].ToString(), + MedicalCardNo = row["medical_card_no"].ToString(), + MedicalConclusionId = medicalConclusionId, + MedicalPackageId = medicalPackageId, + MedicalStartDate = string.IsNullOrEmpty(row["medical_start_date"].ToString()) ? null : Convert.ToDateTime(row["medical_start_date"].ToString()), + MedicalTimes = Convert.ToInt16(row["medical_times"].ToString()), + MedicalTypeId = medicalTypeId, + PatientId = patientId, + PatientName = row["name"].ToString(), + PatientRegisterNo = row["barcode_no"].ToString(), + PersonnelTypeId = personnelTypeId, + Photo = photo, + Remark = row["remark"].ToString(), + ReportPrintTimes = Convert.ToInt16(row["report_print_times"].ToString()), + Salesman = row["salesman"].ToString(), + SexHormoneTermId = null, + SummaryDate = string.IsNullOrEmpty(row["summary_date"].ToString()) ? null : Convert.ToDateTime(row["summary_date"].ToString()), + SummaryDoctorId = summaryDoctorId, + ThirdInfo = row["third_info"].ToString(), + }; + + await _patientRegisterRepository.InsertAsync(data, true); + + + //Stopwatch stopwatch = new Stopwatch(); + //stopwatch.Start(); + + + #region 登记的项目、结果、小结 + + var oldRegisterAsbitemList = await oldDb.Ado.GetDataTableAsync($"select * from register_asbitem where patient_register_id='{row["patient_register_id"].ToString()}'"); + + if (oldRegisterAsbitemList.Rows.Count > 0) + { + List registerCheckTempList = new List(); + List registerCheckAsbitemTempList = new List(); + List registerCheckSummaryTempList = new List(); + List registerCheckItemTempList = new List(); + foreach (DataRow rowAsbitem in oldRegisterAsbitemList.Rows) + { + #region 转换审核医生ID + Guid? auditorUserId = null; + if (!string.IsNullOrWhiteSpace(rowAsbitem["audit_doctor"].ToString())) + { + var userEnt = userList.Where(m => m.Name == rowAsbitem["audit_doctor"].ToString().Trim()).FirstOrDefault(); + if (userEnt != null) + { + auditorUserId = userEnt.Id; + } + } + #endregion + + #region 转换检查医生ID + string checkDoctorId = null; + if (!string.IsNullOrWhiteSpace(rowAsbitem["check_doctor"].ToString())) + { + var userEnt = userList.Where(m => m.Name == rowAsbitem["check_doctor"].ToString().Trim()).FirstOrDefault(); + if (userEnt != null) + { + checkDoctorId = userEnt.Id.ToString(); + } + else + { + checkDoctorId = rowAsbitem["check_doctor"].ToString().Trim(); + } + } + #endregion + + #region 转换组合项目ID + Guid newAsbitemId = Guid.Parse(fieldComparisonTempList.Where(m => m.TableName == "asbitem" && m.OldKeyValue == rowAsbitem["asbitem_id"].ToString()).FirstOrDefault().NewKeyValue); + #endregion + + #region 插入register_check + Guid registerCheckId = GuidGenerator.Create(); + var dataRegisterCheck = new RegisterCheck(registerCheckId) + { + AuditorUserId = auditorUserId, + AuditTime = string.IsNullOrEmpty(rowAsbitem["audit_date"].ToString()) ? null : Convert.ToDateTime(rowAsbitem["audit_date"].ToString()), + CheckDate = string.IsNullOrEmpty(rowAsbitem["check_date"].ToString()) ? null : Convert.ToDateTime(rowAsbitem["check_date"].ToString()), + CheckDoctorId = checkDoctorId, + CheckRequestNo = "", + CheckRequestPrintTimes = (short)1, + CompleteFlag = Convert.ToChar(rowAsbitem["complete_flag"].ToString()), + CriticalRangeValue = null, + //CriticalValueCreateDate = null, + IsCriticalValue = null, + CriticalValueContent = null, + //CriticalValueProcessDate = null, + //CriticalValueProcessDoctor = null, + //CriticalValueProcessFlag = null, + IsAudit = string.IsNullOrEmpty(rowAsbitem["audit_flag"].ToString()) ? 'N' : Convert.ToChar(rowAsbitem["audit_flag"].ToString()), + IsLock = string.IsNullOrEmpty(rowAsbitem["lock_flag"].ToString()) ? 'N' : Convert.ToChar(rowAsbitem["lock_flag"].ToString()), + PatientRegisterId = patientRegisterId, + ThirdInfo = rowAsbitem["third_info"].ToString() + }; + + registerCheckTempList.Add(dataRegisterCheck); + //await _registerCheckRepository.InsertAsync(dataRegisterCheck, true); + #endregion + + + + #region 插入register_check_asbitem + Guid registerCheckAsbitemId = GuidGenerator.Create(); + + var dataRegisterAsbitem = new RegisterCheckAsbitem(registerCheckAsbitemId) + { + Amount = 1, + IsCharge = Convert.ToChar(rowAsbitem["charge_flag"].ToString()), + AsbitemId = newAsbitemId, + ChargePrice = Convert.ToDecimal(rowAsbitem["price"].ToString()), + GroupPackageId = null, + LisRequestId = null, + PatientRegisterId = patientRegisterId, + PayTypeFlag = Convert.ToChar(rowAsbitem["payment_mode"].ToString()), + RegisterCheckId = registerCheckId, + StandardPrice = Convert.ToDecimal(rowAsbitem["standard_price"].ToString()) + }; + registerCheckAsbitemTempList.Add(dataRegisterAsbitem); + //await _registerCheckAsbitemRepository.InsertAsync(dataRegisterAsbitem); + #endregion + + + #region 插入医生小结 + + var oldSummary = rowAsbitem["summary"].ToString(); + if (!string.IsNullOrWhiteSpace(oldSummary)) + { + var dataRegisterCheckSummary = new RegisterCheckSummary + { + RegisterCheckId = registerCheckId, + DisplayOrder = 1, + Summary = oldSummary, + SummaryFlag = '0' + }; + + registerCheckSummaryTempList.Add(dataRegisterCheckSummary); + // await _registerCheckSummaryRepository.InsertAsync(dataRegisterCheckSummary); + + } + + #endregion + + #region 插入明细项目 + + var oldRegisterCheckItemList = await oldDb.Ado.GetDataTableAsync($"select * from register_item where patient_register_id='{row["patient_register_id"].ToString()}' and asbitem_id='{rowAsbitem["asbitem_id"].ToString()}'"); + + if (oldRegisterCheckItemList.Rows.Count > 0) + { + + foreach (DataRow rowRegisterCheckItem in oldRegisterCheckItemList.Rows) + { + #region 转换项目ID 老转新 + Guid newItemId = Guid.Parse(fieldComparisonTempList + .Where(m => m.TableName == "item" && m.OldKeyValue == rowRegisterCheckItem["item_id"].ToString()).FirstOrDefault().NewKeyValue); + + #endregion + + + var dataRegisterCheckItem = new RegisterCheckItem + { + CheckDate = string.IsNullOrEmpty(rowRegisterCheckItem["check_date"].ToString()) ? null : Convert.ToDateTime(rowRegisterCheckItem["check_date"].ToString()), + CriticalValue = null, + CheckDoctorName = rowRegisterCheckItem["check_doctor"].ToString().Trim(), + CriticalRangeValue = null, + ItemId = newItemId, + ReferenceRangeValue = rowRegisterCheckItem["reference_range_value"].ToString(), + RegisterCheckId = registerCheckId, + Result = rowRegisterCheckItem["result"].ToString(), + ResultStatusId = _registerCheckItemManager.GetResultStatusId(rowRegisterCheckItem["result"].ToString(), rowRegisterCheckItem["reference_range_value"].ToString()), + Unit = rowRegisterCheckItem["Unit"].ToString() + }; + registerCheckItemTempList.Add(dataRegisterCheckItem); + // await _registerCheckItemRepository.InsertAsync(dataRegisterCheckItem); + + } + + } + + #endregion + + } + + if (registerCheckTempList.Any()) + { + await _registerCheckRepository.InsertManyAsync(registerCheckTempList); + } + if (registerCheckAsbitemTempList.Any()) + { + await _registerCheckAsbitemRepository.InsertManyAsync(registerCheckAsbitemTempList); + } + if (registerCheckSummaryTempList.Any()) + { + await _registerCheckSummaryRepository.InsertManyAsync(registerCheckSummaryTempList); + } + if (registerCheckItemTempList.Any()) + { + await _registerCheckItemRepository.InsertManyAsync(registerCheckItemTempList); + } + } + + #endregion + + //stopwatch.Stop(); + //_logger.LogInformation($"{row["patient_register_id"]}__{oldRegisterAsbitemList.Rows.Count}__第一片段耗时:{stopwatch.ElapsedMilliseconds}"); + + #region 总检建议、综述、总检诊断 + + + var oldSum = await oldDb.Ado.GetDataTableAsync($"select summary,suggestion,barcode_no from patient_register where patient_register_id='{oldPatientRegisterId}' "); + + if (oldSum.Rows.Count == 1) + { + string oldSummary = oldSum.Rows[0][0].ToString(); + string oldSuggestion = oldSum.Rows[0][1].ToString(); + + if (!string.IsNullOrWhiteSpace(oldSummary)) + { + + Guid sumSummaryHeaderId = GuidGenerator.Create(); + + var dataSumSummaryHeader = new SumSummaryHeader(sumSummaryHeaderId) + { + DisplayOrder = 1, + SummaryFlag = '0', + PatientRegisterId = patientRegisterId, + SummaryTitle = "异常结果如下" + }; + + await _sumSummaryHeaderRepository.InsertAsync(dataSumSummaryHeader); + + Guid sumSummaryContentId = GuidGenerator.Create(); + var dataSumSummaryContent = new SumSummaryContent(sumSummaryContentId) + { + DisplayOrder = 1, + SumSummaryHeaderId = sumSummaryHeaderId, + SummaryContent = oldSummary + }; + + await _sumSummaryContentRepository.InsertAsync(dataSumSummaryContent); + + } + + + if (!string.IsNullOrWhiteSpace(oldSuggestion)) + { + + Guid sumSuggestionHeaderId = GuidGenerator.Create(); + + var dataSumSuggestionHeader = new SumSuggestionHeader(sumSuggestionHeaderId) + { + DisplayOrder = 1, + SuggestionFlag = '0', + PatientRegisterId = patientRegisterId, + SuggestionTitle = "健康建议如下" + }; + + await _sumSuggestionHeaderRepository.InsertAsync(dataSumSuggestionHeader); + + Guid sumSuggestionContentId = GuidGenerator.Create(); + var dataSumSuggestionContent = new SumSuggestionContent(sumSuggestionContentId) + { + DisplayOrder = 1, + SuggestionContent = oldSuggestion, + SuggestionType = SuggestionTypeFlag.HealthGuidance, + SumSuggestionHeaderId = sumSuggestionHeaderId + }; + + await _sumSuggestionContentRepository.InsertAsync(dataSumSuggestionContent); + + + + #region 总症诊断 + var oldSummaryDiagnosis = await oldDb.Ado.GetDataTableAsync($"select diagnosis_id from summary_diagnosis where patient_register_id='{oldPatientRegisterId}' order by display_order asc "); + + if (oldSummaryDiagnosis.Rows.Count > 0) + { + List sumDiagnosisInsert = new List(); + + foreach (DataRow summaryDiagnosis in oldSummaryDiagnosis.Rows) + { + var diagnosisEnt = fieldComparisonTempList + .Where(m => m.TableName == "diagnosis" && m.OldKeyValue == summaryDiagnosis["diagnosis_id"].ToString()).FirstOrDefault(); + if (diagnosisEnt != null) + { + + var dataSumDiagnosis = new SumDiagnosis + { + DisplayOrder = oldSummaryDiagnosis.Rows.IndexOf(summaryDiagnosis) + 1, + PatientRegisterId = patientRegisterId, + DiagnosisId = Guid.Parse(diagnosisEnt.NewKeyValue), + SumSuggestionHeaderId = sumSuggestionHeaderId + }; + + sumDiagnosisInsert.Add(dataSumDiagnosis); + + + } + + + } + + if (sumDiagnosisInsert.Any()) + await _sumDiagnosisRepository.InsertManyAsync(sumDiagnosisInsert); + + } + #endregion + + + } + + + } + + + #endregion + + + var fieldComparison = new FieldComparison + { + FieldName = "id", + NewKeyValue = patientRegisterId.ToString(), + OldKeyValue = row["patient_register_id"].ToString(), + TableName = "patient_register" + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + + await oldDb.Ado.ExecuteCommandAsync($"update tb_export_key set keyvalue='{row["patient_register_id"].ToString()}',addtime=getdate(),handlecount+=1 where tablename='patient_register' "); + + await uow.CompleteAsync(); + + + #region 修改创建者日期跟id + Guid registerDoctorId = Guid.Parse(_configuration.GetValue("AdminId")); + var registerDoctorEnt = userList.Where(m => m.Name == row["register_doctor"].ToString().Trim()).FirstOrDefault(); + if (registerDoctorEnt != null) + { + registerDoctorId = registerDoctorEnt.Id; + } + string sql_update = $"update patient_register set creator_id='{registerDoctorId}',creation_time='{Convert.ToDateTime(row["register_date"]).ToString("yyyy-MM-dd HH:mm:ss")}'"; + sql_update += $" where id='{patientRegisterId}' "; + await newDb.Ado.ExecuteCommandAsync(sql_update); + #endregion + } + } + catch (Exception ex) + { + hangPatientRegisterErrorCount++; + _logger.LogInformation($"数据处理失败,人员id为:{row["patient_register_id"]},异常信息:{ex.ToString()}"); + #region 添加到tb_error_log表 + await oldDb.Ado.ExecuteCommandAsync($"insert into tb_error_log(old_patient_register_id,error_message,addtime) values ('{row["patient_register_id"]}','{ex.StackTrace}',getdate()) "); + #endregion + } + } + + stopwatch2.Stop(); + _logger.LogInformation($"总耗时:{stopwatch2.ElapsedMilliseconds}"); + + _logger.LogInformation($"人员数据处理{oldPatientRegisterList.Rows.Count}条,当前总数{hangPatientRegisterCount}"); + if (isGo) + await TransferPatientRegisterWithDetailData(handCount, startdate, enddate, isGo); + } + else + { + _logger.LogInformation("人员数据已处理完"); + } + + + + } + + /// + /// 反向导入人员等业务信息 + /// + /// 每次处理的人员数量 + /// 是否继续处理 + /// + [HttpPost("api/app/CCTJExportDataOld/TransferPatientRegisterWithDetailReverseData")] + public async Task TransferPatientRegisterWithDetailReverseData(int handCount, bool isGo = false) + { + //当前导入的ID + string nextKeyValue = oldDb.Ado.GetString("select keyvalue from tb_export_key where tablename='patient_register_reverse' "); + + var oldPatientRegisterList = await oldDb.Ado.GetDataTableAsync($"select top {handCount} * from patient_register where patient_register_id<'{nextKeyValue}' order by patient_register_id desc"); + + if (oldPatientRegisterList.Rows.Count > 0) + { + var userList = await _identityUserRepository.GetListAsync(); + List customerOrgRegisterList = await _customerOrgRegisterRepository.GetListAsync(); + + foreach (DataRow row in oldPatientRegisterList.Rows) + { + hangPatientRegisterReverseCount++; + + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + string oldPatientRegisterId = row["patient_register_id"].ToString(); + + //检查是否已经导入 + var isDZPatientRegisterTemp = (await _fieldComparisonRepository.GetListAsync(f => f.TableName == "patient_register" + && f.OldKeyValue == oldPatientRegisterId)); + + + if (isDZPatientRegisterTemp.Count > 0) + { + continue; + } + + + + //档案ID + Guid patientId = Guid.Empty; + + #region 处理档案,未找到档案就生成 + + var patientEnt = await _patientRepository.FirstOrDefaultAsync(m => m.PatientNo == row["patient_id"].ToString()); + if (patientEnt == null) + { + string nationId = null; + if (!string.IsNullOrWhiteSpace(row["nation_id"].ToString())) + { + var nationEnt = (await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "nation" && m.OldKeyValue == row["nation_id"].ToString()).FirstOrDefault(); + if (nationEnt == null) + { + nationId = row["nation_id"].ToString(); + } + else + { + nationId = nationEnt.NewKeyValue; + } + } + + Guid autoPatientId = GuidGenerator.Create(); //档案ID + + var dataPatient = new Patient(autoPatientId) + { + Address = row["address"].ToString(), + BirthDate = string.IsNullOrEmpty(row["birth_date"].ToString()) ? null : Convert.ToDateTime(row["birth_date"].ToString()), + BirthPlaceId = null, + DisplayName = row["name"].ToString(), + Email = row["email"].ToString(), + IdNo = row["id_card_no"].ToString(), + MaritalStatusId = row["marital_status_id"].ToString() == "2" ? '4' : Convert.ToChar(row["marital_status_id"].ToString()), + MedicalCenterId = defaultMedicalCenterId, + MobileTelephone = row["mobile_telephone"].ToString(), + NationId = nationId, + PatientNo = row["patient_id"].ToString(), + PatientPassword = row["patient_password"].ToString(), + PostalCode = row["postalcode"].ToString(), + SexId = ConvertSex(row["sex_id"].ToString()), + SimpleCode = LanguageConverter.GetPYSimpleCode(row["name"].ToString()), + Telephone = row["telephone"].ToString() + }; + + await _patientRepository.InsertAsync(dataPatient, true); + patientId = autoPatientId; + } + else + { + patientId = patientEnt.Id; + } + + + #endregion + + + + Guid patientRegisterId = GuidGenerator.Create(); //生成登记ID + + #region 转换审核医生ID + Guid? AuditDoctorId = null; + if (!string.IsNullOrWhiteSpace(row["audit_doctor"].ToString())) + { + var userEnt = userList.Where(m => m.Name == row["audit_doctor"].ToString().Trim()).FirstOrDefault(); + if (userEnt != null) + { + AuditDoctorId = userEnt.Id; + } + } + #endregion + + #region 转换单位分组ID + Guid? customerOrgGroupId = null; + if (!string.IsNullOrWhiteSpace(row["org_group_id"].ToString())) + { + var customerOrgGroupEnt = (await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "customer_org_group" && m.OldKeyValue == row["org_group_id"].ToString()).FirstOrDefault(); + if (customerOrgGroupEnt != null) + { + customerOrgGroupId = Guid.Parse(customerOrgGroupEnt.NewKeyValue); + } + } + #endregion + + #region 转换单位ID 部门 + Guid customerOrgId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "customer_org" && m.OldKeyValue == row["org_id"].ToString()).FirstOrDefault().NewKeyValue); + #endregion + + #region 转换单位体检次数ID 没有增加默认值 + Guid customerOrgRegisterId = GuidFlag.PersonCustomerOrgRegisterId; + if (row["org_id"].ToString() != "00000") + { + Guid topCustomerOrgId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "customer_org" && m.OldKeyValue == row["org_id"].ToString().Substring(0, 5)).FirstOrDefault().NewKeyValue); + var customerOrgRegisterEnt = customerOrgRegisterList.Where(m => m.CustomerOrgId == topCustomerOrgId + && m.MedicalTimes == (short)Convert.ToInt32(row["org_medical_times"].ToString())).FirstOrDefault(); + if (customerOrgRegisterEnt != null) + { + customerOrgRegisterId = customerOrgRegisterEnt.Id; + } + } + + #endregion + + #region 转换体检结论ID + Guid? medicalConclusionId = null; + if (!string.IsNullOrWhiteSpace(row["medical_conclusion_id"].ToString())) + { + var medicalConclusionEnt = (await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "medical_conclusion" + && m.OldKeyValue == row["medical_conclusion_id"].ToString()).FirstOrDefault(); + if (medicalConclusionEnt != null) + { + medicalConclusionId = Guid.Parse(medicalConclusionEnt.NewKeyValue); + } + } + #endregion + + #region 转换套餐ID + Guid? medicalPackageId = null; + if (!string.IsNullOrWhiteSpace(row["medical_package_id"].ToString())) + { + var medicalPackageEnt = (await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "medical_package" && m.OldKeyValue == row["medical_package_id"].ToString()).FirstOrDefault(); + if (medicalPackageEnt != null) + { + medicalPackageId = Guid.Parse(medicalPackageEnt.NewKeyValue); + } + } + #endregion + + #region 转换体检类别ID + Guid? medicalTypeId = null; + if (!string.IsNullOrWhiteSpace(row["medical_type_id"].ToString())) + { + var medicalTypeEnt = (await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "medical_type" && m.OldKeyValue == row["medical_type_id"].ToString()).FirstOrDefault(); + if (medicalTypeEnt != null) + { + medicalTypeId = Guid.Parse(medicalTypeEnt.NewKeyValue); + } + } + #endregion + + + + #region 转换人员类别ID + Guid? personnelTypeId = null; + if (!string.IsNullOrWhiteSpace(row["personnel_type_id"].ToString())) + { + var personnelTypeEnt = (await _fieldComparisonRepository.GetQueryableAsync()).Where(m => m.TableName == "personnel_type" && m.OldKeyValue == row["personnel_type_id"].ToString()).FirstOrDefault(); + if (personnelTypeEnt != null) + { + personnelTypeId = Guid.Parse(personnelTypeEnt.NewKeyValue); + } + } + #endregion + + #region 转换总检医生ID + Guid? summaryDoctorId = null; + if (!string.IsNullOrWhiteSpace(row["summary_doctor"].ToString())) + { + var userEnt = userList.Where(m => m.Name == row["summary_doctor"].ToString().Trim()).FirstOrDefault(); + if (userEnt != null) + { + summaryDoctorId = userEnt.Id; + } + } + #endregion + + + #region 上传图片,获取地址 + + string photo = ""; + if (!string.IsNullOrEmpty(row["photograph"].ToString())) + { + photo = UpLoadImg(patientRegisterId, Convert.ToDateTime(row["register_date"].ToString()), (byte[])row["photograph"]); + } + + #endregion + + var data = new PatientRegister(patientRegisterId) + { + BirthDate = string.IsNullOrEmpty(row["birth_date"].ToString()) ? null : Convert.ToDateTime(row["birth_date"].ToString()), + MaritalStatusId = row["marital_status_id"].ToString() == "2" ? '4' : Convert.ToChar(row["marital_status_id"].ToString()), + MedicalCenterId = defaultMedicalCenterId, + SexId = ConvertSex(row["sex_id"].ToString()), + Age = string.IsNullOrWhiteSpace(row["age"].ToString()) ? null : Convert.ToInt16(row["age"].ToString()), + AuditDate = string.IsNullOrWhiteSpace(row["audit_date"].ToString()) ? null : Convert.ToDateTime(row["audit_date"].ToString()), + AuditDoctorId = AuditDoctorId, + CompleteFlag = Convert.ToChar(row["complete_flag"].ToString()), + CustomerOrgGroupId = customerOrgGroupId, + CustomerOrgId = customerOrgId, + CustomerOrgRegisterId = customerOrgRegisterId, + GuidePrintTimes = string.IsNullOrWhiteSpace(row["instruct_print_times"].ToString()) ? (short)0 : Convert.ToInt16(row["instruct_print_times"].ToString()), + InterposeMeasure = null, + IsAudit = string.IsNullOrWhiteSpace(row["audit_flag"].ToString()) ? 'N' : Convert.ToChar(row["audit_flag"].ToString()), + IsLock = string.IsNullOrWhiteSpace(row["lock_flag"].ToString()) ? 'N' : Convert.ToChar(row["lock_flag"].ToString()), + IsMedicalStart = string.IsNullOrWhiteSpace(row["medical_start_flag"].ToString()) ? 'N' : Convert.ToChar(row["medical_start_flag"].ToString()), + IsNameHide = string.IsNullOrWhiteSpace(row["name_encrypt_flag"].ToString()) ? 'N' : Convert.ToChar(row["name_encrypt_flag"].ToString()), + IsPhoneFollow = 'N', + IsRecoverGuide = string.IsNullOrWhiteSpace(row["recover_form_flag"].ToString()) ? 'N' : Convert.ToChar(row["recover_form_flag"].ToString()), + IsUpload = string.IsNullOrWhiteSpace(row["upload_flag"].ToString()) ? 'N' : Convert.ToChar(row["upload_flag"].ToString()), + IsVip = string.IsNullOrWhiteSpace(row["vip_flag"].ToString()) ? 'N' : Convert.ToChar(row["vip_flag"].ToString()), + JobCardNo = row["job_card_no"].ToString(), + JobPost = row["job_post"].ToString(), + JobTitle = row["job_title"].ToString(), + MedicalCardNo = row["medical_card_no"].ToString(), + MedicalConclusionId = medicalConclusionId, + MedicalPackageId = medicalPackageId, + MedicalStartDate = string.IsNullOrEmpty(row["medical_start_date"].ToString()) ? null : Convert.ToDateTime(row["medical_start_date"].ToString()), + MedicalTimes = Convert.ToInt16(row["medical_times"].ToString()), + MedicalTypeId = medicalTypeId, + PatientId = patientId, + PatientName = row["name"].ToString(), + PatientRegisterNo = row["barcode_no"].ToString(), + PersonnelTypeId = personnelTypeId, + Photo = photo, + Remark = row["remark"].ToString(), + ReportPrintTimes = Convert.ToInt16(row["report_print_times"].ToString()), + Salesman = row["salesman"].ToString(), + SexHormoneTermId = null, + SummaryDate = string.IsNullOrEmpty(row["summary_date"].ToString()) ? null : Convert.ToDateTime(row["summary_date"].ToString()), + SummaryDoctorId = summaryDoctorId, + ThirdInfo = row["third_info"].ToString(), + }; + + await _patientRegisterRepository.InsertAsync(data, true); + + + + + + #region 登记的项目、结果、小结 + + var oldRegisterAsbitemList = await oldDb.Ado.GetDataTableAsync($"select * from register_asbitem where patient_register_id='{row["patient_register_id"].ToString()}'"); + + if (oldRegisterAsbitemList.Rows.Count > 0) + { + foreach (DataRow rowAsbitem in oldRegisterAsbitemList.Rows) + { + #region 转换审核医生ID + Guid? auditorUserId = null; + if (!string.IsNullOrWhiteSpace(rowAsbitem["audit_doctor"].ToString())) + { + var userEnt = userList.Where(m => m.Name == rowAsbitem["audit_doctor"].ToString().Trim()).FirstOrDefault(); + if (userEnt != null) + { + auditorUserId = userEnt.Id; + } + } + #endregion + + #region 转换检查医生ID + string checkDoctorId = null; + if (!string.IsNullOrWhiteSpace(rowAsbitem["check_doctor"].ToString())) + { + var userEnt = userList.Where(m => m.Name == rowAsbitem["check_doctor"].ToString().Trim()).FirstOrDefault(); + if (userEnt != null) + { + checkDoctorId = userEnt.Id.ToString(); + } + else + { + checkDoctorId = rowAsbitem["check_doctor"].ToString().Trim(); + } + } + #endregion + + #region 转换组合项目ID + Guid newAsbitemId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()) + .Where(m => m.TableName == "asbitem" && m.OldKeyValue == rowAsbitem["asbitem_id"].ToString()).FirstOrDefault().NewKeyValue); + #endregion + + #region 插入register_check + Guid registerCheckId = GuidGenerator.Create(); + var dataRegisterCheck = new RegisterCheck(registerCheckId) + { + AuditorUserId = auditorUserId, + AuditTime = string.IsNullOrEmpty(rowAsbitem["audit_date"].ToString()) ? null : Convert.ToDateTime(rowAsbitem["audit_date"].ToString()), + CheckDate = string.IsNullOrEmpty(rowAsbitem["check_date"].ToString()) ? null : Convert.ToDateTime(rowAsbitem["check_date"].ToString()), + CheckDoctorId = checkDoctorId, + CheckRequestNo = "", + CheckRequestPrintTimes = (short)1, + CompleteFlag = Convert.ToChar(rowAsbitem["complete_flag"].ToString()), + CriticalRangeValue = null, + //CriticalValueCreateDate = null, + IsCriticalValue = null, + CriticalValueContent = null, + //CriticalValueProcessDate = null, + //CriticalValueProcessDoctor = null, + //CriticalValueProcessFlag = null, + IsAudit = string.IsNullOrEmpty(rowAsbitem["audit_flag"].ToString()) ? 'N' : Convert.ToChar(rowAsbitem["audit_flag"].ToString()), + IsLock = string.IsNullOrEmpty(rowAsbitem["lock_flag"].ToString()) ? 'N' : Convert.ToChar(rowAsbitem["lock_flag"].ToString()), + PatientRegisterId = patientRegisterId, + ThirdInfo = rowAsbitem["third_info"].ToString() + }; + + + await _registerCheckRepository.InsertAsync(dataRegisterCheck, true); + #endregion + + + + #region 插入register_check_asbitem + Guid registerCheckAsbitemId = GuidGenerator.Create(); + + var dataRegisterAsbitem = new RegisterCheckAsbitem(registerCheckAsbitemId) + { + Amount = 1, + IsCharge = Convert.ToChar(rowAsbitem["charge_flag"].ToString()), + AsbitemId = newAsbitemId, + ChargePrice = Convert.ToDecimal(rowAsbitem["price"].ToString()), + GroupPackageId = null, + LisRequestId = null, + PatientRegisterId = patientRegisterId, + PayTypeFlag = Convert.ToChar(rowAsbitem["payment_mode"].ToString()), + RegisterCheckId = registerCheckId, + StandardPrice = Convert.ToDecimal(rowAsbitem["standard_price"].ToString()) + }; + + await _registerCheckAsbitemRepository.InsertAsync(dataRegisterAsbitem); + #endregion + + + #region 插入医生小结 + + var oldSummary = rowAsbitem["summary"].ToString(); + if (!string.IsNullOrWhiteSpace(oldSummary)) + { + var dataRegisterCheckSummary = new RegisterCheckSummary + { + RegisterCheckId = registerCheckId, + DisplayOrder = 1, + Summary = oldSummary, + SummaryFlag = '0' + }; + + await _registerCheckSummaryRepository.InsertAsync(dataRegisterCheckSummary); + + } + + #endregion + + #region 插入明细项目 + + var oldRegisterCheckItemList = await oldDb.Ado.GetDataTableAsync($"select * from register_item where patient_register_id='{row["patient_register_id"].ToString()}' and asbitem_id='{rowAsbitem["asbitem_id"].ToString()}'"); + + if (oldRegisterCheckItemList.Rows.Count > 0) + { + + foreach (DataRow rowRegisterCheckItem in oldRegisterCheckItemList.Rows) + { + #region 转换项目ID 老转新 + Guid newItemId = Guid.Parse((await _fieldComparisonRepository.GetQueryableAsync()) + .Where(m => m.TableName == "item" && m.OldKeyValue == rowRegisterCheckItem["item_id"].ToString()).FirstOrDefault().NewKeyValue); + + #endregion + + + var dataRegisterCheckItem = new RegisterCheckItem + { + CheckDate = string.IsNullOrEmpty(rowRegisterCheckItem["check_date"].ToString()) ? null : Convert.ToDateTime(rowRegisterCheckItem["check_date"].ToString()), + CriticalValue = null, + CheckDoctorName = rowRegisterCheckItem["check_doctor"].ToString().Trim(), + CriticalRangeValue = null, + ItemId = newItemId, + ReferenceRangeValue = rowRegisterCheckItem["reference_range_value"].ToString(), + RegisterCheckId = registerCheckId, + Result = rowRegisterCheckItem["result"].ToString(), + ResultStatusId = _registerCheckItemManager.GetResultStatusId(rowRegisterCheckItem["result"].ToString(), rowRegisterCheckItem["reference_range_value"].ToString()), + Unit = rowRegisterCheckItem["Unit"].ToString() + }; + + await _registerCheckItemRepository.InsertAsync(dataRegisterCheckItem); + + } + + } + + #endregion + + } + } + + #endregion + + + #region 总检建议、综述、总检诊断 + + + var oldSum = await oldDb.Ado.GetDataTableAsync($"select summary,suggestion,barcode_no from patient_register where patient_register_id='{oldPatientRegisterId}' "); + + if (oldSum.Rows.Count == 1) + { + string oldSummary = oldSum.Rows[0][0].ToString(); + string oldSuggestion = oldSum.Rows[0][1].ToString(); + + if (!string.IsNullOrWhiteSpace(oldSummary)) + { + + Guid sumSummaryHeaderId = GuidGenerator.Create(); + + var dataSumSummaryHeader = new SumSummaryHeader(sumSummaryHeaderId) + { + DisplayOrder = 1, + SummaryFlag = '0', + PatientRegisterId = patientRegisterId, + SummaryTitle = "异常结果如下" + }; + + await _sumSummaryHeaderRepository.InsertAsync(dataSumSummaryHeader); + + Guid sumSummaryContentId = GuidGenerator.Create(); + var dataSumSummaryContent = new SumSummaryContent(sumSummaryContentId) + { + DisplayOrder = 1, + SumSummaryHeaderId = sumSummaryHeaderId, + SummaryContent = oldSummary + }; + + await _sumSummaryContentRepository.InsertAsync(dataSumSummaryContent); + + } + + + if (!string.IsNullOrWhiteSpace(oldSuggestion)) + { + + Guid sumSuggestionHeaderId = GuidGenerator.Create(); + + var dataSumSuggestionHeader = new SumSuggestionHeader(sumSuggestionHeaderId) + { + DisplayOrder = 1, + SuggestionFlag = '0', + PatientRegisterId = patientRegisterId, + SuggestionTitle = "健康建议如下" + }; + + await _sumSuggestionHeaderRepository.InsertAsync(dataSumSuggestionHeader); + + Guid sumSuggestionContentId = GuidGenerator.Create(); + var dataSumSuggestionContent = new SumSuggestionContent(sumSuggestionContentId) + { + DisplayOrder = 1, + SuggestionContent = oldSuggestion, + SuggestionType = SuggestionTypeFlag.HealthGuidance, + SumSuggestionHeaderId = sumSuggestionHeaderId + }; + + await _sumSuggestionContentRepository.InsertAsync(dataSumSuggestionContent); + + + + #region 总症诊断 + var oldSummaryDiagnosis = await oldDb.Ado.GetDataTableAsync($"select diagnosis_id from summary_diagnosis where patient_register_id='{oldPatientRegisterId}' order by display_order asc "); + + if (oldSummaryDiagnosis.Rows.Count > 0) + { + List sumDiagnosisInsert = new List(); + + foreach (DataRow summaryDiagnosis in oldSummaryDiagnosis.Rows) + { + var diagnosisEnt = (await _fieldComparisonRepository.GetQueryableAsync()) + .Where(m => m.TableName == "diagnosis" && m.OldKeyValue == summaryDiagnosis["diagnosis_id"].ToString()).FirstOrDefault(); + if (diagnosisEnt != null) + { + + var dataSumDiagnosis = new SumDiagnosis + { + DisplayOrder = oldSummaryDiagnosis.Rows.IndexOf(summaryDiagnosis) + 1, + PatientRegisterId = patientRegisterId, + DiagnosisId = Guid.Parse(diagnosisEnt.NewKeyValue), + SumSuggestionHeaderId = sumSuggestionHeaderId + }; + + sumDiagnosisInsert.Add(dataSumDiagnosis); + + + } + + + } + + if (sumDiagnosisInsert.Any()) + await _sumDiagnosisRepository.InsertManyAsync(sumDiagnosisInsert); + + } + #endregion + + + } + + + } + + + #endregion + + + var fieldComparison = new FieldComparison + { + FieldName = "id", + NewKeyValue = patientRegisterId.ToString(), + OldKeyValue = row["patient_register_id"].ToString(), + TableName = "patient_register" + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + + await oldDb.Ado.ExecuteCommandAsync($"update tb_export_key set keyvalue='{row["patient_register_id"].ToString()}',addtime=getdate(),handlecount+=1 where tablename='patient_register_reverse' "); + + await uow.CompleteAsync(); + + + #region 修改创建者日期跟id + Guid registerDoctorId = Guid.Parse(_configuration.GetValue("AdminId")); + var registerDoctorEnt = userList.Where(m => m.Name == row["register_doctor"].ToString().Trim()).FirstOrDefault(); + if (registerDoctorEnt != null) + { + registerDoctorId = registerDoctorEnt.Id; + } + string sql_update = $"update patient_register set creator_id='{registerDoctorId}',creation_time='{Convert.ToDateTime(row["register_date"]).ToString("yyyy-MM-dd HH:mm:ss")}'"; + sql_update += $" where id='{patientRegisterId}' "; + await newDb.Ado.ExecuteCommandAsync(sql_update); + #endregion + } + } + + _logger.LogInformation($"人员数据反向处理{oldPatientRegisterList.Rows.Count}条,当前总数{hangPatientRegisterReverseCount}"); + if (isGo) + await TransferPatientRegisterWithDetailReverseData(handCount, isGo); + } + else + { + _logger.LogInformation("人员数据反向已处理完"); + } + + } + + + #endregion + + + /// + /// 迁移子项目对照数据 + /// + /// + public async Task TranferItemColumnReferenceData() + { + var oldColumnReferenceList = await oldDb.Ado.GetDataTableAsync($"select code_value,interface_code_value from column_reference_detail where column_reference_id=004 and interface_code_value!=''"); + foreach (DataRow item in oldColumnReferenceList.Rows) + { + var fieldComparisonEnt = await _fieldComparisonRepository.FirstOrDefaultAsync(f => f.TableName == "item" && f.OldKeyValue == item["code_value"].ToString().Trim()); + if (fieldComparisonEnt != null) + { + var newItemId = Guid.Parse(fieldComparisonEnt.NewKeyValue); + + + + string oldInterfaceCodeValue = item["interface_code_value"].ToString(); + string[] oldInterfaceCodeValues = oldInterfaceCodeValue.Split(','); + + var inputDto = new UpdateColumnReferenceInterfaceDto + { + ColumnReferenceId = Guid.Parse("3a125a29-ae4d-1ba8-db69-cffd0c629fc0"), + AppCode = new UpdateColumnReferenceCodeDto { CodeValue = newItemId.ToString() }, + InterfaceCodes = oldInterfaceCodeValues.Select(s => new UpdateColumnReferenceInterfaceCodeDto + { + CodeValue = s + }).ToList() + }; + + await _columnReferenceAppService.UpdateInterfaceCodeValuesAsync(inputDto); + } + + } + } + + /// + /// 迁移会员卡相关数据 金额后面统计 + /// + /// + public async Task TranferCardData() + { + + await TransferCardTypeDataAsync(); + await TransferCardRegisterDataAsync(); + } + + /// + /// 迁移会员卡类别数据 + /// + /// + private async Task TransferCardTypeDataAsync() + { + var count = await _cardTypeRepository.GetCountAsync(); + if (count == 0) + { + + var oldCardTypeList = await oldDb.Ado.GetDataTableAsync("select card_type_id,card_type_name,card_mode_id,discount,expiry_day,remark from card_type order by display_order asc"); + if (oldCardTypeList.Rows.Count > 0) + { + foreach (DataRow row in oldCardTypeList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + Guid cardTypeId = GuidGenerator.Create(); + + var data = new CardType(cardTypeId) + { + DisplayName = row["card_type_name"].ToString(), + DisplayOrder = oldCardTypeList.Rows.IndexOf(row) + 1, + CardModeId = row["card_mode_id"].ToString() == "1" ? '0' : '1', + Discount = Convert.ToInt32(row["discount"].ToString()), + ExpiryDay = Convert.ToInt32(row["expiry_day"].ToString()), + Remark = row["remark"].ToString() + }; + + await _cardTypeRepository.InsertAsync(data); + + var fieldComparison = new FieldComparison + { + TableName = "card_type", + FieldName = "id", + NewKeyValue = cardTypeId.ToString(), + OldKeyValue = row["card_type_id"].ToString() + }; + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + } + + + } + _logger.LogInformation($"会员卡类别数据处理完毕,处理数量{oldCardTypeList.Rows.Count}"); + } + else + { + _logger.LogInformation($"会员卡类别数据已存在,未处理"); + } + } + + + + + /// + /// 迁移会员卡数据 + /// + /// + private async Task TransferCardRegisterDataAsync() + { + var count = await _cardRegisterRepository.GetCountAsync(); + if (count == 0) + { + var oldCardRegisterList = await oldDb.Ado.GetDataTableAsync("SELECT [card_register_id],[card_type_id],[card_no],[discount],[expiry_date],[customer_name],[id_card_no]," + + "[telephone],[mobile_telephone],[card_flag],[remark],[sale_date],[amender],[amended_date] FROM [dbo].[card_register] order by card_register_id asc"); + if (oldCardRegisterList.Rows.Count > 0) + { + + foreach (DataRow row in oldCardRegisterList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + Guid cardRegisterId = GuidGenerator.Create(); + + var cardTypeFieldComparison = await _fieldComparisonRepository.FirstOrDefaultAsync(f => f.TableName == "card_type" && f.OldKeyValue == row["card_type_id"].ToString().Trim()); + var data = new CardRegister(cardRegisterId) + { + CardBalance = 0, + CardNo = row["card_no"].ToString(), + IdNo = row["id_card_no"].ToString(), + CardPassword = "", + ExpiryDate = Convert.ToDateTime(row["expiry_date"].ToString()), + Remark = row["remark"].ToString(), + CardTypeId = Guid.Parse(cardTypeFieldComparison.NewKeyValue), + CustomerName = row["customer_name"].ToString(), + Discount = Convert.ToInt32(row["discount"].ToString()), + IsActive = Convert.ToChar(row["card_flag"].ToString()), + MedicalCenterId = defaultMedicalCenterId, + MobileTelephone = row["mobile_telephone"].ToString(), + Telephone = row["telephone"].ToString() + }; + + await _cardRegisterRepository.InsertAsync(data); + + var fieldComparison = new FieldComparison + { + TableName = "card_register", + FieldName = "id", + NewKeyValue = cardRegisterId.ToString(), + OldKeyValue = row["card_register_id"].ToString() + }; + + await _fieldComparisonRepository.InsertAsync(fieldComparison); + + await uow.CompleteAsync(); + } + } + + } + _logger.LogInformation($"会员卡数据处理完毕,处理数量{oldCardRegisterList.Rows.Count}"); + } + else + { + _logger.LogInformation($"会员卡数据已存在,未处理"); + } + } + + + + + #region 私有方法 + + /// + /// 转换老系统适用性别 + /// + /// + /// + private char ConvertForSex(string forSexId) + { + if (forSexId == "0") + { + return 'M'; + } + else if (forSexId == "1") + { + return 'F'; + } + else + { + return 'A'; + } + } + + /// + /// 转换老系统性别 + /// + /// + /// + private char ConvertSex(string SexId) + { + if (SexId == "0") + { + return 'M'; + } + else if (SexId == "1") + { + return 'F'; + } + else + { + return 'U'; + } + } + + /// + /// 转换头像 + /// + /// + /// + /// + /// + private string UpLoadImg(Guid PatientRegisterId, DateTime time, byte[] Photo) + { + string imgurl = $"photo/{time.Year}/{time.Month}/{time.Day}/" + PatientRegisterId; + var isupload = ImageHelper.ByteToImage(Photo, imgurl); + if (!string.IsNullOrEmpty(isupload)) + return isupload; + else + return ""; + } + + + /// + /// 迁移后台用户数据 + /// + /// + private async Task TransferUserData() + { + + var oldUserList = await oldDb.Ado.GetDataTableAsync("select * from users"); + if (oldUserList.Rows.Count > 0) + { + + foreach (DataRow row in oldUserList.Rows) + { + using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) + { + string newUserName = LanguageConverter.GetPYSimpleCode(row["user_id"].ToString().Trim()); + + var isUserName = await _identityUserRepository.FirstOrDefaultAsync(m => m.UserName == newUserName); + if (isUserName != null) + { + newUserName += "2"; + } + var userEnt = new IdentityUserCreateNoEmailDto + { + Email = "", + IsActive = row["valid_flag"].ToString() == "Y" ? true : false, + LockoutEnabled = false, + Name = row["user_name"].ToString().Trim(), + Password = string.IsNullOrWhiteSpace(row["password"].ToString()) ? "888888" : row["password"].ToString(), + PhoneNumber = "", + RoleNames = new string[] { "admin" }, + Surname = "", + UserName = newUserName, + UserPhoto = "", + UserSign = "" + }; + + await _myUserAppService.CreateAsync(userEnt); + + await uow.CompleteAsync(); + + } + } + + + } + + } + + #endregion + } +} diff --git a/src/Shentun.Peis.HttpApi.Host/Shentun.Peis.HttpApi.Host.csproj b/src/Shentun.Peis.HttpApi.Host/Shentun.Peis.HttpApi.Host.csproj index 761af30..0a42ee7 100644 --- a/src/Shentun.Peis.HttpApi.Host/Shentun.Peis.HttpApi.Host.csproj +++ b/src/Shentun.Peis.HttpApi.Host/Shentun.Peis.HttpApi.Host.csproj @@ -2,6 +2,14 @@ + + ES3 + + + + ES3 + + net6.0 Shentun.Peis