<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\PrescriptionRepository;
use App\Models\DiagnosiModel;
use App\Models\DoctorModel;
use App\Models\InquiryModel;
use App\Models\PatientModel;
use App\Models\PharmacistModel;
use App\Models\PharmacyDrugModel;
use App\Models\PharmacyModel;
use App\Models\PrescriptionModel;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Show;
use Dcat\Admin\Admin;
use Dcat\Admin\Layout\Content;

// 处方列表
class PharmacyPrescriptionController extends AdminController
{
    public function index(Content $content)
    {
        return $content
            ->header('处方列表') // 设置 content-header 的标题
            ->description('列表') // 可选，设置 content-header 的副标题
            ->body($this->grid());               // 设置页面主体为 Grid
    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new PrescriptionRepository(), function (Grid $grid) {
            if (! Admin::user()->pharmacy_id) {
                admin_exit(Content::make()->withError(trans('admin.deny')));
            }
            $grid->model()->orderBy('id', 'DESC');
            $grid->model()->where('pharmacy_id', Admin::user()->pharmacy_id);

            $grid->column('id', '处方单编号')->sortable();
            $grid->column('status','处方状态')->using(PrescriptionModel::PRESCRIPTION_STATUS_MAP)->badge(PrescriptionModel::PRESCRIPTION_STATUS_MAP_COLOR);
            $grid->column('prescription_type','处方类型')->using(PrescriptionModel::PRESCRIPTION_TYPE_MAP);
            $grid->column('reject_status','是否驳回')->using(PrescriptionModel::REJECT_STSATUS_MAP);
            $grid->column('patient_name','患者姓名');
            $grid->column('patient_age','患者年龄');
            $grid->column('patient_gender','患者性别')->using(PatientModel::SEX_MAP);
            $grid->column('diagnosis_name','诊断');
            $grid->column('doctor_name','医生姓名');
            $grid->column('pharmacist_name','药师名称');
            $grid->column('drug_info','用药信息');
            $grid->column('drug_info','用药信息')->pluck('drug_name')->label();
            $grid->column('drug_info','用药信息')->display(function ($drugInfo) {
                $answerMap = [1 => '是', 0 => '否'];

                return array_map(function ($item) {
                    return $item['drug_name'].' : '.($item['spec'] ?? '').' : '.$item['num'].($item['unit'] ?? '').' : '.($item['dosage_desc'] ?? '');
                }, $drugInfo);
            })->label();
            $grid->column('pharmacy_name', '药店名称');
            $grid->column('open_source', '开方来源')->using(PrescriptionModel::OPEN_SOURCE_MAP);
            $grid->column('prescription_at', '开方时间');
            $grid->column('review_at', '审方时间');
            // $grid->column('diagnosis_id');
            $grid->column('inquiry_info','问诊问题')->display(function ($inquiryInfo) {
                $answerMap = [1 => '是', 0 => '否'];

                return array_map(function ($item) use ($answerMap) {
                    return $item['question'].' : '.$answerMap[$item['answer']];
                }, $inquiryInfo);
            })->label();

            // $grid->column('doctor_id');
            // $grid->column('doctor_online_hospital_name');
            // $grid->column('doctor_department');
            // $grid->column('doctor_title');
            // $grid->column('doctor_license_no');
            // $grid->column('pharmacy_id');
            // $grid->column('pharmacist_id');
            // $grid->column('pharmacist_license_number');
            $grid->column('created_at', '创建时间');
            $grid->column('is_abnormal', '是否异常')->using(PrescriptionModel::IS_ABNORMAL_MAP)->badge(PrescriptionModel::IS_ABNORMAL_MAP_COLOR);
            $grid->column('is_voided', '是否作废')->using(PrescriptionModel::IS_VOIDED_MAP)->badge(PrescriptionModel::IS_VOIDED_MAP_COLOR);
            // $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel(); // 更改为 panel 布局
                $filter->expand(); // 默认展开搜索框
                $filter->like('id', '处方单编号')->width(3);
                $filter->like('patient_name','患者姓名')->width(3);
                $filter->like('diagnosis_name','诊断')->width(3);
                $filter->in('status','处方状态')->checkbox(PrescriptionModel::PRESCRIPTION_STATUS_MAP)->width(3);
                $filter->in('is_voided','是否作废')->checkbox(PrescriptionModel::IS_VOIDED_MAP)->width(3);
                $filter->in('open_source','开方来源')->checkbox(PrescriptionModel::OPEN_SOURCE_MAP)->width(3);
                $filter->in('prescription_type','处方类型')->checkbox(PrescriptionModel::PRESCRIPTION_TYPE_MAP)->width(3);
            });
            // $show->field('is_voided')->width(3)->using(PrescriptionModel::IS_VOIDED_MAP);

            // 行按钮控制
            $grid->disableCreateButton(); // 禁用创建按钮
            $grid->disableDeleteButton(); // 禁用删除按钮
            $grid->disableEditButton(); // 禁用编辑按钮

            // 工具栏按钮控制
            $grid->disableBatchDelete(); // 禁用批量删除
        });
    }

    /**
     * Make a show builder.
     *
     * @param  mixed  $id
     * @return Show
     */
    protected function detail($id)
    {
        if (! Admin::user()->pharmacy_id) {
            admin_exit(Content::make()->withError(trans('admin.deny')));
        }
        $prescription = PrescriptionModel::where('id', $id)->first();
        if (Admin::user()->pharmacy_id != $prescription->pharmacy_id) {
            admin_exit(Content::make()->withError(trans('admin.deny')));
        }
       

        return Show::make($id, new PrescriptionRepository(), function (Show $show) {
            $show->header('处方详情');
            $show->field('id')->width(3);
            $show->field('status', '处方状态')->width(3)->using(PrescriptionModel::PRESCRIPTION_STATUS_MAP);

            $show->field('patient_name', '患者姓名')->width(3);

            $show->field('patient_age', '患者年龄')->width(3);
            $show->field('patient_gender', '患者性别')->using(PatientModel::SEX_MAP)->width(3);
            $show->field('diagnosis_name', '诊断')->width(3);

            $show->field('inquiry_info', '问诊问题')->width(3)->as(function ($inquiryInfo) {
                $answerMap = [1 => '是', 0 => '否'];

                return array_map(function ($item) use ($answerMap) {
                    return $item['question'].' : '.$answerMap[$item['answer']];
                }, $inquiryInfo);
            })->label();
            $show->field('drug_info', '用药信息')->width(3)->as(function ($drugInfo) {
                return array_map(function ($item) {
                    return $item['drug_name'].' : '.($item['spec'] ?? '').' : '.$item['num'].($item['unit'] ?? '').' : '.($item['dosage_desc'] ?? '');
                }, $drugInfo);
            })->label();
            $show->field('doctor_name', '医生姓名')->width(3);

            $show->field('doctor_online_hospital_name', '医师互联网医院名称')->width(3);
            $show->field('doctor_department', '医师科室')->width(3);
            $show->field('doctor_title', '医师职称')->width(3);

            $show->field('doctor_license_no', '医师执照编号')->width(3);
            $show->field('doctor_signed_pic', '医师签名照')->image('', 100, 100)->width(3);
            $show->field('doctor_introduction', '医师简介')->width(3);

            $show->field('pharmacy_name', '药店名称')->width(3);
            $show->field('pharmacist_name', '药师姓名')->width(3);
            $show->field('pharmacist_license_number', '药师执照编号')->width(3);

            $show->field('pharmacist_signed_pic', '药师签名照')->image('', 100, 100)->width(3);
            # $show->field('prescription_pic','处方单图片地址')->image('', 100, 100)->width(3);
            # $show->field('prescription_pic_eseal')->image('', 100, 100)->width(3);

            $show->field('prescription_at', '开方时间')->width(3);
            $show->field('review_at', '审方时间')->width(3);
            $show->field('open_source', '开方来源')->width(3)->using(PrescriptionModel::OPEN_SOURCE_MAP);

            $show->field('is_voided', '是否作废')->width(3)->using(PrescriptionModel::IS_VOIDED_MAP);
            $show->field('is_abnormal', '是否异常')->width(3)->using([0 => '否', 1 => '是']);
            $show->field('prescription_type', '处方类型')->width(3)->using(PrescriptionModel::PRESCRIPTION_TYPE_MAP);

            $show->panel()->tools(function ($tools) {
                $tools->disableEdit();
                $tools->disableDelete(); // 禁止删除按钮
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new PrescriptionRepository(), function (Form $form) {
            $form->display('id')->width(4);
            $form->radio('status')->options(PrescriptionModel::PRESCRIPTION_STATUS_MAP)->default(PrescriptionModel::PRESCRIPTION_STATUS_PENDING);

            $form->select('patient_id')->options(PatientModel::all()->pluck('name', 'id'))->width(4);
            $form->hidden('patient_name');
            $form->hidden('patient_age');
            $form->hidden('patient_gender');

            $form->select('diagnosis_id')->options(DiagnosiModel::all()->pluck('name', 'id'))->width(4);
            $form->hidden('diagnosis_name');

            $form->select('doctor_id')->options(DoctorModel::where('status', 1)->pluck('name', 'id'))->width(4);
            $form->hidden('doctor_name');
            $form->hidden('doctor_online_hospital_name');
            $form->hidden('doctor_department');
            $form->hidden('doctor_title');
            $form->hidden('doctor_license_no');
            $form->hidden('doctor_signed_pic');

            $form->select('pharmacy_id')->options(PharmacyModel::where('status', 1)->pluck('name', 'id'))->width(4);
            $form->hidden('pharmacy_name');

            $form->select('pharmacist_id')->options(PharmacistModel::where('status', 1)->pluck('name', 'id'))->width(4);
            $form->hidden('pharmacist_name');
            $form->hidden('pharmacist_license_number');
            $form->hidden('pharmacist_signed_pic');

            $form->table('inquiry_info', function ($table) {
                $table->select('inquiry_id', '问题')->options(InquiryModel::all()->pluck('question', 'id'));
                $table->radio('answer', '回答')->options([1 => '是', 0 => '否']);
            })->saveAsJson();

            $form->table('drug_info', function ($table) {
                $table->select('pharmacy_drug_id', '药品')->options(PharmacyDrugModel::with('drug')->get()->pluck('drug.name', 'id'))->width(3);
                $table->number('num', '数量')->min(1)->default(1)->width(4);
            })->saveAsJson();
            $form->switch('is_voided')->width(4);

            $form->display('created_at')->width(4);
            $form->display('updated_at')->width(4);
            // 添加隐藏字段以保存冗余数据

            $form->saving(function (Form $form) {
                $patient = PatientModel::find($form->input('patient_id'));
                $doctor = DoctorModel::find($form->input('doctor_id'));
                $pharmacist = PharmacistModel::find($form->input('pharmacist_id'));
                $diagnosis = DiagnosiModel::find($form->input('diagnosis_id'));
                $pharmacy = PharmacyModel::find($form->input('pharmacy_id'));

                // 根据身份证计算年龄和性别
                if ($patient) {
                    $form->patient_name = $patient->name;
                    $form->patient_age = getAgeByIdCard($patient->id_card);
                    $form->patient_gender = $patient->gender;
                }

                if ($diagnosis) {
                    $form->diagnosis_name = $diagnosis->name; // 假设有诊断名称字段
                }

                if ($doctor) {
                    $form->doctor_name = $doctor->name;
                    $form->doctor_online_hospital_name = $doctor->online_hospital_name; // 假设有在线医院名称字段
                    $form->doctor_department = $doctor->department;
                    $form->doctor_title = $doctor->doctor_title;
                    $form->doctor_license_no = $doctor->license_no;
                    $form->doctor_signed_pic = $doctor->signed_pic;
                }

                if ($pharmacist) {
                    $form->pharmacist_name = $pharmacist->name;
                    $form->pharmacist_license_number = $pharmacist->license_number;
                    $form->pharmacist_signed_pic = $pharmacist->signed_pic;
                }

                if ($pharmacy) {
                    $form->pharmacy_name = $pharmacy->name;
                }
            });
            // 右上角按钮控制
            $form->disableDeleteButton(); // 去掉删除按钮
            $form->disableViewButton(); // 去掉跳转详情页按钮
        });
    }

    // 计算年龄的辅助方法
    private function calculateAge($id_card)
    {
        // 根据身份证计算年龄的逻辑
        // 返回计算出的年龄
    }
}
