reminder/app/Models/Patient.php

149 lines
4.1 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Carbon\Carbon;
class Patient extends Model
{
protected $fillable = [
'user_id',
'name',
'gender',
'age',
'diagnosis',
'discharge_date',
'address',
'phone',
'remark',
'follow_up_count',
'last_follow_up_date',
];
/**
* 获取患者所属用户
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
protected $casts = [
'discharge_date' => 'date',
'last_follow_up_date' => 'date',
];
/**
* 获取随访时间规则(月数)
* 脑卒中/心肌梗塞: 1, 3, 6, 12 个月
* 慢性肾脏病: 1, 2, 3, 6 个月
*/
public function getFollowUpSchedule(): array
{
$diagnosis = $this->diagnosis;
if (str_contains($diagnosis, '慢性肾') || str_contains($diagnosis, '肾脏病')) {
return [1, 2, 3, 6]; // 慢性肾脏病
}
// 脑卒中、心肌梗塞及其他
return [1, 3, 6, 12];
}
/**
* 自动计算已完成的随访次数(过期的月份自动算已完成)
*/
public function getAutoFollowUpCount(): int
{
$schedule = $this->getFollowUpSchedule();
$currentMonth = Carbon::now()->startOfMonth();
$completed = 0;
foreach ($schedule as $months) {
$followUpDate = $this->discharge_date->copy()->addMonths($months);
// 如果随访日期的月份早于当前月份,则算作已完成
if ($followUpDate->startOfMonth()->lt($currentMonth)) {
$completed++;
} else {
break;
}
}
return $completed;
}
/**
* 获取当月需要随访的日期(如果有的话)
*/
public function getCurrentMonthFollowUpDate(): ?Carbon
{
$schedule = $this->getFollowUpSchedule();
$currentMonth = Carbon::now();
$monthStart = $currentMonth->copy()->startOfMonth();
$monthEnd = $currentMonth->copy()->endOfMonth();
foreach ($schedule as $index => $months) {
$followUpDate = $this->discharge_date->copy()->addMonths($months);
// 如果随访日期在当月内
if ($followUpDate->gte($monthStart) && $followUpDate->lte($monthEnd)) {
return $followUpDate;
}
}
return null;
}
/**
* 获取当月随访是第几次
*/
public function getCurrentMonthFollowUpNumber(): ?int
{
$schedule = $this->getFollowUpSchedule();
$currentMonth = Carbon::now();
$monthStart = $currentMonth->copy()->startOfMonth();
$monthEnd = $currentMonth->copy()->endOfMonth();
foreach ($schedule as $index => $months) {
$followUpDate = $this->discharge_date->copy()->addMonths($months);
if ($followUpDate->gte($monthStart) && $followUpDate->lte($monthEnd)) {
return $index + 1;
}
}
return null;
}
/**
* 检查当月是否需要随访
*/
public function needsFollowUpThisMonth(): bool
{
return $this->getCurrentMonthFollowUpDate() !== null;
}
/**
* 检查是否已完成所有随访
*/
public function isCompleted(): bool
{
return $this->getAutoFollowUpCount() >= count($this->getFollowUpSchedule());
}
/**
* 获取诊断类型名称
*/
public function getDiagnosisType(): string
{
if (str_contains($this->diagnosis, '脑卒中')) {
return '脑卒中';
} elseif (str_contains($this->diagnosis, '心肌梗') || str_contains($this->diagnosis, '心梗')) {
return '心肌梗塞';
} elseif (str_contains($this->diagnosis, '慢性肾') || str_contains($this->diagnosis, '肾脏病')) {
return '慢性肾脏病';
}
return $this->diagnosis;
}
}