<?php

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

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SignInController extends Controller
{
    //签到
    public function SignIn(Request $request)
    {
        $userid = $request->get('userid');//中间件产生的参数
        date_default_timezone_set('PRC');
        $MainListIds = request('MainListIds');
        if(empty($MainListIds))  return \Yz::echoError1('id参数不能为空');
        $mainInfos=DB::table('s_list as a')
            ->select('a.*','b.period_begin_time','b.period_end_time')
            ->leftJoin('s_period as b','a.reservation_time','=','b.id')
            ->whereIn('a.id',$MainListIds)->where(['a.is_del'=>0])->get();
        //遍历判断所有要预约的医嘱是否符合条件
        foreach ($mainInfos as $key=>$mainInfo){
                //判断状态
                if($mainInfo->list_status<>1) return \Yz::echoError1($mainInfo->entrust.' 不是预约状态，不可签到');
                if($mainInfo->patient_type<>0 and $mainInfo->is_pay<>1) return \Yz::echoError1($mainInfo->entrust.' 未支付，不可签到');
                if($mainInfo->is_nullify<>0) return \Yz::echoError1($mainInfo->entrust.' 已作废，不可签到');
                //判断时间,当前判断只要是当天就可签到
                $now=date('Y-m-d');
                //判断是否过期
                if($mainInfo->reservation_date<$now)  return \Yz::echoError1($mainInfo->entrust.' 预约已过期');
                //判断是否是预约的时间
                if($mainInfo->reservation_date<>$now)  return \Yz::echoError1($mainInfo->entrust.' 未到预约时间，请于'.$mainInfo->reservation_date.'签到');
                //获取检查项目类名
                $type=DB::table('s_check_item as a')
                    ->select('a.*','b.item_class_name')
                    ->leftJoin('s_check_item_class as b','a.item_class_id','=','b.id')
                    ->where(['a.item_code'=>$mainInfo->entrust_code])->first();
                if(!$type) return \Yz::echoError1($mainInfo->entrust.' 获取分类失败，不可签到');
                $mainInfo->entrust_type=$type->item_class_name;
                //获取预约的检查室
                $checkroom=DB::table('s_department_resources')->where(['id'=>$mainInfo->reservation_sources])->first();
                if(!$checkroom) return \Yz::echoError1($mainInfo->entrust.' 未获取到检查室信息，不可签到');
                $mainInfo->reservation_sources_name=$checkroom->department_resources_name;
        }
        //如果以上都通过，调用盈谷接口进行签到
        $success_item=[];
        $fail_item=[];
        foreach ($mainInfos as $key=>$mainInfo){
            if($mainInfo->patient_type==2){
                $mainInfo->patient_type=3;
            }elseif ($mainInfo->patient_type==3){
                $mainInfo->patient_type=2;
            }
            $p=[];
            $checkroom=$mainInfo->reservation_sources_name;
            if($mainInfo->RISRAcceptDeptCode=='FY2003.00'){//超声科

                $checkroom_array = explode("_", $checkroom);
                if(count($checkroom_array)!=2) {
                    $fail_item[]=$mainInfo->entrust.' 签到失败：未正确关联学组,学组名称：'.$checkroom;
                    continue;
                }
                $p=[
                    'isStudyGroupRegistration'=>'Y',
                    'studyGroupName'=>$checkroom_array[0],
                    'studyGroupCode'=>$checkroom_array[1],
                ];
            }
            if($mainInfo->RISRAcceptDeptCode=='FY2004.00'){//放射科
                $p=[
                    'videoRoomName'=>$checkroom,
                ];
            }
            $data=[
                'hisId'=>$mainInfo->reg_num,
                'yizhuId'=>$mainInfo->entrust_id,
                'isAppt'=>'Y',
                'appointmentTime'=>$mainInfo->reservation_date.' '.$mainInfo->period_begin_time,
                'enrolDoctorName'=>'医技预约',
                'enrolDoctorCode'=>'FYYJYY',
                'admIdIss'=>$mainInfo->patient_type,
                'patientName'=>$mainInfo->user_name,
                'accessionNo'=>$mainInfo->app_num,
                'modalityName'=> $mainInfo->entrust_type,
                'hospitalId'=>1
            ];
            $data= array_merge($data,$p);
           $yg_signin= self::YG_SignIn('?CfgItem=JH1738预约签到',$data);
           if($yg_signin['status']==true){
               //盈谷返回成功,更新本地状态
               $u=DB::table('s_list')->where(['id'=>$mainInfo->id])->update([
                  'list_status'=>2,
                   'check_num'=>$yg_signin['data'][0]['checkNo']
               ]);
               if($u){
                   $success_item[]=['entrust'=>$mainInfo->entrust,'signInData'=>$yg_signin['data']];
                   //记录日志
                   $data = [
                       'list_id' => $mainInfo->id,
                       'reg_num' => $mainInfo->reg_num,
                       'new_status' => 2,
                       'create_user' => $userid,
                       'note' => '登记',
                       'data' => null,//原始数据
                   ];
                   $insertLog = DB::table('s_list_log')->insert($data);
               }else{
                   $fail_item[]=$mainInfo->entrust.' 签到失败：记录未更新';
                 //  return \Yz::echoError1($mainInfo->entrust.' 签到失败：记录未更新');
               }

           }else{
               $fail_item[]=$mainInfo->entrust.' 调用检查系统签到接口失败：'.$yg_signin['msg'];
              // return \Yz::echoError1($mainInfo->entrust.' 调用检查系统签到接口失败：'.$yg_signin['msg']);
           }
        }

        return \Yz::Return(true,'操作完成',['success'=>$success_item,'fail'=>$fail_item]);


    }
    //盈谷签到
    public function YG_SignIn($url,$data)
    {
        $baseUrl=config('app.globals.YingGuBaseUrl');
        $data=json_encode($data,JSON_UNESCAPED_UNICODE);
        $r=\Tools::PostSoap($baseUrl.$url,$data,'盈谷签到');
        if (!json_decode($r, true)) {
            return ['status'=>false,'msg'=>"解析'删除签到接口'数据出错:".$r];
        }
        $res = json_decode($r, true);
        if($res['isSuccess']==true){
            return ['status'=>true,'msg'=>$res['resultMsg'],'data'=>$res['resultDatas']];
        }else{
            return ['status'=>false,'msg'=>$res['resultMsg']];
        }
    }

    //取消签到
    public function CancelSign(Request $request)
    {
        $userid = $request->get('userid');//中间件产生的参数
        date_default_timezone_set('PRC');
        $MainListIds = request('MainListIds');
        if(empty($MainListIds))  return \Yz::echoError1('id参数不能为空');
        $mainInfos=DB::table('s_list as a')
            ->select('a.*','b.period_begin_time','b.period_end_time')
            ->leftJoin('s_period as b','a.reservation_time','=','b.id')
            ->whereIn('a.id',$MainListIds)->where(['a.is_del'=>0])->get();
        //遍历判断所有要预约的医嘱是否符合条件
        foreach ($mainInfos as $key=>$mainInfo) {
            //判断状态
            if ($mainInfo->list_status <> 2) return \Yz::echoError1($mainInfo->entrust . ' 不是 已签到 状态，不可取消签到');
            if ($mainInfo->is_nullify <> 0) return \Yz::echoError1($mainInfo->entrust . ' 已作废，不可取消签到');
        }
        //如果以上都通过，调用盈谷接口进行取消签到
        $success_item=[];
        $fail_item=[];
        foreach ($mainInfos as $key=>$mainInfo) {
            $data=[
                'checkNo'=>$mainInfo->check_num,
                'hisId '=>$mainInfo->reg_num,
                'hospitalId'=>1
            ];
            $yg_cancelsign= self::YG_CancelSign('?CfgItem=JH1739取消预约签到',$data);
            if($yg_cancelsign['status']==true){
                //盈谷返回成功,更新本地状态
                $u=DB::table('s_list')->where(['id'=>$mainInfo->id])->update([
                    'list_status'=>1
                ]);
                if($u){
                    $success_item[]=$mainInfo->entrust;
                    //记录日志
                    $data = [
                        'list_id' => $mainInfo->id,
                        'reg_num' => $mainInfo->reg_num,
                        'new_status' => 1,
                        'create_user' => $userid,
                        'note' => '取消登记',
                        'data' => null,//原始数据
                    ];
                    $insertLog = DB::table('s_list_log')->insert($data);
                }else{
                    $fail_item[]=$mainInfo->entrust.' 取消签到失败：记录未更新';
                }
            }else{
                $fail_item[]=$mainInfo->entrust.' 调用检查系统删除签到接口失败：'.$yg_cancelsign['msg'];
            }
        }
        return \Yz::Return(true,'操作完成',['success'=>$success_item,'fail'=>$fail_item]);
    }
    //调用盈谷取消接口
    public function YG_CancelSign($url,$data)
    {
        $baseUrl=config('app.globals.YingGuBaseUrl');
        $data=json_encode($data,JSON_UNESCAPED_UNICODE);
        $r=\Tools::PostSoap($baseUrl.$url,$data,'盈谷删除签到');

        if (!json_decode($r, true)) {
            return ['status'=>false,'msg'=>"解析'删除签到接口'数据出错:".$r];
        }
        $res = json_decode($r, true);
        if($res['isSuccess']==true){
            return ['status'=>true,''];
        }else{
            return ['status'=>false,'msg'=>$res['resultMsg']];
        }
    }
}
