<?php 
  
  /** 
  * 预约接口
  * @author   gfding
  * @version  1.0
  */ 
  class Api_AppointController extends Ctrl_Api{

    public $SoapUrl = 'https://192.168.90.116:1443/csp/hsb/DHC.Published.ZZJService.BS.ZZJService.CLS?WSDL=1';
    public $POST;

    /**
    * 默认接口
    */
    public function indexAction() {
      try {
        Tool_Fnc::apiMsg('预约接口调用成功', '00000000');exit;
      } catch (SOAPFault $e) {
        print $e;
      }
      exit;
    }

    public function GetAppiontYBTypeAction(){
      $YB[0] = array(
          'YBMeaning'=>'自费',
          'YBCode'=>0,
          );
      try {
        $data = array('total' => 1, 'rows' =>$YB);
        Tool_Fnc::apiMsg('预约接口调用成功', '00000000',$data);exit;
      } catch (SOAPFault $e) {
        print $e;
      }
      exit;
    }


    /**  
    * 获取预约是否扣费 
    * @param $TerminalCode 自助机编号
    * @param $AppointType 预约方式 2 自助机预约
    * @return 
    * { 
    *   "errorcode":"00000000",
      *   "message":"获取业务功能成功",
      *   "data":{
    *     "IsDeductMoney":"0"   //1：扣费,0：不扣费
    *   }
    * }
    */
    public function isAppointCostAction() {
      $p = $_REQUEST;

      $pTerminalCode = empty($p['TerminalCode'])?Tool_Fnc::apiMsg('终端号不能为空', '00000001'):Tool_Fnc::safe_string($p['TerminalCode']);
      $pAppointType = empty($p['AppointType'])?Tool_Fnc::apiMsg('预约方式不能为空', '00000001'):Tool_Fnc::safe_string($p['AppointType']);

      try {
        $IsDeductMoney = array('IsDeductMoney' => 1, );   //1：扣费,0：不扣费
        Tool_Fnc::apiMsg('获取预约是否扣费成功', '00000000', $IsDeductMoney);
      } catch (SOAPFault $e) {
        print $e;
      }
      exit;
    }
    /**
    * 根据一级科室编号查询二级科室信息
    * @param $TerminalCode  自助机编号
    * @param $BusType     业务类型    挂号 1，缴费 2，预约 3，建档 33，办卡 34，检查报告 35，检验报告 36，挂号记录 37，缴费记录 38
    * @param $PatientID   患者ID
    * @param $CDID      一级科室编号  多级科室时使用，暂不使用
    * @param $IsEmergency   是否急诊    1 是， 其他或空 否
    * @param $DeptType    科室类型    特殊类型科室，预留字段暂不使用
    * @param $BID       院区id      病区或分院，暂不使用
    * @return
    * {
        *     "errorcode":"00000000",
        *     "message":"获取二级科室成功",
      *       "data":[
      *         {"DeptID":"2b25226f-7786-488c-adb7-011b82805edb","DeptName":"外手DSA"},
      *         {"DeptID":"f181d762-4f14-4030-866b-01e0ace888c6","DeptName":"骨伤推拿门诊"},
      *         {"DeptID":"daf27b8f-fca0-423d-8163-02269fed68db","DeptName":"呼吸鼾症门诊"},
      *         {"DeptID":"2e7413e6-bfe0-49d7-9800-026a78b01396","DeptName":"过敏门诊"},
      *         {"DeptID":"4ab485cf-257f-4d76-a7aa-3592a9ccb780","DeptName":"性健康门诊"},
      *         {"DeptID":"c4448e9c-6f28-4db0-82d1-cc8b05b0b76e","DeptName":"骨伤推拿门诊"},
      *         {"DeptID":"316f90ec-df39-4f8d-9fa4-02ae4b78ba9a","DeptName":"南楼供应四室"},
      *         {"DeptID":"29a869ea-4306-48a2-8d77-02c2cd5cc694","DeptName":"保健部门诊"},
      *         {"DeptID":"5d29b101-d8a1-4d67-8d2d-0304be8c85e0","DeptName":"干部脑系门诊"},
      *         {"DeptID":"91ffd75a-6e4d-48e8-9d0f-035a7d9675d3","DeptName":"放射诊断质控中心"},
      *         {"DeptID":"0bd2bcff-924b-4aa8-82ad-2145fd6794ac","DeptName":"皮科门诊"},
      *         {"DeptID":"d79cfe98-d6d3-4409-9a17-84702ca82471","DeptName":"普通门诊(T)"}
        *     ]
        *   }
    */
    public function getTwoLevelDeptAction(){
      $p = $_REQUEST;
      $pTerminalCode  = empty($p['TerminalCode'])?Tool_Fnc::ajaxMsg('自助机编号'):Tool_Fnc::safe_string($p['TerminalCode']);
      $pBusType     = empty($p['BusType'])?Tool_Fnc::ajaxMsg('业务类型不能为空务'):Tool_Fnc::safe_string($p['BusType']);
      $pPatientID   = empty($p['PatientID'])?Tool_Fnc::ajaxMsg('患者id不能为空'):Tool_Fnc::safe_string($p['PatientID']);
      $pCDID      = empty($p['CDID'])?'':Tool_Fnc::safe_string($p['CDID']);
      $pIsEmergency   = empty($p['IsEmergency'])?'0':Tool_Fnc::safe_string($p['IsEmergency']);
      $pDeptType    = empty($p['DeptType'])?'1':Tool_Fnc::safe_string($p['DeptType']);
      $pBID       = empty($p['BID'])?'':Tool_Fnc::safe_string($p['BID']);

      $tDate = date('Ymd', time());
      $opts = [
        'ssl' => [
          // set some SSL/TLS specific options
          'verify_peer' => false,
          'verify_peer_name' => false,
          'allow_self_signed' => true
        ],
        'http'=>[ 'user_agent' => 'PHPSoapClient' ]
      ];

      $action = 'MES0008';
      try {
        $client = new SoapClient($this->SoapUrl,
          array(
            "trace" => 1, 
            "exception" => 1, 
            "cache_wsdl" => WSDL_CACHE_NONE, 
            'stream_context' => stream_context_create($opts)
          )
        );
      
        $p = $_REQUEST;
        $date = date("Y-m-d",strtotime("+1 days"));
        $registerdate = date("Y-m-d",time());

        //$tReq = '<root><head><TransID>RCK4031</TransID></head><body><CardTypeCode>1</CardTypeCode><CardNo>'.$PatientID.'</CardNo><PatientID></PatientID><Name></Name><StartDate>'.$registerdate.'</StartDate><EndDate>'.$registerdate.'</EndDate></body></root>';
        $tReq = "<Request>
          <TradeCode>1012</TradeCode>
          <ExtOrgCode></ExtOrgCode>
          <ClientType></ClientType>
          <HospitalId></HospitalId>
          <DepartmentType></DepartmentType>
          <DepartmentCode></DepartmentCode>
          <DepartmentGroupCode></DepartmentGroupCode>
          <ExtUserID></ExtUserID>
        </Request>";
        //Request Params
        $param = array(
          'action'  => $action,
          'message' => $tReq,
        );
        
        //Send Req
        $res = $client->HIPMessageServer($param);
        $result = simplexml_load_string($res->HIPMessageServerResult);
        $message =$result->ResultCode==0?'成功':"获取出诊科室失败" ;
        $errorCode = substr('00000000'.$result->ResultCode,-8);
        $tMO = new ApilogModel;
        $tData = array(
          'req' => json_encode($param),
          'rep' => json_encode($res),
          'funcode' => 'MES0008',
          'fundesc' => '挂号获取科室列表',
          'created' => date('Y-m-d H:i:s', time()),
          'cardno' => $PatientID,
        );
        $tMO->insert($tData);
        $index = 0;
        foreach ($result->Departments->Department as $key => $value) {
          $rows[$index]['DeptID']    = (string) $value->DepartmentCode;
          $rows[$index ++]['DeptName'] =(string) $value->DepartmentName;
        }
        $data = array('total' => $index, 'rows' =>$rows);
        Tool_Fnc::apiMsg($message,$errorCode,$data);
      } catch (SOAPFault $e) {
        print $e;
      }
      exit;

    }
    /**
    * 根据科室编号查询出诊医生信息列表(挂号用)
    * @param $TerminalCode  自助机编号
    * @param $MachineIP   终端ip
    * @param $PatientID   患者id
    * @param $DeptID    科室id
    * @return                 
    *   {
    *     "errorcode": "00000000",
    *     "message":"获取医生出诊成功",
    *     "data":{
    *       "total":2,
    *       "rows": [
    *         {
    *           "DeptID":"FEEEB729-BA1A-4D06-A32C-CCCD6F2B74BA",
    *           "DoctorName":"张三",
    *           "DoctorID":"FEEEB729-BA1A-4D06-A32C-CCCD6F2B74BA",
    *           "DoctorImageURL":"",
    *           "DoctorLevelName":"主任医师",
    *           "DoctorLevel":"01",
    *           "DoctorSpecialty":"医生信息说明",
    *           "APW":"A",
    *           "APWMeaning":"上午",
    *           "TotalFee":"13.00",
    *           "RemainsNum":"20",
    *           "RealID":"20",
    *           "VisitName":"主任号"
    *         },
    *         {
    *           "DeptID":"FEEEB729-BA1A-4D06-A32C-CCCD6F2B74BA",
    *           "DoctorName":"张三",
    *           "DoctorID":"FEEEB729-BA1A-4D06-A32C-CCCD6F2B74BA",
    *           "DoctorImageURL":"",
    *           "DoctorLevelName":"主任医师",
    *           "DoctorLevel":"01",
    *           "DoctorSpecialty":"医生信息说明",
    *           "APW":"A","APWMeaning":"上午",
    *           "TotalFee":"13.00",
    *           "RemainsNum":"0",
    *           "RealID":"20",
    *           "VisitName":"主任号"
    *         }
    *       ]
    *     }
    * }
    */
    public function getAppDoctorListByDeptAction(){
      $p = $_REQUEST;

      $pTerminalCode  = empty($p['TerminalCode'])?Tool_Fnc::ajaxMsg('自助机编号'):Tool_Fnc::safe_string($p['TerminalCode']);
      $pMachineIP   = empty($p['MachineIP'])?'':Tool_Fnc::safe_string($p['MachineIP']);
      $pPatientID   = empty($p['PatientID'])?Tool_Fnc::ajaxMsg('患者id不能为空'):Tool_Fnc::safe_string($p['PatientID']);
      $pDeptID    = empty($p['DeptID'])?'':Tool_Fnc::safe_string($p['DeptID']);


      $tDate = date('Ymd', time());
      $opts = [
        'ssl' => [
          // set some SSL/TLS specific options
          'verify_peer' => false,
          'verify_peer_name' => false,
          'allow_self_signed' => true
        ],
        'http'=>[ 'user_agent' => 'PHPSoapClient' ]
      ];
      $action = 'MES0009';
      try {
        $client = new SoapClient($this->SoapUrl, 
          array(
            "trace" => 1, 
            "exception" => 1, 
            "cache_wsdl" => WSDL_CACHE_NONE, 
            'stream_context' => stream_context_create($opts)
          )
        );

        $pCardTypeCode = 1;
        /** CardTypeCode =>
        * 1 院内诊疗卡
        * 2 银医卡
        * 3 二代身份证
        * 4 居民健康卡
        * 5 医保卡
        * 6 银行卡
        * 7 佛山健康卡
        * 8 省医保
        * 9 市医保
        */
        $pCardNo = $pPatientID;
        $pDeptCode = $pDeptID;


        $tDate = date('Ymd', time());
        $tReq = '<Request>
          <TradeCode>1013</TradeCode>
          <ExtOrgCode></ExtOrgCode>
          <ClientType></ClientType>
          <HospitalId></HospitalId>
          <ExtUserID></ExtUserID>
          <DepartmentCode>'.$pDeptCode.'</DepartmentCode>
        </Request>';
        //Request Params
        $param = array(
          'action'  => $action ,
          'message' => $tReq,
        );

        //Send Req
        $res = $client->HIPMessageServer($param);
        $result = simplexml_load_string($res->HIPMessageServerResult);
        /*接口日志START*/
        $tMO = new ApilogModel;
        $tData = array(
          'req' => json_encode($param),
          'rep' => json_encode($res),
          'funcode' => 'MES0009',
          'fundesc' => '获取科室医生列表',
          'created' => date('Y-m-d H:i:s', time()),
          'cardno' => $PatientID,
        );
        $tMO->insert($tData);
        /*接口日志END*/
        $index = 0;
        $rows=array();
        foreach ($result->Doctors->Doctor as $key => $value) {
          $pai = 0;
          for ($i=1; $i < 8; $i++) { 
            $action = 'MES0010';
            $tReq_doctor= '<Request>
            <TradeCode>1004</TradeCode>
            <ExtOrgCode></ExtOrgCode>
            <ClientType></ClientType>
            <HospitalId></HospitalId>
            <ExtUserID></ExtUserID>
            <StartDate>'.date('Y-m-d',strtotime("+{$i} day")).'</StartDate>
            <EndDate>'.date('Y-m-d',strtotime("+{$i} day")).'</EndDate>
            <DepartmentCode>'.$pDeptCode.'</DepartmentCode>
            <ServiceCode></ServiceCode>
            <DoctorCode>'.$value->DoctorCode.'</DoctorCode>
            <RBASSessionCode >Y</RBASSessionCode>
            <StopScheduleFlag>N</StopScheduleFlag>
            <PatientID>'.$pPatientID.'</PatientID>
            <SessType></SessType>
          </Request>';
            $param = array(
              'action'  => $action ,
              'message' => $tReq_doctor,
            );
            //Send Req
            $doctor_res = $client->HIPMessageServer($param);
            $doctor_result = simplexml_load_string($doctor_res->HIPMessageServerResult);
            $action = 'MES0011';
            $tReq_fs = '<Request>
                    <TradeCode>10041</TradeCode>
                    <ExtOrgCode></ExtOrgCode>
                    <ClientType></ClientType>
                    <HospitalId></HospitalId>
                    <ExtUserID></ExtUserID>
                    <DepartmentCode></DepartmentCode>
                    <DoctorCode></DoctorCode>
                    <RBASSessionCode></RBASSessionCode>
                    <ScheduleItemCode>'.(string)$doctor_result->Schedules->Schedule->ScheduleItemCode.'</ScheduleItemCode>
                    <ServiceDate></ServiceDate>
                  </Request>';
            $param = array(
              'action'  => $action ,
              'message' => $tReq_fs,
            );
            $fs_res = $client->HIPMessageServer($param);
            $fs_result = simplexml_load_string($fs_res->HIPMessageServerResult);
            if ($doctor_result->ResultCode==0&&$doctor_result->RecordCount>0&&$doctor_result->TimeRangeFlag==0&&$fs_result->ResultCode==0){
              $pai++;
            }
          }
            if($pai>0){
              $rows[$index]['DeptID']       = (string) $value->DeptId;
              $rows[$index]['DoctorName']     = (string) $value->DoctorName;
              $rows[$index]['DoctorID']       = (string) $value->DoctorCode;
              $rows[$index]['DoctorImageURL']   = '';
              $rows[$index]['DoctorLevelName']  = (string) $value->DoctorLevel;
              $rows[$index]['DoctorLevel']    = (string) $value->DoctotLevelCode;
              $rows[$index]['DoctorSpecialty']  = (string) $value->Description;
              $rows[$index]['APW']        = '';
              $rows[$index]['APWMeaning']     = '';
              $rows[$index]['TotalFee']       = '';
              $rows[$index]['RemainsNum']     = ''; //TODO: 中医院不限号，设置999
              $rows[$index]['RealID']       = ''; //TODO : 出诊id
              $rows[$index]['VisitName']      = (string) $value->DoctorLevel;
              $rows[$index]['TypeCode']       = '';
              $rows[$index]['TypeName']       = (string) $value->DoctorLevel;
              $rows[$index]['DeptCode']       = (string) $value->DeptId;
              $index ++;
            }
        }
        $message = (string) $result->ResultContent;
        $errorCode = substr('00000000'.$result->ResultCode,-8);
        $data = array('total' => $index, 'rows' =>$rows);
        Tool_Fnc::apiMsg($message,$errorCode,$data);
      } catch (SOAPFault $e) {
        print $e;
      }
      exit;

    }
    public function getAppDoctorListByDeptsAction(){
      $p = $_REQUEST;

      $pTerminalCode  = empty($p['TerminalCode'])?Tool_Fnc::ajaxMsg('自助机编号'):Tool_Fnc::safe_string($p['TerminalCode']);
      $pMachineIP   = empty($p['MachineIP'])?'':Tool_Fnc::safe_string($p['MachineIP']);
      $pPatientID   = empty($p['PatientID'])?Tool_Fnc::ajaxMsg('患者id不能为空'):Tool_Fnc::safe_string($p['PatientID']);
      $pDeptID    = empty($p['DeptID'])?'':Tool_Fnc::safe_string($p['DeptID']);


      $tDate = date('Ymd', time());

      try {
        $client = new SoapClient($this->SoapUrl);

        $pCardTypeCode = 1;
        /** CardTypeCode =>
        * 1 院内诊疗卡
        * 2 银医卡
        * 3 二代身份证
        * 4 居民健康卡
        * 5 医保卡
        * 6 银行卡
        * 7 佛山健康卡
        * 8 省医保
        * 9 市医保
        */
        $pCardNo = $pPatientID;
        $pDeptCode = $pDeptID;


        $tDate = date('Ymd', time());
        $tReq = '<root><head><TransID>RCK4032</TransID></head><body><CardTypeCode>2</CardTypeCode><CardNo>'.$pCardNo.'</CardNo><PatientID></PatientID><Name></Name><DeptCode>'.$pDeptCode.'</DeptCode></body></root>';
        $res = $client->RunMethod(array('Param'=>$tReq));

        /*接口日志START*/
        $tMO = new ApilogModel;
        $tData = array(
          'req' => $tReq,
          'rep' => json_encode($res),
          'funcode' => 'RCK4032',
          'fundesc' => '获取科室医生列表',
          'created' => date('Y-m-d H:i:s', time()),
          'cardno' => $PatientID,
        );
        $tMO->insert($tData);
        /*接口日志END*/
        $result = simplexml_load_string($res->RunMethodResult);
        print_r($result);die;
        $index = 0;
        foreach ($result->data->Rows as $key => $value) {
            $rows[$index]['DeptID']       = (string) $value->DeptCode;
            $rows[$index]['DoctorName']     = (string) $value->DoctorName;
            $rows[$index]['DoctorID']       = (string) $value->DoctorCode;
            $rows[$index]['DoctorImageURL']   = '';
            $rows[$index]['DoctorLevelName']  = (string) $value->TypeName;
            $rows[$index]['DoctorLevel']    = '';
            $rows[$index]['DoctorSpecialty']  = '';
            $rows[$index]['APW']        = '';
            $rows[$index]['APWMeaning']     = '';
            $rows[$index]['TotalFee']       = '';
            $rows[$index]['RemainsNum']     = ''; //TODO: 中医院不限号，设置999
            $rows[$index]['RealID']       = (string) $value->RegSourceID; //TODO : 出诊id
            $rows[$index]['VisitName']      = (string) $value->TypeName;
            $rows[$index]['TypeCode']       = '';
            $rows[$index]['TypeName']       = (string) $value->TypeName;
            $rows[$index]['DeptCode']       = (string) $value->DeptCode;
            $index ++;
        }
        $message = (string) $result->message;
        $errorCode = substr('00000000'.$result->errorCode,-8);
        $data = array('total' => $index, 'rows' =>$rows);
        Tool_Fnc::apiMsg($message,$errorCode,$data);
      } catch (SOAPFault $e) {
        print $e;
      }
      exit;

    }
    /**
     * 获取医生排班信息
     * @param   $fkh [description]
     * @param   $fkh [description]
     * @param   $fkh [description]
     * @param   $fkh [description]
     * @param   $fkh [description]
     * @return  $fkh [description]
     */
    public function getDocVisitAction(){
        $p = $_REQUEST;
        $DeptID   = empty($p['DeptID'])?Tool_Fnc::ajaxMsg('科室编号不能为空'):Tool_Fnc::safe_string($p['DeptID']);
        $DoctorID = empty($p['DoctorID'])?Tool_Fnc::ajaxMsg('医生编号不能为空'):Tool_Fnc::safe_string($p['DoctorID']);
        $VisitType  = empty($p['VisitType'])?Tool_Fnc::ajaxMsg('出诊类型不能为空'):Tool_Fnc::safe_string($p['VisitType']);
        $opts = [
        'ssl' => [
            // set some SSL/TLS specific options
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
          ],
          'http'=>[ 'user_agent' => 'PHPSoapClient' ]
        ];

        $action = 'MES0010';
        $tDate = date('Ymd', time());
        
        try {
            $client = new SoapClient($this->SoapUrl, 
              array(
                "trace" => 1, 
                "exception" => 1, 
                "cache_wsdl" => WSDL_CACHE_NONE, 
                'stream_context' => stream_context_create($opts)
              )
            );
            $index = 0;
            $rows=array();
            for ($i=1; $i < 8 ; $i++) { 
              $tReq = '<Request>
                  <TradeCode>1004</TradeCode>
                  <ExtOrgCode></ExtOrgCode>
                  <ClientType></ClientType>
                  <HospitalId></HospitalId>
                  <ExtUserID></ExtUserID>
                  <StartDate>'.date('Y-m-d',strtotime("+{$i} day")).'</StartDate>
                  <EndDate>'.date('Y-m-d',strtotime("+{$i} day")).'</EndDate>
                  <DepartmentCode>'.$DeptID.'</DepartmentCode>
                  <ServiceCode></ServiceCode>
                  <DoctorCode>'.$DoctorID.'</DoctorCode>
                  <RBASSessionCode ></RBASSessionCode>
                  <StopScheduleFlag>N</StopScheduleFlag>
                  <PatientID></PatientID>
                  <SessType></SessType>
                </Request>';
              $param = array(
                'action'  => $action,
                'message' => $tReq,
              );
              $res = $client->HIPMessageServer($param);
              $result = simplexml_load_string($res->HIPMessageServerResult);
              if($result->RecordCount>0&&$result->ResultCode==0){
                $rows[$index]['DeptID']       = (string) $result->Schedules->Schedule->DepartmentCode;
                $rows[$index]['DeptName']     = (string) $result->Schedules->Schedule->DepartmentName;
                $rows[$index]['DoctorID']     = (string) $result->Schedules->Schedule->DoctorCode;
                $rows[$index]['DoctorName']   = (string) $result->Schedules->Schedule->DoctorName;
                $rows[$index]['AppTime']      = (string) $result->Schedules->Schedule->SessionName;
                $rows[$index]['AppDate']      = (string) $result->Schedules->Schedule->ServiceDate;
                $rows[$index]['APW']          = '';
                $rows[$index]['APWMeaning']   = '';
                $rows[$index]['TotalFee']     = (string) $result->Schedules->Schedule->Fee;
                $rows[$index]['RemainsNum']   = ''; //TODO: 中医院不限号，设置999
                $rows[$index]['RealID']       = (string) $result->Schedules->Schedule->ScheduleItemCode; //TODO : 出诊id
                $rows[$index]['VisitName']    = (string) $result->Schedules->Schedule->DoctorSessType;
                $rows[$index]['TypeCode']     = (string) $result->Schedules->Schedule->DoctorSessTypeCode;
                $rows[$index]['TypeName']     = (string) $result->Schedules->Schedule->DoctorSessType;
                $rows[$index]['DeptCode']     = (string) $result->Schedules->Schedule->DepartmentCode;
                $index++;
              }
            }
            /*接口日志START*/
            $tMO = new ApilogModel;
            $tData = array(
            'req' => json_encode($param),
            'rep' => json_encode($res),
            'funcode' => 'MES0010',
            'fundesc' => '获取科室医生排班信息',
            'created' => date('Y-m-d H:i:s', time()),
            'cardno' => $PatientID,
            );
            $tMO->insert($tData);
            $data = array('total' =>count($rows), 'rows' =>$rows);
            $errorCode = empty($rows)?'00000001':"00000000";
            $message = empty($rows)?'暂无排版信息':"成功";
            Tool_Fnc::apiMsg($message,$errorCode,$data);
        } catch (SOAPFault $e) {
            Tool_Fnc::apiMsg('成功','00000000',array());
            print $e;
        }
    }
    
    public function getAppPeriodListAction(){
        $p = $_REQUEST;
          $PatientID    = empty($p['PatientID'])?Tool_Fnc::ajaxMsg('患者编号不能为空'):Tool_Fnc::safe_string($p['PatientID']);
          $DeptID       = empty($p['DeptID'])?Tool_Fnc::ajaxMsg('科室编号不能为空'):Tool_Fnc::safe_string($p['DeptID']);
          $DoctorID     = empty($p['DoctorID'])?Tool_Fnc::ajaxMsg('医生编号不能为空'):Tool_Fnc::safe_string($p['DoctorID']);
          $DeptName       = empty($p['DeptName'])?Tool_Fnc::ajaxMsg('科室名称不能为空'):Tool_Fnc::safe_string($p['DeptName']);
          $DoctorName     = empty($p['DoctorName'])?Tool_Fnc::ajaxMsg('医生姓名不能为空'):Tool_Fnc::safe_string($p['DoctorName']);
          $RealID       = empty($p['RealID'])?Tool_Fnc::ajaxMsg('出诊编号不能为空'):Tool_Fnc::safe_string($p['RealID']);
          $VisitType    = empty($p['VisitType'])?Tool_Fnc::ajaxMsg('出诊类型不能为空'):Tool_Fnc::safe_string($p['VisitType']);
          $tDate        = date('Ymd', time());
          $opts = [
          'ssl' => [
              // set some SSL/TLS specific options
              'verify_peer' => false,
              'verify_peer_name' => false,
              'allow_self_signed' => true
            ],
            'http'=>[ 'user_agent' => 'PHPSoapClient' ]
          ];
          $action = 'MES0011';
          $tReq = '<Request>
                    <TradeCode>10041</TradeCode>
                    <ExtOrgCode></ExtOrgCode>
                    <ClientType></ClientType>
                    <HospitalId></HospitalId>
                    <ExtUserID></ExtUserID>
                    <DepartmentCode></DepartmentCode>
                    <DoctorCode></DoctorCode>
                    <RBASSessionCode></RBASSessionCode>
                    <ScheduleItemCode>'.$RealID.'</ScheduleItemCode>
                    <ServiceDate></ServiceDate>
                  </Request>';
        try {
            $client = new SoapClient($this->SoapUrl, 
              array(
                "trace" => 1, 
                "exception" => 1, 
                "cache_wsdl" => WSDL_CACHE_NONE, 
                'stream_context' => stream_context_create($opts)
              )
            );
            $param = array(
              'action'  => $action,
              'message' => $tReq,
            );
            $res = $client->HIPMessageServer($param);
            /*接口日志START*/
            $tMO = new ApilogModel;
            $tData = array(
                'req' => json_encode($param),
                'rep' => json_encode($res),
                'funcode' => 'RCK4037',
                'fundesc' => '获取科室医生排班分时信息',
                'created' => date('Y-m-d H:i:s', time()),
                'cardno' => $PatientID,
            );
            $tMO->insert($tData);
            /*接口日志END*/
    
            $result = simplexml_load_string($res->HIPMessageServerResult);
            $message = $result->ResultCode==0?'成功':'失败';
            $errorCode = substr('00000000'.$result->ResultCode,-8);
            if ($result->ResultCode!=0) {
                Tool_Fnc::ajaxMsg($message,"00000001");
            }
            if (!empty($result->TimeRanges->TimeRange)) {
                $index = 0;
                foreach ($result->TimeRanges->TimeRange as $key => $value) {
                    if ( strtotime((string)$value->ServiceDate.' '.(string)$value->EndTime)>time()) 
                    {
                        if((string) $value->ScheduleItemCode != $RealID) continue;
                        $endTime = (string) $value->EndTime;
                        if(strtotime((string)$value->ServiceDate.' '.(string)$value->EndTime) <= time()) continue;

                        $rows[$index]['DeptID']       = (string) $DeptID;
                        $rows[$index]['DeptName']       = (string) $DeptName;
                        $rows[$index]['DoctorID']     = (string) $DoctorID;
                        $rows[$index]['DoctorName']     = (string) $DoctorName;
                        $rows[$index]['AppTime']      = (string) $value->SessionName;
                        $rows[$index]['AppDate']      = (string) $value->ServiceDate;
                        $rows[$index]['APW']          = '';
                        $rows[$index]['APWMeaning']   = '';
                        $rows[$index]['TotalFee']     = '';
                        $rows[$index]['RealID']       = (string) $value->ScheduleItemCode;
                        $rows[$index]['VisitName']    = (string) $value->RankName;
                        $rows[$index]['TypeCode']     = (string) $value->SessionCode;
                        $rows[$index]['TypeName']     = (string) $value->SessionName;
                        $rows[$index]['DeptCode']     = (string) $DeptID;

                        $beginTime = (string) $value->StartTime;
                        $Period = "{$beginTime} - {$endTime}";
                        $rows[$index]['PeriodMeaning'] = $Period;
                        $rows[$index]['RemainsNum']   = (string) $value->AvailableLeftNum; 

                        $AppointNo = (string) $value->AvailableNumStr;
                        list($QueueNo, $sec) = explode(',', $AppointNo, 2);
                        $rows[$index]['QueueNo']   = $QueueNo; 
                        $index ++;
                    }
                }
            }else{
                $rows=array();
            }
            
            $data = array('total' =>count($rows), 'rows' =>$rows);
            Tool_Fnc::apiMsg($message, $errorCode, $data);
        } catch (SOAPFault $e) {
            Tool_Fnc::apiMsg('成功','00000000',array());
            // print $e;
        }
    }
    public function getDocVisitssAction(){
      $p = $_REQUEST;
        $DeptID   = empty($p['DeptID'])?Tool_Fnc::ajaxMsg('科室编号不能为空'):Tool_Fnc::safe_string($p['DeptID']);
        $DoctorID = empty($p['DoctorID'])?Tool_Fnc::ajaxMsg('医生编号不能为空'):Tool_Fnc::safe_string($p['DoctorID']);
        $VisitType  = empty($p['VisitType'])?Tool_Fnc::ajaxMsg('出诊类型不能为空'):Tool_Fnc::safe_string($p['VisitType']);
        $client = new SoapClient($this->SoapUrl);
        $tDate = date('Ymd', time());
        $tReq = '<root>
              <head>
                <TransID>RCK4033</TransID>
              </head>
              <body>
                <DeptCode>'.$DeptID.'</DeptCode>
                <DeptName></DeptName>
                <DoctorCode>'.$DoctorID.'</DoctorCode>
                <DoctorName></DoctorName>
              </body>
            </root>';
      try {
        
        $res = $client->RunMethod(array('Param'=>$tReq));
        /*接口日志START*/
        $tMO = new ApilogModel;
        $tData = array(
          'req' => $tReq,
          'rep' => json_encode($res),
          'funcode' => 'RCK4033',
          'fundesc' => '获取科室医生排班信息',
          'created' => date('Y-m-d H:i:s', time()),
          'cardno' => $PatientID,
        );
        $tMO->insert($tData);
        /*接口日志END*/

        $result = simplexml_load_string($res->RunMethodResult);
        print_r($result);die;
        $message = (string) $result->message;
        $errorCode = substr('00000000'.$result->errorCode,-8);
        if ($result->errorCode!=0) {
          Tool_Fnc::ajaxMsg($message,$errorCode);
        }
        if (!empty($result->data->Rows)) {
          $index = 0;
          foreach ($result->data->Rows as $key => $value) {
            if ((string) $value->HaveCount!=0
              &&strtotime((string)$value->RegDate.' '.(string)$value->EndTime)>time()) {
              $rows[$index]['DeptID']   = (string) $value->DeptCode;
              $rows[$index]['DoctorID']   = (string) $value->DoctorCode;
              $rows[$index]['AppTime']  = (string) $value->SessionName;
              $rows[$index]['AppDate']  = (string) $value->RegDate;
              $rows[$index]['APW']        = '';
              $rows[$index]['APWMeaning']     = '';
              $rows[$index]['TotalFee']       = (string) $value->TotalRegFee;
              $rows[$index]['RemainsNum']     = ''; //TODO: 中医院不限号，设置999
              $rows[$index]['RealID']       = (string) $value->RegSourceID; //TODO : 出诊id
              $rows[$index]['VisitName']      = (string) $value->RankName;
              $rows[$index]['TypeCode']       = (string) $value->RankID;
              $rows[$index]['TypeName']       = (string) $value->RankName;
              $rows[$index]['DeptCode']       = (string) $value->DeptCode;
              $index ++;
            }
          }
        }else{
          $rows=array();
        }
        
        
        $data = array('total' =>count($rows), 'rows' =>$rows);
        Tool_Fnc::apiMsg($message,$errorCode,$data);
      } catch (SOAPFault $e) {
        Tool_Fnc::apiMsg('成功','00000000',array());
        print $e;
      }
    }
    public function confirmAppointOfflineAction(){
      $opts = [
        'ssl' => [
          // set some SSL/TLS specific options
          'verify_peer' => false,
          'verify_peer_name' => false,
          'allow_self_signed' => true
        ],
        'http'=>[ 'user_agent' => 'PHPSoapClient' ]
      ];

      $action = 'MES0021';
      try {
        //TODO: 挂号不收费，返回0
        // $data = array('OrderNo' => '0', 'OrderMoney'=>'0');
        $p = $_REQUEST;
        $TerminalCode = empty($p['TerminalCode'])?Tool_Fnc::apiMsg('终端号不能为空', '00000001'):Tool_Fnc::safe_string($p['TerminalCode']);
        $MachineIP = empty($p['MachineIP'])?'':Tool_Fnc::safe_string($p['MachineIP']);
        $SourceCode = empty($p['SourceCode'])?'':Tool_Fnc::safe_string($p['SourceCode']);
        $Age = empty($p['Age'])?Tool_Fnc::apiMsg('年龄不能为空', '00000001'):Tool_Fnc::safe_string($p['Age']);
        $CashPay = empty($p['CashPay'])?0:Tool_Fnc::safe_string($p['CashPay']);
        $RegCost = empty($p['RegCost'])?0:Tool_Fnc::safe_string($p['RegCost']);
        $Sex = empty($p['Sex'])?Tool_Fnc::apiMsg('性别不能为空', '00000001'):Tool_Fnc::safe_string($p['Sex']);
        $InsurePay = empty($p['InsurePay'])?0:Tool_Fnc::safe_string($p['InsurePay']);
        $AccountPay = empty($p['AccountPay'])?0:Tool_Fnc::safe_string($p['AccountPay']);
        $DeptName = empty($p['DeptName'])?Tool_Fnc::apiMsg('科室名称不能为空', '00000001'):Tool_Fnc::safe_string($p['DeptName']);
        $VisitTypeName = empty($p['VisitTypeName'])?'':Tool_Fnc::safe_string($p['VisitTypeName']);
        $DoctorName = empty($p['DoctorName'])?'':Tool_Fnc::safe_string($p['DoctorName']);
        $CheckCost = empty($p['CheckCost'])?'':Tool_Fnc::safe_string($p['CheckCost']);
        $BusinesType = empty($p['BusinesType'])?1:Tool_Fnc::safe_string($p['BusinesType']);
        $PatientName = empty($p['PatientName'])?Tool_Fnc::apiMsg('病人姓名不能为空', '00000001'):Tool_Fnc::safe_string($p['PatientName']);
        $YBMeaning = empty($p['YBMeaning'])?'':Tool_Fnc::safe_string($p['YBMeaning']);
        $TotalPay = empty($p['TotalPay'])?0:Tool_Fnc::safe_string($p['TotalPay']);
        $APWMeaning = empty($p['APWMeaning'])?'昼夜':Tool_Fnc::safe_string($p['APWMeaning']);
        $Address = empty($p['Address'])?'':Tool_Fnc::safe_string($p['Address']);
        $PatientID = empty($p['PatientID'])?Tool_Fnc::apiMsg('患者ID不能为空', '00000001'):Tool_Fnc::safe_string($p['PatientID']);
        $IDCardNo = empty($p['IDCardNo'])?'':Tool_Fnc::safe_string($p['IDCardNo']);
        $MedCard = empty($p['MedCard'])?'':Tool_Fnc::safe_string($p['MedCard']);
        $PhoneNo = empty($p['PhoneNo'])?'':Tool_Fnc::safe_string($p['PhoneNo']);
        $SpecQueueNo = empty($p['SpecQueueNo'])?'':Tool_Fnc::safe_string($p['SpecQueueNo']);
        $TypeName = empty($p['TypeName'])?'':Tool_Fnc::safe_string($p['TypeName']);
        $TypeCode = empty($p['TypeCode'])?'':Tool_Fnc::safe_string($p['TypeCode']);
        $DeptCode = empty($p['DeptID'])?Tool_Fnc::apiMsg('科室编号不能为空', '00000001'):Tool_Fnc::safe_string($p['DeptID']);
        $DoctorCode = empty($p['DoctorID'])?Tool_Fnc::apiMsg('医生编号不能为空', '00000001'):Tool_Fnc::safe_string($p['DoctorID']);
        $RealID = empty($p['RealID'])?Tool_Fnc::apiMsg('医生编号不能为空', '00000001'):Tool_Fnc::safe_string($p['RealID']);
        $DateTime = empty($p['DateTime'])?Tool_Fnc::apiMsg('预约时间不能为空', '00000001'):Tool_Fnc::safe_string($p['DateTime']);
        if ($Sex=='男') {
          $pSex = 1;
        }else if ($Sex=='女') {
          $pSex = 2;
        }else{
          $pSex = 3;
        }
        if(strlen($MedCard)==18){
          $cardtype = '02';
        }else{
          $cardtype = '03';
        }
        //HIS入参XML
        $tReq = "<Request>
          <TradeCode>1000</TradeCode>
          <ExtOrgCode></ExtOrgCode>
          <ClientType></ClientType>
          <HospitalId></HospitalId>
          <ExtUserID>{$TerminalCode}</ExtUserID>
          <TransactionId></TransactionId>
          <ScheduleItemCode>{$RealID}</ScheduleItemCode>
          <CardNo>{$MedCard}</CardNo>
          <CardType>{$cardtype}</CardType>
          <CredTypeCode></CredTypeCode>
          <IDCardNo></IDCardNo>
          <TelePhoneNo></TelePhoneNo>
          <MobileNo></MobileNo>
          <PatientName></PatientName>
          <PayFlag></PayFlag>
          <PayModeCode></PayModeCode>
          <PayBankCode></PayBankCode>
          <PayCardNo></PayCardNo>
          <PayFee></PayFee>
          <PayInsuFee></PayInsuFee>
          <PayInsuFeeStr></PayInsuFeeStr>
          <PayTradeNo></PayTradeNo>
          <LockQueueNo>{$SpecQueueNo}</LockQueueNo>
          <Gender></Gender>
          <Address></Address>
          <HISApptID></HISApptID>
          <SeqCode></SeqCode>
          <AdmitRange></AdmitRange>
        </Request>";
        $client = new SoapClient($this->SoapUrl, 
          array(
            "trace" => 1, 
            "exception" => 1, 
            "cache_wsdl" => WSDL_CACHE_NONE, 
            'stream_context' => stream_context_create($opts)
          )
        );
        $param = array(
          'action'  => $action,
          'message' => $tReq,
        );
        $res = $client->HIPMessageServer($param);
        $result = simplexml_load_string($res->HIPMessageServerResult);

        /*接口日志START*/
        $tMO = new ApilogModel;
        $tData = array(
          'req' => json_encode($param),
          'rep' => json_encode($res),
          'funcode' => 'MES0021',
          'fundesc' => '提交预约',
          'created' => date('Y-m-d H:i:s', time()),
          'cardno' => $PatientID,
          'name' => $PatientName,
        );
        $tMO->insert($tData);

        /*接口日志END*/

        if ((string)$result->ResultCode!=0) {
          Tool_Fnc::apiMsg((string)$result->ResultContent,'00000001');

        }
        $info = explode('^',$result->OrderContent);
        if ($Sex=="男") {
          $pSex = 1;
        }else{
          $pSex = 2;
        }
        /*预约如本地库*/
        $RegData = array(
          'me_re_date' => $DateTime,
          'me_re_de_id' => $DeptCode,
          'me_re_do_id' => $DoctorCode,
          'me_re_name' => $PatientName,
          'me_re_sex' => $pSex,
          'me_re_me_cardno' => $PatientID,
          'me_re_created' => time(),
          'me_re_updated' => time(),
          'me_re_status' => 4,
          'me_re_orderno' => explode('||',(string) $result->OrderCode)[2],
          'me_re_fee' => (string) $result->RegFee,
          'me_re_type' => 2,
          'me_re_no'=> explode('||',(string) $result->OrderCode)[2],
          'me_re_ydate' => $DateTime,
          'me_re_regid' => (string) $result->OrderCode."-2".(string) $result->TransactionId,
          'me_re_de_name' => $DeptName,
          'me_re_do_name' => $DoctorName,
          'me_re_ydate' => $DateTime,
          'me_typename' => $TypeName,
          'me_re_sessionname' =>$APWMeaning
        );
        $tRO = new RegisterModel;
        if(!$tRO->insert($RegData)){
          Tool_Fnc::apiMsg('系统繁忙请稍后再试！','00000001');
        }
        $data = array(
          'PatientID' => $PatientID,
          'IDNumber' => $IDCardNo,
          'HISPatientID' => $PatientID,
          'PatientName' => $PatientName,
          'SexMeaning' => $Sex,
          'Age' => $Age,
          'ChildAge' => '',
          'RegCode' => (string) $result->OrderCode,
          'VisitDate' => $DateTime,
          'APWMeaning' => $APWMeaning,
          'DeptName' => $DeptName,
          'DoctorName' => $DoctorName,
          'VisitTypeName' => $info['18'],
          'YBMeaning' => $YBMeaning,
          'MTMeaning' => (string) $result->AdmitRange,
          'SourceCodeMeaning' => '自助机',
          // 'QueueNo' => (string) $result->Body->SortNo,
          'QueueNo' => explode('||',(string) $result->OrderCode)[2],
          // 'QueueNoDesc' => (string) $result->Body->WaitTreatNo,
          'QueueNoDesc' => '',
          'InsurePay' => 0.0000,
          'AccountPay' => 0.0000,
          'CashPay' => 0.0000,
          // 'VisitAddress' => (string) $result->Body->TreatLocation,
          'VisitAddress' => (string) $result->AdmitAddress,
          'RegCost' => 0.0000,
          'CheckCost' => 0.0000,
          'TotalPay' =>(string) $result->RegFee,
          'OpTime' => date('Y-m-d T H => i => s',time()),
          'PayTypeMeaning' => '就诊卡',
          'PeriodMeaning' => '',
          'MedRecordNo' => $PatientID,
         );
        Tool_Fnc::apiMsg('挂号确认','00000000',$data);
      } catch (SOAPFault $e) {
        print $e;
      }
      exit;
        }
      public function PushAppointLineAction(){
        $p = $_REQUEST;
        $PatientID = empty($p['PatientID'])?Tool_Fnc::apiMsg('患者ID不能为空', '00000001'):Tool_Fnc::safe_string($p['PatientID']);
        $pTerminalCode  = empty($p['TerminalCode'])?Tool_Fnc::apiMsg('自助机编号不能为空','00000001'):Tool_Fnc::safe_string($p['TerminalCode']);
        $pMachineIP   = empty($p['MachineIP'])?'':Tool_Fnc::safe_string($p['MachineIP']);
        $AppointCode   = empty($p['AppointCode'])?Tool_Fnc::apiMsg('排队号不能为空','00000001'):Tool_Fnc::safe_string($p['AppointCode']);
        $tRO = new RegisterModel;
        $opts = [
          'ssl' => [
            // set some SSL/TLS specific options
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
          ],
          'http'=>[ 'user_agent' => 'PHPSoapClient' ]
        ];
        $action = 'MES0017';
        try{
            $sql = 'select * from register left join wxorder on register.me_re_regid=wxorder.doccon where content like \'%"AdmNo":"'.$AppointCode.'"%\'';
            $registerinfo = $tRO->query($sql);
            if(empty($registerinfo)){
              Tool_Fnc::apiMsg("非自助机系统挂号，无法退号","00000001");
            }
            $me_re_id = $registerinfo[0]['me_re_id'];
            $me_re_regid = $registerinfo[0]['me_re_regid'];
            $TransactionId = explode('||',$me_re_regid);
            $tReq = '<Request> 
              <TradeCode>1003</TradeCode>
              <ExtOrgCode></ExtOrgCode>
              <ClientType></ClientType>
              <HospitalId></HospitalId>
              <ExtUserID>'.$pTerminalCode.'</ExtUserID>
              <AdmNo>'.$AppointCode.'</AdmNo>
              <TransactionId>'.$TransactionId[1].'</TransactionId>
              <RefundType></RefundType>
            </Request>';
            $client = new SoapClient($this->SoapUrl, 
              array(
                "trace" => 1, 
                "exception" => 1, 
                "cache_wsdl" => WSDL_CACHE_NONE, 
                'stream_context' => stream_context_create($opts)
              )
            );
            $param = array(
              'action'  => $action,
              'message' => $tReq,
            );
            $res = $client->HIPMessageServer($param);
            $result = simplexml_load_string($res->HIPMessageServerResult);
            $tMO = new ApilogModel;
            $tData = array(
              'req' => json_encode($param),
              'rep' => json_encode($result),
              'funcode' => MES0017,
              'fundesc' => '退号接口',
              'created' => date('Y-m-d H:i:s', time()),
              'cardno' => $PatientID,
            );
            $tMO->insert($tData);
            $message = (string) $result->ResultContent;
            if((string) $result->ResultCode==0){
              $errorCode = '00000000';
              $message = "退号成功，您的挂号费用会自动退回原支付途径";
              $sql = "update register set me_re_status='5' where me_re_id='{$PatientID}'";
              $tRO->query($sql);
              $time = date('YmdHis',time());
              $refundTime = date('Y-m-d H:i:s',time());
              if (!empty($registerinfo)) {
                $refundman = $registerinfo[0]['TerminalCode'];
                $paytradeno = $registerinfo[0]['transaction_id'];
                $refundamt = $registerinfo[0]['money'];
                $hispayno = (string)$result->HisTradeNo;
                $url = "http://127.0.0.1:4419/apiv1_Ccbzf/CCBRefundTest?money=".$refundamt.'&orderno='.$paytradeno;
                $ch = curl_init();//初始化curl
                curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
                curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
                curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
                $data = curl_exec($ch);//运行cur
                $result = simplexml_load_string($data->head);
                curl_close($ch);
                $sql = "insert into pay (hospcode,time,refundamt,refundman,paytradeno,hispayno,refundtime,out_refund_no) values ('{$AppointCode}','{$time}','{$refundamt}','{$refundman}','{$paytradeno}','{$hispayno}','{$refundTime}','{$paytradeno}')";
                  $tRO->query($sql);
              }
            }else{
              $errorCode = '00000001';
            }
          Tool_Fnc::apiMsg($message,$errorCode);
        }catch (SOAPFault $e) {
          print $e;
        } exit;
      }
      /**
      * [GetAppointOUTlineAction 获取需要退号的记录]
      */
      public function GetAppointOUTlineAction(){
        $p = $_REQUEST;
        $PatientID = empty($p['PatientID'])?Tool_Fnc::apiMsg('患者ID不能为空', '00000001'):Tool_Fnc::safe_string($p['PatientID']);
        $pTerminalCode  = empty($p['TerminalCode'])?Tool_Fnc::apiMsg('自助机编号不能为空','00000001'):Tool_Fnc::safe_string($p['TerminalCode']);
        $pMachineIP   = empty($p['MachineIP'])?'':Tool_Fnc::safe_string($p['MachineIP']);
        $opts = [
          'ssl' => [
            // set some SSL/TLS specific options
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
          ],
          'http'=>[ 'user_agent' => 'PHPSoapClient' ]
        ];

        $action = 'MES0016';
        try {
        $tReq = "<Request>
  <TradeCode>1104</TradeCode>
  <ExtOrgCode></ExtOrgCode>
  <ClientType></ClientType>
  <HospitalId></HospitalId>
  <ExtUserID>{$pTerminalCode}</ExtUserID>
  <CardType></CardType>
  <PatientCard></PatientCard>
  <PatientID>{$PatientID}</PatientID>
  <StartDate>".date('Y-m-d',time())."</StartDate>
  <EndDate>".date('Y-m-d',strtotime("+7 day"))."</EndDate>
  <TransactionId></TransactionId>
  <AdmNo></AdmNo>
</Request>";
        $client = new SoapClient($this->SoapUrl, 
            array(
              "trace" => 1, 
              "exception" => 1, 
              "cache_wsdl" => WSDL_CACHE_NONE, 
              'stream_context' => stream_context_create($opts)
            )
          );
       //Request Params
        $param = array(
          'action'  => $action ,
          'message' => $tReq,
        );

        //Send Req
        $res = $client->HIPMessageServer($param);

        $result = simplexml_load_string($res->HIPMessageServerResult);
        $message = (string) $result->ResultContent;
        if((string) $result->ResultCode==0){
          $errorCode = '00000000';
        }else{
          $errorCode = '00000001';
        }

        $tMO = new ApilogModel;
        $tData = array(
          'req' => json_encode($param),
          'rep' => json_encode($result),
          'funcode' => MES0016,
          'fundesc' => '查询挂号记录',
          'created' => date('Y-m-d H:i:s', time()),
          'cardno' => $PatientID,
        );
        $tMO->insert($tData);
        if ($result->ResultCode!=0) {
          $data = array('total' => 0, 'rows' =>array());
          Tool_Fnc::apiMsg('暂未可取号信息','00000000',$data);
        }
        $rows = array();
        $index = 0;
        if (!empty($result->Orders->Order)) {
          
          foreach ($result->Orders->Order as $key => $value) {
            $Period = (string) $value->SessionName;
            if ($Period=='白天'||$Period=='全天') {
              $Period='07:00-20:00';
            }else{
              $Period=explode(" ",(string) $value->AdmitRange)[1];
            }
            if((string) $value->ReturnFlag=="Y"){
              $rows[$index]['DeptName'] = (string) $value->Department;
              $rows[$index]['DoctorName'] = (string) $value->Doctor;
              $rows[$index]['VisitTypeName'] = (string) $value->DoctorTitle;
              $rows[$index]['VisitTypeCode'] = (string) $value->Doctor;
              $rows[$index]['VisitDate'] = (string) $value->AdmitDate;
              //$rows[$index]['VisitDate'] = (string) $value->AdmitDate;
              $rows[$index]['APWMeaning'] = (string) $Period;
              $rows[$index]['APW'] = (string) $Period;
              $rows[$index]['PeriodMeaning'] = $Period;
              $rows[$index]['CashPay'] = (string) $value->RegFee;
              $rows[$index]['RegCost'] = (string) $value->RegFee;
              $rows[$index]['TotalPay'] = (string) $value->RegFee;
              $rows[$index]['CheckCost'] = (string) $value->RegFee;
              $rows[$index]['PeriodMeaning'] = (string) $value->SessionName;
              $rows[$index]['PeriodCode'] = $Period;
              $rows[$index]['BusType'] = 3;
              $rows[$index]['PatientName'] = (string) $value->Name;
              $rows[$index]['AppointStatus'] = 1;
              $rows[$index]['PatientID'] = $PatientID;
              $rows[$index]['AllowTakeTime'] = $Period;
              $rows[$index]['OrderNo'] = (string) $value->AdmNo;
              $rows[$index]['RegSourceID'] = (string) $value->AdmNo;
              $rows[$index]['DoctID'] = (string) $value->DoctorCode;
              $rows[$index]['DeptCode'] = (string) $value->DepartmentCode;
              $rows[$index]['DoctorCode'] = (string) $value->DoctorCode;
              $rows[$index]['RegDate'] = date('Y-m-d', time());
              $rows[$index]['RegDate'] = date('Y-m-d', time());
             // $rows[$index]['RegDate'] = (string) $value->AdmitDate;
              //$rows[$index]['OrderDate'] = (string) $value->AdmitDate;
              $rows[$index]['AppointCode'] = (string) $value->AdmNo;
              $rows[$index]['IsCost'] = 0;
              $rows[$index]['YBCode'] = 0;
              $index ++;
            }
          }
        }
        $data = array('total' => $index, 'rows' =>$rows);
        Tool_Fnc::apiMsg($message,$errorCode,$data);
      } catch (SOAPFault $e) {
        print $e;
      }
      exit;
    }     
        /**
         * [GetAppointOfflineAction 获取预约记录]
         */
      public function GetAppointOfflineAction(){
        $p = $_REQUEST;
        $PatientID = empty($p['PatientID'])?Tool_Fnc::apiMsg('患者ID不能为空', '00000001'):Tool_Fnc::safe_string($p['PatientID']);
        $pTerminalCode  = empty($p['TerminalCode'])?Tool_Fnc::apiMsg('自助机编号不能为空','00000001'):Tool_Fnc::safe_string($p['TerminalCode']);
        $pMachineIP   = empty($p['MachineIP'])?'':Tool_Fnc::safe_string($p['MachineIP']);
        $opts = [
          'ssl' => [
            // set some SSL/TLS specific options
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
          ],
          'http'=>[ 'user_agent' => 'PHPSoapClient' ]
        ];

        $action = 'MES0016';
        try {
        $tReq = "<Request>
  <TradeCode>1104</TradeCode>
  <ExtOrgCode></ExtOrgCode>
  <ClientType></ClientType>
  <HospitalId></HospitalId>
  <ExtUserID>{$pTerminalCode}</ExtUserID>
  <CardType></CardType>
  <PatientCard></PatientCard>
  <PatientID>{$PatientID}</PatientID>
  <StartDate>".date('Y-m-d',time())."</StartDate>
  <EndDate>".date('Y-m-d',strtotime("+7 day"))."</EndDate>
  <TransactionId></TransactionId>
  <AdmNo></AdmNo>
</Request>";
        $client = new SoapClient($this->SoapUrl, 
            array(
              "trace" => 1, 
              "exception" => 1, 
              "cache_wsdl" => WSDL_CACHE_NONE, 
              'stream_context' => stream_context_create($opts)
            )
          );
       //Request Params
        $param = array(
          'action'  => $action ,
          'message' => $tReq,
        );

        //Send Req
        $res = $client->HIPMessageServer($param);

        $result = simplexml_load_string($res->HIPMessageServerResult);
        $message = (string) $result->ResultContent;
        if((string) $result->ResultCode==0){
          $errorCode = '00000000';
        }else{
          $errorCode = '00000001';
        }

        $tMO = new ApilogModel;
        $tData = array(
          'req' => json_encode($param),
          'rep' => json_encode($result),
          'funcode' => MES0016,
          'fundesc' => '查询挂号记录',
          'created' => date('Y-m-d H:i:s', time()),
          'cardno' => $PatientID,
        );
        $tMO->insert($tData);
        if ($result->ResultCode!=0) {
          $data = array('total' => 0, 'rows' =>array());
          Tool_Fnc::apiMsg('暂未可取号信息','00000000',$data);
        }
        $rows = array();
        $index = 0;
        if (!empty($result->Orders->Order)) {
          
          foreach ($result->Orders->Order as $key => $value) {
            $Period = (string) $value->SessionName;
            if ($Period=='白天'||$Period=='全天') {
              $Period='07:00-20:00';
            }else{
              $Period=explode(" ",(string) $value->AdmitRange)[1];
            }
            if((string) $value->ReturnFlag=="Y"){
              $rows[$index]['DeptName'] = (string) $value->Department;
              $rows[$index]['DoctorName'] = (string) $value->Doctor;
              $rows[$index]['VisitTypeName'] = (string) $value->DoctorTitle;
              $rows[$index]['VisitTypeCode'] = (string) $value->Doctor;
              $rows[$index]['VisitDate'] = (string) $value->AdmitDate;
              //$rows[$index]['VisitDate'] = (string) $value->AdmitDate;
              $rows[$index]['APWMeaning'] = (string) $Period;
              $rows[$index]['APW'] = (string) $Period;
              $rows[$index]['PeriodMeaning'] = $Period;
              $rows[$index]['CashPay'] = (string) $value->RegFee;
              $rows[$index]['RegCost'] = (string) $value->RegFee;
              $rows[$index]['TotalPay'] = (string) $value->RegFee;
              $rows[$index]['CheckCost'] = (string) $value->RegFee;
              $rows[$index]['PeriodMeaning'] = (string) $value->SessionName;
              $rows[$index]['PeriodCode'] = $Period;
              $rows[$index]['BusType'] = 3;
              $rows[$index]['PatientName'] = (string) $value->Name;
              $rows[$index]['AppointStatus'] = 1;
              $rows[$index]['PatientID'] = $PatientID;
              $rows[$index]['AllowTakeTime'] = $Period;
              $rows[$index]['OrderNo'] = (string) $value->AdmNo;
              $rows[$index]['RegSourceID'] = (string) $value->AdmNo;
              $rows[$index]['DoctID'] = (string) $value->DoctorCode;
              $rows[$index]['DeptCode'] = (string) $value->DepartmentCode;
              $rows[$index]['DoctorCode'] = (string) $value->DoctorCode;
              $rows[$index]['RegDate'] = date('Y-m-d', time());
              $rows[$index]['RegDate'] = date('Y-m-d', time());
             // $rows[$index]['RegDate'] = (string) $value->AdmitDate;
              //$rows[$index]['OrderDate'] = (string) $value->AdmitDate;
              $rows[$index]['AppointCode'] = (string) $value->AdmNo;
              $rows[$index]['IsCost'] = 0;
              $rows[$index]['YBCode'] = 0;
              $index ++;
            }
          }
        }
        $data = array('total' => $index, 'rows' =>$rows);
        Tool_Fnc::apiMsg($message,$errorCode,$data);
      } catch (SOAPFault $e) {
        print $e;
      }
      exit;
    }        
    public function OprRgInfoAction(){
          $p = $_REQUEST;
      $PatientID = empty($p['PatientID'])?Tool_Fnc::apiMsg('患者ID不能为空', '00000001'):Tool_Fnc::safe_string($p['PatientID']);
      $MachineIP = empty($p['MachineIP'])?'':Tool_Fnc::safe_string($p['MachineIP']);
      $DoctorName = empty($p['DoctorName'])?Tool_Fnc::apiMsg('医生姓名不能为空','00000001'):Tool_Fnc::safe_string($p['DoctorName']);
      $APWMeaning = empty($p['APWMeaning'])?Tool_Fnc::apiMsg('预约时段不能为空','00000001'):Tool_Fnc::safe_string($p['APWMeaning']);
      $VisitTypeName  = empty($p['VisitTypeName'])?Tool_Fnc::apiMsg('预约时段不能为空','00000001'):Tool_Fnc::safe_string($p['VisitTypeName']);
      $PatientName  = empty($p['PatientName'])?Tool_Fnc::apiMsg('患者姓名不能为空','00000001'):Tool_Fnc::safe_string($p['PatientName']);
      $DeptName = empty($p['DeptName'])?Tool_Fnc::apiMsg('科室名称不能为空','00000001'):Tool_Fnc::safe_string($p['DeptName']);
      $RegSourceID  = empty($p['AppointCode'])?Tool_Fnc::apiMsg('预约编号不能为空','00000001'):Tool_Fnc::safe_string($p['AppointCode']);
      $OrderNo  = empty($p['OrderNo'])?Tool_Fnc::apiMsg('预约序号不能为空','00000001'):Tool_Fnc::safe_string($p['OrderNo']);
      $RegDate  = empty($p['RegDate'])?'':Tool_Fnc::safe_string($p['RegDate']);
      $OrderDate  = empty($p['OrderDate'])?'':Tool_Fnc::safe_string($p['OrderDate']);
      $REMD = new RegisterModel;
      // $data = $REMD->filed('me_re_canclereason')->where('me_re_me_cardno=\''.$PatientID.'\' and me_re_no=\''.$RegSourceID.'\'')->fRow();
      $sql = 'select me_re_canclereason from register where me_re_me_cardno=\''.$PatientID.'\' and me_re_no=\''.$RegSourceID.'\'';
      $data = $REMD->query($sql);
      $array=array(
          'PatientID' => $PatientID,
          'HISPatientID' => $PatientID,
          'PatientName' => $PatientName,
          'VisitDate' => date('Y-m-d',time()),
          'APWMeaning' => $APWMeaning,
          'DeptName' => $DeptName,
          'DoctorName' => $DoctorName,
          'VisitTypeName' => $VisitTypeName,
          'SourceCodeMeaning' => '自助机',
          'OpTime' => date('Y-m-d',time()),
          'PayTypeMeaning' => '就诊卡',
          'PeriodMeaning' => '',
          'MedRecordNo' => $PatientID,
          'QueueNo'=>$OrderNo,
          'WaitTreatNo'=>'',
          'VisitAddress' => $data[0]['me_re_canclereason'],
        );
      Tool_Fnc::apiMsg('成功','00000000',$array);

      
        }
        public function RegfeePredivisionOnlineAction(){
          // string str = "{\"errorcode\":\"00000000\",\"message\":\"挂号分割成功\",\"data\":{\"InsurePay\":\"10\",\"AccountPay\":\"3.0\",\"CashPay\":\"0.0\",\"DivisionID\":\"1000093304\",\"RegID\":\"110\",\"RegCost\":\"10.00\",\"CheckCost\":\"3.00\",\"TotalPay\":\"1.00\"}}";
          $p = $_REQUEST;
          $TerminalCode = empty($p['TerminalCode'])?'':$p['TerminalCode'];
          $MachineIP = empty($p['MachineIP'])?'':$p['MachineIP'];
          $IsEmergency = empty($p['IsEmergency'])?'':$p['IsEmergency'];
          $SourceCode = empty($p['SourceCode'])?'':$p['SourceCode'];
          $AppointType = empty($p['AppointType'])?'':$p['AppointType'];
          $PatientID = empty($p['PatientID'])?'':$p['PatientID'];
          $VisitDate = empty($p['VisitDate'])?'':$p['VisitDate'];
          $APW = empty($p['APW'])?'':$p['APW'];
          $PeriodCode = empty($p['PeriodCode'])?'':$p['PeriodCode'];
          $DeptCode = empty($p['DeptCode'])?'':$p['DeptCode'];
          $DoctorCode = empty($p['DoctorCode'])?'':$p['DoctorCode'];
          $VisitTypeCode = empty($p['VisitTypeCode'])?'':$p['VisitTypeCode'];
          $InsureTypeCode = empty($p['InsureTypeCode'])?'':$p['InsureTypeCode'];
          $MtTypeCode = empty($p['MtTypeCode'])?'':$p['MtTypeCode'];
          $AppointCode = empty($p['AppointCode'])?'':$p['AppointCode'];
          $opts = [
            'ssl' => [
              // set some SSL/TLS specific options
              'verify_peer' => false,
              'verify_peer_name' => false,
              'allow_self_signed' => true
            ],
            'http'=>[ 'user_agent' => 'PHPSoapClient' ]
          ];

          $action = 'MES0022';
          try {
          $tReq = "<Request>
            <TradeCode>1005</TradeCode>
            <ExtOrgCode></ExtOrgCode>
            <ClientType></ClientType>
            <HospitalId></HospitalId>
            <ExtUserID>{$TerminalCode}</ExtUserID>
            <CardNo></CardNo>
            <CardType></CardType>
            <CredTypeCode></CredTypeCode>
            <IDCardNo></IDCardNo>
            <PatientNo>{$PatientID}</PatientNo>
            <OrderApptStartDate></OrderApptStartDate>
            <OrderApptEndDate></OrderApptEndDate>
            <QueryDateFlag></QueryDateFlag>
            <QueryUserType></QueryUserType>
            <OrderStatus>normal</OrderStatus>
            <OrderCode></OrderCode>
          </Request>";
          $client = new SoapClient($this->SoapUrl, 
              array(
                "trace" => 1, 
                "exception" => 1, 
                "cache_wsdl" => WSDL_CACHE_NONE, 
                'stream_context' => stream_context_create($opts)
              )
            );
         //Request Params
          $param = array(
            'action'  => $action ,
            'message' => $tReq,
          );

          //Send Req
          $res = $client->HIPMessageServer($param);

          $result = simplexml_load_string($res->HIPMessageServerResult);
          $message = (string) $result->ResultContent;
          if((string) $result->ResultCode==0){
            $errorCode = '00000000';
          }else{
            $errorCode = '00000001';
          }

          $tMO = new ApilogModel;
          $tData = array(
            'req' => json_encode($param),
            'rep' => json_encode($result),
            'funcode' => MES0022,
            'fundesc' => '查询预约记录',
            'created' => date('Y-m-d H:i:s', time()),
            'cardno' => $PatientID,
          );
          $tMO->insert($tData);
        $rows = array();
        if (!empty($result->Orders->Order)) {
          foreach ($result->Orders->Order as $key => $value) {
            if ((string) $value->OrderCode."-2"==$AppointCode) {
              $Period = (string) $value->SessionName;
              if ($Period=='白天'||$Period=='全天') {
                $Period='08:00-5:30';
              }else if($Period=='上午'){
                $Period='08:00-11:30';
              }else if($Period=='下午'){
                $Period='12:00-5:30';
              }
              $rows['DeptName'] = (string) $value->Department;
              $rows['DoctorName'] = (string) $value->Doctor;
              $rows['VisitTypeName'] = (string) $value->DoctorTitle;
              $rows['VisitTypeCode'] = (string) $value->Doctor;
              $rows['VisitDate'] = (string) $value->AdmitDate;
              $rows['APWMeaning'] = (string) $Period;
              $rows['APW'] = (string) $Period."1";
              $rows['PeriodMeaning'] = $Period."2";
              $rows['CashPay'] = (string) $value->RegFee;
              $rows['RegCost'] = (string) $value->RegFee;
              $rows['TotalPay'] = (string) $value->RegFee;
              $rows['CheckCost'] = (string) $value->RegFee;
              $rows['InsurePay'] = 0;
              $rows['AccountPay'] = 0;
              $rows['PeriodMeaning'] = $Period."3";
              $rows['PeriodCode'] = $Period."4";
              $rows['BusType'] = 3;
              $rows['PatientName'] = (string) $value->Name;
              $rows['AppointStatus'] = 1;
              $rows['PatientID'] = $PatientID;
              $rows['AllowTakeTime'] = $Period;
              $rows['OrderNo'] = explode('||',(string) $value->OrderCode)[2];
              $rows['RegSourceID'] = (string) $value->OrderCode."-2";
              $rows['DoctID'] = '';
              $rows['DivisionID'] = '';
              $rows['DeptCode'] = '';
              $rows['DoctorCode'] = '';
              $rows['RegDate'] = (string) $value->AdmitDate;
              $rows['OrderDate'] = (string) $value->AdmitDate;
              $rows['AppointCode'] = (string) $value->OrderCode."-2";
              $rows['IsCost'] = 0;
              $rows['YBCode'] = 0;
              $rows['RegID'] = (string) $value->OrderCode."-2";
            }
          }
        }
        Tool_Fnc::apiMsg('挂号分割成功','00000000',$rows);
          }catch (SOAPFault $e) {
        print $e;
      }
      exit;
      }
      public function getTonicvoucherAction(){
      $p = $_REQUEST;
      $TerminalCode = empty($p['TerminalCode'])?Tool_Fnc::apiMsg('自助机编号不能为空', '00000001'):Tool_Fnc::safe_string($p['TerminalCode']);
      $PatientID = empty($p['PatientID'])?Tool_Fnc::apiMsg('患者id不能为空', '00000001'):Tool_Fnc::safe_string($p['PatientID']);
      $OrderNo = empty($p['OrderNo'])?'MZJF2019060410157575':Tool_Fnc::safe_string($p['OrderNo']);
      $MachineIP = empty($p['MachineIP'])?'':Tool_Fnc::safe_string($p['MachineIP']);
      $WMOD = new WxorderModel;
      $datetime = date('Y-m-d',time());
      $sql = "select * from wxorder where checkin_no='{$PatientID}' and time>'{$datetime}' and order_status=3 and checkin_no_type=1 order by id desc limit 0,1";
      $ZZJdata = $WMOD->query($sql);
      $opts = [
        'ssl' => [
          // set some SSL/TLS specific options
          'verify_peer' => false,
          'verify_peer_name' => false,
          'allow_self_signed' => true
        ],
        'http'=>[ 'user_agent' => 'PHPSoapClient' ]
      ];

      $action = 'MES0030';
      $client = new SoapClient('https://192.168.90.116:1443/csp/hsb/DHC.Published.ZZJService.BS.ZZJService.CLS?WSDL=1',
            array(
              "trace" => 1, 
              "exception" => 1, 
              "cache_wsdl" => WSDL_CACHE_NONE, 
              'stream_context' => stream_context_create($opts)
            )
          );
      $ADMarray = explode("||",$ZZJdata[0]['hiscode']);
      foreach($ADMarray as $key => $val){
        $adm = explode('-',$val);
          $tReq="<Request>
          <TradeCode>4907</TradeCode>
          <HospitalID>01</HospitalID>
          <CardNo></CardNo>
          <CardType></CardType>
          <SecrityNo>0</SecrityNo>
          <PatientID>{$PatientID}</PatientID>
          <UserCode>{$TerminalCode}</UserCode>
          <TerminalID>{$TerminalCode}</TerminalID>
          <StartDate>".date("Y-m-d",strtotime("-3 days"))."</StartDate>
          <EndDate>".date("Y-m-d",time())."</EndDate>
          <Adm>{$adm[0]}</Adm>
          <OrderNo></OrderNo>
          <InvoiceNo></InvoiceNo>
          <PrtInvNo></PrtInvNo>
          <ExpStr></ExpStr>
        </Request>";
        $param = array(
          'action'  => $action,
          'message' => $tReq,
        );
        //Send Req
        $res = $client->HIPMessageServer($param);

        $result = simplexml_load_string($res->HIPMessageServerResult);
        $message =$result->ResultCode==0?'成功':"暂无缴费明细" ;
        $errorCode = substr('00000000'.$result->ResultCode,-8);
      }
      $inpatientInfo = array(
          'FId'       => $ZZJdata[0]['doccon'],         //处方号
          'RecipeId'    => '',         //发票号
          'RecipeName'  => '',      //财务科目
          'RecipeTime'  => $ZZJdata[0]['time'],      //处方时间
          'TypeName'    => "自费",    //费用类型 自费
          'DeptName'    =>"",      //科室名称
          'DoctorName'  => '',      //医生姓名
          'SumPay'    => $ZZJdata[0]['money'],        //合计费用 "158.56",
          'MedicarePay' => '',     //医保支付 "0.00",
          'SelfPay'   => $ZZJdata[0]['money'],       //个人支付 "158.56",

          'RecipeNo'    =>  $ZZJdata[0]['doccon'],     //发票号
          'TotalMoney'  => $ZZJdata[0]['money'],      //合计费用 "158.56",
        );
        $index = 0;
        if (isset($result->RecordList->Record)) {
          foreach ($result->RecordList->Record as $key => $value) {
            $inpatientInfo['DeptName'] .=(string)$value->AdmDept."、";
            $inpatientInfo['DoctorName'] .=(string)$value->AdmDoctor."、";
            foreach($value->ItemList->Item as $k => $v){
              $rows[$index++] = array(
                'Index'  => (string) $v->ItemCode,     //明细项id "250101103",
                'Category'   => (string) $v->ItemCategory,   //明细项id "250101103",
                'Money'  =>(string) $v->ItemSum,        //备注 "020301"
                'Quantity'   => (string) $v->ItemQty,   //数量 "1",
                'UnitPrice'  => sprintf("%.2f",(string) $v->ItemPrice),    //单价 "17",q
                'Fee'   => (float) $v->ItemSum,     //合计 "17",
              );
            }
          }
        }
        $message = '成功';
        if (empty($rows)) {
          $rows = [];
          $message = '收费项为空';
        }

        $data = array(
          'chargeInfo' => $inpatientInfo, 
          'total' => $index, 
          'rows' => $rows
        );
        Tool_Fnc::apiMsg($message,'00000000',$data);
    }
    public function AppointLockAction(){
      $opts = [
        'ssl' => [
          // set some SSL/TLS specific options
          'verify_peer' => false,
          'verify_peer_name' => false,
          'allow_self_signed' => true
        ],
        'http'=>[ 'user_agent' => 'PHPSoapClient' ]
      ];

      $action = 'MES0012';
      try {
        $client = new SoapClient($this->SoapUrl, 
          array(
            "trace" => 1, 
            "exception" => 1, 
            "cache_wsdl" => WSDL_CACHE_NONE, 
            'stream_context' => stream_context_create($opts)
          )
        );
        //TODO: 挂号不收费，返回0
        // $data = array('OrderNo' => '0', 'OrderMoney'=>'0');
        $p = $_REQUEST;
        $TerminalCode = empty($p['TerminalCode'])?Tool_Fnc::apiMsg('终端号不能为空', '00000001'):Tool_Fnc::safe_string($p['TerminalCode']);
        $PatientID = empty($p['PatientID'])?Tool_Fnc::apiMsg('患者ID不能为空', '00000001'):Tool_Fnc::safe_string($p['PatientID']);
        $RealID = empty($p['RealID'])?Tool_Fnc::apiMsg('医生编号不能为空', '00000001'):Tool_Fnc::safe_string($p['RealID']);
        $MachineIP = empty($p['MachineIP'])?'':Tool_Fnc::safe_string($p['MachineIP']);
        $Sex = empty($p['Sex'])?0:Tool_Fnc::safe_string($p['Sex']);
        $DeptName = empty($p['DeptName'])?Tool_Fnc::apiMsg('科室名称不能为空', '00000001'):Tool_Fnc::safe_string($p['DeptName']);
        $DoctorName = empty($p['DoctorName'])?'':Tool_Fnc::safe_string($p['DoctorName']);
        $PatientName = empty($p['PatientName'])?Tool_Fnc::apiMsg('病人姓名不能为空', '00000001'):Tool_Fnc::safe_string($p['PatientName']);
        $YBMeaning = empty($p['YBMeaning'])?'':Tool_Fnc::safe_string($p['YBMeaning']);
        $IDCardNo = empty($p['IDCardNo'])?'':Tool_Fnc::safe_string($p['IDCardNo']);
        $TypeName = empty($p['TypeName'])?'':Tool_Fnc::safe_string($p['TypeName']);
        $TypeCode = empty($p['TypeCode'])?'':Tool_Fnc::safe_string($p['TypeCode']);
        $SpecQueueNo = empty($p['SpecQueueNo'])?'':Tool_Fnc::safe_string($p['SpecQueueNo']);
        $DeptCode = empty($p['DeptID'])?Tool_Fnc::apiMsg('科室编号不能为空', '00000001'):Tool_Fnc::safe_string($p['DeptID']);
        $DoctorCode = empty($p['DoctorID'])?Tool_Fnc::apiMsg('医生编号不能为空', '00000001'):Tool_Fnc::safe_string($p['DoctorID']);
        $DateTime = date('Y-m-d',time());
        $TradeTime = date('H:i:s',time());
        //HIS入参XML
        $tReq = "<Request><TradeCode>10015</TradeCode><ClientType></ClientType><HospitalID></HospitalID><TradeDate>{$DateTime}</TradeDate><TradeTime>{$TradeTime}</TradeTime><ExtUserID>{$TerminalCode}</ExtUserID><ScheduleItemCode>{$RealID}</ScheduleItemCode><AdmDoc></AdmDoc><PatientID>{$PatientID}</PatientID><CardNo></CardNo><CardType></CardType><CredTypeCode>1</CredTypeCode><IDCardNo></IDCardNo><TransactionId></TransactionId><OldTransactionId></OldTransactionId><Mobile></Mobile><LockQueueNo></LockQueueNo><PayOrdId></PayOrdId></Request>";
        //Request Params
        $param = array(
          'action'  => $action,
          'message' => $tReq,
        );
        $res = $client->HIPMessageServer($param);
        $result = simplexml_load_string($res->HIPMessageServerResult);
        //HIS入参XML
        if($Sex=='男'){
          $me_re_sex=1;
        }
        if($Sex=='女'){
          $me_re_sex=2;
        }
        $Age = Tool_Fnc::getAge($IDCardNo);
        /*接口日志START*/
        $tMO = new ApilogModel;
        $tData = array(
          'req' =>json_encode($param),
          'rep' => json_encode($res),
          'funcode' => 'MES0012',
          'fundesc' => '提交挂号',
          'created' => date('Y-m-d H:i:s', time()),
          'cardno' => $PatientID,
          'name' => $PatientName,
        );
        $tMO->insert($tData);

        /*接口日志END*/

        if (!$result) {
          Tool_Fnc::apiMsg('挂号失败','00000001');

        }
        // print_r($result);die;
        if ((string) $result->ResultCode!=0) {
          Tool_Fnc::apiMsg("锁号失败",'00000001');
        }
        $tMO->insert($tData);
        /*(
            [TradeCode] => 10015
            [TransactionId] => DHC222627221114182400
            [ResultCode] => 0
            [ResultContent] => 锁号成功
            [LockQueueNo] => 2
            [ScheduleItemCode] => 173||202
            [AdmDoc] => 副主任医师
            [AdmDate] => 2022-11-18
            [AdmTime] => 上午
            [RegFee] => 13
        )预约如本地库*/
        $RegData = array(
          'me_re_date' => $DateTime,
          'me_re_de_id' => $DeptCode,
          'me_re_do_id' => $DoctorCode,
          'me_re_name' => $PatientName,
          'me_re_sex' => $me_re_sex,
          'me_re_me_cardno' => $PatientID,
          'me_re_critcode' => $IDCardNo,
          'me_re_created' => time(),
          'me_re_updated' => time(),
          'me_re_status' => 4,
          'me_re_orderno' => (string) $result->LockQueueNo,
          'me_re_fee' => (string) $result->RegFee,
          'me_re_type' => 2,
          'me_re_no'=> (string) $result->LockQueueNo,
          'me_re_ydate' => $DateTime,
          'me_re_regid' => $RealID.'-'.(string) $result->TransactionId,
          'me_re_de_name' => $DeptName,
          'me_re_do_name' => $DoctorName,
          'me_re_ydate' => $DateTime,
          'me_typename' => $TypeName,
          'me_re_sessionname' =>(string) $result->AdmTime
        );
        $tRO = new RegisterModel;
        if(!$tRO->insert($RegData)){
          Tool_Fnc::apiMsg('系统繁忙请稍后再试！','00000001');
        }
        $data = array(
          'PatientID' => $PatientID,
          'IDNumber' => $IDCardNo,
          'HISPatientID' => $PatientID,
          'PatientName' => $PatientName,
          'SexMeaning' => $Sex,
          'Sex' => $Sex,
          'Age' => $Age,
          'ChildAge' => '',
          'RegCode' => (string) $result->LockQueueNo,
          'VisitDate' => (string) $result->AdmDate,
          'APWMeaning' => (string) $result->AdmTime,
          'DeptName' => $DeptName,
          'DoctorName' => $DoctorName,
          'VisitTypeName' =>(string) $result->AdmDoc,
          'YBMeaning' => $YBMeaning,
          'MTMeaning' => '',
          'SourceCodeMeaning' => '自助机',
          'QueueNo' => (string) $result->LockQueueNo,
          'QueueNoDesc' => '',
          'InsurePay' => 0.0000,
          'AccountPay' => 0.0000,
          'CashPay' => 0.0000,
          // 'VisitAddress' => (string) $result->Body->TreatLocation,
          'VisitAddress' => '',
          'RegCost' => (string) $result->RegFee,
          'CheckCost' => 0.0000,
          'TotalPay' => (string) $result->RegFee,
          'OpTime' => (string) $result->AdmDate,
          'PayTypeMeaning' => '就诊卡',
          'PeriodMeaning' => '',
          'MedRecordNo' => $PatientID,
          'RegID'=>(string) $RealID.'-'.(string) $result->TransactionId,
          'BusinesType'=>1
         );
        Tool_Fnc::apiMsg('预约确认','00000000',$data);
      } catch (SOAPFault $e) {
        print $e;
      }
    }
  }
 ?>
