/**
  * addOrder 
  * 
  * @param mixed $request 
  * @param mixed $response 
  * @author mq <*****@*****.**> 
  * @access public
  * @return void
  */
 public function addOrder($request, $response)
 {
     /*{{{*/
     $request->convertToGBK();
     $mobile = $request->buyerPhone;
     $product = DAL::get()->find('Product', $request->saId);
     DBC::requireFalse($product->isNull(), "产品不能为空");
     $user = $this->user;
     $patientId = 0;
     $patientId = $request->curPatientId4Tel;
     if (empty($patientId) && isset($request->patient['id'])) {
         $patientId = $request->patient['id'];
     }
     $rand = 0;
     //患者不存在情况,需创建患者
     if (empty($patientId)) {
         //用户不存在,则创建user并且登录
         if ($user->isNull()) {
             $rand = 1;
             setcookie("MyRand", "1", 0);
             $res = UserClient::getInstance()->createRandUser($mobile);
             $user = $res['user'];
             User::sendRegisterMsg($user->id);
             //自动登录
             UserClient::getInstance()->login($res['user']->name, $res['password']);
         }
         $patientInfo = array();
         $birthday = "{$request->dateyear}-{$request->datemonth}-{$request->dateday}";
         $patientInfo['name'] = $request->patient['name'];
         $patientInfo['sex'] = $request->patient['sex'];
         $patientInfo['province'] = $request->patient['province'];
         $patientInfo['city'] = $request->patient['city'];
         $patientInfo['birthday'] = $birthday;
         $patientInfo['relation'] = $request->patient['relation'];
         $patientInfo['mobile'] = $mobile;
         $params = $patientInfo;
         $patient = PatientClient::getInstance()->add($user, $params);
     } else {
         //用户不存在,则创建user并且登录
         $modifyPatientInfo = array();
         $existedPatientId = $request->existedPatientId;
         if (false == empty($existedPatientId)) {
             $modifyPatientInfo['name'] = $request->patient['name'];
             $modifyPatientInfo['sex'] = $request->patient['sex'];
             $modifyPatientInfo['province'] = $request->patient['province'];
             $modifyPatientInfo['city'] = $request->patient['city'];
             $birthday = "{$request->dateyear}-{$request->datemonth}-{$request->dateday}";
             $modifyPatientInfo['birthday'] = $birthday;
             $modifyPatientInfo['relation'] = $request->patient['relation'];
         }
         $modifyPatientInfo['mobile'] = $mobile;
         $patient = DAL::get()->find('patient', $patientId);
         PatientClient::getInstance()->modifyInfo($patient->id, $modifyPatientInfo);
     }
     //期望时间
     $expectedtimes = '';
     if ($request->expectedtime == 'other') {
         $expectedtimes = $request->expectedtimeInput;
     } else {
         $expectedtimes = $request->expectTimes;
     }
     $expectedtimeStr = "";
     if (false == empty($expectedtimes)) {
         foreach ($expectedtimes as $expectedtime) {
             $expectedtimeStr .= $expectedtime . ' ';
         }
     }
     $inconvenientTime = $request->inconvenientTime;
     if (false == empty($inconvenientTime)) {
         $expectedtimeStr .= '方便时间为:' . $request->inconvenientTime;
     }
     $src = Intention::SRC_WEB;
     $intention = IntentionClient::getInstance()->add4Tel($product, $patient, $expectedtimeStr, $request->diseaseDescription, $src, $request->disease);
     if ($intention->needPay()) {
         $response->setRedirect($response->router->urlfor('payment/showpaytype', array('sourceId' => $intention->id, 'sourceType' => "intention", 'rand' => $rand)));
     } else {
         $response->setRedirect($intention->getUrl());
     }
     return parent::DIRECT_OUTPUT;
 }
    public function newCaseWithMultiPatients($userId, $doctorId, $title, $tag, $content1, $content2, $content3, $attachmentIds, $deviceType, $patientId, $name, $sex, $relation, $province, $city, $mobile, $birthday)
    {/*{{{*/
		$request = new Request();

        /*********start*****修复错误数据:userId为0,手动修复userId,关联到的patient提示重新登录*********/
        if ($userId <= 0)
        {
            //错误数据:patient关联的userId为0,提示用户重新登录
            if (in_array($patientId, self::$patientIds))
            {
                $content = array('gotodetailnotice' => '您在好大夫在线的登陆账号存在安全隐患,我们已通过短信给您发送了新的账号和密码,如果未收的短信请等候或联系我们!');
                if ($request->os == 'ios')
                {
                    $content['sign'] = '1';
                }
                $this->content = $content;
                return 0;
            }
        }
        /*********end*******修复错误数据:userId为0,手动修复userId,关联到的patient提示重新登录*********/

        /*
		if($request->os == 'ios')
		{
			$ver = $request->v;
			error_log("[".XDateTime::now()."] ".print_r("userid=$userId, doctorid=$doctorId, title=$title, $tag, $content1, $content2, $content3, $attachmentIds, $deviceType, $patientId, $name, $sex, $relation, $province, $city, $mobile, $birthday, $ver", true)."\n", 3, "/tmp/whd1.log");
		}
        */
        if(strlen($name) > 20)
        {
            $this->setErrorCode(339);
            return 0;
        }
        $databucket = new Databucket(); 
        if($databucket->isThreadServiceSuspendTime())
        {
           $this->setErrorCode(901); 
           return 0;
        }
        $user = DAL::get()->find('user', $userId);
        if ($userId <=0 || $user->isNull())
        {    
            $this->setErrorCode(107);
            return 0;
        }    
        $errorcode = $this->checkPatientInfo4NewCase($patientId, $name, $sex, $relation, $province, $city, $birthday, $mobile);
        if($errorcode != 0)
        {
            $this->setErrorCode($errorcode);
            return 0;
        }
        if(0 == $patientId)
        {/*{{{*/
            $birthday = ($birthday != "") ? date('Y-m-d',$birthday) : "";
            $params = array(
                'name' => $name,
                'sex' => $sex,
                'relation' => $relation,
                'province' => $province,
                'birthday' => $birthday,
                'city' => $city,
                'mobile' => $mobile,
            );
            $patient = PatientClient::getInstance()->add($user, $params);
        }/*}}}*/
        else
        {
            if(isset($user->patients[$patientId]))
            {
                PatientClient::getInstance()->updateMobile($patientId, $mobile);
                $patient = $user->patients[$patientId];
            }
            else
            {
                $this->setErrorCode(316);
                return 0;
            }
        }
        $askSpace = new NullEntity();
        //兼容android客户端,doctorId传null字符串的bug
        if ($doctorId == 'null')
        {
            $doctorId = 0;
            $appVer = $request->v;
        }

        if($doctorId)
        {
            $doctor = DAL::get()->find('doctor', $doctorId);
            if($doctor->isNull())
            {
                $this->setErrorCode(132);
                return 0;
            }
            $askSpace = $doctor->space;
            if($askSpace->isNull())
            {
                $this->setErrorCode(144);
                return 0;
            }
            try
            {
                SpaceClient::getInstance()->ensureAllowAskRule($user, $askSpace);
            }
            catch(Exception $ex)
            {
                $this->setErrorCode(320);
                return 0;
            }
        }
        $options = array();
        $options['title'] = $title;
        $options['disease'] = $tag;
        $options['content'] = $content1;
        if ($content2)
        {
            $options['content'] .= "\n\n曾经治疗情况和效果:\n\n".$content2;
        }

        $options['attachmentIds'] = $attachmentIds;
        $options['facultyId'] = 0;
        //就诊过的医院
        $options['prehospital'] = '';
        if($askSpace->isNull() == false)
        {
            $options['facultyId'] = $askSpace->host->hospitalfaculty->faculty->id;
        }
        $options['deviceType'] = $deviceType;
        $options['title'] = htmlspecialchars_decode($options['title'], ENT_QUOTES);
        $options['disease'] = htmlspecialchars_decode($options['disease'], ENT_QUOTES);
        if(mb_strlen(XString::cntrim($options['title'])) < 5 || mb_strlen(XString::cntrim($options['title'])) > 10)
        {
            $this->setErrorCode(167);
            return 0;
        }
        if(mb_strlen(XString::cntrim($options['disease'])) < 1 || mb_strlen(XString::cntrim($options['disease'])) > 20)
        {
            $this->setErrorCode(304);
            return 0;
        }
        if ($user->isNull() || $patient->isNull())
        {
            error_log(print_r(debug_backtrace(), true), 3, '/tmp/ask_user_null.log');
            $this->setErrorCode(206);
            return 0;
        }
        $noticeAfterCase = "您的咨询将由网站医学助理按病情转交合适的医生回复。70%的咨询可在3天内得到医生回复,未回复的咨询将在7天后过期。如病情紧急建议直接去医院就诊。";

        /*加点患者提问成功扣分*/
        $res = ScoreClient::getInstance()->ask($user->id);
        $src = $deviceType;
        $hospital = $options['prehospital'];
        $disease = $options['disease'];
        $title = $options['title'];
        $content = $options['content'];
        $hopeHelp = $content3;
        if($options['attachmentIds'])
        {
            $attachmentIds = explode("," , $options['attachmentIds']); 
        }
        else
        {
            $attachmentIds = array();
        }
        $thread = IntentionClient::getInstance()->add4ThreadFromWap($patient, $askSpace, $src, $hospital, $content, $attachmentIds, $disease, $title, '', $hopeHelp);
        //todo::伪装展示
        $this->content = array('threadId' => $thread->id, 'caseType' => 'thread',  'sign' => 0, 'noticeAfterCase' => $noticeAfterCase);
        if ($thread->isNull())
        {
            $this->setErrorCode(169);
            return 0;
        }
    }/*}}}*/
 public function updateAttachment2Intention($request, $response)
 {/*{{{*/
     $id = $request->intentionId; 
     $attachmentIds = explode(',', $request->attachIds);
     $intention = DAL::get()->find('intention', $request->intentionId);
     if($intention->isNull())
     {
         $thread = DAL::get()->find('thread', $request->threadId);
         $intention = $thread->intention;  
         if($intention->isNull())
         {
             $intention = IntentionClient::getInstance()->thread2Intention4Front($thread);
         }
     }
     DBC::requireFalse(false == $intention->canModify(), "医生已回复,该咨询不能被修改");
     $attachmentIds = array_merge($attachmentIds, $intention->attachmentIds);
     $intention = IntentionClient::getInstance()->addContent2Intention($intention, 'web', '', $attachmentIds);
     if ($request->src == "detail")
     {
         $response->setRedirect($intention->getTouchUrl($this->touchDomain));
     }
     else
     {
         $response->setRedirect($response->router->urlfor('newcase/showintentionupdate', array('id' => $id)));
     }
 }/*}}}*/
 public function createIntentionRecord($request, $response)
 {
     /*{{{*/
     $request->convertToGBK();
     $sheets = $request->sheets;
     $phoneNumber = $request->phoneNumber;
     $answerSheetArr = WendaClient::getInstance()->processAnswerSheets($sheets, $this->curInspector);
     $answerSheet = reset($answerSheetArr['add']);
     $answer = $answerSheet->getAnswerByQuestionContent(IntentionRecord::$questionDesc[IntentionRecord::QUESTION_6]);
     $intentionRecord = IntentionClient::getInstance()->createIntentionRecord($answer->content, $this->curInspector, $phoneNumber, XDateTime::now(), $answerSheet->id);
     $url = $response->router->urlfor("intention/showintentionrecorddetail", array('answerSheetId' => $intentionRecord->answersheetId, 'inspectorUserName' => $intentionRecord->inspector->realName, 'startTime' => $intentionRecord->answeringTime));
     $response->setRedirect($url);
     return parent::DIRECT_OUTPUT;
 }
    public function orderPost($request, $response)
    {/*{{{*/
        $msg = $this->checkOrderPostInfo($request, $response);
        if($msg)
        {
            $this->message($msg, $response);
            return false;
        }

        $space = $this->_newSpace;
        $patient = $this->modifyPatientInfo($request, $response);
        if(false == $patient instanceof Patient)
        {
            $this->message($patient, $response);
            return false;
        }
        $date = $request->date;
		$registertime = $request->registertime;

        $schedule = 0;
        if ($registertime && $date)
        {
            $schedule = $date.' '.$registertime.':00';
        }

		$disease = $request->disease;
		$userCategory = $request->userCategory;
		$goal = array_sum($request->getRequest('goal', array()));
		$scheduleStr = $request->datetime;
		$address = $request->address;
		$lastHospitalOrLastTreatedTime = $request->lastHospital;
		$description = $request->description;
        $attachmentIds = $request->attachmentids;
        $attachmentIds = is_array($attachmentIds) ? $attachmentIds : explode(',', $attachmentIds); 
        $smsModel = $request->smsModel;
        $patientMobile = $patient->mobile; 
		$response->space = $space;

        if ($space->isBookingOpened() && !empty($schedule) && !empty($disease)) 
        {
            $lastHospital = BookingOrder::USER_CATEGORY_OLD == $userCategory? '': $lastHospitalOrLastTreatedTime;
            $lastTreatedTime = BookingOrder::USER_CATEGORY_OLD == $userCategory? $lastHospitalOrLastTreatedTime: '';

            $intention = IntentionClient::getInstance()->add4Booking($space->getValidBookingProduct(), $patient, $space, 
                $disease, $userCategory, $goal, $schedule, $scheduleStr, $address, $lastHospital, $lastTreatedTime, $smsModel, $description, 
                $attachmentIds, Intention::SRC_WEB, $patientMobile);
            $response->setRedirect($this->_newSpace->getUrl().'booking/ordersuccess?id='.$intention->id);
        }
        else 
        {
            $this->message('目前不能提交', $response, array('forward'=>"http://".URL_PREFIX."passport.haodf.com/mybooking/showorderdetail?id=".$request->id,'isJiaHao'=>true));
        }
    }/*}}}*/
    public function newPhoneCallOrderWithMultiPatients($userId, $doctorId, $contractId, $phoneNumber, $content, $deviceType, $patientId, $name, $birthday, $sex, $province, $city, $relation, $payType)
    {/*{{{*/
        if (in_array($patientId, self::$patientIds))
        {
            $this->setErrorCode(1000);
            return 0;
        }
        if(false == XString::isMobile(trim($phoneNumber)))
        {
            $this->setErrorCode(110);
            return 0;
        }
        $product = DAL::get()->find('product', $contractId);
        if($product->isNull())
        {
            $this->setErrorCode(300);
            return 0;
        }
        //没有电话分成合同
        if($product->contract->isNull() || $product->contract->isInvalid())
        {
            $this->setErrorCode(333);
            return 0;
        }
        if("" == trim($content))
        {
            $this->setErrorCode(302);
            return 0;
        }
        $user = DAL::get()->find('user', $userId);
		if ($user->isNull() || $user->id == 0)
		{
            $this->setErrorCode(107);
            return 0;
        }
        $source = Intention::SRC_IOS;
        if(strtolower($deviceType) == 'iphone')
        {
            $source = Intention::SRC_IOS;
        }
        else if(strtolower($deviceType) == 'ipad')
        {
            $source = Intention::SRC_IPAD;
        }
        else if(strtolower($deviceType) == 'android')
        {
            $source = Intention::SRC_ANDROID;
        }
        $expectedtimeStr = "越快越好";
        //创建或更新patient
        if(0 == $patientId)
        {
            $birthday = date('Y-m-d',$birthday);
            if("" == trim($name))
            {
                $this->setErrorCode(176);
                return 0;
            }
            if("" == trim($birthday))
            {
                $this->setErrorCode(171);
                return 0;
            }
            if("" == trim($sex))
            {
                $this->setErrorCode(172);
                return 0;
            }
            if("" == trim($province))
            {
                $this->setErrorCode(173);
                return 0;
            }
            if("" == trim($city))
            {
                $this->setErrorCode(174);
                return 0;
            }
            if("" == trim($relation))
            {
                $this->setErrorCode(175);
                return 0;
            }
            $patientInfo = array();
            $patientInfo['name'] = $name;
            $patientInfo['sex'] = $sex;
            $patientInfo['province'] = $province;
            $patientInfo['city'] = $city;
            $patientInfo['birthday'] = $birthday;
            $patientInfo['relation'] = $relation;
            $patientInfo['mobile'] = $phoneNumber;
            $params = $patientInfo;
            $patient = PatientClient::getInstance()->add($user, $params);
        }
        else
        {
            $modifyPatientInfo = array();
            $modifyPatientInfo['mobile'] = $phoneNumber;
            $patientId = $patientId;
            $patient = DAL::get()->find('patient', $patientId);
            PatientClient::getInstance()->modifyInfo($patient->id , $modifyPatientInfo);
        }
        $intention = IntentionClient::getInstance()->add4Tel($product, $patient, $expectedtimeStr, $content, $source);
        $this->content = array('id' => $intention->id);
    }/*}}}*/
 public function replenish($request, $response)
 {/*{{{*/
     $proposal = DAL::get()->find('proposal', $request->proposalid);
     $user = $this->user;
      DBC::requireEquals($this->user->id, $proposal->user->id, '你不能操作别人的数据');
     $content = $request->content;
     $attachmentIds = array_filter(explode(",", $request->attachmentIds));
     $src = Intention::SRC_WEB;
     $intention = IntentionClient::getInstance()->replenishByProposal($proposal, $src, $content, $attachmentIds);
     $url = $intention->getUrl();
     $url .= "&fromReplenish=1";
     $response->setRedirect($url);
 }/*}}}*/
 public function fenZhen400Intention($request, $response)
 {
     /*{{{*/
     $startTime = $request->intentionStartTime ? $request->intentionStartTime : '';
     $response->intentionStartTime = $startTime;
     $endTime = $request->intentionEndTime ? $request->intentionEndTime : '';
     $response->intentionEndTime = $endTime;
     $inspectorUserName = $request->inspectorUserName ? $request->inspectorUserName : '';
     $inspectorId = -1;
     if ($inspectorUserName) {
         $user = DAL::get()->find_by_fld_UserName('user', $inspectorUserName);
         $inspectorId = DAL::get()->find_by_userid('inspector', $user->id)->id;
     }
     $response->inspectorUserName = $inspectorUserName;
     $response->page = $request->page ? $request->page : 1;
     $res = IntentionClient::getInstance()->queryIntentionList4Fenzhen400(new XPager($response->page, $pageSize = 20), $startTime, $endTime, $inspectorId);
     $response->intentionList = $res['list'];
     $response->pageLink = '';
     $response->total = 0;
     if (false == empty($res['pageInfo'])) {
         $response->pageLink = PageNav::getNavLink(PageNav::getPageNavTemplate("fenzhen400intention?intentionStartTime={$startTime}&intentionEndTime={$endTime}&inspectorUserName={$inspectorUserName}&page="), $res['pageInfo']['nowpage'], $res['pageInfo']['pagesize'], $res['pageInfo']['total']);
         $response->total = $res['pageInfo']['total'];
     }
 }
Example #9
0
    public function newBookingOrder($userId, $doctorId, $schedule, $disease, $bookingGoal, $hospital, $userCategory, $description, $attachmentIds, $deviceType, $patientId)
    {/*{{{*/
        if (in_array($patientId, self::$patientIds))
        {
            $this->setErrorCode(1000);
            return 0;
        }

        if($this->isBookingServiceSuspendTime())
        {
           $this->setErrorCode(902); 
           return 0;
        }
        if ($userId <= 0)
        {
            $this->setErrorCode(107);
            return 0;
        }
        $user = DAL::get()->find('user', $userId);
        $patient = DAL::get()->find('patient', $patientId);
        if($patient->isNull() || $patient->user->id != $userId)
        {
            $this->setErrorCode(309);
            return 0;
        }
        $patientMobile = $patient->mobile;
        if ($user->isNull())
        {
            $this->setErrorCode(107);
            return 0;
        }
        $doctor = DAL::get()->find('doctor', $doctorId);
        $opend = $doctor->space->isBookingOpened();
        $spaceBusinessRequirement = $doctor->space->getSpaceBusinessRequirement4Booking();
        if(false == $opend || $spaceBusinessRequirement->isNull())
        {
            $this->setErrorCode(305);
            return 0;
        }
        $scheduleList = $spaceBusinessRequirement->serializedSchedule;
        $list = explode(",", $schedule);
        $date = $list[0];//日期
        $dateTime = $list[1];//上午,下午
        $showContent = self::getShowContent($date, $dateTime, $scheduleList);
        $registerTime = $showContent['registertime'];
        if($registerTime)
        {
            $schedule = $date.' '.$registerTime.':00';
        }
        else
        {
            $schedule = $date;
        }
        $address = $showContent['address'];
        $treatment = '无';
        $smsModel = isset($showContent['smsmodel']) ? $showContent['smsmodel'] : BookingOrder::SMSMODEL_OLD;
        $validateInput = (strlen($patientMobile) != 11) || $disease || $bookingGoal || $hospital || $description;
        if(false == $validateInput)
        {
            $this->setErrorCode(306);
            return 0;
        }
        $attachmentIds = explode(',', $attachmentIds);
        if (!empty($schedule) && !empty($disease)) {
            $lastHospital = BookingOrder::USER_CATEGORY_OLD == $userCategory? '': $hospital;
            $lastTreatedTime = BookingOrder::USER_CATEGORY_OLD == $userCategory? $hospital: '';
            $product = ProductClient::getInstance()->getFirstBookingProduct($doctor->space);

            $intention = IntentionClient::getInstance()->add4Booking($product, $patient, $doctor->space, $disease, 
                $userCategory, $bookingGoal, $schedule, $dateTime, $address, $lastHospital, $lastTreatedTime, 
                $smsModel, $description, $attachmentIds, $deviceType, $patientMobile);
            $info = array('orderId' => $intention->id);
            $this->content = $info;
        }else
        {
            $this->setErrorCode(307);
            return 0;
        }
    }/*}}}*/
Example #10
0
 public function creatNewOrderbyOldOrder($request, $response)
 {/*{{{*/
     $product = DAL::get()->mustFind('product', $request->productid);
     if ($product->isNull()) $this->exit();
     $proposal = DAL::get()->find('Proposal', $request->telOrderId);
     $ip = RequestDelegate::getIp();
     $intention = IntentionClient::getInstance()->createWithProduct($proposal->patient, $product, Intention::SRC_TOUCH, array(), $ip);
     NodeClient::getInstance()->copyFromSources($intention, array($proposal));//复制病例
     $response->setRedirect($response->router->urlfor('tel/payway', array('payableid'=>$intention->id)));
 }/*}}}*/
 public function replenish($request, $response)
 {/*{{{*/
     $intention = DAL::get()->find('intention', $request->intentionid);
     $user = $this->user;
     DBC::requireEquals($this->user->id, $intention->user->id, '你不能操作别人的数据');
     if($intention->isFromThread() && $intention->hasSpace())
     {
         DBC::requireTrue($intention->space->isCaseOpen(), '医生已经关闭咨询区,不能补充意向了');
     }
     $content = $request->content;
     $attachmentIds = array_filter(explode(",", $request->attachmentIds));
     $patient = $intention->patient;
     $intention = IntentionClient::getInstance()->replenishFromIntention($intention, Intention::SRC_WEB, $content, $attachmentIds);
     $url = $intention->getUrl();
     $url .= "&fromReplenish=1";
     $response->setRedirect($url);
 }/*}}}*/
    public function showList($request, $response)
    {/*{{{*/
        if ($response->isQQ)
        {
            $this->checkLogin($request, $response);
        }
        $isLogin = UserClient::getInstance()->isLogin();
        if ($isLogin == false)
        {
            $response->setRedirect('/thread/commonlogin.htm');
            return;
        }
        $user = UserClient::getInstance()->getCurrentUser();
        $patients = $user->patients;
        $patient = array_shift($patients);

        $caseInfos = array();
        $intentionList = IntentionClient::getInstance()->getIntentionListByUser($user, 1, 100);
        foreach ($intentionList['intentions'] as $intention)
        {
            $iInfo = array();
            $iInfo['ctime'] = $intention->ctime;
            $iInfo['id'] = $intention->id;
            $iInfo['title'] = $intention->title;
            $iInfo['userPostCount'] = 1;
            $iInfo['spacePostCount'] = 0;
            $iInfo['desc'] = $intention->isRefused()? '问题已经被拒绝':'等待医生回答中';
            $iInfo['doctorName'] = $intention->space->isNull()? '暂无': $intention->space->host->name;
            $iInfo['spaceUrl'] = $intention->space->isNull()? 'javascript:;':'/doctor/'.$intention->space->host->getEncodeId().'htm';
            $caseInfos[] = $iInfo;
        }

        $proposalInfos = DAL::get()->queryCtime2Ids('proposal', $user, ServiceDef::TYPE_FLOW, array(Proposal::STATUS_NORMAL));
        $proposalList = DAL::get()->find('proposal', array_values($proposalInfos));
        foreach ($proposalList as $proposal)
        {
            $pInfo = array();
            $pInfo['ctime'] = $proposal->ctime;
            $pInfo['id'] = $proposal->id;
            $pInfo['title'] = $proposal->title;
            $pInfo['userPostCount'] = 1;
            $pInfo['spacePostCount'] = 0;
            $pInfo['desc'] = '等待医生回答中';
            $pInfo['doctorName'] = $proposal->space->isNull()? '暂无': $proposal->space->host->name;
            $pInfo['spaceUrl'] = $proposal->space->isNull()? 'javascript:;':'/doctor/'.$proposal->space->host->getEncodeId().'htm';
            $caseInfos[] = $pInfo;
        }

        $dprList = FlowClient::getInstance()->getFlowsByUser($user);
        foreach ($dprList as $doctorPatientRef)
        {
            $dprInfo = array();
            $dprInfo['ctime'] = $doctorPatientRef->ctime;
            $dprInfo['id'] = $doctorPatientRef->id;
            $dprInfo['title'] = $doctorPatientRef->title;
            $dprInfo['userPostCount'] = $doctorPatientRef->postCount;
            $dprInfo['spacePostCount'] = $doctorPatientRef->spacePostCount;
            $dprInfo['desc'] = '医生已回答';
            $dprInfo['doctorName'] = $doctorPatientRef->space->isNull()? '暂无': $doctorPatientRef->space->host->name;
            $dprInfo['spaceUrl'] = $doctorPatientRef->space->isNull()? 'javascript:;':'/doctor/'.$doctorPatientRef->space->host->getEncodeId().'htm';
            $caseInfos[] = $dprInfo;
        }

        $response->user = $user;
        $response->patient = $patient;
        $response->caseInfos = $caseInfos;
    }/*}}}*/
    public function loadMoreIntentionList($request, $response)
    {/*{{{*/
        $patientId = $request->patientId;
        $patient = new NullEntity();
        $intentions = array();
        $pages = $totalCaseCnt = $loadUrl = '';
        $nowPage = $request->getRequest('p', 1);
        $response->nowPage = $nowPage;
        $pager = new XPager($nowPage, self::PAGESIZE_CASE);

        if(false == empty($patientId))
        {
            $patient = DAL::get()->mustFind('Patient', $patientId);
            DBC::requireTrue($this->user->id == $patient->user->id, '无效数据');
            $res = IntentionClient::getInstance()->getIntentionListByPateint($patient, $pager->nowPage, $pager->pageSize);
            $loadUrl = $response->touchUrl.'/intention/loadmoreintentionlist?patientId='.$patient->id.'&p=';
        }
        else
        {
            $res = IntentionClient::getInstance()->getIntentionListByUser($this->user, $pager->nowPage, $pager->pageSize);
            $loadUrl = $response->touchUrl.'/intention/loadmoreintentionlist?p=';
        }
        $intentions = $res['intentions'];

        $response->titleAndDisease = $this->getTitleAndDisease($intentions);
        $response->intentions = $intentions;
        $response->pages = isset($res['pageInfo']['pages'])?$res['pageInfo']['pages']:'0';
        $response->totalCaseCnt = isset($res['pageInfo']['total'])?$res['pageInfo']['total']:'0';
        $response->loadUrl = $loadUrl;
    }/*}}}*/
	public function askPost($request, $response)
	{/*{{{*/
        $preHostpital = $request->getRequest('case_prehospital', ''). " ".$request->getRequest('case_prekeshi', '');
        $isLogin = UserClient::getInstance()->isLogin();
        if (false == $isLogin)
        {
            $username = $request->patient['mobileOrEmail'];
            $password = $request->password;
            $this->_newUser = UserClient::getInstance()->register($username, $password);
            User::sendRegisterMsg($this->_newUser->id);
            $this->_newUser = UserClient::getInstance()->login($username, $password, false);
        }
        if ($this->_newUser->isNull())
        {
            throw new BizException('对不起,您的密码输入有误。建议您到好大夫在线取回密码');
        }

    	$spaceUserId = $request->getRequest('host_user_id', 0);
		$askSpace = DAL::get()->find('space', $spaceUserId);
		if ($askSpace->isNull())
		{
			$askSpace = DAL::get()->find('space', 0);
		}

        $options = array();
        $options['title'] = $request->getRequest('case_title', '');
        $options['disease'] = $request->getRequest('case_disease_tag', '');
        $options['prehospital'] = $preHostpital;
        $options['ExpireAction'] = $request->getRequest('case_expire_action');
        //post content; for unity
        $contents = "";
        foreach(IntentionContentsFix::$postRule as $id => $item)
        {
            $textAreaName =IntentionContentsFix::$textAreaNames[$id];
            $contents .= IntentionContentsFix::$postRule[$id]."\n".$request->$textAreaName;
        }
        $options['content'] = $contents;

		$options['allowSpaceReplyCount'] = '3';
		$options['attachmentIds'] = $request->getRequest('post_patient_attachment_ids', '');
        
		$caseTypeId = 0;
		$options['facultyId'] = $request->getRequest('host_user_faculty_id', 0);
		$out = array();
		$res = $this->_userIsAllowAsk($askSpace, $out, $response);
		if (false === $res) {
			return false;
		}
        $user = $this->_newUser;
        $patients = $user->patients;
        $patientInfos = array_shift($patients);
		if ($patientInfos == null || $patientInfos->isNull()) {
			$patient = $request->patient;
			if (empty($patient))
			{
                throw new BizException('系统忙,请重试');
			}

            $patient['birthday'] = $request->dateyear."-".$request->datemonth."-".$request->dateday;
            $params = array(
                'name' => $patient['name'],
                'sex' => $patient['sex'],
                'relation' => $patient['relation'],
                'province' => $patient['province'],
                'birthday' => $patient['birthday'],
                'city' => $patient['city'],
                'mobile' => $patient['mobileOrEmail'],
            );

            $patient = PatientClient::getInstance()->add($user, $params);
		} else {
			$patient = $patientInfos;
		}
		if ($this->_newUser->isNull())
		{
			error_log(print_r(debug_backtrace(), true), 3, '/tmp/ask_user_null.log');
            throw new BizException('系统忙,请重试');
		}

        $src = $_SERVER['HTTP_HOST'];
        $hospital = $options['prehospital'];
        $disease = $options['disease'];
        $content = $options['content'];
        $title = $options['title'];
        $attachmentIds = explode(',', $options['attachmentIds']);
        $askSpace = $askSpace;
        $intention = IntentionClient::getInstance()->add4ThreadFromWap($patient, $askSpace, $src, $hospital, $content, $attachmentIds, $disease, $title);
		if (false == $intention->isNull())
		{
            $response->setRedirect($response->router->urlfor('hzhospitalthread/askcomplete', array('id'=>$intention->id)));
		}
		else
        {
            throw new BizException('提交咨询出错,请重试');
        }
	}/*}}}*/
    /**
     * askPost 
     * 
     * @param mixed $request 
     * @param mixed $response 
     * @access public
     * @return void
     */
    public function askPost($request, $response)
    {/*{{{*/
        AskSessionInfo::checkBindDtos();

        $askSpace = AskSessionInfo::getBindSpace();
        $patient = AskSessionInfo::getBindPatient();

        if($patient->isNull())
        {
            $response->setRedirect($response->router->urlfor('newcase/askindex'));
            return false;
        }

        $bindBingLiDtos = AskSessionInfo::getBindDtos();
        if (empty($bindBingLiDtos))
        {
            $response->setRedirect($response->router->urlfor('newcase/askindex'));
            return false;
        }

        if(false == $askSpace->isNull())
        {
            $product = ProductClient::getInstance()->getFirstFlowProduct($askSpace);
        }
        else
        {
            $product = FirstFlowPoolVirtualProduct::fetch();
         //   $product = new FirstFlowPoolVirtualProduct();
        }

        $intention = IntentionClient::getInstance()->createWithProduct($patient, $product, Intention::SRC_WEB, $bindBingLiDtos);

        if(false == $intention->isNull())
        {
            AskSessionInfo::session_destroy();
            $response->setRedirect($response->router->urlfor('newcase/asksuccess', array('id'=>$intention->id)));
        }
        else
        {
            $this->message('提交医疗请求出错,请重试', $response);
        }
    }/*}}}*/
    public function newList($request, $response)
    {/*{{{*/
        $response->controller = 'Index';
        $response->object = 'flow';
        $this->initialize($request, $response);
        $this->forceSpaceModuleCheck('Case', $response);

        //threads总数和flow总数
        $threadsCount = ThreadClient::getInstance()->getUnSpacePostThreadsCount($this->_newSpace->id,
            $this->_newUser->id, array('isBrowser'=>$this->_newUser->isNull()));
        $flowsCount = FlowClient::getInstance()->getFlowListCount($this->_newSpace->id, array('p_type'=>'all', 'isBrowser'=>$this->_newUser->isNull()));
        $response->flowCount = $threadsCount + $flowsCount;

        $options = array();
        $options['filterUserId'] = $this->_newUser->id;
        $options['spaceId'] = $this->_newSpace->id;
        $nowPage = intval($request->getRequest('p', 1));
        $nowPage = $nowPage > 0 ? $nowPage : 1;
        $pageSize = 25;

        $freeFlowCount = FlowClient::getInstance()->getFreeFlowCntBySpace($this->_newSpace, $needCache = false);
        $chargeFlowCount = FlowClient::getInstance()->getPaiedFlowCntBySpace($this->_newSpace, $needCache = false);
        $response->chargeFlowCount = $chargeFlowCount;

        $threadOptions = array();
        $threadOptions['nowPage'] = $nowPage;
        $threadOptions['pageSize'] = $pageSize;
        if (false == $this->_newUser->isNull())
        {
            $threadOptions['excludeuser'] = $this->_newUser->id;
        }
        $unPostThreadList = ThreadClient::getInstance()->getUnSpacePostThreads($this->_newSpace->id, $this->_newUser->id, $threadOptions);
        $myThreadIds = array();
        if (false == $this->_newUser->isNull())
        {
            $myThreadIds = ThreadClient::getInstance()->getMyThreadInSpace($this->_newSpace->id, $this->_newUser->id);
        }
        $nowPageThreadCount = count($unPostThreadList);
        if ($nowPageThreadCount < $pageSize)
        {
            if ($nowPageThreadCount > 0)
            {
                $options['from'] = 0;
                $options['pageSize'] = $pageSize - $nowPageThreadCount;
            }
            else
            {
                $options['from'] = (($nowPage-1) * $pageSize == $threadsCount - count($myThreadIds)) ? 0 : (($nowPage - 1) * $pageSize - $threadsCount + count($myThreadIds)) ;
                $options['pageSize'] = $pageSize;
            }
            $res = FlowClient::getInstance()->getAllFlows($options);
            $flowList = $unPostThreadList + $res['refs'];
        }
        else
        {
            $flowList = $unPostThreadList;
        }

        $userSelfFlowCnt = 0;
        if(false == $this->_newUser->isNull())
        {
            $userSelfFlowCnt = FlowClient::getInstance()->getAllFlowCnt(array('spaceId' => $this->_newSpace->id, 'userId' => $this->_newUser->id));
        }

        $pageInfo = Pager::calcPageInfo(($freeFlowCount + $chargeFlowCount + $threadsCount - $userSelfFlowCnt), $nowPage, $pageSize);
        $response->pagelink = PageNav::getNavLink(PageNav::getPageNavTemplate("?&p="), $pageInfo['nowpage'], $pageInfo['pagesize'], $pageInfo['total']);

        $userSelf = array();
        //当前患者的流
        if($nowPage == 1 && $this->_newUser->isNull() == false && $this->_newUser->id != $this->_newSpace->user->id)
        {
            $userSelf = ThreadClient::getInstance()->getMyThreadAndFlowInSpace($this->_newSpace->id, $this->_newUser->id);
            if(false == empty($userSelf))
            {
                $response->lastPostList = DoctorPatientPostClient::getInstance()->getLastPosts4Flows(array_keys($userSelf));
            }
        }

        //取intention
        $intentionList = array();
        if(false == $this->_newUser->isNull())
        {
            $intentionList = IntentionClient::getInstance()->queryThreadIntentions($this->_newUser->id, '', '', $this->_newSpace->id);
        }

        $response->out = array_merge($intentionList, $userSelf , $flowList);
        $response->flowList = $response->out;
        $this->getCommonData($request, $response, $userSelf + $flowList);
    }/*}}}*/
 /**
     * @brief 补充意向(回复)
     * @author cs
     * @exampleUrl 
     *
     * @Param $intentionId 意向id
     * @Param $userId 用户id
     * @Param $content 补充的内容
     * @Param $attachmentIds  附件id数组
     * @Param $os 设备类型 ios  or  android
     *
     * @Returns  array('intentionId', 'userId') 
  */
 public function replenish($intentionId, $userId, $content, $attachmentIds, $os='ios')
 {/*{{{*/
     $intention = DAL::get()->find('intention', $intentionId);
     $user = DAL::get()->find('user', $userId);
     if ($intention->isNull())
     {
         $this->setErrorCode(700);
         return 0;
     }
     if ($user->isNull())
     {
         $this->setErrorCode(107);
         return 0;
     }
     if ($intention->user->id != $user->id)
     {
         $this->setErrorCode(701);
         return 0;
     }
     if ($content == '' && empty($attachmentIds))
     {
         $this->setErrorCode(702);
         return 0;
     }
     $source = Intention::SRC_ANDROID;
     if (array_key_exists($os, Intention::$srcDef))
     {
         $source = $os;
     }
     $attachmentIds = array_filter(explode(",", $attachmentIds));
     $intention = IntentionClient::getInstance()->replenishFromIntention($intention, $source, $content, $attachmentIds);
     if ($intention->isNull())
     {
         $this->setErrorCode(703);
         return 0;
     }
     $this->content = array('intentionId' => $intention->id, 'userId' => $intention->user->id);
 }/*}}}*/