<?php

namespace App\Api\Controllers;

use App\Http\Controllers\BaseApiController;
use App\Models\DoctorCorrectionModel;
use App\Models\DoctorModel;
use App\Models\PatientModel;
use App\Models\PrescriptionLogModel;
use App\Models\PrescriptionModel;
use App\Models\User;
use Datetime;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

// 医师控制器
class DoctorController extends BaseApiController
{
    // 医师详情
    public function detail()
    {
        $authInfo = auth('api')->user();
        $doctor = DoctorModel::where('user_id', $authInfo->id)->first();
        if ($doctor) {
            return $this->success($doctor);
        }

        return $this->failed('医师信息获取失败');
    }

    // 医师签名图片上传
    public function upload(Request $request)
    {
        // 验证上传的图片文件
        $validator = Validator::make($request->all(), [
            'image' => 'required|image|mimes:jpeg,png,jpg|max:10240',
        ]);
        if ($validator->fails()) {
            return $this->failed('图片必须2Mb以内，且是jpeg,png,jpg三种格式~');
        }

        // 获取上传的图片
        if ($request->hasFile('image')) {
            $path = Storage::putFile('license-images', $request->file('image'));
            // 返回完整图片地址
            $imageUrl = Storage::url($path);

            // 签名图片地址记录到数据库
            $authInfo = auth('api')->user();
            $doctor = DoctorModel::where('user_id', $authInfo->id)->first();
            $doctor->signed_pic = $path;
            if ($doctor->save()) {

                return $this->success(['message' => 'ok', 'url' => $imageUrl]);
            }

            return $this->failed('签名图片上传失败');
        } else {
            return $this->failed('签名图片上传失败');
        }

    }

    // 医师开方接口
    public function prescription(Request $request)
    {
        $prescription_id = $request->input('id');
        if (empty($prescription_id)) {
            return $this->failed('ID 不能为空');
        }
        $authInfo = auth('api')->user();
        $doctor = DoctorModel::where('user_id', $authInfo->id)->first();
        if (! $doctor) {
            return $this->failed('医师信息不存在');
        }
        $prescription = PrescriptionModel::where('id', $prescription_id)->first();
        if ($prescription->doctor_id != $doctor->id) {
            return $this->failed('您没有权限开方该处方');
        }
        $prescription->status = PrescriptionModel::PRESCRIPTION_STATUS_REVIEWING;
        if ($prescription->save()) {
            // 获取患者信息
            $patient = PatientModel::where('id', $prescription->patient_id)->first();
            // 生成医师开方日志
            $dateTime = new DateTime($prescription->created_at);
            $dateTime->modify('+3 minutes');
            $prescription_at = $dateTime->format('Y-m-d H:i:s');
            $doctorLog = new PrescriptionLogModel;
            $doctorLog->pharmacy_id = $prescription->pharmacy_id;
            $doctorLog->pharmacy_name = $prescription->pharmacy_name;
            $doctorLog->log_info = $doctor->name.'在'.$prescription_at.'为'.$prescription->patient_name.'（'.$patient->mobile.'）开具处方单（处方单编号：'.$prescription_id.'）';
            $doctorLog->save();

            return $this->success('开方成功');
        } else {
            return $this->failed('开方失败');
        }
    }

    // 医师自动开方
    public function isAuto(Request $request)
    {
        $authInfo = auth('api')->user();
        $doctor = DoctorModel::where('user_id', $authInfo->id)->first();
        if (! $doctor) {
            return $this->failed('医师信息不存在');
        }
        $doctor->is_auto = $request->input('is_auto');
        if ($doctor->save()) {
            return $this->success('设置成功');
        }

        return $this->failed('设置失败');
    }

    // 医师纠错
    public function correction(Request $request)
    {
        $authInfo = auth('api')->user();
        $doctor = DoctorModel::where('user_id', $authInfo->id)->first();
        if (! $doctor) {
            return $this->failed('医师信息不存在');
        }
        $content = $request->input('content');
        if (empty($content)) {
            return $this->failed('纠错内容不能为空');
        }
        $correction = new DoctorCorrectionModel();
        $correction->doctor_id = $doctor->id;
        $correction->doctor_name = $doctor->name;
        $correction->is_handle = DoctorCorrectionModel::IS_HANDLE_FALSE;
        $correction->content = $content;
        if ($correction->save()) {
            return $this->success('纠错上报成功!');
        }

        return $this->failed('纠错失败');
    }

    // 医师退出
    public function logout()
    {
        $authInfo = auth('api')->user();
        // 医师表user_id改为0
        // $doctor = DoctorModel::where('user_id', $authInfo->id)->first();
        // if (! $doctor) {
        //     return $this->failed('医师信息不存在');
        // }
        // $doctor->user_id = 0;
        // $doctor->save();
        // user表中last_login_type字段改为0
        // $user = User::where('id', $authInfo->id)->where('last_login_type', User::LOGIN_TYPE_DOCTOR)->first();
        $user = User::where('id', $authInfo->id)->first();
        if (! $user) {
            return $this->failed('用户不存在');
        }
        $user->last_login_type = User::LOGIN_TYPE_USER;
        if ($user->save()) {
            return $this->success('退出成功!');
        }

        return $this->failed('退出失败!');
    }
}
