<?php

namespace App\Services\Xml;

use App\Http\Controllers\API\Admin\YeWu\PlanListController;
use App\Services\Admin\YeWu\PlanListService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ShenQingDanService
{
    public function Save($result, $jsonData)
    {
        date_default_timezone_set('PRC');
        $Body = $result['message']['Request']["Body"];
        $Header = $result['message']['Request']["Header"];
        $orderList = isset($Body['AddRisAppBillRt']['OrderList']) ? $Body['AddRisAppBillRt']['OrderList'] : [];
        if (!empty($orderList) && !isset($orderList[0])) {
            // 如果OrderList当前不是数组的数组，则将其转换为单元素数组
            $orderList = array($orderList);
        }
        $insert_count = 0;//成功插入数量
        $yuyueInfo=false;//自动预约信息
        DB::beginTransaction();
        foreach ($orderList as $key => $order) {
            $patient_type = null;
            if (isset($Body["PATAdmInfo"]["PAADMTypeCode"])) {
                $p = $Body["PATAdmInfo"]["PAADMTypeCode"];
                if ($p == 'O') $patient_type = 1;
                if ($p == 'H') $patient_type = 3;
                if ($p == 'E') $patient_type = 2;
                if ($p == 'I') $patient_type = 0;
            }
            $params = [
                'list_status' => 0,
                'reg_num' => $Body["PATPatientInfo"]["PATPatientID"] ? $Body["PATPatientInfo"]["PATPatientID"] : null,
                'user_name' => $Body["PATPatientInfo"]["PATName"] ? $Body["PATPatientInfo"]["PATName"] : null,
                'user_sex' => $Body["PATPatientInfo"]["PATName"] == '男' ? 1 : 2,
                'entrust_code' => $order["RISRCode"] ? $order["RISRCode"] : null,
                'entrust' => $order["RISRDesc"] ? $order["RISRDesc"] : null,
                'is_pay' => $order["OrdBillStatus"] == '已收费' ? 1 : 0,
                'reservation_department' => $order["AppDeptDesc"] ? $order["AppDeptDesc"] : null,
                'entrust_date' => $order["RISRSubmitTime"] ? substr($order["RISRSubmitTime"], 0, 10) : null,
                'entrust_time' => $order["RISRSubmitTime"] ? substr($order["RISRSubmitTime"], 11, 8) : null,
                'user_brithday' => $Body["PATPatientInfo"]["PATDob"] ? $Body["PATPatientInfo"]["PATDob"] : null,
                'docotr' => $Body["PATAdmInfo"]["PAADMDocDesc"] ? $Body["PATAdmInfo"]["PAADMDocDesc"] : null,
                'patient_type' => $patient_type,
                'user_phone' => $Body["PATPatientInfo"]["PATTelephone"] ? $Body["PATPatientInfo"]["PATTelephone"] : null,
                'implement_department' => $order["RISRAcceptDeptDesc"] ? $order["RISRAcceptDeptDesc"] : null,
                'entrust_id' => $order["OEORIOrderItemID"] ? $order["OEORIOrderItemID"] : null,//his传过来的本地医嘱id
                'episodeid' => $Body["PATAdmInfo"]["PAADMVisitNumber"] ? $Body["PATAdmInfo"]["PAADMVisitNumber"] : null,  //就诊号
                'RISRExamID' => $order["RISRExamID"] ? $order["RISRExamID"] : null,  //检查号
                'RISRAcceptDeptCode' => $order["RISRAcceptDeptCode"] ? $order["RISRAcceptDeptCode"] : null,  //接收科室代码
                'warddesc' => $Body["PATAdmInfo"]["PAADMAdmWardDesc"] ? $Body["PATAdmInfo"]["PAADMAdmWardDesc"] : null,  //病区
                'beddesc' => $Body["PATAdmInfo"]["PAADMCurBedNo"] ? $Body["PATAdmInfo"]["PAADMCurBedNo"] : null,  //病床号
                'app_num' => $order["RISRAppNum"] ? $order["RISRAppNum"] : null,  //申请单号

            ];
            $requiredFields = [
                'reg_num', 'user_name', 'user_sex', 'entrust', 'is_pay',
                'reservation_department', 'entrust_date', 'entrust_time',
                'user_brithday', 'patient_type',
                'implement_department', 'entrust_id', 'episodeid', 'RISRAcceptDeptCode','app_num'
            ];

            // 判断是否为空
            foreach ($requiredFields as $field) {
                if (!isset($params[$field]) || $params[$field] === null) {
                //    return \Yz::echoError1('参数' . $field . '不能为空');
                    DB::rollBack();
                    return \Yz::XMLReturn($Header['SourceSystem'], $Header['MessageID'], -1, '参数' . $field . '不能为空');
                }
            }

            $insertListId = DB::table('s_list')->insertGetId($params);
            if ($insertListId) {
                if(config('app.globals.自动预约')==1){
                    $planser=new PlanListService();
                    $yuyue= $planser->AutoYuYue($params['reg_num'],[$params['entrust_id']],$params['episodeid'],4);
                    if($yuyue['status']==false){
                        DB::rollBack();
                        return \Yz::XMLReturn($Header['SourceSystem'], $Header['MessageID'], -1, '自动预约失败，'.$yuyue['msg'].'，推送失败');
                    }
                    if($yuyue['status']===true){
                        $yuyueInfo[]=$yuyue['data'];
                    }
                }
                $data = [
                    'list_id' => $insertListId,
                    'reg_num' => $Body["PATPatientInfo"]["PATPatientID"],
                    'new_status' => 0,
                    'create_user' => '接口',
                    'note' => '创建记录',
                    'data' => $jsonData,//原始数据
                ];
                $insertLog = DB::table('s_list_log')->insert($data);
                if ($insertLog) {
                    $insert_count++;

                } else {
                    DB::rollBack();
                    return \Yz::XMLReturn($Header['SourceSystem'], $Header['MessageID'], -1, '失败');
                }
            } else {
                DB::rollBack();
                return \Yz::XMLReturn($Header['SourceSystem'], $Header['MessageID'], -1, '失败');
            }

        }
        if (count($orderList) == $insert_count) {
            DB::commit();

            return \Yz::XMLReturn($Header['SourceSystem'], $Header['MessageID'], 0, ['SendStatus'=>true,"YuyueInfo"=>$yuyueInfo]);
        } else {
            DB::rollBack();
            return \Yz::XMLReturn($Header['SourceSystem'], $Header['MessageID'], -1, '失败');
        }
    }

    //更新申请单状态 P缴费 D、U、C作废
    public function UpdateStatus($result, $jsonData)
    {
        date_default_timezone_set('PRC');
        $Body = $result['message']['Request']["Body"];
        $Header = $result['message']['Request']["Header"];
        $orderList = isset($Body['UpdateOrdersRt']['OEORIInfoList']['OEORIInfo']) ? $Body['UpdateOrdersRt']['OEORIInfoList']['OEORIInfo'] : [];

        if (!empty($orderList) && !isset($orderList[0])) {
            // 如果OrderList当前不是数组的数组，则将其转换为单元素数组
            $orderList = array($orderList);
        }
        //dd($orderList);
        $u_count = 0;//循环的数量
        try {
            $msg='提示:';
            DB::beginTransaction();
            $data=[];
            $zuofei=['D','U','C'];
            $jiaofei=['P'];
            foreach ($orderList as $key => $order) {
                $beizhu='';
                $mainInfo=DB::table('s_list')->where(['reg_num'=>$Body['UpdateOrdersRt']['PATPatientID'],'entrust_id'=>$order['OEORIOrderItemID'],'RISRAcceptDeptCode'=>$order['AcceptDeptCode']])->first();
                if(!!$mainInfo){
                    if(in_array($order['OEORIStatusCode'],$zuofei)){   //如果是作废
                        $beizhu='作废';
                        $data=[
                            'is_nullify'=>1,
                            'updated_at'=>date('Y-m-d H:i:s')
                        ];
                    }
                    if(in_array($order['OEORIStatusCode'],$jiaofei)){ //如果是完成
                        $beizhu='缴费完成';
                        $data=[
                            'is_pay'=>1,
                            'updated_at'=>date('Y-m-d H:i:s')
                        ];
                    }
                    $update=DB::table('s_list')->where('id',$mainInfo->id)->update($data);
                    if ($update) {
                        $data = [
                            'list_id' => $mainInfo->id,
                            'reg_num' => $Body["UpdateOrdersRt"]["PATPatientID"],
                            'new_status' => $mainInfo->list_status,
                            'create_user' => '接口',
                            'note' => $beizhu,
                            'data' => $jsonData,//原始数据
                        ];
                        $insertLog = DB::table('s_list_log')->insert($data);
                        if ($insertLog) {
                            $u_count++;

                        } else {
                            DB::rollBack();
                            return \Yz::XMLReturn($Header['SourceSystem'], $Header['MessageID'], -1, '失败');
                        }
                    } else {
                        $msg=$msg.$order['OEORIOrderItemID'].' 无更新;';
                    }
                }else{
                    //推送过来的检查项目可能不在库里，不在的直接忽略
//                    DB::rollBack();
//                    return \Yz::XMLReturn($Header['SourceSystem'], $Header['MessageID'], -1, '更新失败:'.$order['OEORIOrderItemID'].'未找到此医嘱');
                    $msg=$msg.$order['OEORIOrderItemID'].'不存在;';
                }
            }


                DB::commit();
                return \Yz::XMLReturn($Header['SourceSystem'], $Header['MessageID'], 0, '成功。'.$msg);

        } catch (\Exception $e) {
            DB::rollBack();
            // 处理异常
            Log::error('发生错误: ' . $e->getMessage(), [
                'exception' => $e
            ]);
            return \Yz::XMLReturn($Header['SourceSystem'], $Header['MessageID'], -1, $e->getMessage());

        }

    }

    //检查完成
    public function CheckFinish($result, $jsonData)
    {
        date_default_timezone_set('PRC');
        $Body = $result['message']['Request']["Body"];
        $Header = $result['message']['Request']["Header"];
        $orderList = isset($Body['RisCompleteRt']['OEORIOrderItemIDList']) ? $Body['RisCompleteRt']['OEORIOrderItemIDList'] : [];

//        if (!empty($orderList) && !isset($orderList[0])) {
//            // 如果OrderList当前不是数组的数组，则将其转换为单元素数组
//            $orderList = array($orderList);
//        }

        //dd($orderList);
        $u_count = 0;//循环的数量
        try {
            $msg='';
            DB::beginTransaction();
            foreach ($orderList as $key => $order) {
                $mainInfo=DB::table('s_list')->where(['reg_num'=>$Body['RisCompleteRt']['PATPatientID'],'entrust_id'=>$order['OEORIOrderItemID'],'RISRExamID'=>$Body['RisCompleteRt']['RISRExamID']])->first();
                if(!!$mainInfo){
                    $data=[
                        'list_status'=>3,
                        'updated_at'=>date('Y-m-d H:i:s')
                    ];
                    $update=DB::table('s_list')->where('id',$mainInfo->id)->update($data);
                    if($update){
                        $data = [
                            'list_id' => $mainInfo->id,
                            'reg_num' => $Body["RisCompleteRt"]["PATPatientID"],
                            'new_status' => 3,
                            'create_user' => '接口',
                            'note' => "体检完成",
                            'data' => $jsonData,//原始数据
                        ];
                        $insertLog = DB::table('s_list_log')->insert($data);
                        if ($insertLog) {
                            $u_count++;

                        } else {
                            DB::rollBack();
                            return \Yz::XMLReturn($Header['SourceSystem'], $Header['MessageID'], -1, '失败');
                        }
                    }else{
                        $msg=$msg.$order['OEORIOrderItemID'].' 无更新;';
                    }
                }else{
                    DB::rollBack();
                    return \Yz::XMLReturn($Header['SourceSystem'], $Header['MessageID'], -1, '更新失败:'.$order['OEORIOrderItemID'].'未找到此医嘱');
                }
            }
            if (count($orderList) == $u_count) {
                DB::commit();
                return \Yz::XMLReturn($Header['SourceSystem'], $Header['MessageID'], 0, '成功');
            } else {
                DB::rollBack();
                return \Yz::XMLReturn($Header['SourceSystem'], $Header['MessageID'], -1, '更新失败:'.$msg);
            }

        } catch (\Exception $e) {
            DB::rollBack();
            // 处理异常
            Log::error('发生错误: ' . $e->getMessage(), [
                'exception' => $e
            ]);
            return \Yz::XMLReturn($Header['SourceSystem'], $Header['MessageID'], -1, $e->getMessage());
        }
    }


}
