<?php
namespace App\Services\mH5;
use App\Services\Admin\YeWu\AppointmentService;
use DateTime;
use Illuminate\Support\Facades\DB;
use App\Services\mH5\PersonService;
class OrganizationService
{
        public function GetList($arr){
            //如果查询可用机构列表则数组 ‘type’字段传 ‘enable’,查全部 则传 ‘all’
            $result=array();
            if($arr['type']){
                $list=DB::table('medical_institution');
                if ($arr['type']=='enable'){
                    $list=$list->where(['status'=>1]);
                }
                if ($arr['type']=='all'){
                    $list=$list->whereIn('status',[0,1]);
                }
                if($arr['yuyue_type']=='jiankangzheng_mf'){
                    $list= $list->where(['enable_yuyue'=>1,'enable_jiankangzheng_mf'=>1]);
                }
                if($arr['yuyue_type']=='laonianren_mf'){
                    $list= $list->where(['enable_yuyue'=>1,'enable_laonianren_mf'=>1]);
                }
                $list= $list->get();
                if(count($list)>0){
                    $result['status']=true;
                    $result['list']=$list;
                }else{
                    $result['msg']='未找到有效机构';
                    $result['status']=false;
                }
            }else{
                $result['msg']='未设置查询参数';
                $result['status']=false;
            }
            return $result;

        }

        //获取体检机构可预约日历时间表
        public function GetCalendar($arr){
            $result=array();
            date_default_timezone_set('PRC');
            $nowtime=date("Y-m-d H:i:s");
            if($arr['type']){
                if ($arr['type']=='enable'){
                    $list=DB::table('institutional_calendar')->where(['status'=>1,'institution_id'=>$arr['org_id']])->where('end_time','>',$nowtime)->get();
                    if(count($list)>0){
                        $result['list']=$list;
                        $result['status']=true;
                    }else{
                        $result['status']=false;
                        $result['msg']="无可预约日期";
                    }
                }
                return $result;


            }else{
                $result['msg']='未设置查询参数';
                $result['status']=false;
            }
            return $result;
        }
        //开始预约
        public function StartYuYue($arr,$type=1){
            $result=array();
            $openid=$arr['openid'];
            $group=$arr['group'];
            $info=$arr['info'];

            //判断用户是否有效
            $cha_info=DB::table('persons')->select(['id','name','id_card_num','sex'])->where(['openid'=>$openid,'status'=>1])->get();
            if(!count($cha_info)){
                return \Yz::Return(false,'未找到有效用户');
            }
            //判断用户是否预约过
            date_default_timezone_set('PRC');
            $nowtime=date("Y-m-d H:i:s");
            $currentYear = date('Y');
            $firstDay = date('Y-01-01', strtotime($currentYear));
            $lastDay = date('Y-12-31', strtotime($currentYear));
            $free_type=0;
            if(isset($info['is_zifei']) and $info['is_zifei']=='zifei'){
                //自费忽略判断资格，多少次都行
                $free_type=1;
            }else{
                //如果是免费体检判断资格
                if($type==1){
                    $month=config('app.globals.HealthyCardTimeRange');
                    //如果是健康证体检，则先查寻是否有体检记录
                    $cha_jkz=DB::table('examination_records')->where(['id_card_num'=>$cha_info[0]->id_card_num,'fee_type'=>0,'is_del'=>0])->orderBy('id','desc')->first();
                    //，如果有判断是否快到期(先不判断是否体检通过)，能否继续预约
                    if(!!$cha_jkz){
                        $date = new DateTime($cha_jkz->created_at);
                        $date->modify('+'.$month.' months');
                        $now = new DateTime();
                        if ($date > $now) {
                            return \Yz::Return(false,'本年度已经体检过，请于:'. $date->format('Y-m-d H:i:s').'后再进行预约');
                        }
                    }
                    //查询是否有预约记录
                    $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));

                }

                $cha=DB::table('appointment_record')->where([['id_card_num','=',$cha_info[0]->id_card_num],['is_del','=','0'],['created_at','>',$firstDay],['created_at','<',$lastDay],'fee_type'=>0])->whereIn('status',[1,2])->get();
                if(count($cha)) {
                    return \Yz::Return(false,'本年度已经预约过，无法继续预约');
                }
                //判断是否免费体检过
                $s=app()->make(PersonService::class);
                $char=$s->GetPersonRecode(['openid'=>$openid,'group'=>$group]);

                if(!$char['status']){
                    return \Yz::Return(false,$char['msg']);
                }
            }

            //判断预约的时间是否可行
            $q_date=DB::table('institutional_calendar')->select(['date','time','count'])->where(['id'=>$info['calendar_id'],'status'=>1])->where('end_time','>',$nowtime)->get();
            if(!count($q_date)){
                return \Yz::Return(false,'预约时间无效，或已截止预约');
            }
            //判断预约数量是否达到设定值
            $q_count=DB::table('appointment_record')->where(['calendar_id'=>$info['calendar_id']])->count();
            if($q_count>=$q_date[0]->count){
                return \Yz::Return(false,'当前时间段预约已满');
            }

            //获取体检机构编号sn
            $jgINfo=DB::table('medical_institution')->where('id',$info['org_id'])->first();

            $Hmac=\App\Lib\HSM::Hmac($cha_info[0]->name.$cha_info[0]->id_card_num.$info['org_id']);
            if($Hmac['status']!=true){
                return \Yz::echoError1('HMAC摘要失败');
            }
             $sfz_HSM=\App\Lib\HSM::HsmDecrypt($cha_info[0]->id_card_num);
            if($sfz_HSM['status']!=true){
                return \Yz::echoError1('身份证解密失败');
            }
            $sfz_mingwen=$sfz_HSM['data'];
            $data=[];
            if($type==1){
                $data= [
                    'type'=>$type,
                    'calendar_id' => $info['calendar_id'],
                    'name' => $cha_info[0]->name,
                    'id_card_num' => $cha_info[0]->id_card_num,
                    'sex'=>$cha_info[0]->sex,
                    'age'=>\App\Lib\Tools::calculateAgeFromID($sfz_mingwen,$nowtime),
                    'birthday'=>\App\Lib\Tools::getBirthdayFromIDCard($sfz_mingwen),
                    'person_id'=>$cha_info[0]->id,
                    'openid'=>$openid,
                    'date'=>$q_date[0]->date,
                    'time'=>$q_date[0]->time,
                    'fee_type'=>$free_type,
                    'doc_type_id'=>$info['doc_id'],
                    'doc_type_name'=>$info['doc_name'],
                    'org_id'=>$info['org_id'],
                    'org_code'=>$jgINfo->sn,
                    'status'=>1,
                    'hmac'=>$Hmac['data'],
                ];
            }
            if($type==2){  //如果是65老年人免费体检
                //判断年龄
                $s=new AppointmentService();
                if(!$s->isOver65($sfz_mingwen)) return \Yz::echoError1("用户年龄不满足条件，不可预约");
                $data= [
                    'type'=>$type,
                    'calendar_id' => $info['calendar_id'],
                    'name' => $cha_info[0]->name,
                    'id_card_num' => $cha_info[0]->id_card_num,
                    'sex'=>$cha_info[0]->sex,
                    'age'=>\App\Lib\Tools::calculateAgeFromID($sfz_mingwen,$nowtime),
                    'birthday'=>\App\Lib\Tools::getBirthdayFromIDCard($sfz_mingwen),
                    'person_id'=>$cha_info[0]->id,
                    'openid'=>$openid,
                    'date'=>$q_date[0]->date,
                    'time'=>$q_date[0]->time,
                    'fee_type'=>$free_type,
                    'org_id'=>$info['org_id'],
                    'org_code'=>$jgINfo->sn,
                    'status'=>1,
                    'hmac'=>$Hmac['data'],
                ];
            }
            //如果都通过则继续
            DB::beginTransaction();
            try {
                $idd=DB::table('appointment_record')->insertGetId($data);
                if($type==1){
                    $file=array();
                    foreach ($info['upfileList'] as $key=> $fvalue) {
                        foreach ($fvalue as $key2=> $fvalue2) {
                            $file[]=[
                                'type' =>$key,
                                'appointment_record_id' =>$idd,
                                'imgurl' =>$fvalue2,
                            ];
                        }
                    }

                    $i_img=DB::table('appointment_img')->insert($file);
                }

                if($idd){
                    DB::commit();
                    return \Yz::Return(true,'预约完成');
                }else{
                    DB::rollback();
                    return \Yz::Return(false,'预约失败');
                }

            } catch (Exception $e) {

                DB::rollback();
                return \Yz::Return(false,'预约失败');
            }




        }
}
