<?php

namespace App\Http\Controllers\API\H5;

use App\Http\Controllers\Controller;
use App\Services\ReportService;
use Illuminate\Http\Request;
use App\Http\Controllers\API\PEISApiController;
use Illuminate\Support\Facades\DB;

class ReportController extends Controller
{
  public function GetReportList()
  {
    $openid = request('openid');
    $tj_status = request('tj_status');
    $hospital_id=request('hospital_id');
    if (!isset($openid)) return \Yz::echoError1("openid不能为空");
    if (!isset($hospital_id)) return \Yz::echoError1("hospital_id不能为空");

    $user = DB::table('web_users')->where(['openid' => $openid, 'status' => 1, 'is_del' => 0])->first();
    if (!$user) return \Yz::echoError1('用户不存在');
    $persons = DB::table('web_user_person')->where(['user_id' => $user->id, 'is_del' => 0])->pluck('id_number')->toArray();
    $report_list=[];
    $peis = new PEISApiController();
    foreach ($persons as $key => $id_number) {
      $data = [
        '电话号码' => "",
        '证件号码' => $id_number,
        '体检号' => ""
      ];
      $reports = $peis::Post('体检报告查询', $hospital_id, $data);
      if (count($reports['data']) > 0) {
        $reports_detail_list = $reports['data'];
        foreach ($reports_detail_list as $key => $reports_detail) {
          $report_list[]=$reports_detail;
        }
      }
    }
    $list=[];

    foreach ($report_list as $key => $report) {
      $report_list[$key]['is_read']=0;
      if($report['体检状态']=='报告已出' || $report['体检状态']=='总检完成'){
        $cha=DB::table('report_l1_records')->where(['体检号' => $report['体检号']])->first();
        if(!!$cha and $cha->is_read==1){
          $report_list[$key]['is_read']=1;
        }
      }
      if(isset($tj_status) and $tj_status!==0){
        if($tj_status==1 and $report['体检状态']=='报告已出' || $report['体检状态']=='总检完成'){
          $list[]= $report_list[$key];
        }
        if($tj_status==2 and $report['体检状态']=='报告未出'){
          $list[]= $report_list[$key];
        }
      }else{
        $list[]= $report_list[$key];
      }

    }
    return \Yz::Return(true, "查询完成", ['list' => $list]);


//    $list = DB::table('report_l1_records')->select('姓名', '性别', '登记时间', '套餐名称', '体检号', '体检状态', 'is_read')->whereIn('证件号码', $persons);
//    if(isset($tj_status) and $tj_status!==0){
//      if($tj_status===1){
//        $tj_status='报告未出';
//        $list=$list->where('体检状态', $tj_status);
//
//      }
//      if($tj_status===2){
//        $tj_status='报告已出';
//        $list=$list->where('体检状态', $tj_status);
//        $list = $list->where(function ($query) use ($tj_status) {
//          $query->where('体检状态', '报告已出')->orWhere('体检状态', '总检完成');
//        });
//      }
//
//    }
//    $list=$list->get();
//    return \Yz::Return(true, "查询完成", ['list' => $list]);
  }

  public function GetReportJieLunJianYi()
  {
    $YiBanJianChaList = [
      ['name' => "身高(cm)",
        'code' => "SG"],
      ['name' => "体重(kg)",
        'code' => "TZ"],
      ['name' => "收缩压",
        'code' => "XY(SSY)"],
      ['name' => "血红蛋白",
        'code' => "BXBSM"],
    ];
    $tijian_num = request('tijian_num');
    $hospital_id=request('hospital_id');
    if (!isset($tijian_num)) return \Yz::echoError1("tijian_num不能为空");
    if (!isset($hospital_id)) return \Yz::echoError1("hospital_id不能为空");
    $report = DB::table('report_l1_records as a')->where(['a.体检号' => $tijian_num])->first();
    if (!$report) {
      //如果本地没报告，则尝试拉取一下思信的报告
      $peis = new PEISApiController();
      $data = [
        '电话号码' => "",
        '证件号码' => "",
        '体检号' => $tijian_num
      ];
      $res = $peis::Post('体检报告查询', $hospital_id, $data);
      if(count($res['data']) > 0) {
        $res = $res['data'][0];
        $report_res = new ReportService();
        $save=  $report_res->Save($res);
        if($save['status']){
          $report = DB::table('report_l1_records as a')->where(['a.体检号' => $tijian_num])->first();
        }else{
          return $save;
        }
      }else{
        return \Yz::echoError1("查询报告详情失败");
      }

    }
    if (!!$report){
      if ($report->体检状态 == '报告未出') return \Yz::echoError1("此报告暂时未出");
      $items = DB::table('report_l2_items as b')->leftJoin('report_l3_base_items as c', 'b.id', '=', 'c.report_l2_id')->where(['b.reprort_l1_id' => $report->id])->get();
      $v_error_items = [];
      $error_items = [];
      $base_items = [];
      foreach ($items as $item) {
        foreach ($YiBanJianChaList as $ybitem) {
          if ($item->基础项目代码 == $ybitem['code']) {
            $base_items[] = [
              'name' => $ybitem['name'],
              'value' => $item->结果值,
            ];
          }
        }
        if ($item->异常标识 != null and $item->异常标识 != '') {
          $error_items[] = $item;
        }
      }

      $info = [];
      $info['name'] = $report->姓名;
      $info['base_date'] = $base_items;
      $info['items'] = [
        'all_count' => count($items),
        'ipt_error_count' => count($v_error_items),//重要异常数量
        'error_count' => count($error_items),//异常数量

      ];
      $info['content'] = $report->总检建议;

      return \Yz::Return(true, "查询完成", ['info' => $info]);
    }
  }

  //完整报告中的列表
  public function GetReportDetaiList()
  {
    $tijian_num = request('tijian_num');
    $report = DB::table('report_l1_records as a')->where(['a.体检号' => $tijian_num])->first();
    if (!$report) return \Yz::echoError1("查询报告失败");
    if ($report->体检状态 == '报告未出') return \Yz::echoError1("此报告暂时未出");
    $items = DB::table('report_l2_items as b')->leftJoin('report_l3_base_items as c', 'b.id', '=', 'c.report_l2_id')->where(['b.reprort_l1_id' => $report->id])->get();
    $list = [];

    foreach ($items as $item) {
      $ShouFeiName = $item->收费项目名称;
      if (!isset($list[$ShouFeiName])) {
        $error_count = 0;
        $list[$ShouFeiName] = ['id' => $item->report_l2_id, 'error_count' => $error_count];
      }
      if ($item->异常标识 != null and $item->异常标识 != '') {
        $error_count++;
      }
      $list[$ShouFeiName] = ['id' => $item->report_l2_id, 'error_count' => $error_count];
    }
    return \Yz::Return(true, "查询完成", ['list' => $list]);
  }

  public function GetReportDetai()
  {
    $id = request('id');
    $l2 = DB::table('report_l2_items')->where(['id' => $id])->first();
    $items = DB::table('report_l3_base_items')->where(['report_l2_id' => $id])->orderBy('基础项目顺序')->get();
    if ($l2->科室类型 == 'PACS') {
      $suojian = [];
      $zhenduan = [];
      foreach ($items as $item) {
        $suojian[] = $item->所见;
        $jielun[] = $item->结论;
      }

      if (count($items) > 0) {
        return \Yz::Return(true, "查询完成", ['is_pacs'=>true,'suojian' => $suojian,'jielun' => $jielun]);
      } else {
        return \Yz::echoError1('此项暂无内容');
      }

    } else {

      $error_items = [];
      foreach ($items as $item) {
        if ($item->异常标识 != null and $item->异常标识 != '') {
          $m = '';
          if ($item->异常标识 == '↓') {
            $m = '低';
          }
          if ($item->异常标识 == '↑') {
            $m = '高';
          }
          $error_items[] = $item->基础项目名称 . $m;
        }
        if($item->结果类型=='数值' and $item->结果值!='' and $item->结果值!=null){
          $range = $this->convertToArray($item->结果值范围);
          $item->结果值范围=$range;
          $item->最大范围=[];
          if(count($range)>1){
            $kuadu=$range[1]-$range[0];
            if(($item->结果值-$range[1])/$kuadu<=1){
              $max=$range[1]+$kuadu;
            }else{
              $max=$item->结果值;
            }
            $item->最大范围=[0,$max];
          }
        }
      }
      if (count($items) > 0) {
        return \Yz::Return(true, "查询完成", ['is_pacs'=>false,'list' => $items, 'error_items' => $error_items]);
      } else {
        return \Yz::echoError1('此项暂无内容');
      }
    }


  }
  function convertToArray($input) {
    // 检查是否是范围表示法
    if (preg_match('/^(\d*\.?\d*)-(\d*\.?\d*)$/', $input, $matches)) {
      return [(float)$matches[1], (float)$matches[2]];
    }

    // 检查是否是小于符号
    if (preg_match('/^<(\d*\.?\d*)$/', $input, $matches)) {
      return [0, (float)$matches[1]];
    }

    // 检查是否是小于等于符号
    if (preg_match('/^<=(\d*\.?\d*)$/', $input, $matches)) {
      return [0, (float)$matches[1]];
    }

    // 如果没有匹配，返回原始输入
    return $input;
  }


}
