<?php

namespace App\Console\Commands;

use App\Models\DoctorModel;
use App\Models\PatientModel;
use App\Models\PharmacyModel;
use App\Models\PrescriptionLogModel;
use App\Models\PrescriptionModel;
use DateTime;
use Illuminate\Console\Command;

class PrescriptionCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mohe:prescription';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '自动审开方';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('开始自动审开方...');
        // 如果处方单是审方状态，同时对应的药店开启自动审方
        $prescriptions = PrescriptionModel::where('status', 1)
            ->where('status', PrescriptionModel::PRESCRIPTION_STATUS_REVIEWING)
            ->get();

        if ($prescriptions->count() > 0) {
            $this->info('没有需要审方的处方单');

            return;
        }
        foreach ($prescriptions as $prescription) {
            // 查询对应的医师是手动并且药师为自动
            $pharmacist = PharmacyModel::where('id', $prescription->pharmacy_id)->first();
            $doctor = DoctorModel::where('id', $prescription->doctor_id)->first();
            if ($doctor->is_auto == 0 && $pharmacist->is_auto == 1) {
                // 更新处方单状态
                $prescriptionInfo = PrescriptionModel::find($prescription->id);
                if ($prescriptionInfo) {
                    $prescriptionInfo->status = PrescriptionModel::PRESCRIPTION_STATUS_SUCCESS;
                    $prescriptionInfo->save();
                    // 获取患者信息
                    $patient = PatientModel::where('id', $prescriptionInfo->patient_id)->first();
                    // 生成审方日志
                    $dateTime = new DateTime($prescription->created_at);
                    $dateTime->modify('+5 minutes');
                    $pharmacistLog = new PrescriptionLogModel;
                    $pharmacistLog->pharmacy_id = $prescription->pharmacy_id;
                    $pharmacistLog->pharmacy_name = $prescription->pharmacy_name;
                    $currentTime = $dateTime->format('Y-m-d H:i:s');
                    $pharmacistLog->log_info = $prescription->pharmacist_name.'在'.$currentTime.'为'.$prescription->patient_name.'（'.$patient->mobile.'）审方(处方单编号：'.$prescription->id.')';
                    $pharmacistLog->save();
                    $this->info($prescription->id.'审方成功');
                }
            }
        }

    }
}
