<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class realHouse extends MY_Controller {

    public $price;
    /**
     * 当前页码
     *
     * @access private
     * @var string
     */
    private $_current_page = 1;

    /**
     * 每页条目数
     *
     * @access private
     * @var int
     */
    private $_limit = 10;

    /**
     * 偏移
     *
     * @access private
     * @var int
     */
    private $_offset = 0;

    /**
     * 条目总数
     *
     * @access private
     * @var int
     */
    private $_total_count = 0;
    private $f;

    public function __construct()
    {

        parent::__construct();
        $realHouse = $this->config->item('is_open_real_house');
        $this->load->model('broker_model');
        if($this->router->fetch_method() != 'notify')
        {
            $packageId = $this->user_arr['package_id'];
            //$realNumLimit =$this->broker_model->get_realnum_by_packageid($packageId);
            if (empty($realHouse)) {
                exit('暂未开放！');
            }
        }
        $this->price = 299;
        //加载支付模型类
        $this->load->model('payment_model');
        $this->load->model('real_house_model');
    }
    /**
     * 学规免罚考试
     */
    public function paper_index(){
        //特殊情况的经纪人可以参加
        $broker_all = array('BK67843','BK53310','BK42764','BK69307','BK92389','BK104742','BK77410','BK76396','BK37815','BK67387','BK50408','BK111605','BK69063','BK27568','BK84705','BK6367','BK94893','BK21385','BK91029','BK113553','BK51857','BK83777','BK57120','BK7682','BK93379','BK30661','BK8831','BK81612','BK80723','BK81444','BK69944','BK7613','BK82112','BK106994','BK13634','BK92215','BK104162','BK82286','BK110675','BK16937','BK8135','BK111069','BK63586','BK14093','BK26666','BK54369','BK7902','BK29008','BK57885','BK112108','BK53888','BK0739','BK25115','BK86463','BK62664','BK70002','BK60586','BK30819','BK61987','BK45792','BK52987','BK61768','BK41063','BK44805','BK92521','BK56193','BK100921','BK53986','BK22011','BK19142','BK69256','BK11261','BK97472','BK2249','BK67312','BK31785','BK67104');
        //经纪人参数
        $info = $this->user_arr;
        $broker_info = $this->real_house_model->getRealHouseInfo($info['uid']);
        //放心看状态
        $real_status = $broker_info['real_status'];
        if($real_status >= 1 || in_array($broker_info['username'],$broker_all)){
            //判定此人是否学规免罚获得通过
            $paper_score = $this->real_house_model->getPaperScoreRecord($info['uid']);
            if($paper_score){
                $this->jump('/realHouse/marginAccount/', '你已经参加过学规免罚活动！', 3000);
            }else{
                //判定此人是否学规免罚今天已考过一次
                $date = date('Ymd',time());
                $paper_today_record = $this->real_house_model->getPaperTodayScoreRecord($info['uid'],$date);
                if($paper_today_record){
                    $this->jump('/realHouse/marginAccount/', '休息一下，请您明天继续参与!', 3000);
                }
            }
        }else{
            $this->jump('/realHouse/marginAccount/', '请先开通放心看!', 3000);
        }

        //抽取所有题目
        $title_total = $this->real_house_model->getTotalPaperTitle();
        if($title_total){
            $total_count = count($title_total);
            $each_answer = array();
            for($i=0;$i<$total_count;$i++){
                //获取相应题目下的答案
                $each_answer[$i]['title_id'] = $title_total[$i]['id'];
                $each_answer[$i]['title'] = $title_total[$i]['title'];
                $each_answer[$i]['answer'] = $this->real_house_model->getPaperTitleAnswer($title_total[$i]['id']);
            }
            if($total_count >= 20){
                $rand_title_id = array_rand($each_answer,20);
            }else{
                $rand_title_id = array_rand($each_answer,$total_count);
            }

        }else{
            $this->jump('/realHouse/marginAccount/', '请耐心等待学规免罚考试开放！', 3000);
        }
        if($_POST){
            $all_value    = $_POST;
            $title_all_id = $all_value['title_id'];
            $error_value  = 0;
            $select_all   = array();
            for($i=0;$i<count($title_all_id);$i++){
                $title_id     = $title_all_id[$i];
                $right_answer =  $this->real_house_model->get_right_answer($title_id);
                //获取当题的详细信息
                $select_all[$i]   =  $this->real_house_model->getPaperInfo($title_id);
                //判断有几题不正确
                if($all_value['select_num_'.$title_id] != $right_answer){
                    $select_all[$i]['error_type'] = $this->real_house_model->num_contact($all_value['select_num_'.$title_id]);
                    $error_value++;
                }
            }
            $result      = serialize($select_all);
            $final_score = 100-($error_value*5);
            //插入考试日志表
            $data['broker_id']        = $info['uid'];
            $data['paper_result']     = $result;
            $data['score']            = $final_score;
            $data['paper_time']       = time();
            $data['paper_time_today'] = date('Ymd',time());
            $result_log_id            = $this->real_house_model->insertPaperResult($data);
            if($result_log_id){
                if($final_score == 100){
                    //通过学规免罚更新经纪人表
                    $this->real_house_model->updateBrokerFree($info['uid'], array('free_punish_num' => 1));
                    if(in_array($broker_info['username'],$broker_all)){
                        $this->real_house_model->updateBroker($info['uid'], array('real_status' => 2));
                        $this->real_house_model->updateBrokerStatus($info['uid'], array('status' => 1,'reason'=>0,'time'=>time()));
                        $this->jump('/realHouse/marginAccount/', '恭喜您通过考核，您已恢复放心看功能，快去使用吧！', 3000);
                    }else{
                        $this->jump('/realHouse/marginAccount/', '恭喜您通过考核，您获得一次免扣罚机会，将在您被扣罚时自动使用！', 3000);
                    }

                }else{
                    $this->jump('/realHouse/watch_paper_wrong/', '很遗憾您本次成绩为'.$final_score.'分，未通能过考核，您可明天继续参与！', 3000);
                }
            }else{
                $this->jump('/realHouse/marginAccount/', '请重新参与考试！', 3000);
            }
        }
        $data_page['paper_info_id'] = $rand_title_id;
        $data_page['paper_info']    = $each_answer;
        $data_page['css']           = load_css('zsb/css/v1.0/style1.css,zsb/css/v1.0/realhouse.css');
        $this->view('realHouse', 'realHouse_paper_index', $data_page);
    }

    //查看经纪人错题信息
    public function watch_paper_wrong(){
        //经纪人参数
        $info         = $this->user_arr;
        $wrong_info   = $this->real_house_model->getBrokerWrongTitle($info['uid']);
        $paper_result =  unserialize($wrong_info['paper_result']);
        $data_page['paper_result']  = $paper_result;
        $data_page['css']           = load_css('zsb/css/v1.0/style1.css,zsb/css/v1.0/realhouse.css');
        $this->view('realHouse', 'realHouse_paper_wrong_info', $data_page);
    }


    /**
     * 保证金管理
     */
    public function marginAccount()
    {

        //经纪人参数
        $info = $this->user_arr;
        $uid = $info['uid'];
        $realHouseMoney = $this->real_house_model->getBrokerRealHouseMoney($uid);
        $brokerLog = $this->real_house_model->getBrokerLog($uid);
		//放心看的数量
        $count = $this->real_house_model->getRealSell($uid);

        $this->load->model('zsb_api_model');

	    $info = $this->zsb_api_model->getRequrstData('realInfo');
		$data = $info['data'];
	    $unReportResult = $data['unReportResult'];
	    $remitCount = $data['remitCount'];
	    $is_applay = 0;
	    if($unReportResult<=0 && $remitCount<=0){
		    $is_applay = 1;
	    }
	    $data_page['statusList'] = array(
		    '0' => '待处理',
		    '1' => '已处理',
		    '2' => '成功',
		    '3' => '处理失败'
	    );
	    $real_status = $data['real_status'];
	    $money = $data['money'];
	    $real_house_money = $data['real_house_money'];
	    $data_page['real_status'] = $real_status;
	    $data_page['real_count'] = $count;
	    $data_page['is_applay'] = $is_applay;
	    $data_page['real_money'] = $money;
        $data_page['brokerLog'] = $brokerLog;
        $data_page['realHouseMoney'] = $real_house_money;
        $data_page['page_title'] = '放心看管理-保证金账户';
        $data_page['css'] = load_css('zsb/css/v1.0/style1.css,zsb/css/v1.0/realhouse.css');
        $data_page['info'] = $info;
        $this->view('realHouse', 'realHouse_marginAccount', $data_page);
    }

    /**
     * 举报记录
     */
    public function reportRecord()
    {
        $model_param = $this->input->post();
        $data_page = $model_param;

        //经纪人参数
        $info = $this->user_arr;
        $this->load->helper(array('form', 'url'));
        //定义搜索条件
        $data_page['searchList'] = array('99' => '选择查询条件') + array('rowId' => '房源编号');
        $data_page['typeList'] = array('99' => '选择举报原因') + array('0' => '房源不可看', '1' => '价格不准确', '2' => '图片不真实', '3' => '描述不真实');
        //$data_page['reportList'] = array('99' => '选择处理结果') + array('1' => '举报成功(扣罚)', '2' => '举报失败', '0' => '待处理' ,'3'=> '举报成功(不扣罚)');
        $data_page['reportList'] = array('99' => '选择处理结果') + array('1' => '举报成功(扣罚)', '2' => '举报失败', '0' => '待处理');
        $data_page['reportListArr'] = array('99' => '选择处理结果') + array('1' => '举报成功(扣罚)', '2' => '举报失败', '0' => '待处理' ,'3'=> '举报成功(不扣罚)');
        $data_page['appealList'] = array('99' => '选择申诉状态') + array('0' => '未申诉', '1' => '已申诉', '2' => '申诉成功', '3' => '申诉失败');
        //$searchData = array('uid' => $info['uid'], 'note' => 1);

        //获取参数
        /*if (!empty($_POST)) {
            $data_page['search'] = $this->input->post('search', true);
            $data_page['keyword'] = $this->input->post('keyword', true);
            $data_page['type'] = $this->input->post('type', true);
            $data_page['report_result'] = $this->input->post('report_result', true);
            $data_page['appeal'] = $this->input->post('appeal', true);

            if (!empty($data_page['search']) && !empty($data_page['keyword'])) {
                $searchData['rowid'] = intval($data_page['keyword']);
            }
            if ( (!empty($data_page['type']) || $data_page['type'] == '0') && $data_page['type'] != 99) {
                $searchData['type'] = intval($data_page['type']);
            }
            if ( (!empty($data_page['report_result']) || $data_page['report_result'] == '0') && $data_page['report_result'] != 99) {
                $searchData['report_result'] = intval($data_page['report_result']);
            }
            if ( (!empty($data_page['appeal']) || $data_page['appeal'] == '0') && $data_page['appeal'] != 99) {
                $searchData['appeal'] = intval($data_page['appeal']);
            }
        }*/
        //分页参数
        $page = $this->input->post( 'page' , TRUE);
        $page = (isset($page)&& intval($page) > 0) ? intval($page) : 1;
        $this->_init_pagination($page);

        $model_param['page'] = $page;
        $model_param['limit'] = $this->_limit;
        $this->load->model('zsb_api_model');
        $resReportRecord = $this->zsb_api_model->getRequrstData('reportRecord', $model_param);

        $this->_total_count = $resReportRecord['data']['page_info']['total'];

        //$this->_total_count = $this->real_house_model->getReportCount($searchData);
        //$reportData = $this->real_house_model->getReport($searchData, $this->_offset, $this->_limit);
        $pages  = $this->_total_count > 0 ? ceil( $this->_total_count / $this->_limit ) : 0;
        //是否显示分页
        $pagination = NULL;
        if ($this->_total_count > $this->_limit) {
            $pagination = helper_pagination( $this->_current_page , $pages , $this->_total_count );
        }
        $data_page['realHouseMoney'] = $this->real_house_model->getBrokerRealHouseMoney($this->user_arr['uid']);
        $data_page['reportData'] = $resReportRecord['data']['page_data'];
        $data_page['page_title'] = '放心看管理-举报记录';
        $data_page['css'] = load_css('zsb/css/v1.0/style1.css,zsb/css/v1.0/realhouse.css,zsb/css/v1.0/feedback.css');
        $data_page['js'] = load_js('common/js/swf/swfupload.js,zsb/js/v1.0/swfu.js,zsb/js/v1.0/handlers.js');
        $data_page['info'] = $info;
        $data_page['page']  = $this->_current_page;
        $data_page['pagination'] = $pagination;
        $this->view('realHouse', 'realHouse_reportRecord', $data_page);
    }


    /**
     * 申述Ajax
     */
    public function appealAjax()
    {
        $model_param = $this->input->get();
        $this->load->model('zsb_api_model');
        $res = $this->zsb_api_model->getRequrstData('reportRecordAppeal', $model_param);

        /*$tbl = $this->input->get( 'tbl' , TRUE);
        $houseId = $this->input->get( 'houseId' , TRUE);

        $searchData['uid'] = $this->user_arr['uid'];
        $searchData['note'] = 1;
        $searchData['rowid'] = intval($houseId);
        $searchData['tbl'] = $tbl;
        $searchData['report_result'] = 0;
        $searchData['appeal'] = 0;
        $data = $this->real_house_model->getReport($searchData, 0, 10, 'id,tbl,rowid,type,report_result,reason,appeal,report_time');
        $typeList = array('0' => '房源不可看', '1' => '价格不准确', '2' => '图片不真实', '3' => '描述不真实');
        foreach ($data as $key => $value) {
            $data[$key]['reason'] = iconv('gbk', 'utf8', $value['reason']);
            $data[$key]['type'] = iconv('gbk', 'utf8', $typeList[$value['type']]);
            $data[$key]['report_time'] = date('Y-m-d H:i:s', $value['report_time']);
        }
        //查看该房源是否申请过实勘
        $this->load->model('sell_model');
        $houseInfo = $this->sell_model->find_by_id(intval($houseId));
        $result['appealed'] = $houseInfo['is_true_visit'] > 0 ? 1 : 0;
        $result['status'] = 1;
        $result['data'] = $data;*/

        echo json_encode($res['data']);exit;
    }

    /**
     * 申请提现
     */
    public function applyRemit(){
        $type = $this->input->post( 'type' , TRUE);
        $result['status'] = 0;
        $result['msg'] = '';
        $result['data'] = array();

        $this->load->model('sell_model');

        $rre = $this->sell_model->broker_real_frozen(1);
        if(!$rre['code']){
            $result['msg'] = iconv('gbk','utf8',$rre['msg']);
            echo json_encode($result);exit;
        }

        //学规免罚使用记录
        $use_log = $this->real_house_model->getBrokerUselog($this->user_arr['uid']);
        if($use_log){
            $time_limit = $use_log['end_time'];
            $time_limit2= $time_limit;
            if($time_limit > time()){
                $msg = '由于您使用学规免罚功能，在'.date("m月d日",$time_limit2).'前您无法申请提现!';
                $result['msg'] = iconv('gbk','utf8',$msg);
                echo json_encode($result);exit;
            }
        }
        // 2018年7月21日 10:16:58  xzk  qq724087709
        $realHouseInfo = $this->real_house_model->getRealHouseInfo($this->user_arr['uid']);
        if(!$realHouseInfo['real_status']>0){
            $msg = '未开通放心看';
            $result['msg'] = iconv('gbk','utf8',$msg);
            echo json_encode($result);exit;
        }

        //判断是否有足够的保证金
        $realHouseMoney = $realHouseInfo['real_house_money'];
        if ($realHouseMoney < $this->price) {
            $msg = '保证金余额不足';
            $result['msg'] = iconv('gbk','utf8',$msg);
            echo json_encode($result);exit;
        }

        //判断是否有支付宝账号

        $session_info = $this->broker_model->get_user_session();

        if(empty($session_info['alipay_acount'])){
            $msg = '亲爱的经纪人您好，支付宝支付3个月后及微信支付12个月后的保证金提现，直接打入您提供的支付宝账号内，请立<a  target="_blank"  href="/ucenter_information/index/"><span style="color: red;">立即维护</span></a>支付宝账户信息！';
            $result['msg'] = iconv('gbk','utf8',$msg);
            echo json_encode($result);exit;
        }

        //判断是否有房源为待处理状态
        $searchData = array();
        $searchData['uid'] = $this->user_arr['uid'];
        $searchData['report_result'] = 0;
        $count = $this->real_house_model->getReportCount($searchData);
        if ($count > 0) {
            $msg = '很抱歉！您账号中有'. $count .'条房源正处虚假审核处理中，处理完毕后即可进行提现申请，请您耐心等待！如有任何疑问，请电话咨询： '. $this->getPhone(4);
            $result['msg'] = iconv('gbk','utf8',$msg);
            echo json_encode($result);exit;
        }
        if ($type == 0) {
            //判断是否是六个月前的第二次提现
            $now_time       = time();
            //获取现在时间前六个月时间
            $six_month_before  = $this->real_house_model->getSixMonthTime($now_time);
            //判断前六个月之内是否已经有两次成功提现
            $apply_count = $this->real_house_model->getSixMonthApplyTimes($this->user_arr['uid'],$six_month_before,3,1);
            if($apply_count == '0' || !$apply_count || empty($apply_count)){
                //没有提现记录
                $realHouseCount = $this->real_house_model->getUidRealHouseNum($this->user_arr['uid']);
                if ($realHouseCount > 0) {
                    $result['status'] = 2;
                    $msg = '您的账户中仍有'. $realHouseCount .'条“放心房”在线展示，提现后“放心房”标签将被去除哦！';
                    $result['msg'] = iconv('gbk','utf8',$msg);
                    echo json_encode($result);exit;
                }
                $result['status'] = 2;
                $msg = '申请提现后在保证金到账前，您将无法参与放心看计划，是否继续提现？';
                $result['msg'] = iconv('gbk','utf8',$msg);
                echo json_encode($result);exit;
            }elseif($apply_count >= '1'){
                //六个月内已经有一次提现记录，可以在体现一次规定日期内不可以在参加放心看计划
                //获取前六个月内的第一次提现的时间
                $first_time = $this->real_house_model->getSixMonthFristApply($this->user_arr['uid'],$six_month_before,3,1);
                $first_time = $first_time[0]['create_time'];
                //限定时间
                $six_month_after  = $this->real_house_model->getSixMonthTime($first_time,'+6');
                $result['status'] = 2;
                $msg = '您本次申请提现后，在'.date('Y',$six_month_after).'年'.date('m',$six_month_after).'月'.date('d',$six_month_after).'日前，将无法参再次申请参与放心看计划，是否继续提现？';
                $result['msg'] = iconv('gbk','utf8',$msg);
                echo json_encode($result);exit;

            }
        }

        //符合提现条件
        $this->real_house_model->applyRemit($this->user_arr['uid']);
        $result['status'] = 1;
        $msg = '您的提现申请已提交成功，预计15工作日内将保证金原路退回，请您注意余额变动；';
        $result['msg'] = iconv('gbk','utf8',$msg);
        echo json_encode($result);exit;
    }

    //再次申请放心看计划时，判断前六个月内是否有两次提现操作
    public function pay_six_month(){
        $now_time = time();
        //获取是否是第一次参加放心看计划
        $first_pay_record = $this->real_house_model->getBrokerPayRecord($this->user_arr['uid']);
        if($first_pay_record){
            //获取现在时间前六个月时间
            $six_month_before  = $this->real_house_model->getSixMonthTime($now_time);
            if($six_month_before){
                //判断前六个月之内是否已经有两次成功提现
                $apply_count = $this->real_house_model->getSixMonthApplyTimes($this->user_arr['uid'],$six_month_before,3,1);

                $teshu = array('865633','820281','911933');
                if($apply_count >= 2 && !in_array($this->user_arr['uid'],$teshu)){
//                    echo $apply_count;die;
                    //六个月内已经有2次申请退出记录，规定日期内不可以在参加放心看计划
                    //获取前六个月内的第一次提现的时间改为上上次时间
                    $first_time = $this->real_house_model->getSixMonthFristApply($this->user_arr['uid'],$six_month_before,3,1);
                    $first_time = $first_time[1]['create_time'];
                    //限定时间
                    $six_month_after  = $this->real_house_model->getSixMonthTime($first_time,'+6');
                    $result['status'] = 2;
                    $msg = '您在'.date('Y',$six_month_after).'年'.date('m',$six_month_after).'月'.date('d',$six_month_after).'日前，无法参再次申请参与放心看计划，如有疑问，请您拨打025-57791365进行咨询。';
                    $result['msg'] = iconv('gbk','utf8',$msg);
                    echo json_encode($result);exit;
                }else{
                    //跳转充值页面
                    $result['status'] = 1;
                    echo json_encode($result);exit;
                }
            }
        }else{
            //第一次参与充值，直接跳转充值页面
            $result['status'] = 1;
            echo json_encode($result);exit;
        }
    }

    private function getPhone($type = 1)
    {
        $modelBroker = new Broker_model();
        $databaseSlave = $modelBroker->getDatabaseSlave();
        $result = $databaseSlave
            ->where('type =', $type)
            ->select('telno')
            ->get('telno_config')
            ->result_array();
        $phone = isset($result[0]['telno']) ? $result[0]['telno'] : '';
        return $phone;
    }
    public function appeal()
    {
        $model_param = $this->input->post();
        $model_param['reason'] = iconv('gbk', 'utf8', $model_param['reason']);
        $model_param['property_rights_name'] = iconv('gbk', 'utf8', $model_param['property_rights_name']);

        $this->load->model('zsb_api_model');
        $res = $this->zsb_api_model->getRequrstData('realHouseAppeal', $model_param);

        /*$ids = $this->input->post( 'ids' , TRUE);
        $images = $this->input->post( 'p_filename' , TRUE);
        $reason = $this->input->post( 'reason' , TRUE);
        $checkConsent = $this->input->post( 'checkConsent' , TRUE);
        $houseId = $this->input->post( 'houseId' , TRUE);
        $brokerData = $this->real_house_model->getRealHouseInfo($this->user_arr['uid']);
        $time = time();
        $appealData = array();
        $appealData['uid'] = $brokerData['uid'];
        $appealData['username'] = $brokerData['username'];
        $appealData['truename'] = $brokerData['truename'];
        $appealData['survey'] = intval($checkConsent);
        $appealData['reason'] = addslashes($reason);
        $appealData['time'] = $time;
        $appealData['buildingnum'] = $this->input->post( 'buildingnum' , TRUE);
        $appealData['unitnum'] = $this->input->post( 'unitnum' , TRUE);
        $appealData['roomnum'] = $this->input->post( 'roomnum' , TRUE);

        $appealData['internal_num'] = $this->input->post( 'internal_num' , TRUE);
        $appealData['appeal_qiqaun'] = $this->input->post( 'appeal_qiqaun' , TRUE);
        $appealData['owner_phone'] = $this->input->post( 'owner_phone' , TRUE);

        if($appealData['owner_phone']){
            if(preg_match("/^1[3,4,5,7,8,9]{1}[0-9]{9}$/", $appealData['owner_phone'])  == '0'){
                $this->jump('/realHouse/reportRecord/', '请填写正确的业主电话', 3000);
            }
        }else{
            $this->jump('/realHouse/reportRecord/', '请填写业主电话', 3000);
        }
        $appealData['property_rights_num'] = $this->input->post( 'property_rights_num' , TRUE);
        $appealData['property_rights_name'] = $this->input->post( 'property_rights_name' , TRUE);
        if(!$appealData['property_rights_name']){
            $this->jump('/realHouse/reportRecord/', '请填写产权人姓名信息', 3000);
        }
        $appealData['property_rights_person_id'] = $this->input->post( 'property_rights_person_id' , TRUE);
        //批量插入数据，这边表结构太乱，要循环插入很多次
        foreach ($ids as $value) {
            $appealData['report_id'] = $value;
            $appealId = $this->real_house_model->insertAppeal($appealData);
            //更新当前举报记录的申述状态
            $this->real_house_model->updateReport($value, array('appeal' => 1));
            foreach ($images as $image) {
                $imageData = array();
                $imageData['appeal_id'] = $appealId;
                $imageData['img'] = $image;
                $imageData['time'] = $time;
                $this->real_house_model->insertAppealImage($imageData);
            }
        }

        if ($checkConsent) {
            //更新房源问题实勘
            $this->load->model('sell_model');
            $this->sell_model->update(array('is_true_visit' => 1), $houseId);
        }

        //申诉成功后 微信消息通知
        houseOptions($this->user_arr['uid'],$houseId,4);*/

        $this->jump('/realHouse/reportRecord/', '提交成功', 3000);
    }

    public function recharge()
    {
        $info = $this->user_arr;
        $payMethod = $this->config->item('payMethod');
        $realHouseMoney = $this->real_house_model->getBrokerRealHouseMoney($info['uid']);
        if ($realHouseMoney >= $this->price) {
            echo $this->payment_model->get_check_result_str('该用户已缴纳保证金');
            return;
        }
        //判断是否已经有两次提现记录
        $now_time = time();
        //获取是否是第一次参加放心看计划
        $first_pay_record = $this->real_house_model->getBrokerPayRecord($info['uid']);
        if($first_pay_record){
            //获取现在时间前六个月时间
            $six_month_before  = $this->real_house_model->getSixMonthTime($now_time);
            if($six_month_before){
                //判断前六个月之内是否已经有两次成功提现
                $apply_count = $this->real_house_model->getSixMonthApplyTimes($info['uid'],$six_month_before,3,1);
                $teshu = array('865633','820281','911933');
                if($apply_count >= 2 && !in_array($info['uid'],$teshu)){
                    $this->jump('/realHouse/marginAccount/', '参数有误', 3000);return;
                }
            }
        }
        $info['payMethod'] = $payMethod;
        //开通了微信支付则默认选中微信支付
        if (in_array('alipay',$payMethod)) {
            $info['pay_type'] = 'alipay';
        } elseif (in_array('wxpay',$payMethod)) {
            $info['pay_type'] = 'wxpay';
        }
        //头部
        $info['recharge_record'] = '/realHouse/marginAccount/';
        $data_page['page_title'] = '放心看管理-保证金账户';
        $data_page['js'] = load_js('common/js/jquery.validate.min.js');
        $data_page['page_js'] = load_js('zsb/js/v1.0/pay.js');
        $data_page['css'] = load_css('zsb/css/v1.0/style1.css,zsb/css/v1.0/realhouse.css');
        $data_page['info'] = $info;
        $this->view('realHouse', 'realHouse_recharge', $data_page);
    }

    //支付功能
    public function pay()
    {
        //经纪人参数
        $info = $this->user_arr;
        $price = $this->price;
        $payMethod = $this->config->item('payMethod');
        //历史遗留问题back_name实际上是bank_name
        $payType = $this->input->post('back_name');
        //检查支付方式
        if (!in_array($payType, $payMethod)) {
            echo $this->payment_model->get_check_result_str('支付参数有误');
            return;
        }
        //判断是否已经有两次提现记录
        $now_time = time();
        //获取是否是第一次参加放心看计划
        $first_pay_record = $this->real_house_model->getBrokerPayRecord($info['uid']);
        if($first_pay_record){
            //获取现在时间前六个月时间
            $six_month_before  = $this->real_house_model->getSixMonthTime($now_time);
            if($six_month_before){
                //判断前六个月之内是否已经有两次成功提现
                $apply_count = $this->real_house_model->getSixMonthApplyTimes($info['uid'],$six_month_before,3,1);
                $teshu = array('865633','820281','911933');
                if($apply_count >= 2 && !in_array($info['uid'],$teshu)){
                    $this->jump('/realHouse/marginAccount/', '参数有误', 3000);return;
                }
            }
        }

        $transaction_id = $this->real_house_model->getTransactionId();
        $data = array(
            'transaction_id' => $transaction_id,
            'broker_id' => $info['uid'],
            'broker_username' => $info['username'],
            'broker_phone' => $info['telno'],
            'broker_truename' =>$info['truename'],
            'money' => $price,
            'create_time' => time(),
            'pay_type' => $payType,
            'pay_status' => 0,
            'order_status' => 1,
            'source' => 1,
            'ip' => GetIP()
        );
        $id = $this->real_house_model->createOrder($data);
        if (!$id) {return;}
        //支付的公共参数
        $bank_base_url = $this->config->item('base_url') . 'realHouse';
        $bank_transfer_para = $payType . '/' . $info['uid'] . '/' . $id . '/';
        $return_url = $bank_base_url . '/success/' . $bank_transfer_para;
        $notify_url = $bank_base_url . '/notify/' . $bank_transfer_para;
        //测试数据
        if($this->isTester()){
            $price = 0.01;
        }
//        $price = 0.01;
        //$notify_url = 'http://esfadmin.house365.com/notify_hf.php';
        if ($payType == 'alipay') {
            $this->load->library('payment/alipayNew/lib/Encryption');
            $res['data'] = array();
            // 业务参数数组
            $bizContent = array(
                "timeout_express"	=>	"30m",
                "product_code"		=>	"FAST_INSTANT_TRADE_PAY",
                "total_amount"		=>	$price,
                "subject"			=>	iconv('GBK','UTF-8//IGNORE','缴纳保证金'),
                "out_trade_no"		=>	$transaction_id,
                "enable_pay_channels" => "balance,moneyFund,debitCardExpress"
            );
            $bizContent = json_encode($bizContent);
            // 公共参数数组
            $sParam = array(
                'app_id'			=>	APP_ID,
                'method'			=>	"alipay.trade.page.pay",
                'charset'			=>	"utf-8",
                'sign_type'			=>	"RSA",
                'sign'				=>	"",
                'timestamp'			=>	date("Y-m-d H:i:s",time()),
                'version'			=>	"1.0",
                'notify_url'		=>	$notify_url,
                'return_url'		=>	$return_url,
                'biz_content'		=>	$bizContent
            );

            $encpt = new Encryption();		// 实例化支付宝支付类
            /** 设置私钥 */
            $encpt->setRsaPriKeyFile(PRIVATE_KEY);
            $content = $encpt->requestAlipay($sParam);
            echo $content;exit;
        } elseif ($payType == 'wxpay') {
            $info = $this->user_arr;
            //获取纪经人积分和等级
            $credit_level = $this->payment_model->get_broker_base($info);
            $info['credit'] = $credit_level['credit'];
            $info['level'] = $credit_level['level'];
            $info['documentation'] = $this->config->item('documentation');
            $data_page['info'] = $info;
            $data_page['page_title'] = '放心看管理-保证金账户';
            $data_page['js'] = load_js('common/js/jquery.validate.min.js');
            $data_page['page_js'] = load_js('zsb/js/v1.0/pay.js');
            $data_page['css'] = load_css('zsb/css/v1.0/style1.css,zsb/css/v1.0/realhouse.css');
            //验证选中的套餐及银行
            $para = array(
                'transaction_id' => $transaction_id,
                'price' => $price,
                'bg_ret_url' => $return_url,
                'page_ret_url' =>$notify_url,
                'ord_desc' =>  'esf_zsb_housebean',
                'id' => $id,
                'ip' => GetIP(),
            );
            $data_page['para'] = $para;
            $data = $this->getWxPayCode($id);
            if($data['status'] == 0 || empty($data["url"])){
                echo $this->payment_model->get_check_result_str($data['msg']);
                return;
            }
            $data_page['url'] = $data["url"];
            $this->view('realHouse', 'realHouse_wxpay', $data_page);
        }
    }
    //ajax刷新二维码
    public function refreshWxPayCode()
    {
        $this->load->model('ajax_model');
        $id = intval($_REQUEST['id']);
        $data = $this->getWxPayCode($id);
        echo $this->ajax_model->array_to_json($data);
    }
    //获取微信支付二维码
    private function getWxPayCode($id)
    {
        $info = $this->user_arr;
        $recharge = $this->real_house_model->getOrderById($id);
        $data = array('status' => 0);
        if (!$recharge || $recharge['broker_id'] != $info['uid'] || $recharge['pay_status'] != 0) {
            $this->load->model('ajax_model');
            echo $this->ajax_model->array_to_json($data);exit;
        }
        //支付的公共参数
        $bank_base_url = $this->config->item('base_url') . 'realHouse';
        $bank_transfer_para = 'wxpay/' . $info['uid'] . '/' . $id . '/';
        $notify_url = $bank_base_url . '/notify/' . $bank_transfer_para;
        $transaction_id = $recharge['transaction_id'];
        $price = $recharge['money'];
        //测试数据
        if($this->isTester()){
            $price = 0.01;
        }
//        $price = 0.01;
        //$notify_url = 'http://esfadmin.house365.com/notify_hf.php';
        $this->load->library('payment/wxpay/NativePay');
        $notify = new NativePay();
        $input = new WxPayUnifiedOrder();
        $input->SetBody(iconv('gbk','utf-8','缴纳保证金'));
        $input->SetOut_trade_no($transaction_id);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 70));
        if($info['uid'] == 2515 && false){
            $input->SetTotal_fee(1);
        }else{
            $input->SetTotal_fee($price*100);
        }
        $input->SetNotify_url($notify_url);
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id("365365");
        $input->SetLimitPay("no_credit");
        $result = $notify->GetPayUrl($input);
        if($result['return_code'] == 'FAIL' || $result['result_code'] == 'FAIL' || empty($result["code_url"])){
            $msg = !empty($result['err_code_des']) ? iconv('utf-8','gbk',$result['err_code_des']): '支付参数有误';
            $data['msg'] = $msg;
            return $data;
        }
        $data['status'] = 1;
//        $data['url'] = 'https://api.qrserver.com/v1/create-qr-code/?size=298x298&data='.urlencode($result["code_url"]);
        $data['url']    = 'http://newrent.house365.com/api/common/get-qr-code?size=298&margin=0&url='.urlencode($result['code_url']);
        return $data;
    }

    public function success($pay_api = null, $broker_id = null, $id = null)
    {
        //判断参数的是否存在
        if ($pay_api == '' || $broker_id == '' || $id == '') {
            echo $this->payment_model->get_check_result_str('参数不合法');
            return;
        }
        //经纪人参数
        $info = $this->user_arr;
        $data_page['page_title'] = '放心看管理-保证金账户';
        $data_page['css'] = load_css('zsb/css/v1.0/style1.css,zsb/css/v1.0/realhouse.css');
        $data_page['info'] = $info;
        //测试环境无法回调的问题解决
        if($this->isTester()){
            $recharge = $this->real_house_model->getOrderById($id);
            if ($recharge['pay_status'] == 0) {
              $this->real_house_model->payFinish($recharge);
            }
        }
        //测试环境无法回调的问题解决

        $this->view('realHouse', 'realHouse_success', $data_page);
    }

    public function isTester(){
        return isset($_COOKIE['zsb_test']) && $_COOKIE['zsb_test']=='house365';
    }

    //后台线程异步执行
    public function notify($pay_api = null, $broker_id = null, $id = null)
    {
        //判断参数的是否存在
        if ($pay_api == '' || $broker_id == '' || $id == '') {
            return;
        }
        //支付系统反馈信息
        $data = $_POST;
        if ($pay_api == 'alipay') //支付宝
        {
            $this->load->library('payment/alipayNew/lib/Encryption');
            $encpt = new Encryption();
            $encpt->setRsaPubKeyFile(PUBLIC_KEY);
            /** 处理获取到的参数 */
            $rParam = $encpt->disposeResponseData($data);
            $stringToBeSign = $rParam['stringToBeSigned'];
            $signature = $rParam['signature'];
            /** 验证支付结果 */
            $result = $encpt->verify($stringToBeSign, $signature);
            //校验正确性
            if($result && ( $data['trade_status'] == 'TRADE_SUCCESS' || $data['trade_status'] == 'TRADE_FINISHED' ) && ($data['auth_app_id'] == APP_ID || $data['app_id'] == APP_ID)){
                $verify_result = true;
            }
        }
        if ($pay_api == 'wxpay') //微信支付
        {
            $this->load->library('payment/wxpay/PayNotifyCallBack');
            $notify = new PayNotifyCallBack();
            //微信回调请求参数，以及验签结果
            $result = $notify->Handle(false);
            //验签失败处理
            if($result['return_code'] != 'SUCCESS'){
                return;
            }
            $verify_result = true;
        }
        if ($verify_result)  //验证成功
        {
            $recharge = $this->real_house_model->getOrderById($id);
            if (!$recharge || $recharge['broker_id'] != $broker_id || $recharge['pay_status'] == 1
                || $pay_api != $recharge['pay_type']) {
                return;
            }
            if($pay_api == 'wxpay'){
                if($recharge['money'] * 100 != $result['data']['total_fee']){
                    return;
                }
                $recharge['new_payment_order_id'] = $result['data']['transaction_id'];
            }
            if($pay_api == 'alipay'){
                if( $recharge['transaction_id'] != $data['out_trade_no']){
                    return;
                }
                if($recharge['money']  != $data['total_amount']){
                    return;
                }
                $recharge['new_payment_order_id'] = $data['trade_no'];
            }
            //修改经纪人保证金金额
            $result = $this->real_house_model->payFinish($recharge);
            if ($result) {
                if ($pay_api == 'wxpay') {
                    $reply = "<xml>
                                <return_code><![CDATA[SUCCESS]]></return_code>
                                <return_msg><![CDATA[OK]]></return_msg>
                          </xml>";
                    echo $reply;
                }
                if ($pay_api == 'alipay') {
                    echo 'success';
                }
            }
        }

    }

    /**
     * 初始化分页参数
     *
     * @access public
     * @param  int  $current_page
     * @param  int  $page_size
     * @return void
     */
    private function _init_pagination($current_page = 1 , $page_size = 0)
    {
        /** 当前页 */
        $this->_current_page = ( $current_page && is_numeric( $current_page ) ) ?
            intval( $current_page ) : 1;

        /** 每页多少项 */
        $this->_limit = ( $page_size && is_numeric( $page_size ) ) ?
            intval( $page_size ) : $this->_limit;

        /** 偏移量 */
        $this->_offset = ( $this->_current_page - 1 ) * $this->_limit;

        if($this->_offset < 0)
        {
            redirect(base_url());
        }
    }

    //支付协议
    public function agreement()
    {
        //头部
        $data_page['page_title'] = '"放心看"保证金协议-365租售宝经纪人版';
        $data_page['css'] = load_css('common/css/base.css,zsb/css/v1.0/public.css'
            . ',zsb/css/v1.0/style1.css');
        $this->load->view('realHouse_agreement', $data_page);
    }



	/*
	 * 开通放心看
	 */
    public function openReal(){
    	$this->load->model('zsb_api_model');
    	$re = $this->zsb_api_model->getRequrstData('openReal');
    	//$data = $this->array_iconv($re,'utf-8','gbk');
		echo json_encode($re);die;
    }

    /*
     * 放心看开通的检查
     */
    public function realCheckPay(){
    	$post = $this->input->post();
	    $this->load->model('zsb_api_model');
	    $re = $this->zsb_api_model->getRequrstData('realCheckPay',$post);
	    echo json_encode($re);die;
    }

	/*
	 * 放心看开通的检查
	 */
	public function realHouseRemit(){
		$post = $this->input->post();
		$this->load->model('zsb_api_model');
		$re = $this->zsb_api_model->getRequrstData('realHouseRemit',$post);
		echo json_encode($re);die;
	}

}
