<?php

namespace App\Api\Controllers;

use App\Http\Controllers\BaseApiController;
use App\Models\PatientModel;
use App\Models\PharmacyCorrectionModel;
use App\Models\PharmacyModel;
use App\Models\PrescriptionLogModel;
use App\Models\PrescriptionModel;
use App\Models\User;
use Carbon\Carbon;
use DateTime;
use Illuminate\Http\Request;

// 药店控制器
class PharmacyController extends BaseApiController
{
    public function test()
    {
        return $this->success(['a' => 1, 'b' => 2, 'c' => 3]);
    }

    public function PharmacyList(Request $request)
    {
        $search_input = $request->input('search_input');
        $query = PharmacyModel::query();
        if ($search_input) {
            $query->where('name', 'like', "%{$search_input}%");
            // ->orWhere('address','like',"%{$search_input}%");
        }
        // 是否闭店、是否在营业时间段、是否启用
        $query = $query->where('is_open', PharmacyModel::IS_OPEN_TRUE)
            ->where('status', PharmacyModel::STATUS_TRUE)
            ->where('business_start', '<=', Carbon::now()->format('H:i'))
            ->where('business_end', '>=', Carbon::now()->format('H:i'));

        $data = $query->paginate(10);

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

    // 获取药店详情
    public function detail(Request $request)
    {
        $authInfo = auth('api')->user();
        $pharmacy = PharmacyModel::where('user_id', $authInfo->id)->first();
        if (! $pharmacy) {
            return $this->failed('药店信息不存在');
        }

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

    // 药店信息纠错
    public function correction(Request $request)
    {
        $authInfo = auth('api')->user();
        $pharmacy = PharmacyModel::where('user_id', $authInfo->id)->first();
        if (! $pharmacy) {
            return $this->failed('药店信息不存在');
        }
        $content = $request->input('content');
        if (empty($content)) {
            return $this->failed('纠错内容不能为空');
        }
        $correction = new PharmacyCorrectionModel();
        $correction->pharmacy_id = $pharmacy->id;
        $correction->pharmacy_name = $pharmacy->name;
        $correction->is_handle = PharmacyCorrectionModel::IS_HANDLE_FALSE;
        $correction->content = $content;
        if ($correction->save()) {
            return $this->success('纠错上报成功!');
        } else {
            return $this->failed('纠错失败');
        }
    }

    // 药店审方
    public function prescription(Request $request)
    {
        $id = $request->input('id');
        if (empty($id)) {
            return $this->failed('ID 不能为空');
        }
        $authInfo = auth('api')->user();
        $Pharmacy = PharmacyModel::where('user_id', $authInfo->id)->first();
        if (! $Pharmacy) {
            return $this->failed('药店信息不存在');
        }
        $prescription = PrescriptionModel::where('id', $id)->where('pharmacy_id', $Pharmacy->id)->where('status', PrescriptionModel::PRESCRIPTION_STATUS_REVIEWING)->first();
        if (! $prescription) {
            return $this->failed('请传递正确的处方单');
        }
        $prescription->status = PrescriptionModel::PRESCRIPTION_STATUS_SUCCESS;
        if ($prescription->save()) {
            $patient_id = $prescription->patient_id;
            $patient = PatientModel::where('id', $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();

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

    // 设置店铺营业时间
    public function setBusinessTime(Request $request)
    {
        $authInfo = auth('api')->user();
        $pharmacy = PharmacyModel::where('user_id', $authInfo->id)->first();
        $request->validate([
            'business_start' => 'required|date_format:H:i:s', // 验证格式为 HH:mm
            'business_end' => 'required|date_format:H:i:s',  // 验证格式为 HH:mm
        ]);

        // 将时间格式化为 H:i:s 格式
        $pharmacy->business_start = Carbon::createFromFormat('H:i:s', $request->input('business_start'))->format('H:i:s');
        $pharmacy->business_end = Carbon::createFromFormat('H:i:s', $request->input('business_end'))->format('H:i:s');
        if ($pharmacy->save()) {
            return $this->success('设置成功!');
        } else {
            return $this->failed('设置失败');
        }
    }

    // 开店或闭店
    public function open(Request $request)
    {
        $authInfo = auth('api')->user();
        $pharmacy = PharmacyModel::where('user_id', $authInfo->id)->first();
        if (! $pharmacy) {
            return $this->failed('药店信息不存在');
        }
        $is_open = $request->input('is_open');

        $pharmacy->is_open = $is_open;
        if ($pharmacy->save()) {
            return $this->success('操作成功!');
        } else {
            return $this->failed('操作失败');
        }
    }

    // 药店退出登录
    public function logout()
    {
        $authInfo = auth('api')->user();

        // 药店表user_id改为0
        $pharmacy = PharmacyModel::where('user_id', $authInfo->id)->first();
        if (! $pharmacy) {
            return $this->failed('药店信息不存在');
        }
        $pharmacy->user_id = 0;
        $pharmacy->save();
        // user表last_login_type改为0
        $user = User::where('id', $authInfo->id)->where('last_login_type', User::LOGIN_TYPE_PHARMACY)->first();
        if (! $user) {
            return $this->failed('用户不存在');
        }
        $user->last_login_type = User::LOGIN_TYPE_USER;
        if ($user->save()) {
            return $this->success('退出成功!');
        }

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