<?php

namespace App\Http\Controllers\API\Admin\YeWu;

use App\Http\Controllers\Controller;
use App\Services\Admin\YeWu\AppointmentService;
use Illuminate\Http\Request;
use App\Services\Admin\YeWu\HealthCheckupService;
use App\Services\mH5\PersonService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class HealthCheckupController extends Controller
{
    //创建体检记录
    public function CreateRecord(){
        $CheckupInfo=request('checkup_info');
        if(!$CheckupInfo)   return \Yz::echoError1('检查信息为空');
        if(!$CheckupInfo['name']) return \Yz::echoError1('姓名不能为空');
        if(!isset($CheckupInfo['id_card_num'])) return \Yz::echoError1('id_card_num不能为空');
        if(!isset($CheckupInfo['institution_sn'])) return \Yz::echoError1('体检机构编码institution_sn不能为空');
        if(!isset($CheckupInfo['tijian_num'])) return \Yz::echoError1('体检号tijian_num不能为空');
        if(!isset($CheckupInfo['tijian_time'])) return \Yz::echoError1('体检时间tijian_time不能为空');
        if(!isset($CheckupInfo['report_content'])) return \Yz::echoError1('报告内容report_content不能为空');
        if(!isset($CheckupInfo['issue_time'])) return \Yz::echoError1('发证时间issue_time不能为空');
        if(!isset($CheckupInfo['expire_time'])) return \Yz::echoError1('证件到期时间expire_time不能为空');

        if(!isset($CheckupInfo['sex'])) return \Yz::echoError1('性别sex不能为空');

        $s=app()->make(HealthCheckupService::class);
        $res= $s->CreateRecord($CheckupInfo);
        $data=isset($res['data'])?$res['data']:[];
        return \Yz::Return($res['status'],$res['msg'],$data);
    }
    //查询能否进行免费体检
    public function CheckRequirements(){
        $id_card_num=request('id_card_num');
        $name=request('name');
        $type=request('type');//体检类型 1,健康证2老年人
        $currentOrgName=request('org_name');
        $org_code=request('org_code');
        $doctor_name=request('doctor_name');

        if(empty($currentOrgName) && !empty($org_code)){
            $orgInfo = DB::table('medical_institution')->where('sn', $org_code)->first();
            if($orgInfo){
                $currentOrgName = $orgInfo->org_name;
            }
        }

        $s=app()->make(AppointmentService::class);
        return $s->CheckAppointment($name,$id_card_num,$type,$currentOrgName,$doctor_name);
    }

    //获取个人预约记录详情
    public function GetAppointmentRecord(){
        $id_card_num=request('id_card_num');
        $s=app()->make(PersonService::class);
        return $s->GetAppointmentRecord(['id_num'=>$id_card_num]);
    }

    //提交pdf文件
    public function UploadFile(Request $request){
        $file=request('file');
        $id_card_num=request('id_card_num');
        $tijian_num=request('tijian_num');
        date_default_timezone_set('PRC');
        $currentYear = date('Y');
        $firstDay = date('Y-01-01', strtotime($currentYear));
        $lastDay = date('Y-12-31', strtotime($currentYear));

        $cha=DB::table('examination_records')->where(['id_card_num'=>$id_card_num,'tijian_num'=>$tijian_num,'is_del'=>0])->whereBetween('created_at', [$firstDay, $lastDay])->get();
        if(count($cha)==0) return \Yz::echoError1('未找到此用户对应的体检号记录，无法存储报告');

        if ($file->isValid()) {

            $s=app()->make(HealthCheckupService::class);
            $save=$s->SaveFile(['file'=>$file]);

            if(!$save['status']) return \Yz::echoError1('文件保持失败');

            $u=DB::table('examination_records')->where(['id'=>$cha[0]->id])->update(['report_file'=>Storage::url($save['data'])]);
            if($u>0){
                return \Yz::Return(true,'上传成功',['file'=>$save['data']]);
            }else{
                return \Yz::echoError1('保存文件失败');
            }

        }else{
            return \Yz::echoError1('获取文件失败');
        }

    }

    //对外接口，创建体检记录 姓名、电话、身份证、体检机构编码、体检号、pdfs
    public function CreateCheckupPdf()
    {
        date_default_timezone_set('PRC');
        $id_card_num=request('id_card_num');
        $name=request('name');
        $tel=request('tel');
        $tijian_num=request('tijian_num');
        $type=request('type');
        $org_code=request('org_code');
        $pdfs=request('pdfs');
        $free_type=request('free_type');
        if(!isset($tijian_num)) return \Yz::echoError1('体检号不能为空');
        if(!isset($id_card_num)) return \Yz::echoError1('身份证不能为空');
        if(!isset($pdfs)) return \Yz::echoError1('pdfs不能为空');
        if(!isset($org_code)) return \Yz::echoError1('机构码不能为空');
        $org_id=DB::table('medical_institution')->where('sn',$org_code)->first();
        if(!$org_id) return \Yz::echoError1('机构码不存在');

        //检查体检流水号是否存在，存在禁止再次插入。
        $check_cunzai=DB::table('examination_records')->where(['tijian_num'=>$tijian_num,'institution_id'=>$org_id->id,'is_del'=>0])->get();
        if(count($check_cunzai)>0) return \Yz::echoError1('此体检号已经存在，禁止创建');
        $sex=\App\Lib\Tools::getGenderFromIDCard($id_card_num);
        $age=\App\Lib\Tools::calculateAgeFromID($id_card_num,date('Y-m-d H:i:s'));
        $birthday=\App\Lib\Tools::getBirthdayFromIDCard($id_card_num);
        //HSM加密
        $HSM_sfz =\App\Lib\HSM::HsmEncrypt($id_card_num);
        if($HSM_sfz['status']!=true){
            return \Yz::echoError1('调用HSM加密失败');
        }

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

        $id_card_num=$HSM_sfz['data'];
        $Hmac=\App\Lib\HSM::Hmac($name.$id_card_num.$tel.$org_id->id);
        if($Hmac['status']!=true){
            return \Yz::echoError1('HMAC摘要失败');
        }

        $i=DB::table('examination_records')->insertGetId([
            "name"=>$name,
            "age"=>$age,
            "birthday"=>$birthday,
            "tel"=>$tel,
            "sex"=>$sex,
            "id_card_num"=>$id_card_num,
            "type"=>$type,
            "fee_type"=>$free_type,
            "institution_id"=>$org_id->id,
            "tijian_num"=>$tijian_num,
            "pdfs"=>isset($pdfs)?json_encode($pdfs,JSON_UNESCAPED_UNICODE):'',
            'hmac'=>$Hmac['data'],
        ]);
        if($i){

            return \Yz::Return(true,'记录完成',["num"=>$tijian_num]);
        }else{
            return \Yz::echoError1("操作失败");
        }

    }

    //根据身份证号码查询体检记录列表
    public function GetPersonCheckUpList(){
        $id_card_num=request('id_card_num');
        $s=app()->make(HealthCheckupService::class);
        return $s->GetPersonCheckUpList(['id_card_num'=>$id_card_num]);
    }
    //根据体检号查询体检详情
    public function GetPersonCheckUpDetail(){
        $tijian_num=request('tijian_num');
        $s=app()->make(HealthCheckupService::class);
        return $s->GetPersonCheckUpDetail(['tijian_num'=>$tijian_num]);
    }

    //admin后台获取体检记录列表
    public function GetCheckUpList(Request $request){
        $userid = $request->get('userid');//中间件产生的参数
        $group = $request->get('role');//中间件产生的参数
        $page =request('page');
        $pageSize =request('pageSize');
        $searchInfo=request('searchInfo');
        $s=app()->make(HealthCheckupService::class);
        return $s->GetCheckUpList(['userid'=>$userid,'group'=>$group,'page'=>$page,'pageSize'=>$pageSize,'searchInfo'=>$searchInfo]);
    }
    //统计各个体检机构体检数量
    public function CheckUpCount(Request $request)
    {
        $s_group=[1,8];
        $userid = $request->get('userid');//中间件产生的参数
        $group = $request->get('role');//中间件产生的参数
        $searchInfo=request('searchInfo');
        if(!in_array($group,$s_group) ){
            $cha=DB::table('medical_institution')->where(['link_user_id'=>$userid])->first();
            if(!!$cha){
                $searchInfo['org_id']=$cha->id;
            }else{
                return \Yz::echoError1("当前用户，未关联体检机构");
            }

        }
        $list=DB::table('examination_records as a')
            ->select('b.sn','b.org_name',DB::raw('count(*) as count'))
            ->leftJoin('medical_institution as b','a.institution_id','=','b.id');

        if(empty($searchInfo['dateRange'])){
            $searchInfo['start']=date('Y-m-d')." 00:00:00";
            $searchInfo['end']= date('Y-m-d')." 23:59:59";
        }else{
            $searchInfo['start']=$searchInfo['dateRange'][0]." 00:00:00";
            $searchInfo['end']=$searchInfo['dateRange'][1]." 23:59:59";
        }

        if(isset($searchInfo['org_id'])){
            $list=$list->where('a.institution_id',$searchInfo['org_id']);
        }
        if(isset($searchInfo['checkType'])){
            $list=$list->where('a.type',$searchInfo['checkType']);
        }
        $list=$list
            ->where([['a.is_del','=',0],['a.created_at','>=',$searchInfo['start']],['a.created_at','<=',$searchInfo['end']]])
            ->groupBy('b.sn','b.org_name')
            ->orderBy('count','desc')
            ->get();
        return \Yz::Return(true,'查询成功',['list'=>$list,'dateRange'=>[$searchInfo['start'],$searchInfo['end']]]);
    }

    //删除体检记录，用于取消总检
    public function DelCheckUpInfo()
    {
        $id_card_num=request('id_card_num');
        $tijian_num=request('tijian_num');
        $code=request('code');
        $doctor_name=request('doctor_name');

        if(!isset($id_card_num)) return \Yz::echoError1('证件号不能为空');
        if(!isset($tijian_num)) return \Yz::echoError1('体检号不能为空');
        if(!isset($code)) return \Yz::echoError1('机构编码不能为空');

        $HSM_sfz =\App\Lib\HSM::HsmEncrypt($id_card_num);
        if($HSM_sfz['status']!=true){
            return \Yz::echoError1('调用HSM加密失败');
        }
        $id_card_num=$HSM_sfz['data'];
        $org_id=DB::table('medical_institution')->where('sn',$code)->first();
        if(!$org_id) return \Yz::echoError1('机构不存在');
        $info=DB::table('examination_records')->where(['tijian_num'=>$tijian_num,'id_card_num'=>$id_card_num,'institution_id'=>$org_id->id,'is_del'=>0])->first();
        if(!$info) return \Yz::echoError1('未找到对应记录');

        //记录删除日志
//        $deleteLogService = app()->make(\App\Services\DeleteLogService::class);
//        $deleteLogService->logDeletion(
//            'examination_records',
//            $info->id,
//            $info->name,
//            $info->id_card_num,
//            null,
//            $doctor_name,
//            '接口删除-取消总检',
//            $org_id->org_name ?? '',
//            $info->type ?? '',
//            ''
//        );

        $del=DB::table('examination_records')->where(['id'=>$info->id])->update(['is_del'=>1]);
        if($del){
            return \Yz::Return(true,'删除成功',[]);
        }else{
            return \Yz::echoError1('删除失败');
        }

    }

}
