<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\ExternalCmPrescription;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class ExternalCmPrescriptionController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new ExternalCmPrescription(), function (Grid $grid) {
            $grid->model()->orderBy('id', 'desc');
            $grid->column('id')->sortable();
            $grid->column('medicalInsurance','是否医保处方')->display(function ($medicalInsurance){
                if($medicalInsurance == "1"){
                    return '是';
                }else if($medicalInsurance == "0"){
                    return '否';
                }else{
                    return '未知';
                }
            });
            $grid->column('idcardTypeCode')->display(function($idcardTypeCode){
                if($idcardTypeCode == "01"){
                    return '身份证';
                }else if($idcardTypeCode == "02"){
                    return '居民户口薄';
                }else if($idcardTypeCode == "03"){
                    return '护照';
                }else if($idcardTypeCode == "04"){
                    return '军官证';
                }else if($idcardTypeCode == "05"){
                   return '驾驶证';
                }else if($idcardTypeCode == "06"){
                    return '港澳居民来往内地通行证';
                }else if($idcardTypeCode == "07"){
                    return '台湾居民来往内地通行证';
                }else if($idcardTypeCode == "99"){
                    return '其他有效证件';
                }else{
                    return '未知';
                }
            });
            $grid->column('idcardNo');
            $grid->column('name');
            $grid->column('genderCode','性别')->display(function ($genderCode){
                if($genderCode == 1){
                    return '男';
                }else if($genderCode == 2){
                    return '女';
                }else{
                    return '未知';
                }
            });
            $grid->column('birthdate')->display(function($birthdate){
                // 检查字符串长度是否为8
                if (strlen($birthdate) == 8 && ctype_digit($birthdate)) {
                    // 提取年、月、日部分
                    $year = substr($birthdate, 0, 4); // 截取前4位作为年份
                    $month = substr($birthdate, 4, 2); // 截取中间2位作为月份
                    $day = substr($birthdate, 6, 2); // 截取最后2位作为日期
                    // 拼接成目标格式
                    $formattedDate = $year . "-" . $month . "-" . $day . "-";
                    // 输出结果
                    return $formattedDate;
                } else {
                    // 如果长度不符合要求或包含非数字字符
                    return '';
                }
            });
            // $grid->column('visitNo');
            $grid->column('hosRxCode');
            $grid->column('rxTypeCode');
            $grid->column('tcmPasteCnt');
            //$grid->column('tcmUseCode');
            $grid->column('tcmUseDes');
            // $grid->column('tcmDecoctCode');
            $grid->column('tcmDecoctDes');
            // $grid->column('tcmFrequencyCode');
            $grid->column('tcmFrequencyDes');
            $grid->column('tcmOnceDosage');
            $grid->column('onceDosageDes');
            $grid->column('rxDescription');
            $grid->column('rxAmount');
            $grid->column('unifiedOrgCode');
            $grid->column('orgName');
            $grid->column('deptCode');
            $grid->column('deptName');
            $grid->column('deptClassCode');
            $grid->column('deptClassName');
            $grid->column('doctIdcardNo');
            $grid->column('doctName');
            $grid->column('rxDatetime')->display(function ($rxDatetime) {
                return self::formatDateTime($rxDatetime);
            });
            $grid->column('doctCaSign');
            $grid->column('originalData');
            $grid->column('certificate');
            $grid->column('rotateTypeCode');
            $grid->column('items');
            $grid->column('addAmountItems');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
        
            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel(); // 更改为 panel 布局
                $filter->expand(); // 默认展开搜索框
                $filter->equal('hosRxCode','处方编号')->width(3);
                $filter->equal('idcardNo','患者就诊卡证号码')->width(3);
                $filter->equal('name','姓名')->width(3);
                $filter->equal('doctName','开处方医师姓名')->width(3);
        
            });


            // 禁用详情按钮
            $grid->disableViewButton();
            // 禁用编辑按钮
            $grid->disableEditButton();
            // 禁用删除按钮
            $grid->disableDeleteButton();
            $grid->disableCreateButton(); // 禁用创建按钮

            $titles = [
                'hosRxCode' => '处方编号',
                'idcardNo' => '患者就诊卡证号码',
                'name' => '姓名',
                'doctName' => '开处方医师姓名',
                'rxDatetime' => '开处方日期时间',
                'tcmPasteCnt' => '处方帖数',
                'tcmOnceDosage' => '一次用量（ml）',
                'onceDosageDes' => '一次用量描述', 
                'originalData' => '数据原文',
                'certificate' => '数字证书',
                'items' => '处方明细（json字符串）',
            ];
            $grid->export($titles)->filename("处方列表（中药）")->rows(function($rows){
                foreach ($rows as $index => &$row) {
                    $row['rxDatetime'] = self::formatDateTime($row['rxDatetime']);
                }
                return $rows;
            });

        });
    }


    public static function formatDateTime($timeString) {
        // 判断字符串是否为空
        if (empty($timeString)) {
            return "";
        }
    
        // 去除可能的多余空格
        $timeString = trim($timeString);
    
        // 检查字符串长度是否为15（YYYYMMDD HHMMSS）
        if (strlen($timeString) != 15 || !ctype_digit(str_replace(' ', '', $timeString))) {
            return "";
        }
    
        // 提取日期部分
        $datePart = substr($timeString, 0, 8); // 截取前8位作为日期部分
        $year = substr($datePart, 0, 4); // 年
        $month = substr($datePart, 4, 2); // 月
        $day = substr($datePart, 6, 2); // 日
    
        // 提取时间部分
        $timePart = substr($timeString, 9, 6); // 截取后6位作为时间部分
        $hour = substr($timePart, 0, 2); // 时
        $minute = substr($timePart, 2, 2); // 分
        $second = substr($timePart, 4, 2); // 秒
    
        // 拼接成目标格式
        $formattedDateTime = $year . "-" . $month . "-" . $day . " " . $hour . ":" . $minute . ":" . $second;
    
        // 返回结果
        return $formattedDateTime;
    }

    public static function getPrescriptionName($code) {
        $prescriptions = [
            '01' => '普通处方',
            '02' => '急诊处方',
            '03' => '儿科处方',
            '04' => '毒性药品',
            '05' => '精神 I 类',
            '06' => '精神 II 类',
            '07' => '精神III类',
            '08' => '戒毒药品',
            '09' => '麻醉处方',
            '99' => '其他处方'
        ];
        return isset($prescriptions[$code]) ? $prescriptions[$code] : '未知处方';
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new ExternalCmPrescription(), function (Show $show) {
            $show->field('id');
            $show->field('idcardTypeCode');
            $show->field('idcardNo');
            $show->field('name');
            $show->field('genderCode');
            $show->field('birthdate');
            $show->field('visitNo');
            $show->field('hosRxCode');
            $show->field('rxTypeCode');
            $show->field('tcmPasteCnt');
            $show->field('tcmUseCode');
            $show->field('tcmUseDes');
            $show->field('tcmDecoctCode');
            $show->field('tcmDecoctDes');
            $show->field('tcmFrequencyCode');
            $show->field('tcmFrequencyDes');
            $show->field('tcmOnceDosage');
            $show->field('onceDosageDes');
            $show->field('rxDescription');
            $show->field('rxAmount');
            $show->field('unifiedOrgCode');
            $show->field('orgName');
            $show->field('deptCode');
            $show->field('deptName');
            $show->field('deptClassCode');
            $show->field('deptClassName');
            $show->field('doctIdcardNo');
            $show->field('doctName');
            $show->field('rxDatetime');
            $show->field('doctCaSign');
            $show->field('originalData');
            $show->field('certificate');
            $show->field('rotateTypeCode');
            $show->field('items');
            $show->field('addAmountItems');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new ExternalCmPrescription(), function (Form $form) {
            $form->display('id');
            $form->text('idcardTypeCode');
            $form->text('idcardNo');
            $form->text('name');
            $form->text('genderCode');
            $form->text('birthdate');
            $form->text('visitNo');
            $form->text('hosRxCode');
            $form->text('rxTypeCode');
            $form->text('tcmPasteCnt');
            $form->text('tcmUseCode');
            $form->text('tcmUseDes');
            $form->text('tcmDecoctCode');
            $form->text('tcmDecoctDes');
            $form->text('tcmFrequencyCode');
            $form->text('tcmFrequencyDes');
            $form->text('tcmOnceDosage');
            $form->text('onceDosageDes');
            $form->text('rxDescription');
            $form->text('rxAmount');
            $form->text('unifiedOrgCode');
            $form->text('orgName');
            $form->text('deptCode');
            $form->text('deptName');
            $form->text('deptClassCode');
            $form->text('deptClassName');
            $form->text('doctIdcardNo');
            $form->text('doctName');
            $form->text('rxDatetime');
            $form->text('doctCaSign');
            $form->text('originalData');
            $form->text('certificate');
            $form->text('rotateTypeCode');
            $form->text('items');
            $form->text('addAmountItems');
        
            $form->display('created_at');
            $form->display('updated_at');
        });
    }
}
