<?php

namespace App\Http\Controllers\API\Third;

use App\Http\Controllers\API\His\HisController;
use App\Http\Controllers\Controller;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;

class CSharpController extends Controller
{
    public static $request;
    public static $Url = 'http://192.168.5.117/WebServiceToHis_BS/AcceptMessage.ashx';

    public function PacsSaveApplyInfo(Request $request)
    {
        $orderNo = $request->query('orderNo');
        $res = $this->SaveApply($orderNo);
        return \Yz::JsonReturn($res['status'],$res['msg'],$res['data']);
    }

    //通知pacs  检查申请单推送
    public function SaveApply($orderNo)
    {
        if(config('app.globals.是否推送Pacs')==0){
            return ['status'=>false,'msg'=>'推送Pacs未开启','data'=>[]];
        }

        Log::info('推送申请单'.$orderNo);
        $entrust = DB::table('s_list')->where(['entrust_id' => $orderNo, 'list_status' => 2, 'is_nullify' => 0])->first();
        $reservation_time='';
        if(isset($entrust->roster_id) and !empty($entrust->roster_id)){
           $plan= DB::table('s_source_roster_detail')->where(['id' => $entrust->roster_id])->first();
           if(!!$plan){
               $reservation_time=$plan->begin_time;
           }

        }
        if ($entrust) {
            //查询his获取检查申请单
            $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,
            ];
            $hisInfo=[];
            $His = new HisController();
            $res = $His::Get("查询检查申请单", $sendHisData);
            if ($res['code'] == 200) {
                $res_data = $res['data'];
                foreach ($res_data as $data_k => $data_v) {
                    $hisInfo=$data_v;
                }
            }
            $patientTypeMap = [
                0 => 'I', // I - 住院
                1 => 'O', // O - 门诊
                2 => 'E', // E - 急诊
                3 => 'H', // H - 体检
            ];
            $guid = Str::uuid()->toString();
            $sex = 'U';
            if ($entrust->user_sex == 1) $sex = 'M';
            if ($entrust->user_sex == 2) $sex = 'F';
            $send_data = [
                'Request' => [
                    'Head' => [
                        'TradeCode' => 'SaveApplyInfo',
                        'TradeTime' => date('Y-m-d H:i:s'),
                        'TradeNo' => $guid,
                        'BranchCode' => '01',
                        'HospitalCode' => '01'
                    ],
                    'Body' => [
                        'patientinfo' => [
                            'patientid' => $entrust->reg_num,
                            'patientname' => $entrust->user_name,
                            'patientsex' => $sex,
                            'patientbirthday' => $entrust->user_brithday,
                            'age' => \Tools::calculateAge($entrust->user_brithday),
                            'identifyid' => $entrust->idCardNumber,
                            'mobilephone' => $entrust->user_phone,
                            'home_detail_address'=>$hisInfo['address']??'',
                            'visitinfo' => [
                                'visitsqno' => $entrust->episodeid,
                                'inpatientno'=>$hisInfo['patientNo']??'',
                                'outpatientno'=>$hisInfo['cardNo']??'',
                                'caseno'=>$hisInfo['markNo']??'',
                                'source' => $patientTypeMap[$entrust->patient_type],
                                'bed_no' =>  $hisInfo['bedNo']??'',
                                'inpatientareacode' => $hisInfo['areaCode']??'',
                                'inpatientarea' => $hisInfo['areaName']??'',
                            ],
                            'applyinfo' =>
//                                [
//                                'accessionnumber' => $entrust->app_num,
//                                'hisapplytime' => $entrust->reservation_date . ' ' . $reservation_time,//与pacs 张工沟通  传 预约的日期
//                                'hisapplydeptcode'=> $hisInfo['orderDeptCode']??'',
//                                'hisapplydept'=> $hisInfo['orderDeptName']??'',
//                                'hisapplydoctorcode'=> $hisInfo['orderPersonCode']??'',
//                                'hisapplydoctor'=> $hisInfo['orderPersonName']??'',
//                                'diagnosis'=> $hisInfo['diagnosisName']??'',
//                                'applyorderinfo' => [
//                                    'orderno' => $entrust->entrust_id,
//                                    'bodypartexamined' => $hisInfo['examPosiBigName']??'',
//                                    'studyclass1his' => $hisInfo['requestTypeName']??'',
//                                    'checkitemcode' => $entrust->entrust_code,
//                                    'checkitemname' => $entrust->entrust,
//                                    'factprice' =>$hisInfo['itemList'][0]['itemCost']??'',
//                                ],
//                            ],
                                $hisInfo
                        //    'hisinfo'=>$hisInfo
                        ]
                    ]
                ]
            ];
            self::RequestLog(self::$Url, $send_data, "推送检查申请单", 'PACS接口');
            $response = Http::post(self::$Url, $send_data);

            if (!$response->successful()) {
                self::$request->response_data = "请求PACS接口失败";
                self::$request->save();
                return ['status'=>false,'msg'=>'请求PACS接口失败','data'=>[]];
            }

            // 处理成功的响应
            $res_string = json_encode($response->json(), JSON_UNESCAPED_UNICODE);
            // dd($res_string);
            $str_len = mb_strlen($res_string, 'utf-8');
            $str_size = $str_len / 1024;
            $save_res = $res_string;
            if ($str_size > 10) $save_res = '{"data":"Row size too large"}';
            self::$request->response_data = $save_res;
            self::$request->save();
            $res = json_decode($res_string, true);
            if (isset($res['Response']['Head']['TradeStatus']) and $res['Response']['Head']['TradeStatus'] == 'AA') {
                return ['status'=>true,'msg'=>'推送成功','data'=>['entrust_id' => $entrust->entrust_id,'res'=>$res]];
            } else {
                return ['status'=>false,'msg'=>'推送失败','data'=>[]];
            }
        } else {
            return ['status'=>false,'msg'=>'医嘱不存在','data'=>[]];
        }
    }

    public function PacsCancelApplyInfo(Request $request)
    {
        $orderNo = $request->query('orderNo');//医嘱号
        $res=$this->CancelApply($orderNo);
        return \Yz::JsonReturn($res['status'],$res['msg'],$res['data']);

    }

    //检查申请单撤销
    public function CancelApply ($orderNo)
    {
        if(config('app.globals.是否推送Pacs')==0){
            return ['status'=>false,'msg'=>'推送Pacs未开启','data'=>[]];
        }
        Log::info('撤销推送申请单'.$orderNo);
        $entrust = DB::table('s_list')->where(['entrust_id' => $orderNo])->first();
        if ($entrust) {
            $guid = Str::uuid()->toString();
            $send_data = [
                'Request' => [
                    'Head' => [
                        'TradeCode' => 'CancelApplyInfo',
                        'TradeTime' => date('Y-m-d H:i:s'),
                        'TradeNo' => $guid,
                        'BranchCode' => '01',
                        'HospitalCode' => '01'
                    ],
                    'Body' => [
                        'patientinfo' => [
                            'patientid' => $entrust->reg_num,
                        ],
                        'applyinfo' => [
                            'accessionnumber' => $entrust->app_num,
                        ]
                    ]
                ]
            ];
            self::RequestLog(self::$Url, $send_data, "撤销检查申请单", 'PACS接口');
            $response = Http::post(self::$Url, $send_data);

            if (!$response->successful()) {
                self::$request->response_data = "请求PACS接口失败";
                self::$request->save();
                return ['status'=>false,'msg'=>'请求PACS接口失败','data'=>[]];
            }
            // 处理成功的响应
            $res_string = json_encode($response->json(), JSON_UNESCAPED_UNICODE);
            // dd($res_string);
            $str_len = mb_strlen($res_string, 'utf-8');
            $str_size = $str_len / 1024;
            $save_res = $res_string;
            if ($str_size > 10) $save_res = '{"data":"Row size too large"}';
            self::$request->response_data = $save_res;
            self::$request->save();
            $res = json_decode($res_string, true);
            if (isset($res['Response']['Head']['TradeStatus']) and $res['Response']['Head']['TradeStatus'] == 'AA') {
                return ['status'=>true,'msg'=>'推送成功','data'=>['entrust_id' => $entrust->entrust_id]];
            } else {
                return ['status'=>false,'msg'=>'撤销失败','data'=>[]];
            }
        } else {
            return ['status'=>false,'msg'=>'医嘱不存在','data'=>[]];
        }
    }

    public static function RequestLog($url, $post_data, $mark, $code = 0)
    {
        self::CheckTableName();
        foreach ($post_data as $key => $post_datum) {
            $str_len = mb_strlen(json_encode($post_datum, JSON_UNESCAPED_UNICODE), 'utf-8');
            $str_size = $str_len / 1024;
            if ($str_size > 10) {
                $post_data["$key"] = 'Row size too large';
            }
        }
        $post_data = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        self::$request->code = $code;
        self::$request->mark = $mark;
        self::$request->post_data = $post_data == '[]' ? '{}' : $post_data;
        self::$request->request_url = $url;
        self::$request->save();
    }

    public static function CheckTableName()
    {
        $table_name = 'zz_peis_log_' . date('ym');
        $table_count = DB::select('select count(1) as c from information_schema.TABLES where table_schema = ? and table_name = ?', [env('DB_DATABASE'), $table_name])[0];
        if ($table_count->c === 0) {
            Schema::create($table_name, function (Blueprint $table) {
                $table->id();
                $table->string('code', 50)->index();
                $table->string('mark', 50)->index();
                $table->text('post_data');
                $table->text('response_data')->nullable();
                $table->string('request_url', 2000);
                $table->timestamps();
            });
        }
        self::$request = new \App\Models\PEISLog();
        self::$request->setTable($table_name);
    }
}
