<?php

namespace App\Community\Controllers;

use App\Models\Order;
use App\Models\Patient;
use App\Models\PatientRemark;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;

class VaccineUserController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '计免用户';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Order());
        $grid->model()->orderByDesc('id');

        $is_amdin = Admin::user()->isRole('administrator');
        $user = Admin::user();
        if(!$is_amdin){
            $grid->model()->where(['organization_id'=>$user->org_id,'product_type'=>4]);
        }

        $grid->model()->GroupBy('patient_id');
        $grid->column('orderPatient.name', __('姓名'));
        $grid->column('orderUser.nickname', __('监护人'));
        $grid->column('orderPatient.phone', __('监护人手机号'))->display(function ($w){
            if(empty($w)) return Patient::where('id',$this->patient_id)->value('phone');
            return $w;
        });
        $grid->column('orderPatient.birthday', __('出生日期'));
        $grid->column('patient_id', __('备注'))->display(function ($w) use($user) {
            return PatientRemark::where(['org_id'=>intval($user->org_id),'patient_id'=>$w,'type'=>2])->value('remark');
        });

        $grid->filter(function ($flter){
            $flter->like('orderPatient.name','请输入用户姓名');
            $flter->like('orderUser.nickname','请输入监护人姓名');
            $flter->between('orderUser.birthday','生日')->datetime();
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Order::findOrFail($id));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Order());

        $form->setAction('/cdms/api/paitent_remark');
        $form->hidden('patient_id');
        $org_id = Admin::user()->org_id;
        $form->hidden('org_id')->default(intval($org_id));
        $form->hidden('type')->default(2);
        $form->textarea('remark','备注')->default(function () use ($org_id,$form){
            return PatientRemark::where(['org_id'=>intval($org_id),'patient_id'=>$form->model()->patient_id,'type'=>2])->value('remark');
        });
        return $form;
    }
}
