<?php

namespace App\Http\Controllers\API\mH5;

use App\Http\Controllers\Controller;
use App\Lib\HSM;
use App\Services\Admin\YeWu\AppointmentService;
use App\Services\mH5\PersonService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Storage;

class PersonController extends Controller
{
    //注册
     public function Register(Request $request){
         $openid = $request->get('userid');//中间件产生的参数
         $info =request('info');
         $s=app()->make(PersonService::class);
         return $s->Register(['openid'=>$openid,'info'=>$info]);
    }
    public function GetPersonRecode(Request $request){
        $openid = $request->get('userid');//中间件产生的参数
        $group = $request->get('role');//中间件产生的参数
        $s=app()->make(PersonService::class);
        return $s->GetPersonRecode(['openid'=>$openid,'group'=>$group]);
    }
    //获取用户体检详情和pdf
    public function GetPersonReportDetail(){
        $sfz =request('sfz');
        $type =request('type');
        $orig_sfz=$sfz;
        $tijian_count=0;//最近体检的总数
        //HSM加密
        $HSM_sfz =\App\Lib\HSM::HsmEncrypt($sfz);
        if($HSM_sfz['status']!=true){
            return \Yz::echoError1('调用HSM加密失败');
        }
        $sfz=$HSM_sfz['data'];
        $info=DB::table('examination_records')->where(['id_card_num'=>$sfz,'is_del'=>0]);
        if(isset($type)){
            $info=$info->where('type',$type);
        }
        $info=$info ->orderBy('id', 'desc')->first();
        $sixin_info=false;
        if(!!$info){
            $tijian_count++;
            $info->pdfs=count(json_decode($info->pdfs, true));
            $info->biao='examination_records';
            $item=DB::table('report_result_item')
                ->where(['examination_id'=>$info->id])
                ->select(['item_name','item_result','flag'])->get();

            $info->items=$item;
            if(strlen($info->id_card_num)>30){
                //HSM解密
                $HSM_sfz =\App\Lib\HSM::HsmDecrypt($info->id_card_num);
                if($HSM_sfz['status']!=true){
                    return \Yz::echoError1('调用HSM解密失败');
                }
                $info->id_card_num=$HSM_sfz['data'];
            }
            if(strlen($info->tel)>20){
                //HSM解密
                $HSM_tel =\App\Lib\HSM::HsmDecrypt($info->tel);
                if($HSM_tel['status']!=true){
                    return \Yz::echoError1('调用HSM解密失败');
                }
                $info->tel=$HSM_tel['data'];
            }
            $sixin_info=$info;

        }
        $pingTaiOrgList=['北京市大兴区西红门镇社区卫生服务中心'];
        $pingTaiInfo=false;
        $pingTai=DB::table('health_certificate_push')
            ->select('*','identifierValue as id_card_num','examDate as tijian_time','healthExaminationId as tijian_num')
            ->where(['identifierValue'=>$orig_sfz])
            ->whereIn('hospitalName',$pingTaiOrgList)
            ->orderBy('id', 'desc')
            ->first();
        if(!!$pingTai && $type==1){
            $pingTai->biao='health_certificate_push';
            $tijian_count++;
            $fieldsMap = [
                'hasBacterialDysentery' => '细菌性痢疾',
                'hasTyphoid' => '伤寒和副伤寒',
                'hasViralHepatitis' => '病毒性肝炎（甲型、戊型）',
                'hasActiveTB' => '活动性肺结核',
                'hasSkinDiseases' => '化脓性或渗出性皮肤病',
                'hasHandFungal' => '手部真菌感染性疾病(如手癣、指甲癣等)',
                'hasCholera' => '霍乱',
                'hasAmebicDysentery' => '阿米巴性痢疾',
                'hasHandEczema' => '手部湿疹',
                'hasHandPsoriasis' => '手部的银屑病或者鳞屑',
            ];
            $pingTaiInfo=$pingTai;
            $pingTaiInfo->type=1;
            $item = [];
            foreach ($fieldsMap as $field => $name) {
                $value = $pingTaiInfo->$field ?? null;

                // 根据字段值判断状态
                switch ($value) {
                    case 1:
                        $status = '有';
                        break;
                    case 2:
                        $status = '无';
                        break;
                    case -1:
                        $status = '未检查';
                        break;
                    case null:
                        $status = '未填写';
                        break;
                    default:
                        $status = '未填写';
                }
                $d=[
                    'field' => $field,
                    'item_name' => $name,
                    'value' => $value,     // 原始值（可选，用于前端判断或回显）
                    'item_result' => $status,   // 中文状态
                    'flag'=>null,
                ];
                if($status<>'无'){
                    $d=[
                        'field' => $field,
                        'item_name' => $name,
                        'value' => $value,     // 原始值（可选，用于前端判断或回显）
                        'item_result' => $status,   // 中文状态
                        'flag'=>'异常',
                    ];
                }


                $item[] = $d;
            }
            $pingTaiInfo->items=$item;
            $pdf=DB::table('health_certificate_push_pdf')
                ->where([  'hospitalCode' => $pingTaiInfo->hospitalCode,'healthExaminationId' => $pingTaiInfo->healthExaminationId])
                ->orderBy('id', 'desc')
                ->first();
            $pingTaiInfo->pdfs=0;
            if(!!$pdf){
                $pingTaiInfo->pdfs=1;
            }

        }
        if($sixin_info || $pingTaiInfo){
            $list=[$sixin_info,$pingTaiInfo];
            return \Yz::Return(true,'',['list'=>$list,'tijian_count'=>$tijian_count]);
        }else{
            return \Yz::echoError1('未找到相关体检信息');
        }

    }
    //修改H5获取用户pdf方式，改为根据体检提供的pdf链接地址获取pdf
    public function GetPersonPdfDetailByLink()
    {
        $recordid =request('recordid');
        $pdf_num =request('pdf_num');
        $biao =request('biao');
        if($biao=='examination_records'){
            $query=DB::table('examination_records')->where(['id'=>$recordid,'is_del'=>0])->first();
        }
        if($biao=='health_certificate_push'){
            $query=DB::table('health_certificate_push')->where(['id'=>$recordid])->first();
            $pdf=DB::table('health_certificate_push_pdf')
                ->where([  'hospitalCode' => $query->hospitalCode,'healthExaminationId' => $query->healthExaminationId])
                ->orderBy('id', 'desc')
                ->first();

            $query->pdfs=json_encode([$pdf->pdf_url],JSON_UNESCAPED_UNICODE);

        }

        if(!$query) return \Yz::echoError1('未找到对应体检记录');

        $pdfs=json_decode($query->pdfs, true);

        $pdfurl=$pdfs[$pdf_num];

        // 使用 GuzzleHttp 获取第三方 PDF 地址的内容
        $client = new Client();
        $response = $client->get($pdfurl);

        return  response($response->getBody());
//        return response($response->getBody()->getContents(), 200)
//            ->header('Content-Type', 'application/pdf')
//            ->header('Content-Disposition', 'inline; filename="sample.pdf"');
//        $date = date("Ymd");
//        $filename = 'pdf_' . time() . '.pdf';
//        Storage::disk('public')->put('/pdf/'.$date.'/'."a.pdf", $response->getBody());
//
//        return \Yz::Return(true,'获取成功',['fileurl' =>'/storage/pdf/'.$date.'/'.$filename]);


    }

    //用户扫码跳转输入身份证和电话 查询用户体检详情和pdf
    public function H5GetPersonReportDetail(){
        $get_info =request('info');
        $info=DB::table('examination_records');
        if(isset($get_info['tj_num'])){
            $HSM =\App\Lib\HSM::HsmDecrypt($get_info['tj_num']);
            if($HSM['status']!=true){
                return \Yz::echoError1('调用HSM解密失败');
            }
            $get_info['tj_num']  = $HSM['data'];
            if(isset($get_info['jigou_code'])){ //如果有体检机构 则根据体检机构和体检号进行查询，否则根据id查询
                $org=DB::table('medical_institution')->where(['sn'=>$get_info['jigou_code']])->first();
                if(!$org) return \Yz::echoError1('体检机构不存在');
                $info=$info->where(['tijian_num'=>$get_info['tj_num'],'institution_id'=>$org->id]);
            }else{
                $info=$info->where(['id'=>$get_info['tj_num']]);
            }

        }else{
            if(!isset($get_info['sfz'])) return \Yz::echoError1('身份证不能为空');
            if(!isset($get_info['tel'])) return \Yz::echoError1('电话不能为空');

            //HSM加密
            $HSM_sfz =\App\Lib\HSM::HsmEncrypt($get_info['sfz']);
            if($HSM_sfz['status']!=true){
                return \Yz::echoError1('调用HSM加密失败');
            }
            $get_info['sfz']=$HSM_sfz['data'];
            if(isset($get_info['tel'])){
                $HSM_tel =\App\Lib\HSM::HsmEncrypt($get_info['tel']);
                if($HSM_tel['status']!=true){
                    return \Yz::echoError1('调用HSM加密失败');
                }
                $get_info['tel']=$HSM_tel['data'];
            }
            $info=$info->where(['id_card_num'=>$get_info['sfz'],'tel'=>$get_info['tel']]);
        }


        $info=$info->where(['is_del'=>0]) ->orderBy('id', 'desc')->first();
        if($info){
            $HSM_sfz =\App\Lib\HSM::HsmDecrypt($info->id_card_num);
            if($HSM_sfz['status']!=true){
                return \Yz::echoError1('调用HSM解密失败');
            }
            $info->id_card_num = $HSM_sfz['data'];
            $item=DB::table('report_result_item')
                ->where(['examination_id'=>$info->id])
                ->select(['item_name','item_result','flag'])->get();
            $info->items=$item;

            $accessTimeout = \JWT::GetGetSecretTimeOut();
            $refreshTimeout = \JWT::GetRefreshTokenTimeOut();
            $access_token = \JWT::BuildJWT('yz','access',$info->id_card_num,'mH5user',$accessTimeout);
            $refresh_token = \JWT::BuildJWT('yz','refresh',$info->id_card_num,'',$refreshTimeout);

            return \Yz::Return(true,'',['info'=>$info,'token'=>$access_token,'refresh_token'=>$refresh_token]);
        }else{
            return \Yz::echoError1('未找到相关体检信息');
        }

    }
    //给体检提供查看用户健康证报告的url 用于体检那边生成二维码
    public function GetReportUrl()
    {
        $tijian_num =request('tijian_num');
        $code =request('code');
        //$baseUrl='http://223.71.106.251:82';
        $baseUrl=env('QIANZHI_WAIWANG');
        $org=DB::table('medical_institution')->where(['sn'=>$code])->first();
        if(!$org) return \Yz::echoError1('体检机构不存在');
        $report=DB::table('examination_records')->where(['tijian_num'=>$tijian_num,'institution_id'=>$org->id,'is_del'=>0])->first();
        if(!!$report){
            $HSM=\App\Lib\HSM::HsmEncrypt($report->id);
            if($HSM['status']!=true){
                return \Yz::echoError1('调用HSM加密失败');
            }
            $tijian_num=$HSM['data'];
            $url=$baseUrl.'/mh5/#/personReportLogin?lg_type=ewm&&tj_num='.$tijian_num;
            return \Yz::Return(true,'获取成功',$url);
        }else{
            return \Yz::echoError1('没有此体检号对应的记录');
        }


    }

    //H5用户获取自己的 本年度 预约记录详情 2024-07-18 23:35
    //获取从h5自助预约的信息
    public function H5GetAppointmentRecord(Request $request)
    {
        date_default_timezone_set('PRC');
        $currentYear = date('Y');
        $firstDay = date('Y-01-01', strtotime($currentYear));
        $lastDay = date('Y-12-31', strtotime($currentYear));

        $openid = $request->get('userid');//中间件产生的参数
        $sfz =request('sfz');

        $HSM=\App\Lib\HSM::HsmEncrypt($sfz);
        if($HSM['status']!=true){
            return \Yz::echoError1('调用HSM加密失败');
        }
        $sfz=$HSM['data'];

        if(isset($sfz)){
            $info=DB::table('appointment_record as a')
                ->select('a.id','a.name','a.id_card_num','a.date','a.time','a.type','a.doc_type_name','a.created_at','b.org_name')
                ->join('medical_institution as b','a.org_code','=','b.sn')
                ->where(['a.id_card_num'=>$sfz,'a.is_del'=>0])->whereNull('a.source')
                ->whereBetween('a.created_at',[$firstDay,$lastDay])->orderBy('a.id','desc')->first();
            if(!!$info){
                $info->id_card_num=request('sfz');
            }
            return \Yz::Return(true,'查完完成',$info);
        }

    }

    public function isAgeOver65()
    {
        $sfz =request('sfz');
        if(!isset($sfz)) return \Yz::echoError1("身份证不能为空");
        $s= new AppointmentService();
        return \Yz::Return(true,"查询完成",$s->isOver65($sfz));
    }
}
