<?php
namespace App\Services\Admin\YeWu;
use DateTime;
use Illuminate\Support\Facades\DB;
class AppointmentService
{
    //获取体检记录列表
    public function GetAppointmentList($arr){
        $sql=' where 1=1';
        $canshu=array();
        if($arr['searchInfo']['status']){
            $sql=$sql .' and a.status = ? ';
            array_push($canshu, $arr['searchInfo']['status']);
        }
        if($arr['searchInfo']['userinfo']){
            if (preg_match('/\d/', $arr['searchInfo']['userinfo'])) {
                $HSM =\App\Lib\HSM::HsmEncrypt($arr['searchInfo']['userinfo']);
                if($HSM['status'] !=true){
                    return \Yz::echoError1('身份证号加密失败');
                }
                $encode_id_card_num=$HSM['data'];
                $sql=$sql .' and (a.id_card_num like ? or a.id_card_num = ?)';
                array_push($canshu, '%'.$arr['searchInfo']['userinfo'].'%');
                array_push($canshu, $encode_id_card_num);
            }else{
                $sql=$sql .' and   a.name like ?';
                array_push($canshu, '%'.$arr['searchInfo']['userinfo'].'%');
            }
        }
        if($arr['searchInfo']['calendarId']){
            $sql=$sql .' and a.calendar_id = ? ';
            array_push($canshu, $arr['searchInfo']['calendarId']);
        }
        if(isset($arr['searchInfo']['type'])){
            $sql=$sql .' and a.type = ? ';
            array_push($canshu, $arr['searchInfo']['type']);
        }

        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.org_code=?';
            array_push($canshu, $cha[0]->sn);
        }else{
            if($arr['searchInfo']['orgId']){
                $cha=DB::table('medical_institution')->where(['id'=>$arr['searchInfo']['orgId']])->get();
                $sql=$sql .' and  a.org_code=?';
                array_push($canshu, $cha[0]->sn);
            }

        }

        array_push($canshu,($arr['page']-1)*$arr['pageSize'],$arr['pageSize']);

        $query=DB::select("select a.*,b.org_name from appointment_record as a LEFT JOIN
    medical_institution as b on a.org_code=b.sn ".$sql." and (a.is_del<>1 or a.is_del is null) order by a.id desc limit ?,?",$canshu);

        $count=DB::select("select count(*) as  c from appointment_record as a  ".$sql ." and (a.is_del<>1 or a.is_del is null) ",$canshu);
        return \Yz::Return(true,'',['list'=>$query,'count'=>$count[0]->c]);

    }
    //检测是否有登记预约记录
    public function CheckAppointment($name,$id_card_num,$type,$currentOrgName='',$doctor_name=''){
        if(strlen($id_card_num)>0){
            date_default_timezone_set('PRC');
            $currentYear = date('Y');
            $firstDay = date('Y-01-01', strtotime($currentYear));
            $lastDay = date('Y-12-31', strtotime($currentYear));


            //查询预约登记表
            if($type==1 and $this->isOver65($id_card_num,16)===false){
                return \Yz::echoError1("未满16周岁，禁止登记");
            }
            if($type==2 and $this->isOver65($id_card_num)===false){
                return \Yz::echoError1("年龄不满足条件");
            }
            $HSM =\App\Lib\HSM::HsmEncrypt($id_card_num);
            if($HSM['status'] !=true){
                return \Yz::echoError1('身份证号加密失败');
            }
            $encode_id_card_num=$HSM['data'];
//            $c=DB::table('appointment_record as a')
//                ->leftJoin('medical_institution as b', 'a.org_id', '=', 'b.id')
//                ->select(['a.id','a.org_id','a.id_card_num','a.created_at as insertime','b.org_name'])
//                ->where(['a.id_card_num'=>$id_card_num,'a.is_del'=>0,'a.type'=>$type,['a.created_at','>=',$firstDay],['a.created_at','<=',$lastDay]])->whereIn('a.status',[1,2])->get();

            $c=DB::table('appointment_record as a')
                ->leftJoin('medical_institution as b', 'a.org_code', '=', 'b.sn')
                ->select(['a.id','a.org_id','a.id_card_num','a.created_at as insertime','b.org_name'])
                ->where(function ($query) use ($id_card_num, $encode_id_card_num) {
                    $query->where('a.id_card_num', $id_card_num)
                        ->orWhere('a.id_card_num', $encode_id_card_num);
                });

            if($type==2){
               $c=$c->whereIn('a.status', [1, 2]);
            }
            if($type==1){
                $month=config('app.globals.HealthyCardTimeRange');
                //如果是健康证体检，则先查寻是否有体检记录
                $cha_jkz=DB::table('examination_records as a')
                    ->leftJoin('medical_institution as b','a.institution_id','=','b.id')
                    ->select('a.*','b.org_name')
                    ->where(['a.id_card_num'=>$encode_id_card_num,'a.is_del'=>0,'a.type'=>$type])->orderBy('a.id','desc')->first();
                //，如果有判断是否快到期(先不判断是否体检通过)，能否继续预约
                if(!!$cha_jkz){

                    $date = new DateTime($cha_jkz->created_at);
                    $date->modify('+'.$month.' months');
                    $now = new DateTime();
                    if ($date > $now) {
                        $conflictService = app()->make(\App\Services\ConflictService::class);
                        $conflictService->logConflict($name, $encode_id_card_num, $currentOrgName,$doctor_name, $cha_jkz->org_name, $cha_jkz->created_at, $type, 'CheckAppointment');
                        return \Yz::ReturnNew(false,'该人员已于'.$cha_jkz->created_at.'在'.$cha_jkz->org_name.'登记');
                    }
                }
                //查询是否有预约记录
                $currentDate = date('Y-m-d');
                $firstDay = date('Y-m-d', strtotime('-'.$month.' months', strtotime($currentDate)));
                //   $firstDay = date('Y-01-01', strtotime($currentYear));
                $lastDay = date('Y-12-31', strtotime($currentYear));
                $c=$c->whereIn('a.status', [2]);
            }
            $c=$c->where(['a.type' => $type,'a.is_del'=>0, ['a.created_at', '>=', $firstDay], ['a.created_at', '<=', $lastDay]]);

            $c=$c->get();
            if(count($c)){
                $conflictService = app()->make(\App\Services\ConflictService::class);
                //dd($name, $encode_id_card_num, $currentOrgName, $c[0]->org_name, $c[0]->insertime, $type, 'CheckAppointment');
                $conflictService->logConflict($name, $encode_id_card_num, $currentOrgName,$doctor_name, $c[0]->org_name, $c[0]->insertime, $type, 'CheckAppointment');
                $result['status']=false;
                $result['msg']='该人员已于'.$c[0]->insertime.'在'.$c[0]->org_name.'登记.';
                $result['info']=$c;
            }else{
                if($type==2){
                    $gongwei=  self::CheckGongWei($name,$id_card_num);
                    if( $gongwei['status']===false) {
                        $result['status'] = false;
                        $result['msg'] = $gongwei['msg'];
                        $result['GongWeiinfo'] = $gongwei['GongWeiinfo'];
                        return $result;
                    }
                }

              $result['status']=true;
              $result['msg']='该人员当年无体检记录，可正常登记。';
              $result['info']=$c;


            }


        }else{
            $result['status']=false;
            $result['msg']='用户证件号未传';
        }
        return $result;

    }
    public function CheckGongWei($name,$id_card_num){
        date_default_timezone_set('PRC');
        $currentYear = date('Y');
        $firstDay = date('Y-01-01', strtotime($currentYear));
        $lastDay = date('Y-12-31', strtotime($currentYear));
        $SendData='<com:queryCheckUp>
         <!--Optional:-->
       <xm>'.$name.'</xm>
         <!--Optional:-->
         <sfz>'.$id_card_num.'</sfz>
      </com:queryCheckUp>';

        $url = config('app.globals.GongWeiBaseUrl');
         $res=\Yz::XmlHttp($SendData,$url);
         //如果没有返回queryCheckUp节点，返回异常
        if(!isset($res['queryCheckUp']) and  $res!="") {
            $result['status']=false;
            $result['msg']='公卫接口异常';
            $result['GongWeiinfo']=$res;
            return $result;
        }
        $result=[];
        if(isset($res['queryCheckUp']['zt']) and $res['queryCheckUp']['zt']=="查无此人"){
            $result['status']=false;
            $result['msg']='查无此人，未建档或姓名、身份证号与公卫档案不符';
            $result['GongWeiinfo']=$res['queryCheckUp'];
            return $result;
        }
        if(isset($res['queryCheckUp']['tjrq']) and ($res['queryCheckUp']['tjrq']>=$firstDay and $res['queryCheckUp']['tjrq']<=$lastDay)){
          //判断老年人体检字段
           if(isset($res['queryCheckUp']['sflnrtj']) and $res['queryCheckUp']['sflnrtj']==1){
               $result['status']=false;
               $result['msg']='公卫系统已存在该年体检记录，请登录公卫系统查询或咨询公卫系统';
               $result['GongWeiinfo']=$res['queryCheckUp'];
           }else{
               $result['status']=true;
               $result['msg']='公卫有记录，但是没有老年人体检';
               $result['GongWeiinfo']=$res['queryCheckUp'];
           }

        }else{
            $result['status']=true;
            $result['msg']='公卫无记录';
            if( $res=="" or  $res==null){
                $result['GongWeiinfo']="公卫返回空";
            }else{
                $result['GongWeiinfo']=$res['queryCheckUp'];
            }

        }
        return $result;
    }

   public function isOver65($idCard,$ageLine=65) {
        // 从身份证号中提取出生日期
       if(strlen($idCard)<>18) return false;
        $birthYear = substr($idCard, 6, 4);
        $birthMonth = substr($idCard, 10, 2);
        $birthDay = substr($idCard, 12, 2);

//        // 将出生日期转换为日期对象
//        $birthdate = new DateTime($birthYear . '-' . $birthMonth . '-' . $birthDay);
//
//        // 获取当前日期
//        $currentDate = new DateTime();
//
//        // 计算年龄差
//        $ageDiff = $birthdate->diff($currentDate)->y;


        $birthYear = substr($idCard, 6, 4); // 例如，假设身份证号的格式为：XXXXXXYYMMDDZZZZ
        $currentYear = date('Y'); // 获取当前年份

        // 将字符串转换为整数
        $birthYear = intval($birthYear);
        $currentYear = intval($currentYear);
        $ageDiff= $currentYear - $birthYear;
        // 判断年龄是否大于设定年龄
        if ($ageDiff >= $ageLine) {
            return true;
        } else {
            return false;
        }
    }

}
