<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
ini_set('display_errors',false);
error_reporting(0);

/**
 * Pay Class
 *
 * 租售宝支付中心模块
 *
 * @package     zsb
 * @subpackage      Controllers
 * @category        Controllers
 * @author      sun
 */
class Payment extends MY_Controller {
    
   /**
    * 解析函数
    * @access public
    * @return void
    */
    public function __construct()
    {     
        parent::__construct();

		$functionSwitch = $this->config->item('functionSwitch');
		if($this->router->fetch_method() == 'recharge' && empty($functionSwitch['payment']))
		{
			$this->jump('/', '没有权限！');
		}

		$this->functionSwitch = $functionSwitch;

        //加载支付模型类
        $this->load->model('payment_model');
		/****链家屏蔽start****/
        $this->load->model('broker_model');
        $this->is_prohibit = $this->broker_model->is_prohibit($this->user_arr['agentcode']);
		//$this->is_prohibit = false;
        /*****链家屏蔽end****/
    }
    
    /**
     * 首页
     */
    public function index() 
    {
        //经纪人参数
        $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');
        //充值页
        $info['recharge_url'] = $this->payment_model->get_module_url('recharge');
        //充值记录页
        $info['recharge_record_url'] = $this->payment_model->get_module_url('recharge_record');
        //房豆明细
        $info['transaction_detail_url'] = $this->payment_model->get_module_url('transaction_detail');
        //获取新新6个交易记录
        $paymentHousebeanRecord = new PaymentHousebeanRecord();    
        /******链家屏蔽start******/          
        $paymentHousebeanWay = new PaymentHousebeanWay();
        if($this->is_prohibit){           
            //获取搜索途径
            $infofroms = $paymentHousebeanWay->getByMethod(); 
            $search_infofrom = array_keys(SqlCombinHelper::changeToKeyArray($infofroms, 'alias'));
            unset($search_infofrom[0]);//recharge
            unset($search_infofrom[2]);//loginActivity
            unset($search_infofrom[4]);//telBuying            
            $transaction_record = $paymentHousebeanRecord->getNewByWayAlias($info['uid'],$search_infofrom, 6);
            
        }else{
            $transaction_record = $paymentHousebeanRecord->getNewBy($info['uid'], 6);
        }
        /******链家屏蔽end******/  
        if (isset($transaction_record) && !empty($transaction_record))
        {
            $info['credit'] = $transaction_record[0]['remain_num'];
            //实例购买产品名称
            
            foreach($transaction_record as $k => $v)
            {
                $transaction_record[$k]['name'] = $paymentHousebeanWay->
                        getNameByWayAlias($v['way_alias']);
                $transaction_record[$k]['source'] = PaymentHousebeanSource
                        ::getSourcedescription($v['source']);
            }
        }
        else
        {
            $transaction_record = array();
        }

        //把交易记录加入配置页面
        $info['transaction_record'] = $transaction_record;
        //头部
        $data_page['page_title'] = '支付中心-首页';
        $data_page['css'] = load_css('zsb/css/v1.0/style1.css');
        if ($info['smallphoto'] == '')
        {
            $info['smallphoto'] = STATIC_SOURCE_URL . '/zsb/images/v1.0/defaultface.jpg';
        }
			
		// 2016-1-14 添加星级数据 -----------start -------->
		
		$broker_new_info =$this->broker_model->get_broker_info_by_uid($info['uid']);
        $expire_housebeannum =$this->broker_model->check_broker_expire_housebeannum($info['uid']);

		// 2016-1-14 添加星级数据 -----------end -------->
        $data_page['info'] = $info;
		$data_page['broker_new_info'] = $broker_new_info;
		$data_page['is_prohibit'] = $this->is_prohibit;//链家屏蔽
        $data_page['expire_housebeannum'] = $expire_housebeannum;
		$data_page['functionSwitch'] = $this->functionSwitch;
		$data_page['google_analytics'] = get_ga_js_code('/支付中心/首页/');
        $this->view('payment', 'payment_index', $data_page);
    }
    
    //充值页
    public function recharge($id = null)
    {
        //读取支付失败后重新支付
        $info = $this->user_arr;
        $payMethod = $this->config->item('payMethod');
        if ($id) 
        {
            //查询记录 检查id是否存在 并实例化充值记录类
            $paymentRechargeRecord = new PaymentRechargeRecord();
            $recharge = $paymentRechargeRecord->getOneByIdAndBrokerId($id, $info['uid'], 0);
            if (!$recharge) 
            {
                echo $this->payment_model->get_check_result_str('没有此充值记录');
                return;
            }
            $select_active = $recharge['active_type'];
            $info['price'] = $recharge['price'];
            $info['bank_name'] = $recharge['bank_name'];
            $info['id'] = $recharge['id'];
            $info['type'] = $recharge['active_type'];
            $info['invoice'] = $recharge['invoice'];
        }
        else
        {
            //默认选中第一个套餐及工商银行
            $select_active = 1;
            $info['bank_name'] = 'zggsyh';
            //开通了微信支付则默认选中微信支付
            if(in_array('wxpay',$payMethod)){
                $info['bank_name'] = 'wxpay';
            }elseif(in_array('alipay',$payMethod)){
                $info['bank_name'] = 'alipay';
            }
        }

		// 2016-1-14 添加星级数据 -----------start -------->


		$broker_new_info =$this->broker_model->get_broker_info_by_uid($info['uid']);

		// 2016-1-14 添加星级数据 -----------end -------->

        //获取纪经人积分和等级
        $credit_level = $this->payment_model->get_broker_base($info);
        $info['credit'] = $credit_level['credit'];
        $info['level'] = $credit_level['level'];
        //头部
        $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');
        //银行
        $info['bank'] = $this->payment_model->gate_port;
        //$info['active'] = $this->payment_model->get_recharge_active();
        //获取支付配置信息
        $payment_config = $this->config->item('payment');
        //判断交易是否参加优惠活动
        $info['is_active'] = $this->payment_model->is_active($payment_config['active']['endtime']);
        //帮助中心配置
        $info['documentation'] = $this->config->item('documentation');
        //支付协议
        $info['payment_agreement'] = $this->payment_model->get_module_url('agreement');;
        //支付配置
        $info['payment_config'] = $payment_config;
        //完成充值跳转页
        $info['recharge_record'] = $this->payment_model->get_module_url('recharge_record');
        $info['select_active'] = $select_active;
        //支付方式配置
        $info['payMethod'] = $payMethod;
        $data_page['info'] = $info;
		$data_page['broker_new_info'] = $broker_new_info;
		$data_page['google_analytics'] = get_ga_js_code('/支付中心/立即充值/');
        $this->view('payment', 'payment_recharge', $data_page);
    }
    
    //支付功能
    public function pay($id = null) 
    {
        //经纪人参数
        $info = $this->user_arr;
        //需要验证的条件
        $rtn_status = array(
            'check_price' => false, 'check_pay_way' => false, 
            'exist_id' => false
        );
        //获取支付配置信息
        $payment_config = $this->config->item('payment');
        //套餐类型 并计算出价格
        $type = $this->input->post('type');
        if ($type == 0) 
        {
            $price = $this->input->post('else_num');
            /*价格参数必须大于5为正整数*/
            if ($price >= 5 && preg_match('/^[1-9]\d*$/', $price)) {
                $rtn_status['check_price'] = true;
            }
        } else {
            //检查钱的方式
            $rtn_status['check_price'] = $this->payment_model->check_price(
                    $payment_config['price'], $type);
            $price = $payment_config['price'][$type];
        }

		
        //$price = '0.01';
        //钱的验证结果
        if ($rtn_status['check_price'] == false) 
        {
            echo $this->payment_model->get_check_result_str('充值金额参数有误');
            return;
        }
        //银行支付
        $bank_name = $this->input->post('back_name');

        //检查支付方式
        $rtn_status['check_pay_way'] = $this->payment_model->check_pay_way($bank_name);
        if ($rtn_status['check_pay_way'] == false)
        {
            echo $this->payment_model->get_check_result_str('支付参数有误');
            return;
        }
        //判断交易是否参加优惠活动
        $is_active = $this->payment_model->is_active($payment_config['active']['endtime']);
        //充值方案
        $program = '充值' . $price . '元';
        if ($is_active) 
        {
            $program .= ',赠送' . $payment_config['active']['percentage'] . '房豆';
        }
        //发票抬头
        $invoice = $this->input->post('invoice', true);
        //来源
        $source = PaymentHousebeanSource::getSource();
        //实例化充值记录类
        $paymentRechargeRecord = new PaymentRechargeRecord();
        //判断是否已经创建订单信息 如果有直接查，反之则需要创建
        if ($id == null) { //没有
            //插入充值记录$brokerId, $orderId, $program, 
            //$source, $num, $invoice, $type = 1
            //交易号
            $transaction_id = PaymentTransactionId::getTransactionId(
                    $this->payment_model->way_alias);
            $id = $paymentRechargeRecord->insert($info['uid'], $type, $price, $bank_name,
                        $transaction_id, $program, $source, 0, $invoice);
        } else {
            //创建过 检查id是否存在
            $recharge = $paymentRechargeRecord->getOneByIdAndBrokerId($id, $info['uid'], 0);
            if (!$recharge) 
            {
                echo $this->payment_model->get_check_result_str('没有此充值记录');
                return;
            }
             //交易号
            $transaction_id = $recharge['transaction_id'];
            $field_values = array(
                'active_type' => $type, 'price' => $price,
                'program' => $program, 'invoice' => $invoice,
                'bank_name' => $bank_name
            );
            //更新重选过的参数
            $paymentRechargeRecord->update($field_values, $id, $info['uid']);
        }
        if (!$id) {return;}
        //判断是银联支付还是支付宝接口
        $pay_api = $this->payment_model->get_pay_api($bank_name);
        //支付的公共参数
        $bank_base_url = $this->config->item('base_url') . $this->payment_model->module_controll;
        $bank_transfer_para = $pay_api . '/' . $info['uid'] . '/' . $id . '/';
        $return_url = $bank_base_url . '/success/' . $bank_transfer_para;
        $notify_url = $bank_base_url . '/notify/' . $bank_transfer_para;

        /*测试完请注意把测试代码删除，或者加上城市判断，这个代码要是合肥站和南京站的uid一样不就有漏洞了
		if($info['uid']=='816039' || $info['uid']=='835248')
		{
			$price = '0.01';
		}
        */

		//$price = '0.01';

        if ($pay_api == 'chinapay')//银联
        {
            //验证选中的套餐及银行
            $para = array(
                'transaction_id' => $transaction_id,
                'price' => $price,
                'bg_ret_url' => $notify_url,
                'page_ret_url' =>$return_url,
                'ord_desc' => 'esf_zsb_housebean',
            );
			
			
			if(GB_CITY == 'hf')
			{
				$para['MerId'] = '481601604090501';
				$para['bank_gate_id'] = $this->payment_model->gate_port[$bank_name]['newPort'];//获取银行网关号
				$chinapayVersion = 'new';
			}
			else
			{
				$para['bank_gate_id'] = $this->payment_model->gate_port[$bank_name]['port'];//获取银行网关号
				$chinapayVersion = 'old';
			}

            $this->load->library('payment/chinapay/ChinaPay', array('chinapayVersion' => $chinapayVersion), 'cp');
            echo $this->cp->dopay($para, 'POST');
        }
        else if ($pay_api == 'alipay') //支付宝
        {
            /*
             * 以前的逻辑
            //验证选中的套餐及银行
            $para = array(
                'transaction_id' => $transaction_id,
                'price' => $price,
                'bg_ret_url' => $return_url,
                'page_ret_url' =>$notify_url,
                'ord_desc' =>  'esf_zsb_housebean',
                'ip' => GetIP(),
            );
            $this->load->library('payment/alipay/Alipay', '', 'ap');
            echo $this->ap->dopay($para, 'POST');
            */
            $this->load->library('payment/alipayNew/lib/Encryption');
            $res['data'] = array();
            //测试数据
            //$price = 0.01;
            //$notify_url = 'http://esfadmin.house365.com/notify_hf.php';
            // 业务参数数组
            $bizContent = array(
                "timeout_express"	=>	"30m",
                "product_code"		=>	"FAST_INSTANT_TRADE_PAY",
                "total_amount"		=>	$price,
                "subject"			=>	iconv('GBK','UTF-8//IGNORE','租售宝充值'),
                //"subject"			=>	"租售宝充值",
                "out_trade_no"		=>	$transaction_id
            );
            $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;
        }
        else if ($pay_api == 'wxpay') //微信
        {
            $info = $this->user_arr;
            //获取纪经人积分和等级
            $credit_level = $this->payment_model->get_broker_base($info);
            $info['credit'] = $credit_level['credit'];
            $info['level'] = $credit_level['level'];
            $broker_new_info =$this->broker_model->get_broker_info_by_uid($info['uid']);
            $data_page['broker_new_info'] = $broker_new_info;
            $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');
            //验证选中的套餐及银行
            $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"];
            $data_page['google_analytics'] = get_ga_js_code('/支付中心/立即充值/');
            $this->view('payment', 'payment_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;
        $paymentRechargeRecord = new PaymentRechargeRecord();
        $recharge = $paymentRechargeRecord->getOneByIdAndBrokerId($id, $info['uid'], 0);
        $data = array('status' => 0);
        if (!$recharge) {
            $this->load->model('ajax_model');
            echo $this->ajax_model->array_to_json($data);exit;
        }
        //支付的公共参数
        $bank_base_url = $this->config->item('base_url') . $this->payment_model->module_controll;
        $bank_transfer_para = 'wxpay/' . $info['uid'] . '/' . $id . '/';
        $notify_url = $bank_base_url . '/notify/' . $bank_transfer_para;
        $transaction_id = $recharge['transaction_id'];
        $price = $recharge['price'];
        $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");
        $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'] = 'http://paysdk.weixin.qq.com/example/qrcode.php?data='.urlencode($result["code_url"]);
//        $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 transaction($tab = 'detail')
    {
        //验证页面tab是否合法 自动跳转到页面页
        if (!in_array($tab, array_keys($this->payment_model->transaction_tab))) {
            $this->jump($this->payment_model->get_module_url('transaction_detail'),
                    '参数不合法');
            return;
        }
        //经纪人参数
        $info = $this->user_arr;
        //获取纪经人积分和等级
        $credit_level = $this->payment_model->get_broker_base($info);
        $info['credit'] = $credit_level['credit'];
        $info['level'] = $credit_level['level'];
        $paymentHousebeanWay = new PaymentHousebeanWay();

        //搜索参数
        $info['source'] = $this->input->post('source');
        $info['infofrom'] = $this->input->post('infofrom');
        $info['start_time'] = $this->input->post('start_time');
        $info['end_time'] = $this->input->post('end_time');
        $page = $this->input->post('page');
        $info['page'] = (!isset($page) || $page == '') ? 1 
                : $this->input->post('page');
        //渠道
        $sources = PaymentHousebeanSource::$sourceDescription;
        $sources[0] = '全部渠道';
        ksort($sources);
        $info['sources'] = $sources;
        //一页展示多少条记录
        $pagesize = 6;
        $start = ($info['page'] - 1) * $pagesize;
        if ($info['start_time'] == '' || $info['end_time'] == '') 
        {
            $info['start_time'] = date('Y-m-d', strtotime('-1 months'));
            $info['end_time'] = date('Y-m-d');
        }
        else
        {
            //判断时间区间范围是在一个月当中
            $start_time = strtotime($info['start_time']);
            $end_time =  strtotime($info['end_time']);
            if ($end_time - $start_time > 2764799)
            {
            $this->jump($this->payment_model->get_module_url('transaction_detail'),
                    '时间区间必须小于一个月');
                return;
            }
        }
        if ($tab == 'recharge')//充值页
        {
            //充值记录类
            $paymentRechargeRecord = new PaymentRechargeRecord();
            $infofroms = array(array('name' => '充值', 'alias' => 'recharge'));
            $info['recharge_num'] = $paymentRechargeRecord->getSumBy($info['uid'],
                    $info['start_time'], $info['end_time'],
            1, $info['source']);
            $total_count = $paymentRechargeRecord->getCountBy($info['uid'], 
                    $info['start_time'], $info['end_time'] . ' 23:59:59',
            1, $info['source']);
            $transaction_record = $paymentRechargeRecord->getListBy($info['uid'],
                    $info['start_time'], $info['end_time'] . ' 23:59:59', 
                    $type = 1, $info['source'],
                    $start, $pagesize);
            if (isset($transaction_record) && !empty($transaction_record))
            {
                foreach($transaction_record as $k => $v)
                {
                    $transaction_record[$k]['source'] = PaymentHousebeanSource
                            ::getSourcedescription($v['source']);
                }
            }
            else
            {
                $transaction_record = array();
            }
        }
        else 
        {

            if ($tab == 'expend') //房豆消费
            {
                $infofroms = $paymentHousebeanWay->getByMethod('expend');
            }
            else if ($tab == 'get')//房豆获取
            {
                $infofroms = $paymentHousebeanWay->getByMethod('get');
            }
            else //房豆明细
            {
               $infofroms = $paymentHousebeanWay->getByMethod(); 
            }
            //实例化操作记录类
            $paymentHousebeanRecord = new PaymentHousebeanRecord();
             //获取搜索途径
            $search_infofrom = $info['infofrom'] == '' ? 
                    array_keys(SqlCombinHelper::changeToKeyArray($infofroms, 'alias'))
                    : $info['infofrom'];
		
            //消耗房豆总和
            if ($tab == 'expend' || $tab == 'detail')
            {
                if ($tab == 'detail' && is_array($search_infofrom)) 
                {
                    $expend_infofrom = $info['infofrom'] == '' ? 
                            array_keys(SqlCombinHelper::changeToKeyArray(
                        $paymentHousebeanWay->getByMethod('expend'), 'alias'))
                            : $info['infofrom'];
                }
                else
                {
                    
					$total_expend_inforom = array_keys(SqlCombinHelper::changeToKeyArray(
                        $paymentHousebeanWay->getByMethod('expend'), 'alias'));

					$expend_infofrom = in_array($search_infofrom,$total_expend_inforom) ? $search_infofrom : "";



                }
				if($expend_infofrom){
					 $info['expend_num'] = $paymentHousebeanRecord->getSumBy($info['uid'], 
                    $info['start_time'], $info['end_time'] . ' 23:59:59', 'expend', 
                        $info['source'], $expend_infofrom);
				
				}
               
				//if($_GET['xue']==1){
				//		var_dump($expend_infofrom);
				//	}
            }
            //获取房豆总和
            if ($tab == 'get' || $tab == 'detail')
            {

                if ($tab == 'detail' && is_array($search_infofrom)) 
                {
                    $get_infofrom = $info['infofrom'] == '' ? 
                            array_keys(SqlCombinHelper::changeToKeyArray(
                        $paymentHousebeanWay->getByMethod('get'), 'alias'))
                            : $info['infofrom'];
                }
                else
                {

					$all_get_infofrom = array_keys(SqlCombinHelper::changeToKeyArray(
                        $paymentHousebeanWay->getByMethod('get'), 'alias'));
					
                    $get_infofrom = in_array($search_infofrom,$all_get_infofrom) ? $search_infofrom : "";
                }
                
				if($get_infofrom){
					 $info['get_num'] = $paymentHousebeanRecord->getSumBy($info['uid'], 
                    $info['start_time'], $info['end_time'] . ' 23:59:59', 'get', 
                        $info['source'], $get_infofrom);
				
				}

               
            }

			/******链家屏蔽start******/            
         
			if($this->is_prohibit){
				if($tab == 'expend'){               
					unset($search_infofrom[1]);//telBuying    
					
				}elseif ($tab == 'get') {
					unset($search_infofrom[0]);//recharge
					unset($search_infofrom[2]);//loginActivity               
						
				}else{
					unset($search_infofrom[0]);//recharge
					unset($search_infofrom[2]);//loginActivity
					unset($search_infofrom[4]);//telBuying    
					 
				}
                
            } 
			/******链家屏蔽end******/ 
            //总行数

            $total_count = $paymentHousebeanRecord->getCountBy($info['uid'], 
                    $info['start_time'], $info['end_time'] . ' 23:59:59', null, $info['source'], 
                    $search_infofrom);

           //房豆相应的操作记录
           $transaction_record = $paymentHousebeanRecord->getListBy($info['uid'], 
                   $info['start_time'], $info['end_time'] . ' 23:59:59', null, 
                   $info['source'], $search_infofrom, $start, $pagesize);

            if (isset($transaction_record) && !empty($transaction_record))
            {
                foreach($transaction_record as $k => $v)
                {
                    $transaction_record[$k]['name'] = $paymentHousebeanWay->
                            getNameByWayAlias($v['way_alias']);
                    $transaction_record[$k]['source'] = PaymentHousebeanSource
                            ::getSourcedescription($v['source']);
                }
            }
            else
            {
                $transaction_record = array();
            }
        }
        //计算总页数
        $pages  = $total_count > 0 ? ceil($total_count / $pagesize) : 0;
          //是否显示分页
        $pagination = NULL;
        if($total_count > $pagesize)
        {
            $pagination = helper_pagination($info['page'], $pages, $total_count);
        }
        $info['total_count'] = $total_count;

        $info['transaction_record'] = $transaction_record;
        $info['pagination'] = $pagination;
        //获取途径
        $infofroms = array_merge(array('0' => array('alias' => '0', 'name' => '全部途径')), $infofroms);
        $info['infofroms'] = SqlCombinHelper::changeToKeyArray($infofroms, 'alias');
		/******链家屏蔽start******/
		if($this->is_prohibit){
			unset($info['infofroms']['recharge']);
			unset($info['infofroms']['loginActivity']);
			unset($info['infofroms']['telBuying']);
		}
	   
		/******链家屏蔽end*****/
        //页面tab参数配置
        $info['page_tab'] = $this->payment_model->get_transaction_tab();

		/******链家屏蔽start******/
        if($this->is_prohibit){
            unset($info['page_tab']['recharge']);
        }
        /******链家屏蔽end*****/

        $info['tab'] = $tab;
        //搜索日期
        $info['select_time_tab'] = $this->input->post('select_time_tab');
        //充值页
        $info['recharge_url'] = $this->payment_model->get_module_url('recharge');
        //搜索提交页
        $info['submit_url'] = $this->payment_model->get_module_url($tab);
        $data_page['info'] = $info;

		// 2016-1-14 添加星级数据 -----------start -------->
		
		$broker_new_info =$this->broker_model->get_broker_info_by_uid($info['uid']);

		// 2016-1-14 添加星级数据 -----------end -------->

        //头部
        $data_page['page_title'] = '支付中心-交易记录';
		$data_page['is_prohibit'] = $this->is_prohibit;//链家屏蔽
        $data_page['css'] = load_css('zsb/css/v1.0/style1.css');
        $data_page['page_js'] = load_js('common/js/My97DatePicker/WdatePicker.js');
		$data_page['google_analytics'] = get_ga_js_code('/支付中心/交易记录/');
		$data_page['broker_new_info'] = $broker_new_info;
		$data_page['functionSwitch'] = $this->functionSwitch;

        $this->view('payment', 'payment_transaction', $data_page);
    }
    
    //充值成功
    public function success($pay_api = null, $broker_id = null, $id = null) {
        //判断参数的是否存在
        if ($pay_api == '' || $broker_id == '' || $id == '') {
            $this->jump($this->payment_model->get_module_url('recharge'),
                    '参数不合法');
            return;
        }

		//支付系统反馈信息
		$data = $_POST;

		if(GB_CITY == 'hf')
		{
			$chinapayVersion = 'new';
		}
		else
		{
			$chinapayVersion = 'old';
		}

		//file_put_contents('payment_log_success_777.log', var_export($_POST,true),FILE_APPEND);
        //验证支付签名
        if ($pay_api == 'chinapay') //银联
        {
			$data['Signature'] = urlencode($data['Signature']);

            $this->load->library('payment/chinapay/ChinaPay', array('chinapayVersion' => $chinapayVersion), 'cp');
            $verify_result = $this->cp->success($data);
        }
        if ($pay_api == 'alipay') { //支付宝
            /*
            $this->load->library('payment/alipay/Alipay', '', 'ap');
            $verify_result = $this->ap->success();
            */
            //最新版支付宝是以GET方式传递参数
            $data = $_GET;
            $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['auth_app_id'] == APP_ID || $data['app_id'] == APP_ID)){
                $verify_result =  true;


                /***** 测试环境无法回调的处理 上线请去除*****/
                /*
                $paymentRechargeRecord = new PaymentRechargeRecord();
                $recharge = $paymentRechargeRecord->getOneByIdAndBrokerId($id, $broker_id, 0);
                if (!$recharge || $recharge['status'] == 1) {return;}//已经支付过了
                //获取支付配置信息
                $payment_config = $this->config->item('payment');
                //判断交易是否参加优惠活动
                $info['is_active'] = $this->payment_model->is_active($payment_config['active']['endtime']);
                //优惠活动 各种倍率
                $rate = $info['is_active'] ? $payment_config['active']['rate'] : $payment_config['init_rate'];
                //暂定5元
                //$price = 5;
                $price = $recharge['price'];
                $num = $rate * $price;
                //充值增送积分
                $growthBrokerCredit = new GrowthBrokerCredit(array('id' => $broker_id));
                $growthBrokerCredit->increase('recharge', null, $num, 1, $recharge['transaction_id']);
                //充值方案
                $program = '充值' . $price . '元';
                if ($info['is_active'])
                {
                    $program .= ',赠送' . $payment_config['active']['percentage'] . '房豆';
                }
                $growthCredit = new GrowthCredit();
                $remain_num = $growthCredit->getValidCredit($broker_id);
                $field_values = array(
                    'program' => $program, 'num' => $num,'source'=>1,
                    'remain_num' => $remain_num,
                    'status' => 1, 'ctime' => date('Y-m-d H:i:s')
                );

                //房豆充值成功通知财务系统任务表
                $paymentRechargeRecord->successJobInsert(array('payment_housebean_id' => $id));

                //更新重选过的参数
                $paymentRechargeRecord->update($field_values, $id, $broker_id);
                $paymentRechargeRecord->copyRechargeSuccessRecord($id);
                */
                /***** 测试环境无法回调的处理 上线请去除*****/

            }
        }
        //经纪人参数
        $info = $this->user_arr;
        if ($verify_result) //验证成功
        {
            $paymentRechargeRecord = new PaymentRechargeRecord();
            $recharge = $paymentRechargeRecord->getOneByIdAndBrokerId($id, $broker_id, 1);
            $info['num'] = $recharge['num'];
        }
        else
        {
            $this->jump($this->payment_model->get_module_url('recharge'),
                    '数字签名失败');
            return;
        }
        //获取纪经人积分和等级
        $credit_level = $this->payment_model->get_broker_base($info);
        $info['credit'] = $credit_level['credit'];
        $info['level'] = $credit_level['level'];
        //头部
        $data_page['page_title'] = '支付中心-支付成功';
        $data_page['css'] = load_css('zsb/css/v1.0/style1.css');
        //充值页
        $info['recharge_url'] = $this->payment_model->get_module_url('recharge');
        //充值记录页
        $info['recharge_record_url'] = $this->payment_model->get_module_url('recharge_record');
        //购买新产品
        $info['buy_url'] = $this->payment_model->get_module_url();
        $data_page['info'] = $info;
        $this->view('payment', 'payment_success', $data_page);
    }
    
    //后台线程异步执行
    public function notify($pay_api = null, $broker_id = null, $id = null)
    {
        //判断参数的是否存在
        if ($pay_api == '' || $broker_id == '' || $id == '') {
            $this->jump($this->payment_model->get_module_url('recharge'),
                    '参数不合法');
            return;
        }
		
		//支付系统反馈信息
		$data = $_POST;

		if(GB_CITY == 'hf')
		{
			$chinapayVersion = 'new';
		}
		else
		{
			$chinapayVersion = 'old';
		}

        //验证支付签名
        if ($pay_api == 'chinapay') //银联
        {
            $this->load->library('payment/chinapay/ChinaPay',array('chinapayVersion' => $chinapayVersion), 'cp');
            $verify_result = $this->cp->notify($data);
        }
        if ($pay_api == 'alipay') //支付宝
        {
            /*
            $this->load->library('payment/alipay/Alipay', '', 'ap');
            $verify_result = $this->ap->notify();
            */
            //测试数据
            $msg = "************************************************ \n";
            $msg .= date('Y-m-d H:i:s').var_export($data,true)." \n";
            $log = dirname(__FILE__)."/notify_alipay";
            file_put_contents($log,$msg,FILE_APPEND );
            $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') //微信支付
        {
            //ini_set('display_errors','On');
            //error_reporting(E_ALL);
            $this->load->library('payment/wxpay/PayNotifyCallBack');
            $notify = new PayNotifyCallBack();
            //微信回调请求参数，以及验签结果
            $result = $notify->Handle(false);
            /*
            $msg = "************************************************ \n";
            $msg .= date('Y-m-d H:i:s').var_export($result,true)." \n";
            $log = dirname(__FILE__)."/notify";
            file_put_contents($log,$msg,FILE_APPEND );
            */
            //验签失败处理
            if($result['return_code'] != 'SUCCESS'){
                return;
            }
            $verify_result = true;
        }
        if ($verify_result)  //验证成功
        {
            $paymentRechargeRecord = new PaymentRechargeRecord();
            $recharge = $paymentRechargeRecord->getOneByIdAndBrokerId($id, $broker_id, 0);
            if (!$recharge || $recharge['status'] == 1) {return;}//已经支付过了
            if($pay_api == 'wxpay'){
                //任何支付都需校验金额正确性，原银联支付及支付宝支付均不严谨
                if($recharge['price'] * 100 != $result['data']['total_fee']){
                    return;
                }
            }
            if($pay_api == 'alipay'){
                if( $recharge['transaction_id'] != $data['out_trade_no']){
                    return;
                }
                //任何支付都需校验金额正确性，原银联支付及支付宝支付均不严谨
                if($recharge['price']  != $data['total_amount']){
                    return;
                }
            }
            //获取支付配置信息
            $payment_config = $this->config->item('payment');
            //判断交易是否参加优惠活动
            $info['is_active'] = $this->payment_model->is_active($payment_config['active']['endtime']);
            //优惠活动 各种倍率
            $rate = $info['is_active'] ? $payment_config['active']['rate'] : $payment_config['init_rate'];
            //暂定5元
            //$price = 5;
            $price = $recharge['price'];
            $num = $rate * $price;
            //充值增送积分
            $growthBrokerCredit = new GrowthBrokerCredit(array('id' => $broker_id));
            $growthBrokerCredit->increase('recharge', null, $num, 1, $recharge['transaction_id']);
            //充值方案
            $program = '充值' . $price . '元';
            if ($info['is_active']) 
            {
                $program .= ',赠送' . $payment_config['active']['percentage'] . '房豆';
            }
            $growthCredit = new GrowthCredit();
            $remain_num = $growthCredit->getValidCredit($broker_id);
            $field_values = array(
                'program' => $program, 'num' => $num,'source'=>1,
                'remain_num' => $remain_num,
                'status' => 1, 'ctime' => date('Y-m-d H:i:s')
            );

			//房豆充值成功通知财务系统任务表
			$paymentRechargeRecord->successJobInsert(array('payment_housebean_id' => $id));

            //更新重选过的参数
            $paymentRechargeRecord->update($field_values, $id, $broker_id);
            $paymentRechargeRecord->copyRechargeSuccessRecord($id);
            //通知微信
            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';
            }
            //向移动提交数据
            /*
            if ($pay_api != 'chinapay') {
                //经纪人参数
                $this->load->model('broker_model');
                $this->broker_model->set_uid($broker_id);
                $info = $this->broker_model->get_broker_info();
                $submit_data = array(
                    'trade_type_id' => 2,
                    'trade_activity' => $this->input->post("subject"),
                    'trade_time' => strtotime($this->input->post("notify_time")),
                    'trade_id' => $this->input->post("trade_no"),
                    'order_id' => $recharge['transaction_id'],
                    'order_amount' => $this->input->post("total_fee") * 100,
                    'user_name' => $info['truename'],
                    'user_tel' => $info['telno'],
                    'order_status' => 1,
                    'alipay_id' => $this->input->post("buyer_email"),
                    'order_city' => 'nj',
                );
                $this->load->helper('common_api_helper');
                curl_post_contents($this->config->item('alipay_mobile_notify_url'), $submit_data);
                echo 'success';
            }
            */
        }
        
    }
    
    //支付协议
    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('payment_agreement', $data_page);
    }

    public function alipay_test()
    {
        //验证选中的套餐及银行
        $para = array(
            'transaction_id' => 'ss',
            'price' => 0.01,
            'bg_ret_url' => "http://www.baidu.com",
            'page_ret_url' => "http://www.baidu.com",
            'ord_desc' =>  'esf_zsb_housebean',
            'ip' => GetIP(),
        );
        $this->load->library('payment/alipay/Alipay', '', 'ap');
        echo $this->ap->dopay($para, 'POST');
    }


	//发房协议
    public function houseagreement() 
    {
        //头部
        $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('house_agreement', $data_page);
    }
    public function orderQuery()
    {
        $this->load->library('payment/wxpay/NativePay');
        $out_trade_no = $_REQUEST["out_trade_no"];
        $input = new WxPayOrderQuery();
        $input->SetOut_trade_no($out_trade_no);
        $result = WxPayApi::orderQuery($input);
        $data = array('status' => 0);
        if(!empty($result['trade_state']) && $result['trade_state'] == 'SUCCESS'){
            $data['status'] = 1;
        }
        $this->load->model('ajax_model');
        echo $this->ajax_model->array_to_json($data);
    }
    public function successNew($id)
    {
        if(empty($id)){
            $this->jump($this->payment_model->get_module_url('recharge'),'参数不合法');
            return;
        }
        //经纪人参数
        $info = $this->user_arr;
        $broker_new_info =$this->broker_model->get_broker_info_by_uid($info['uid']);
        $data_page['broker_new_info'] = $broker_new_info;
        $paymentRechargeRecord = new PaymentRechargeRecord();
        //此处由于微信回调存在延迟，不能查询已支付的订单
        $recharge = $paymentRechargeRecord->getOneByIdAndBrokerIdNoStatus($id, $info['uid']);
        if(empty($recharge)){
            $this->jump($this->payment_model->get_module_url('recharge'),'参数不合法');
            return;
        }
        $data_page['orderId'] = $recharge['transaction_id'];
        $data_page['price'] = $recharge['price'];
        //获取纪经人积分和等级
        $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['page_title'] = '支付中心-支付成功';
        $data_page['css'] = load_css('zsb/css/v1.0/style1.css');
        $data_page['info'] = $info;
        $this->view('payment', 'payment_success_new', $data_page);
    }
}
