<?php

namespace App\Api\Controllers;

use App\Http\Controllers\BaseApiController;
use App\Models\DoctorModel;
use App\Models\PatientModel;
use App\Models\PharmacistModel;
use App\Models\PharmacyDrugModel;
use App\Models\PharmacyModel;
use App\Models\PrescriptionLogModel;
use App\Models\PrescriptionModel;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

// 问诊人控制器
class PrescriptionController extends BaseApiController
{
    public function test()
    {
        // 分派医师 医师当日开方未达到上限以及是否在时间段的搜索出来
        // $site_config = DB::table('admin_settings')->where('slug', 'site_config')->value('value');
        // $site_config = json_decode($site_config, true);
        // $pharmacy = PharmacyDrugModel::where('pharmacy_id',1)->get();
        $doctors = DoctorModel::query()->where('status', 1)->get();
        $randomDoctor = $doctors->random();

        return $this->success($randomDoctor);
    }

    // 处方列表
    public function prescriptionList(Request $request)
    {
        $authInfo = auth('api')->user();
        $query = PrescriptionModel::query();
        // TODO 判断当前登录的用户角色
        // $userInfo = User::with(['doctor', 'pharmacist'])->find($authInfo->id);
        if ($authInfo->last_login_type == User::LOGIN_TYPE_USER) {
            $query->where('user_id', $authInfo->id);
        } elseif ($authInfo->last_login_type == User::LOGIN_TYPE_DOCTOR) { // 医师
            $doctor = DoctorModel::query()->where('user_id', $authInfo->id)->first();
            $query->where('doctor_id', $doctor->id);
        } elseif ($authInfo->last_login_type == User::LOGIN_TYPE_PHARMACY) { // 药店
            $pharmacy = PharmacyModel::query()->where('user_id', $authInfo->id)->first();
            $query->where('pharmacy_id', $pharmacy->id);
        }

        // 时间段
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
        if ($start_time && $end_time) {
            $query->whereBetween('created_at', [$start_time, $end_time]);
        } elseif ($start_time) {
            $query->where('created_at', '>=', $start_time);
        } elseif ($end_time) {
            $query->where('created_at', '<=', $end_time);
        }

        // 状态
        $status = $request->input('status');
        if ($status) {
            $query->where('status', $status);
        }

        // 分页
        $page = $request->input('page', 1);
        $perPage = $request->input('per_page', 10);
        $prescription = $query->orderBy('id', 'desc')->paginate($perPage, ['*'], 'page', $page);

        // $prescription = $query->paginate(10);
        return $this->success($prescription);
    }

    // 处方详情
    public function prescriptionDetail(Request $request)
    {
        $prescription_id = $request->input('prescription_id');
        $prescription = PrescriptionModel::query()->where('id', $prescription_id)->first();

        return $this->success($prescription);
    }

    // 开方
    public function create(Request $request)
    {
        // $userId = auth('api')->user()->id;
        // 生成处方单号
        $patient_id = $request->input('patient_id');
        // 获取问诊人信息
        $patient = PatientModel::query()->where('id', $patient_id)->first();
        $prescription_umber = '';
        $data = [];
        $data['prescription_umber'] = '';  // TODO 处方单编号生成逻辑待定
        $data['status'] = 0; // TODO Model中增加枚举
        $data['user_id'] = ''; // TODO 获取当前用户ID
        // 问诊人信息
        $data['patient_id'] = $patient_id; // 问诊人编号
        $data['patient_name'] = $patient->name; // 问诊人姓名
        $data['patient_age'] = $patient->age; // 问诊人年龄
        $data['patient_gender'] = $patient->gender; // 问诊人性别
        // 诊断信息
        $data['diagnosis_id'] = $request->input('diagnosis_id');
        $data['diagnosis_name'] = $request->input('diagnosis_name');
        // 问诊问题
        $data['inquiry_info'] = ''; // TODO 问诊问题
        // 用药信息
        $data['drug_info'] = ''; // TODO 用药信息
        // 分派医师 医师当日开方未达到上限以及是否在时间段的搜索出来
        $site_config = DB::table('admin_settings')->where('slug', 'site_config')->value('value');
        $site_config = json_decode($site_config, true);
        $prescription_limit = $site_config['prescription_limit'];

        // 判断是否开启时间段
        $doctors = DoctorModel::query()->where('status', 1)->get();
        $randomDoctor = $doctors->random();
        // foreach ($doctors as $key => $doctor) {

        // }
        // 判断是否为医师自动开方

        $pharmacy_id = $request->input('pharmacy_id');
        $pharmacy = PharmacyModel::query()->where('id', $pharmacy_id)->first();
        // 生成医师开方日志
        $dockor_log = [];
        $dockor_log['pharmacy_id'] = $pharmacy_id;
        $dockor_log['pharmacy_name'] = $pharmacy->name;
        $currentTime = Carbon::now()->toDateTimeString();
        $dockor_log['log_info'] = $randomDoctor->mame.'在'.$currentTime.'为'.$patient->name.'（'.$patient->mobile.'）开具处方单（处方单编号：'.$prescription_umber.'）';
        PrescriptionLogModel::create($dockor_log);
        // 分派药师,先搜索是否存在默认药师，如果不存在则随机抽取一个
        $pharmacist = PharmacistModel::query()->where('status', 1)->where('is_default', 1)->where('pharmacy_id', $pharmacy_id)->first();
        if (! $pharmacist) {
            $pharmacists = PharmacistModel::query()->where('status', 1)->where('pharmacy_id', $pharmacy_id)->get();
            $pharmacist = $pharmacists->random();
        }
        //  判断是否药师自动审方
        // 生成药师审方日志
        $pharamcy_log = [];
        $pharamcy_log['pharmacy_id'] = $pharmacy_id;
        $pharamcy_log['pharmacy_name'] = $pharmacy->name;
        $currentTime = Carbon::now()->toDateTimeString();
        $pharamcy_log['log_info'] = $pharmacist->name.'在'.$currentTime.'为'.$patient->name.'（'.$patient->mobile.'）审方';
        // 给医师发送短信

        // 给药师发送短信

        // 生成处方单信息

        return $this->success($data);
    }
}
