DCS/ruiyiweiUX/Assets/Scripts/Services/PatientInfoService.cs

330 lines
10 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using System.Linq;
public class PatientInfoService : IPatientInfoService
{
public event Action<PatientInfo> OnPatientInfoChanged;
private PatientInfo _currentPatient;
private const string PATIENT_DATA_KEY = "CurrentPatientData";
private const string PATIENT_FILES_FOLDER = "PatientFiles";
public PatientInfoService()
{
LoadPatientInfo();
}
public PatientInfo GetCurrentPatient()
{
return _currentPatient;
}
public void SetCurrentPatient(PatientInfo patient)
{
_currentPatient = patient;
OnPatientInfoChanged?.Invoke(patient);
}
public void ClearCurrentPatient()
{
try
{
_currentPatient = null;
PlayerPrefs.DeleteKey(PATIENT_DATA_KEY);
PlayerPrefs.Save();
OnPatientInfoChanged?.Invoke(null);
var authService = ServiceLocator.Get<IAuthenticationService>();
var logService = ServiceLocator.Get<UserLogService>();
logService?.LogUserOperation(
authService?.CurrentUsername ?? "system",
"清空患者信息",
"退出主界面返回登录界面",
true);
}
catch (Exception ex)
{
Debug.LogError($"清空病人信息失败: {ex.Message}");
}
}
public bool SavePatientInfo(PatientInfo patient)
{
try
{
_currentPatient = patient;
// 保存到PlayerPrefs简化实现
var json = JsonUtility.ToJson(patient);
PlayerPrefs.SetString(PATIENT_DATA_KEY, json);
PlayerPrefs.Save();
OnPatientInfoChanged?.Invoke(patient);
// 记录患者信息保存日志
var authService = ServiceLocator.Get<IAuthenticationService>();
var logService = ServiceLocator.Get<UserLogService>();
logService?.LogUserOperation(
authService?.CurrentUsername ?? "system",
"保存患者信息",
$"姓名: {patient.Name}, 住院号: {patient.HospitalId}",
true);
return true;
}
catch (Exception ex)
{
Debug.LogError($"保存病人信息失败: {ex.Message}");
// 记录失败日志
var authService = ServiceLocator.Get<IAuthenticationService>();
var logService = ServiceLocator.Get<UserLogService>();
logService?.LogUserOperation(
authService?.CurrentUsername ?? "system",
"保存患者信息",
$"失败: {ex.Message}",
false);
return false;
}
}
private void LoadPatientInfo()
{
try
{
var json = PlayerPrefs.GetString(PATIENT_DATA_KEY, "");
if (!string.IsNullOrEmpty(json))
{
_currentPatient = JsonUtility.FromJson<PatientInfo>(json);
}
}
catch (Exception ex)
{
Debug.LogError($"加载病人信息失败: {ex.Message}");
}
}
/// <summary>
/// 从文件加载病人信息
/// </summary>
public PatientInfo LoadPatientFromFile(string filePath)
{
try
{
if (!File.Exists(filePath))
{
Debug.LogError($"文件不存在: {filePath}");
return null;
}
string extension = Path.GetExtension(filePath).ToLower();
PatientInfo patient = null;
switch (extension)
{
case ".json":
patient = LoadFromJSON(filePath);
break;
case ".csv":
patient = LoadFromCSV(filePath);
break;
case ".txt":
patient = LoadFromTXT(filePath);
break;
default:
Debug.LogError($"不支持的文件格式: {extension}");
return null;
}
if (patient != null)
{
SetCurrentPatient(patient);
SavePatientInfo(patient); // 保存到本地
Debug.Log($"成功从文件加载病人信息: {patient.Name}");
}
return patient;
}
catch (Exception ex)
{
Debug.LogError($"从文件加载病人信息失败: {ex.Message}");
return null;
}
}
/// <summary>
/// 从JSON文件加载
/// </summary>
private PatientInfo LoadFromJSON(string filePath)
{
// string json = File.ReadAllText(filePath, Encoding.UTF8);
// JsonUtility.FromJson<PatientInfo>(json);
PatientInfo jsonData = JsonMgr.Instance.LoadData<PatientInfo>(filePath);
return jsonData;
}
/// <summary>
/// 从CSV文件加载
/// 格式: 姓名,住院号,性别,年龄,身高,体重,身份证号
/// </summary>
private PatientInfo LoadFromCSV(string filePath)
{
string[] lines = File.ReadAllLines(filePath, Encoding.UTF8);
if (lines.Length < 2) // 至少需要标题行和数据行
{
throw new Exception("CSV文件格式错误至少需要两行数据");
}
// 跳过标题行,取第一个病人数据
string[] data = lines[1].Split(',');
if (data.Length < 7)
{
throw new Exception("CSV文件数据列数不足需要7列数据");
}
return new PatientInfo
{
Name = data[0].Trim(),
HospitalId = data[1].Trim(),
Gender = data[2].Trim(),
Age = int.TryParse(data[3].Trim(), out int age) ? age : 0,
Height = float.TryParse(data[4].Trim(), out float height) ? height : 0f,
Weight = float.TryParse(data[5].Trim(), out float weight) ? weight : 0f,
// IdNumber = data[6].Trim()
};
}
/// <summary>
/// 从文本文件加载
/// 格式: 每行一个字段,按顺序为姓名、住院号、性别、年龄、身高、体重、身份证号
/// </summary>
private PatientInfo LoadFromTXT(string filePath)
{
string[] lines = File.ReadAllLines(filePath, Encoding.UTF8)
.Where(line => !string.IsNullOrWhiteSpace(line))
.ToArray();
if (lines.Length < 7)
{
throw new Exception("文本文件数据不足需要7行数据");
}
return new PatientInfo
{
Name = lines[0].Trim(),
HospitalId = lines[1].Trim(),
Gender = lines[2].Trim(),
Age = int.TryParse(lines[3].Trim(), out int age) ? age : 0,
Height = float.TryParse(lines[4].Trim(), out float height) ? height : 0f,
Weight = float.TryParse(lines[5].Trim(), out float weight) ? weight : 0f,
// IdNumber = lines[6].Trim()
};
}
/// <summary>
/// 导出病人信息到文件
/// </summary>
public bool ExportPatientToFile(PatientInfo patient, string filePath)
{
try
{
string extension = Path.GetExtension(filePath).ToLower();
switch (extension)
{
case ".json":
return ExportToJSON(patient, filePath);
case ".csv":
return ExportToCSV(patient, filePath);
case ".txt":
return ExportToTXT(patient, filePath);
default:
Debug.LogError($"不支持的导出格式: {extension}");
return false;
}
}
catch (Exception ex)
{
Debug.LogError($"导出病人信息失败: {ex.Message}");
return false;
}
}
/// <summary>
/// 导出完整的患者会话数据(包含测量数据)
/// </summary>
public bool ExportCompletePatientData(PatientInfo patient, string filePath)
{
try
{
// 获取会话服务中的测量数据
var sessionService = ServiceLocator.Get<PatientSessionService>();
if (sessionService?.CurrentSession != null)
{
return sessionService.ExportSessionData(filePath);
}
else
{
// 如果没有会话数据,仅导出患者基本信息
Debug.LogWarning("没有活动会话数据,仅导出患者基本信息");
return ExportPatientToFile(patient, filePath);
}
}
catch (Exception ex)
{
Debug.LogError($"导出完整患者数据失败: {ex.Message}");
return false;
}
}
private bool ExportToJSON(PatientInfo patient, string filePath)
{
JsonMgr.Instance.SaveData(patient, filePath);
return true;
}
private bool ExportToCSV(PatientInfo patient, string filePath)
{
var csv = new StringBuilder();
csv.AppendLine("姓名,住院号,性别,年龄,身高,体重,身份证号");
csv.AppendLine($"{patient.Name},{patient.HospitalId},{patient.Gender},{patient.Age},{patient.Height},{patient.Weight}");
File.WriteAllText(filePath, csv.ToString(), Encoding.UTF8);
return true;
}
private bool ExportToTXT(PatientInfo patient, string filePath)
{
var txt = new StringBuilder();
txt.AppendLine(patient.Name);
txt.AppendLine(patient.HospitalId);
txt.AppendLine(patient.Gender);
txt.AppendLine(patient.Age.ToString());
txt.AppendLine(patient.Height.ToString());
txt.AppendLine(patient.Weight.ToString());
// txt.AppendLine(patient.IdNumber);
File.WriteAllText(filePath, txt.ToString(), Encoding.UTF8);
return true;
}
/// <summary>
/// 获取支持的文件格式
/// </summary>
public string[] GetSupportedFileExtensions()
{
return new string[] { ".json", ".csv", ".txt" };
}
/// <summary>
/// 获取文件选择过滤器
/// </summary>
public string GetFileFilter()
{
return "支持的文件|*.json;*.csv;*.txt|JSON文件|*.json|CSV文件|*.csv|文本文件|*.txt";
}
}