<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\ExternalPrescription;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use App\Models\PharmacyModel;
use App\Models\ExternalPrescriptionModel;
use App\Admin\Extensions\ToolBar\Actions\ExternalPrescriptionImportAction;
use Box\Spout\Common\Entity\Style\Color;
use Box\Spout\Writer\Common\Creator\Style\StyleBuilder;
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use Dcat\EasyExcel\Excel;
use Illuminate\Http\Request;

class ExternalPrescriptionController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new ExternalPrescriptionModel(), function (Grid $grid) {
            $grid->model()->orderBy('id', 'DESC');
            $grid->column('id')->sortable();
            $grid->column('external_prescription_id');
            $grid->column('issue_at')->sortable();
            $grid->column('status');
            $grid->column('company_name');
            $grid->column('pharmacy_name');
            // $grid->column('pharmacy_id');
            $grid->column('agent');
            $grid->column('patient_name');
            $grid->column('patient_mobile');
            $grid->column('patient_gender')->using(ExternalPrescriptionModel::SEX_MAP);
            $grid->column('patient_age');
            $grid->column('patient_id_card');
            $grid->column('doctor_name');
            $grid->column('diagnosis');
            $grid->column('drug_info')->display(function ($drugInfoJson) {
                // 尝试将 $drugInfoJson 解码为数组
                $drugInfoArray = json_decode($drugInfoJson, true);
                // 检查解码是否成功且 $drugInfoArray 是一个数组
                if (is_array($drugInfoArray)) {
                    // 使用 array_map 来格式化每个药物的信息
                    $formattedDrugs = array_map(function ($item) {
                        return $item['drug_name'] . ' : ' . ($item['drug_spec'] ?? '') . ' : ' . $item['drug_num'];
                    }, $drugInfoArray);
                    // 将数组转换为以逗号分隔的字符串（或根据您的需求进行其他格式化）
                    return implode(', ', $formattedDrugs);
                } else {
                    // 如果解码失败或 $drugInfoJson 不是一个有效的 JSON 字符串，返回原始值或错误消息
                    return $drugInfoJson; // 或者返回一个错误消息，如 'Invalid JSON'
                }
            })->label(); // 设置列的标签
            $grid->column('pharmacist_name');
            $grid->column('review_at');
            $grid->column('pharmacist_attr');
            $grid->column('dispatcher');
            $grid->column('checker');
            $grid->column('dispenser');
            // $grid->column('created_at');
            // $grid->column('updated_at')->sortable();
            // 工具栏普通按钮
            $grid->tools(function ($tools) {
                $tools->append(new ExternalPrescriptionImportAction()); // 导入药品信息
            });
            
            $grid->filter(function (Grid\Filter $filter) {
                //$filter->equal('id');
                $filter->panel(); // 更改为 panel 布局
                $filter->expand(); // 默认展开搜索框
                $filter->equal('external_prescription_id','580处方单编号')->width(3);
                $filter->equal('pharmacy_id')->select(PharmacyModel::all()->pluck('name', 'id'))->width(3);
                // $filter->equal('pharmacy_id','药店编号')->width(3);
            });

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

        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        //$this->title('580处方单详情');
        
        return Show::make($id, new ExternalPrescriptionModel(), function (Show $show) {
            $show->field('id');
            $show->field('external_prescription_id','580处方单编号');
            $show->field('issue_at','处方开具时间');
            $show->field('status','状态');
            $show->field('company_name','企业名称');
            $show->field('pharmacy_name','药店名称');
            //$show->field('pharmacy_id');
            $show->field('agent','会员/代理人');
            $show->field('patient_name','就诊人姓名');
            $show->field('patient_mobile','就诊人手机号');
            $show->field('patient_gender','就诊人性别')->using(ExternalPrescriptionModel::SEX_MAP)->width(3);
            $show->field('patient_age','就诊人年龄');
            $show->field('patient_id_card','就诊人身份证号');
            $show->field('doctor_name','接诊医师姓名');
            $show->field('diagnosis','诊断');
            $show->field('drug_info','用药信息')->as(function ($drugInfoJson) {
                // 尝试将 $drugInfoJson 解码为数组
                $drugInfoArray = json_decode($drugInfoJson, true);
                // 检查解码是否成功且 $drugInfoArray 是一个数组
                if (is_array($drugInfoArray)) {
                    // 使用 array_map 来格式化每个药物的信息
                    $formattedDrugs = array_map(function ($item) {
                        return $item['drug_name'] . ' : ' . ($item['drug_spec'] ?? '') . ' : ' . $item['drug_num'];
                    }, $drugInfoArray);
                    // 将数组转换为以逗号分隔的字符串（或根据您的需求进行其他格式化）
                    return implode(', ', $formattedDrugs);
                } else {
                    // 如果解码失败或 $drugInfoJson 不是一个有效的 JSON 字符串，返回原始值或错误消息
                    return $drugInfoJson; // 或者返回一个错误消息，如 'Invalid JSON'
                }
            })->label(); // 设置列的标签
            $show->field('pharmacist_name','审核药师');
            $show->field('review_at','审核时间');
            $show->field('pharmacist_attr','药师属性');
            $show->field('dispatcher','调配人');
            $show->field('checker','核对人');
            $show->field('dispenser','发药人');
            // $show->field('created_at');
            // $show->field('updated_at');
            $show->panel()->tools(function ($tools) {
                $tools->disableEdit();
                $tools->disableDelete(); // 禁止删除按钮
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new ExternalPrescriptionModel(), function (Form $form) {
            $form->display('id');
            $form->text('external_prescription_id');
            $form->text('issue_at');
            $form->text('status');
            $form->text('company_name');
            $form->text('pharmacy_name');
            $form->text('pharmacy_id');
            $form->text('agent');
            $form->text('patient_name');
            $form->text('patient_mobile');
            $form->text('patient_gender');
            $form->text('patient_age');
            $form->text('patient_id_card');
            $form->text('doctor_name');
            $form->text('diagnosis');
            $form->text('drug_info');
            $form->text('pharmacist_name');
            $form->text('review_at');
            $form->text('pharmacist_attr');
            $form->text('dispatcher');
            $form->text('checker');
            $form->text('dispenser');
        
            $form->display('created_at');
            $form->display('updated_at');
        });
    }


    public function exportPrescriptionTemplate(Request $request)
    {
        $sheet1Head = ['处方编号','处方开具时间','处方状态','企业名称','门店名称','会员/代理人','就诊人姓名','就诊人电话','就诊人性别','就诊人年龄','就诊人身份证号','接诊医师姓名','诊断','药品名称','药品规格','药品数量','审核药师','药师审核时间','药师属性','调配人','核对人','发药人'];
        $sheet1Data = [
            ['P1734339107979HN0','2024-12-16 16:51:48','正常','国药控股国大药房河南连锁有限公司','江阴市正鑫医药有限公司','会员_1085','赵海英','13335150001','女','34','','陆海','维生素D缺乏症,急性上呼吸道感染','维生素AD滴剂','10粒*3板','1','林俊杰','2024-12-16 16:51:58','总部药师','','',''],
            ['P1734339107979HN0','2024-12-16 16:51:48','正常','国药控股国大药房河南连锁有限公司','江阴市正鑫医药有限公司','会员_1085','赵海英','13335150001','女','34','','陆海','维生素D缺乏症,急性上呼吸道感染','飞扬胃肠炎片','24片','1','林俊杰','2024-12-16 16:51:58','总部药师','','',''],
        ];

        $sheet1 = Excel::createSheet($sheet1Data, '处方明细列表', $sheet1Head)->row(function (array $row) {
            $style = (new StyleBuilder)
                ->setBackgroundColor(Color::YELLOW)
                ->build();

            return WriterEntityFactory::createRowFromArray($row, $style);
        });

        return Excel::export([$sheet1])->headings(false)->download('580-处方明细.xlsx');
    }
}
