<?php
namespace App\Services\Admin\YeWu;
use Illuminate\Support\Facades\Log;
use App\Lib\HSM;
use Illuminate\Support\Facades\DB;
use App\Services\mH5\PersonService;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class HealthCheckupService
{
    //创建体检记录
    public function CreateRecord($CheckupInfo){
        date_default_timezone_set('PRC');
        $currentYear = date('Y');
        $firstDay = date('Y-01-01', strtotime($currentYear));
        $lastDay = date('Y-12-31', strtotime($currentYear));

        $age=\App\Lib\Tools::calculateAgeFromID($CheckupInfo['id_card_num'],date('Y-m-d H:i:s'));
        $birthday=\App\Lib\Tools::getBirthdayFromIDCard($CheckupInfo['id_card_num']);

        //HSM加密
        $HSM_sfz =\App\Lib\HSM::HsmEncrypt($CheckupInfo['id_card_num']);
        if($HSM_sfz['status']!=true){
            //return \Yz::echoError1('调用HSM加密失败');
            return ['status'=>false,'msg'=>'调用HSM加密失败'];
        }
        $CheckupInfo['id_card_num']=$HSM_sfz['data'];

        //如果此次报告内容是免费类型，则检查今年是否进行过免费体检
//        if($CheckupInfo['fee_type']==0){
//            $s=app()->make(PersonService::class);
//            $check=$s->GetPersonRecode(['id_num'=>$CheckupInfo['id_card_num']]);
//
//            if(!$check['status']) return  $check;
//        }

        $org_id=DB::select("select id from medical_institution where sn=?",[$CheckupInfo['institution_sn']]);
        if(count($org_id)!=1) return ['status'=>false,'msg'=>'机构码不存在'];
        $status=false;

        //检查体检流水号是否存在，存在禁止再次插入。
        $check_cunzai=DB::table('examination_records')->where(['tijian_num'=>$CheckupInfo['tijian_num'],'institution_id'=>$org_id[0]->id,'is_del'=>0])->get();
        if(count($check_cunzai)>0)  return ['status'=>false,'msg'=>'此体检号已经存在，禁止创建'];

        DB::beginTransaction(); // 开始事务
        try {
            // 执行数据库操作
           // if($CheckupInfo['type']==1){
                //如果体检类型为健康证 更新预约记录表

                $u= DB::table('appointment_record')
                    ->where([
                        'id_card_num'=>$CheckupInfo['id_card_num'],
                        'org_id'=>$org_id[0]->id,
                        'status'=>1,
                        'org_code'=>$CheckupInfo['institution_sn'],
                    ])->whereBetween('created_at',[$firstDay,$lastDay])->update(['status'=>2]);


         //   }


            $img_url='';
            if(isset($CheckupInfo['head_img'])){
                $date = date("Ymd");
//                preg_match('/^(data:\s*image\/(\w+);base64,)/', $CheckupInfo['head_img'], $res);
//                $file = base64_decode(Str::after($CheckupInfo['head_img'], $res[1]));
                $file = base64_decode($CheckupInfo['head_img']);
                $filePath = 'APIUpload/'.$date.'/'.$CheckupInfo['tijian_num'].$CheckupInfo['id_card_num'].'.jpg';
                Storage::disk('public')->put($filePath, $file);
                $img_url='/storage/'.$filePath;
            }

            if(isset($CheckupInfo['tel'])){
                $HSM_tel =\App\Lib\HSM::HsmEncrypt($CheckupInfo['tel']);
                if($HSM_tel['status']!=true){
                  //  return \Yz::echoError1('调用HSM加密失败');
                    return ['status'=>false,'msg'=>'调用HSM加密失败'];

                }
                $CheckupInfo['tel']=$HSM_tel['data'];
            }
            $Hmac=\App\Lib\HSM::Hmac($CheckupInfo['name'].$CheckupInfo['id_card_num'].$CheckupInfo['tel'].$CheckupInfo['result_status']);
            if($Hmac['status']!=true){
               // return \Yz::echoError1('HMAC摘要失败');
                return ['status'=>false,'msg'=>'HMAC摘要失败'];
            }

            $u2=DB::table('examination_records')->insertGetId([
                "name"=>$CheckupInfo['name'],
                "sex"=>$CheckupInfo['sex'],
                "age"=>$age,
                "birthday"=>$birthday,
                "tel"=>$CheckupInfo['tel'],
                "head_img"=>$img_url,
                "id_card_num"=>$CheckupInfo['id_card_num'],
                "type"=>1,
                "fee_type"=>isset($CheckupInfo['free_type'])?$CheckupInfo['free_type']:null,
                "industry_type"=>$CheckupInfo['industry_type'],
                "institution_id"=>$org_id[0]->id,
                "tijian_time"=>$CheckupInfo['tijian_time'],
                "register_time"=>$CheckupInfo['register_time'],//登记时间
                "tijian_num"=>$CheckupInfo['tijian_num'],
                "report_content"=>isset($CheckupInfo['report_content'])?json_encode($CheckupInfo['report_content'],JSON_UNESCAPED_UNICODE):'',
                "result_status"=>$CheckupInfo['result_status'],
                "issue_time"=>$CheckupInfo['issue_time'],
                "expire_time"=>$CheckupInfo['expire_time'],
                "pdfs"=>isset($CheckupInfo['pdfs'])?json_encode($CheckupInfo['pdfs']):'',
                'hmac'=>$Hmac['data'],
            ]);



                if( $u2>0){
                    foreach ($CheckupInfo['report_content'] as $item){
                        if(isset($item['item_range']) and is_array($item['item_range'])){
                            $item['item_range']=json_encode($item['item_range'],JSON_UNESCAPED_UNICODE);
                        }
                        $item['examination_id']=$u2;
                        $item['tijian_num']=$CheckupInfo['tijian_num'];
                        DB::table('report_result_item')->insert($item);
                    }

                    DB::commit(); // 提交事务
                    $status=true;
                }else{

                    DB::rollBack(); // 回滚事务
                }


        } catch (\Exception $e) {
            DB::rollBack(); // 回滚事务
            Log::error('发生错误: ' . $e->getMessage(), [
                'exception' => $e
            ]);

        }

        if($status){
            return ['status'=>true,'msg'=>'记录完成','data'=>["num"=>$CheckupInfo['tijian_num']]];
        }else{
            return ['status'=>false,'msg'=>'操作失败'];
        }

    }

    //保存文件返回存储路径
    public function SaveFile($arr){

        $date = date("Ymd");
        $path = $arr['file']->store('public/reportPDF/'.$date);
        return \Yz::Return(true,'',$path);
    }
    //查询个人查询体检记录列表
    public function GetPersonCheckUpList($arr){
        $list = DB::table("examination_records")->where(['id_card_num'=>$arr['id_card_num'],'is_del'=>0])->get();
        return \Yz::Return(true,'查询成功',['list'=>$list,'count'=>count($list)]);
    }
    //根据体检号查询体检详情
    public function GetPersonCheckUpDetail($arr){

        $detail=DB::table('examination_records')->where(['tijian_num'=>$arr['tijian_num'],'is_del'=>0])->first();
        if(!empty($detail)){
            return \Yz::Return(true,'查询成功',$detail);
        }else{
            return \Yz::echoError1("未找到记录");
        }


    }
    //获取体检记录列表
    public function GetCheckUpList($arr){
        $sql=' where 1=1';
        $canshu=array();

        if($arr['searchInfo']['dateRange']){

            $sql=$sql . ' and a.created_at>=? and a.created_at<=? ';
            array_push($canshu,$arr['searchInfo']['dateRange'][0].' 00:00:00',$arr['searchInfo']['dateRange'][1].' 23:59:59');
        }


        if($arr['group']==7){
            $cha=DB::table('medical_institution')->where(['link_user_id'=>$arr['userid']])->get();
            $sql=$sql .' and  a.institution_id=?';
            array_push($canshu, $cha[0]->id);
        }else{
            if($arr['searchInfo']['orgId']){

                $sql=$sql .' and  a.institution_id=?';
                array_push($canshu, $arr['searchInfo']['orgId']);
            }

        }
        array_push($canshu,($arr['page']-1)*$arr['pageSize'],$arr['pageSize']);
        $query=DB::select("select a.*,b.org_name from examination_records as a LEFT JOIN  medical_institution as b on a.institution_id=b.id ".$sql." and a.is_del=0 order by a.id desc limit ?,?",$canshu);
        foreach ($query as $key=>$item){
            $item->psfds=json_decode($item->pdfs,true);
        }
        $count=DB::select("select count(*) as  c from examination_records as a  ".$sql." and a.is_del=0",$canshu);
        return \Yz::Return(true,'',['list'=>$query,'count'=>$count[0]->c]);

    }
}
