<?php

namespace App\Http\Controllers\API\Third;

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

class YiJiController extends Controller
{
    //查询是否跳转医技
    public function CheckAppointment()
    {

        $cardNo = request('cardNo');//病人id
        $visitSqNo = request('visitSqNo');//门诊挂号流水号/住院流水号
        $requestNoList= request('requestNoList');//申请单号(数组)
        $moOrderList = request('OrderNoList');//医嘱号列表（数组）
        $visitTypeCode = request('visitTypeCode');// 01:门诊 02:急诊 03:住院 04:体检 05:互联网 09:其他


        $is_redirect = false;
        $url = "";
        $entrust_ids = [];
        foreach ($requestNoList as $requestNo) {
            //1.查询his，获取申请单全部检查项目
            $data = [
                'visitSqNo' => $visitSqNo,
                'requestNo' => $requestNo,
                'visitTypeCode' => $visitTypeCode,
                'feeFlag' => 0,
            ];

            $His = new HisController();
            $res = $His::Get("查询检查申请单", $data);
            if ($res['code'] == 200) {
                $res_data = $res['data'];
                foreach ($res_data as $data_k => $data_v) {
                    $date = DateTime::createFromFormat('YmdHis', $data_v['requestDate']);
                    if ($date) {
                        $entrust_datePart = $date->format('Y-m-d'); // 日期部分
                        $entrust_timePart = $date->format('H:i:s'); // 时间部分
                    } else {
                        $entrust_datePart = '';
                        $entrust_timePart = '';
                    }
                    $birthday_f = DateTime::createFromFormat('Ymd', $data_v['patientBirthDate']);
                    if ($birthday_f) {
                        $birthday = $birthday_f->format('Y-m-d');
                    }else{
                        $birthday='';
                    }

                    $mapping = [
                        '03' => 0, // 住院 -> 0
                        '01' => 1, // 门诊 -> 1
                        '02' => 2, // 急诊 -> 2
                        '04' => 3, // 体检 -> 3
                    ];

                    $patientType = $mapping[$visitTypeCode] ?? 9;
                    foreach ($data_v['itemList'] as $item_k => $item) {
                        $entrust_ids[] = $item['orderNo'];
                        //查询库里是否存在该检医嘱
                        $db_item = DB::table('s_list')->where(['entrust_id' => $item['orderNo']])->first();
                        if (!$db_item) {
                            //如果不存在则进行创建
                            $params = [
                                'list_status' => 0,
                                'reg_num' => $data_v['cardNo'],
                                'user_name' =>$data_v['patientName'],
                                'user_sex' => $data_v['patientGenderName'] == '男' ? 1 : 2,
                                'entrust_code' => $item['termCode'],
                                'entrust' => $item['termName'],
                                'is_pay' => $data_v["chargeStatusName"] == '已收费' ? 1 : 0,
                                'reservation_department' =>$data_v["orderDeptName"],
                                'entrust_date' =>$entrust_datePart,
                                'entrust_time' =>$entrust_timePart,
                                'user_brithday' =>$birthday,
                                'docotr' => $data_v["orderPersonName"],
                                'patient_type' => $patientType,
                                'user_phone' => $data_v["mobile"],
                                'implement_department' =>$item['execDeptName'],
                                'entrust_id' => $item['orderNo'],
                                'episodeid' => $visitSqNo,
                                //  'RISRExamID' => $order["RISRExamID"] ? $order["RISRExamID"] : null,  //检查号,先屏蔽掉，获取不到
                                'RISRAcceptDeptCode' => $item["execDeptCode"],    //接收科室代码
                                'warddesc' => $data_v["areaName"],  //病区
                                'wardcode' => $data_v["areaCode"],  //病区
                                'bedname' => $data_v["bedName"],  //病床号
                                'bedno' => $data_v["bedNo"],  //病床号
                                'app_num' => $data_v["requestNo"],  //申请单号
                                'medicalHistory' => $data_v["medicalHistory"],  //病史摘要
                                'diagnosisName' => $data_v["diagnosisName"],  //临床诊断（诊断名称）
                                'idCardNumber' => $data_v["idCardNumber"],  //身份证号
                            ];
                           $list_id= DB::table('s_list')->insertGetId($params);
                           if($list_id){
                               $i_log = DB::table('s_list_log')->insert([
                                   'list_id' =>$list_id,
                                   'reg_num' => $data_v['cardNo'],
                                   'old_status' => 0,
                                   'new_status' => 0,
                                   'create_user' => 'his',
                                   'note' => '创建记录',
                                   'data' => json_encode($params)
                               ]);
                           }

                        }
                    }
                }
            }else{
                return \Yz::JsonError('Roc接口查询失败');
            }

        }




        if (true) {
            $is_redirect = true;
            $url = $this->build_yiji_url($cardNo, $entrust_ids, $visitSqNo);
        } else {
            $is_redirect = false;
        }
        return \Yz::JsonReturn(true, '查询成功', ['is_redirect' => $is_redirect, 'url' => $url]);
    }

    function QueryHisShenQingDan()
    {

    }

    function build_yiji_url($regnum, $entrustid, $episodeid)
    {
        // 固定参数
        $dotype = 1;
        $appointment_type = 1;

        // 判断 entrustid 是否为数组，如果是，则用逗号 , 拼接并分别进行 rawurlencode 编码
        if (is_array($entrustid)) {
            // 对数组中的每个元素进行 rawurlencode 编码后再拼接
            $entrustid_str = implode(',', array_map('rawurlencode', $entrustid));
        }

        // 构造查询参数，并对 regnum 和 episodeid 使用 rawurlencode 编码
        $params = [
            'regnum' => rawurlencode($regnum),
            'entrustid' => $entrustid_str,
            'episodeid' => rawurlencode($episodeid),
            'dotype' => $dotype,
            'appointment_type' => $appointment_type,
        ];

        // 使用 http_build_query 构建查询字符串，注意设置第四个参数为 PHP_QUERY_RFC3986
        // 以确保生成的 URL 符合 RFC 3986 标准
        $query = http_build_query($params, '', '&', PHP_QUERY_RFC3986);

        // 返回完整 URL
        return "http://192.168.80.76/yiji?$query";
    }
}
