<?php

namespace App\Http\Controllers\API\Third;

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

class PacsController extends Controller
{
    //报到机调用此接口查询预约的记录
    public function GetEntrustInfo(){
        $orderNo = request('orderNo');//医嘱号
        $idCardNumber = request('idCardNumber');//身份证
        $visitSqNo = request('visitSqNo');//门诊挂号流水号/住院流水号
        $dateRange = request('dateRange');//医嘱开单日期
        $requestNo = request('requestNo');//申请单号
        // 判断所有字段是否都为空
        if (empty($orderNo) && empty($idCardNumber) && empty($visitSqNo) && empty($dateRange) && empty($requestNo)) {
            return \Yz::JsonError("缺失查询条件");
        }
        $entrust_list=DB::table('s_list')->select(
            "list_status",
            "is_nullify",
            "reg_num",
            "user_name",
            "user_sex",
            "user_brithday",
            "user_phone",
            "entrust_code",
            "entrust",
            "is_pay",
            "reservation_department",
            "entrust_date",
            "entrust_time",
            "docotr as doctor",
            "patient_type",
            "implement_department",
            "entrust_id",
            "episodeid",
            "RISRAcceptDeptCode",
            "reservation_date",
            "reservation_time",
            "canel_time as cancel_time",
            "warddesc",
            "wardcode",
            "bedname",
            "bedno",
            "app_num",
            "medicalHistory",
            "diagnosisName",
            "idCardNumber",
            "reservation_sources as reservation_sources_id",

        )->where(['reservation_date'=>date('Y-m-d'),'is_pay'=>1,'is_del'=>0,'is_nullify'=>0]);
        if(isset($dateRange)){
            if(!is_array($dateRange)) return \Yz::JsonError("日期范围必须是数组");
            $entrust_list=$entrust_list->whereBetween('entrust_date',[$dateRange[0],$dateRange[1]]);
        }
        if(isset($orderNo)){
            $entrust_list=$entrust_list->where('entrust_id',$orderNo);
        }
        if(isset($visitSqNo)){
            $entrust_list=$entrust_list->where('episodeid',$visitSqNo);
        }
        if(isset($requestNo)){
            $entrust_list=$entrust_list->where('app_num',$requestNo);
        }
        if(isset($idCardNumber)){
            $entrust_list=$entrust_list->where('idCardNumber',$idCardNumber);
        }
        $entrust_list=$entrust_list->get();




        $His = new HisController();

        foreach ($entrust_list as $entrust) {
            $entrust->reservation_sources_name=null;
            if(!empty($entrust->reservation_sources_id)){
                $source=DB::table('s_department_resources')
                    ->where('id',$entrust->reservation_sources_id)
                    ->first();
                if(!!$source){
                    $parts = explode('-', $source->department_resources_name);
                    $entrust->reservation_sources_name = $parts[0];
                }
            }
            $patientHisTypeMap = [
                0 => '03', // I - 住院
                1 => '01', // O - 门诊
                2 => '02', // E - 急诊
                3 => '04', // H - 体检
            ];
            $sendHisData = [
                'visitSqNo' => $entrust->episodeid,
                'requestNo' => $entrust->app_num,
                'visitTypeCode' => $patientHisTypeMap[$entrust->patient_type],
                'moOrder' =>  $entrust->entrust_id,
            ];
            $entrust->requestTypeCode='';
            $entrust->requestTypeName='';
            $entrust->orderDeptCode='';
            $res = $His::Get("查询检查申请单", $sendHisData);
            if ($res['code'] == 200) {
                $res_data = $res['data'];
                foreach ($res_data as $data_k => $data_v) {
                    $hisInfo=$data_v;
                    $entrust->requestTypeCode=$hisInfo['requestTypeCode'];
                    $entrust->requestTypeName=$hisInfo['requestTypeName'];
                    $entrust->orderDeptCode=$hisInfo['orderDeptCode'];
                }
            }
        }
        return \Yz::JsonReturn(true,'查询完成',$entrust_list);

    }
    //报到机调用此接口通知已经报道
    public function SignIn(){
        $orderNo = request('orderNo');//医嘱号
        $checkNo = request('checkNo');//报道号（检查号）
        if(!isset($orderNo)) return \Yz::JsonError('医嘱号不能为空');
        if(!isset($checkNo)) return \Yz::JsonError('报道号不能为空');
        $entrust = DB::table('s_list')->where(['entrust_id' => $orderNo,'is_nullify'=>0,'is_del'=>0])->first();
        if(!$entrust) return \Yz::JsonError('未找到对应医嘱');
        if($entrust->list_status <> 1) return \Yz::JsonError('医嘱当前状态无法报道');
        $data = [
            'list_status' => 2,
            'check_num' => $checkNo,
        ];
        $u = DB::table('s_list')->where(['entrust_id' => $orderNo])->update($data);
        if($u){
            $i_log = DB::table('s_list_log')->insert([
                'list_id' =>$entrust->id,
                'reg_num' => $entrust->reg_num,
                'old_status' => $entrust->list_status,
                'new_status' => 2,
                'create_user' => '报到机接口',
                'note' => '报到成功',
                'data' => json_encode(['checkNo'=>$checkNo],JSON_UNESCAPED_UNICODE)
            ]);
            //通知pacs
            $pacs=new CSharpController();
            $pacs_res=$pacs->SaveApply($entrust->entrust_id);
            $i_log = DB::table('s_list_log')->insert([
                'list_id' =>$entrust->id,
                'reg_num' => $entrust->reg_num,
                'old_status' => $entrust->list_status,
                'new_status' => 2,
                'create_user' => 'Pacs接口',
                'note' => '通知PacS',
                'data' => json_encode($pacs_res,JSON_UNESCAPED_UNICODE)
            ]);
            return \Yz::JsonReturn(true,'报道成功',['orderNo'=>$orderNo,'pacs_info'=>$pacs_res]);
        }else{
            return \Yz::JsonError('报道失败');
        }

    }
    //报到机调用此接口通知取消报道
    public function CancelSignIn(){
        $orderNo = request('orderNo');
        $entrust = DB::table('s_list')->where(['entrust_id' => $orderNo,'is_nullify'=>0,'is_del'=>0])->first();
        if(!$entrust) return \Yz::JsonError('未找到对应医嘱');
        if($entrust->list_status <> 2) return \Yz::JsonError('医嘱当前状态无法取消报道');
        $data = [
            'list_status' => 1,
            'check_num' => '',
        ];
        $u = DB::table('s_list')->where(['entrust_id' => $orderNo])->update($data);
        if($u){
            return \Yz::JsonReturn(true,'取消报道成功',['orderNo'=>$orderNo]);
        }else{
            return \Yz::JsonError('取消报道失败');
        }
    }

    //Pacs调用此接口通知已经报道 给Pacs用，通知本系统到检（场景，不经过报到机直接人工窗口）
    public function SignInOnPacs(){
        $orderNo = request('orderNo');//医嘱号
        $checkNo = request('checkNo');//报道号（检查号）
        if(!isset($orderNo)) return \Yz::JsonError('医嘱号不能为空');
        if(!isset($checkNo)) return \Yz::JsonError('报道号不能为空');
        $entrust = DB::table('s_list')->where(['entrust_id' => $orderNo,'is_nullify'=>0,'is_del'=>0])->first();
        if(!$entrust) return \Yz::JsonError('未找到对应医嘱');
        if($entrust->list_status <> 1) return \Yz::JsonError('医嘱当前状态无法报道');
        $data = [
            'list_status' => 2,
            'check_num' => $checkNo,
        ];
        $u = DB::table('s_list')->where(['entrust_id' => $orderNo])->update($data);
        if($u){
            $i_log = DB::table('s_list_log')->insert([
                'list_id' =>$entrust->id,
                'reg_num' => $entrust->reg_num,
                'old_status' => $entrust->list_status,
                'new_status' => 2,
                'create_user' => 'Pacs通知',
                'note' => '报到成功',
                'data' => json_encode(['checkNo'=>$checkNo],JSON_UNESCAPED_UNICODE)
            ]);

            return \Yz::JsonReturn(true,'报道成功',['orderNo'=>$orderNo]);
        }else{
            return \Yz::JsonError('报道失败');
        }

    }
    //Pacs调用此接口通知取消报道 给Pacs用，通知本系统取消报道（场景，不经过报到机直接人工窗口）
    public function CancelSignInOnPacs(){
        $orderNo = request('orderNo');
        $entrust = DB::table('s_list')->where(['entrust_id' => $orderNo,'is_nullify'=>0,'is_del'=>0])->first();
        if(!$entrust) return \Yz::JsonError('未找到对应医嘱');
        if($entrust->list_status <> 2) return \Yz::JsonError('医嘱当前状态无法取消报道');
        $data = [
            'list_status' => 1,
            'check_num' => '',
        ];
        $u = DB::table('s_list')->where(['entrust_id' => $orderNo])->update($data);
        if($u){
            return \Yz::JsonReturn(true,'取消报道成功',['orderNo'=>$orderNo]);
        }else{
            return \Yz::JsonError('取消报道失败');
        }
    }

}
