<?php
namespace User\Controller;
use Common\Controller\MemberbaseController;
class CenterController extends MemberbaseController {
	
	function _initialize(){
		parent::_initialize();
		vendor('Alipay.Corefunction');
		vendor('Alipay.Md5function');
		vendor('Alipay.Notify');
		vendor('Alipay.Submit'); 
		$this->check_login();
		$this->users_model=D("Common/Users");
		$this->usercourse_obj = D("Common/UsercourseView");
		$this->course_obj = D("Common/Course");
		$this->section_obj = D("Common/Section");
		$this->livesection_obj = D("Common/Livesection");
		$this->order_obj = D("Common/Order");
		$this->card_obj = D("Common/Card");
		$this->application_obj=D("Common/Application");
		$this->teacher_order = D("Common/Teacher_order");
		$this->papers_obj = D("Common/Exam_papers");
		$this->userpapers_obj = D("Common/Exam_userpapers");
		$this->myerrors = D("Common/Exam_myerrors");
		$this->shiti_obj = D("Common/Exam_shiti");
		$this->vipuser =M("Vipuser");
		$this->mycoupon =M("Mycoupon");
		$this->coupon=M("Coupon");
		$this->playpoint=M("Playpoint");
		$this->message_obj=M("Message");
		$userid=sp_get_current_userid();
		$user=$this->users_model->where(array("id"=>$userid))->find();
		$avatar=$user['avatar'];
        $isvip=$this->vipuser->where(array("uid"=>$userid ,"state"=>1))->find();
	    if($isvip){
	  	   $now=date("Y-m-d H:i:s");         
	  	   if(strtotime($isvip['endtime'])-strtotime($now)<0){
	  		$data['state']=2;
	  		$this->vipuser->where(array("uid"=>$userid))->save($data);
	  	   }
		} 
		$this->assign('avatar',$avatar);
		$this->assign('user_type',$user['user_type']);
		$this->assign('user',$user);
	}
	public function index() {
		$userid=sp_get_current_userid();
		$user=$this->users_model->where(array("id"=>$userid))->find();
		$count==$this->usercourse_obj->order('addtime desc')->where(array("user_id"=>$userid))->count();
		$page = $this->page($count, 5);
	    $isvip=$this->vipuser->where(array("uid"=>$userid ,"state"=>1))->find();
		if($isvip){
		  $playid=$this->playpoint->where(array('uid'=>$userid))->select();
		  foreach($playid as $n=> $val){   
		  	$id[]=$playid[$n]['cid'];
		  	$map['id']  = array('in',$id);
		  	$learning=$this->course_obj->order('id desc')->where($map)->select();
		  }
		  foreach($learning as $n=> $val){   
		  	$learning[$n]['course_id']=$learning[$n]['id'];
		  	$learning[$n]['studied']=$this->usercourse_obj->where(array('user_id'=>$userid,'course_id'=>$learning[$n]['id']))->getField('studied');
		  }
		}else{
			  $learning=$this->usercourse_obj->order('addtime desc')->where(array("user_id"=>$userid))->select();
		}
	
		if($learning){
			$learning_=1;
		}
	    foreach($learning as $n=> $val){   
			 $learning[$n]['youxiaoqi']=$this->course_obj->where(array('id'=>$val['course_id']))->getField('youxiaoqi');
			 $learning[$n]['course_type']=$this->course_obj->where(array('id'=>$val['course_id']))->getField('course_type');
			 $learning[$n]['ftfaddress']=$this->course_obj->where(array('id'=>$val['course_id']))->getField('ftfaddress');
			 $learning[$n]['teacher']=$this->course_obj->where(array('id'=>$val['course_id']))->getField('cs_teacher');
			 $learning[$n]['ftfstarttime']=$this->course_obj->where(array('id'=>$val['course_id']))->getField('ftfstarttime');
			 $learning[$n]['endtime']=subDate($learning[$n]['youxiaoqi'],$learning[$n]['addtime']);
             $learning[$n]['remainder']=time2string(strtotime($learning[$n]['endtime'])-strtotime(date('Y-m-d H:i:s')));
             $urlArr = explode("|",$learning[$n]['studied']);  
             $jnum=count( $urlArr)-1;
             $cs_id=$learning[$n][course_id];
			 $learning[$n]['ismarket']=$this->course_obj->where(array('id'=>$val['course_id']))->getField('markedid');
             if($learning[$n]['course_type']=='live'){
             	 $znum=$this->livesection_obj->where(array('csid'=>$cs_id))->count();
             }else{
				 if(!empty($learning[$n]['ismarket'])){
					$url=$this->marketUrl."/index.php?g=market&m=market&a=getMyMarketCourseSection";
					$date['marketId']=$learning[$n]['ismarket'];
					$date['marketcount']=$this->user_obj->where(array('id'=>$learning[$n]['teacher']))->getField('marketcount');
					$date['marketpass'] =$this->user_obj->where(array('id'=>$learning[$n]['teacher']))->getField('marketpass');
					$sc_list=json_decode(post_curl($url,$date),true);
					$znum=count($sc_list);
				 }else{
					 $znum=$this->section_obj->where(array('cs_id'=>$cs_id,'type_id'=>0,'state'=>1))->count();
				 }
             }
             $learning[$n]['bili'] = round(($jnum/$znum)*100);
             $learning[$n]['jnum']=$jnum;
             $learning[$n]['znum']=$znum;
	      }
		 $this->assign('learning',$learning);
		 $this->assign('learning_',$learning_);
		 $this->assign("Page", $page->show('Admin'));
		 $this->display(':center');
	}
	public function myclass(){
		$this->display(':index');
	}
	public function jihuo(){
	    $this->display(':jihuo');
	}
	public function jihuo_post(){
	   $this->usercourse = D("Common/Usercourse");
	   if(!sp_check_verify_code()){
    		$this->error("验证码错误！");
    	}
    	$rules = array(
    			array('card_name', 'require', '请输入激活码', 1 ),
    	);
    	if($this->card_obj->validate($rules)->create()===false){
    		$this->error($this->card_obj->getError());
    	}else{
    		$map['card_name']=I("post.card_name");
    		if($this->card_obj->where($map)->find()==false){
    			$this->error("输入的激活码错误！");
    		}else{
    			$carddata=$this->card_obj->where($map)->find();
    		   if($carddata['use_state']==1 or $carddata['card_state']==1){
    		      $this->error("激活码已经被使用，或激活码被锁定！");
    		   }else{
    		     $userid=sp_get_current_userid(); 
    		   	 $state['use_state']=1;
    		   	 $state['user_id']=$userid;
    		       		     
    		     if( $this->usercourse->where(array('user_id'=>$userid,'course_id'=>$carddata['cs_id']))->find()){
    		     	$this->error("已经购买了此课程，请不要重复激活！");
    		     }else{
    		     	 $cs_info=$this->course_obj->where(array('id'=>$carddata['cs_id']))->find();
    		     	 $c_data['user_id']=$userid;
	    	         $c_data['course_id']=$carddata['cs_id'];
	    	         $c_data['addtime']=date('Y-m-d H:i:s');
	    	         $c_data['state']=1;
					 $c_data['course_price']=$cs_info['cs_price'];
					 $c_data['teacher_id']=$cs_info['cs_teacher'];
					  $sailes['u_id']=$cs_info['cs_teacher'];
	    	          $sailes['c_id']=$carddata['cs_id'];
	    	          $sailes['money']=round($cs_info['cs_price']*C('cardbili') ,2); 					  
	    	          $sailes['addtime']=date('Y-m-d H:i:s');
	    	          $this->teacher_order->add($sailes);
             	     $this->usercourse->add($c_data);
    		     	 $this->card_obj->where($map)->save($state);
    		         $this->success('课程激活成功',U("User/center/count"));
    		     }                            
    		   } 
    		}
    	}  	
	}
    public function learned(){
		$userid=sp_get_current_userid();
		$user=$this->users_model->where(array("id"=>$userid))->find();
		$count==$this->usercourse_obj->order('addtime desc')->where(array("user_id"=>$userid))->count();
		$page = $this->page($count, 9);
	    $isvip=$this->vipuser->where(array("uid"=>$userid ,"state"=>1))->find();
		if($isvip){
		  $playid=$this->playpoint->where(array('uid'=>$userid))->select();
		  foreach($playid as $n=> $val){   
		  	$id[]=$playid[$n]['cid'];
		  	$map['id']  = array('in',$id);
		  	$learning=$this->course_obj->order('id desc')->where($map)->select();
		  }
		  foreach($learning as $n=> $val){   
		  	$learning[$n]['course_id']=$learning[$n]['id'];
		  	$learning[$n]['studied']=$this->usercourse_obj->where(array('user_id'=>$userid,'course_id'=>$learning[$n]['id']))->getField('studied');
		  }
		}else{
			 $learning=$this->usercourse_obj->order('addtime desc')->where(array("user_id"=>$userid))->select();
		}
	
		if($learning){
			$learning_=1;
		}
	    foreach($learning as $n=> $val){   
			 $learning[$n]['youxiaoqi']=$this->course_obj->where(array('id'=>$val['course_id']))->getField('youxiaoqi');
			 $learning[$n]['course_type']=$this->course_obj->where(array('id'=>$val['course_id']))->getField('course_type');
			 $learning[$n]['teacher']=$this->course_obj->where(array('id'=>$val['course_id']))->getField('cs_teacher');
			 $learning[$n]['endtime']=subDate($learning[$n]['youxiaoqi'],$learning[$n]['addtime']);
             $learning[$n]['remainder']=time2string(strtotime($learning[$n]['endtime'])-strtotime(date('Y-m-d H:i:s')));
			 $learning[$n]['ismarket']=$this->course_obj->where(array('id'=>$val['course_id']))->getField('markedid');
             $urlArr = explode("|",$learning[$n]['studied']);  
             $jnum=count( $urlArr)-1;
             $cs_id=$learning[$n][course_id];
			 
			 if(!empty($learning[$n]['ismarket'])){
				$url=$this->marketUrl."/index.php?g=market&m=market&a=getMyMarketCourseSection";
				$date['marketId']=$learning[$n]['ismarket'];
				$date['marketcount']=$this->user_obj->where(array('id'=>$learning[$n]['teacher']))->getField('marketcount');
				$date['marketpass'] =$this->user_obj->where(array('id'=>$learning[$n]['teacher']))->getField('marketpass');
				$sc_list=json_decode(post_curl($url,$date),true);
				$znum=count($sc_list);
			 }else{
				$znum=$this->section_obj->where(array('cs_id'=>$cs_id,'type_id'=>0,'state'=>1))->count();
			 }
             $learning[$n]['bili'] = round(($jnum/$znum)*100);
             $learning[$n]['jnum']=$jnum;
             $learning[$n]['znum']=$znum;
			 
	    } 
		 $this->assign('learning',$learning);
		 $this->assign('learning_',$learning_);
		 $this->assign("Page", $page->show('Admin'));
		 $this->display(':learned');
    }
    public function collect(){
    	$userid=sp_get_current_userid();
		$model = M('user_favorites'); 
		$count==$model->where(array("user_id"=>$userid))->count();
		$page = $this->page($count, 3);
    	$collect=$model->order('id desc')->where(array("uid"=>$userid))->select();
		foreach($collect as $n=> $val){
			$collect[$n]['voo']=$this->course_obj->where('id=\''.$val['object_id'].'\'')->field('cs_name,cs_picture,id,cs_addtime')->find();
			$collect[$n]['teacherid']=$this->course_obj->where('id=\''.$val['object_id'].'\'')->getField('cs_teacher');
			$collect[$n]['teachername']=$this->users_model->where('id=\''.$collect[$n]['teacherid'].'\'')->getField('user_nicename');
		}
       if($collect){
		   $collect_=1;
		}
		$this->assign('collect',$collect);
		$this->assign('collect_',$collect_);
		$this->assign('page', $page->show('Admin'));
		$this->display(':collect');
    }
    public function pinglun(){
     	
        $this->display(':pinglun');
    }
     public function setting(){
     	$userid=sp_get_current_userid();
		$user=$this->users_model->where(array("id"=>$userid))->find();
		$this->assign('user',$user);
        $this->display(':setting');
    }
     public function pic(){
     	$this->display(':pic');
    }
     public function security(){
     	
        $this->display(':security');
    }
     public function securitysave(){
     	$currentPassword=I("post.currentPassword");
     	$newPassword=I("post.newPassword");
     	$confirmPassword=I("post.confirmPassword");
        $userid=sp_get_current_userid();
		$user=$this->users_model->where(array("id"=>$userid))->find();
        if(strlen($newPassword) < 5 || strlen($password) > 20){
	       $this->error("密码长度至少5位，最多20位！");
        	
	    }
	    $user_pass=sp_password($newPassword);
		if($newPassword!=$confirmPassword){
		   $this->error("两次输入密码不一致！");
		   exit();
		}
		if(sp_compare_password($currentPassword, $user['user_pass'])){
			$data['user_pass']=$user_pass;
		   if($this->users_model->where(array('id'=>$userid))->save($data)){
		    session("user",null);
			$_SESSION['login_http_referer']=$referer;
			$this->success("密码更新成功！");
		   }
		}else{
		   $this->error("输入当前密码不正确！");
		}
    }
     public function count(){
     	$userid=sp_get_current_userid();
		$count1=$this->card_obj->where(array('user_id'=>$userid,'use_state'=>1))->order('addtime desc')->count();
     	$count2=$this->usercourse_obj->where(array("user_id"=>$userid))->order('addtime desc')->count();
		$page1 = $this->page($count1, 30);
		$page2 = $this->page($count2, 30);
     	$inflow=$this->card_obj->limit($page1->firstRow . ',' . $page1->listRows)->where(array('user_id'=>$userid,'use_state'=>1,'type_id'=>2))->order('addtime desc')->select();
     	$outflow=$this->usercourse_obj->limit($page2->firstRow . ',' . $page2->listRows)->where(array("user_id"=>$userid))->order('addtime desc')->select();
     	foreach($inflow as $n=> $val){           
            $inflownum=$inflownum+$val['card_price'];
	      }  
     	foreach($outflow as $n=> $val){           
            $outflownum=$outflownum+$val['course_price'];
	      }  
     	$this->assign('inflownum',$inflownum);
     	$this->assign('outflownum',$outflownum);
     	$this->assign('inflow',$inflow);
        $this->assign('outflow',$outflow);
		$this->assign("Page1", $page1->show('Admin'));
		$this->assign("Page2", $page2->show('Admin'));
     	$this->display(':count');
    }
    public function card(){
     	
        $this->display(':card');
    }
    public function vipcard(){
    	$this->display(':vipcard');
    }
	public function buyvip(){
		$this->display(':buyvip');
	}    	
    public function buyviporder(){
		$vipdata['price']=C('VIPPRICE');
		if(empty($vipdata['price'])){
			$vipdata['price']=0;
		}
		$vipdata['vipend']=date('Y-m-d',strtotime("+1 month"));  
		$this->assign('vipdata',$vipdata);
		$this->display(':buyviporder');
	}
	public function createorder(){
 	    $out_trade_no = date('Ymdhms').rand(100,999);
 	    $userid=sp_get_current_userid();
 	    $user=$this->user_obj->where(array("id"=>$userid))->find();
			$course_id=-1;
			$viptime_post=I("post.viptime_post");
			$vipprice_post=I("post.vipprice_post");
			$viptimes_post=I("post.viptimes_post");
			$order['user_id']=sp_get_current_userid();
			$order['orderid']=$out_trade_no;
			$order['course_id']=$course_id;
			$order['state']=2;
			$order['viptimes']=$viptime_post;
			$order['total']=$viptime_post*$vipprice_post;
			$order['addtime']=date('Y-m-d H:i:s');
			$order['viptimes']=$viptimes_post;
			$check=$this->order_obj->where(array("user_id"=>$userid,"course_id"=>$course_id,"state"=>2))->find();
			if(!$check){
					$this->order_obj->add($order);
					$this->assign("out_trade_no",$out_trade_no);
			}else{
				 $order['order']=$check['order'];
				 $this->order_obj->where(array('orderid'=>$check['orderid']))->save($order);
			     $this->assign("out_trade_no",$check['order']);
			}
			$this->assign("user",$user);
	    $this->assign("order",$order);
	    $this->display(':createorder');
	}
	public function payment(){
	    $payment=I("post.payment");
	    if($payment==''){
	    	$this->error('请选择支付方式！');
	    	exit();
	    }
	    if($payment=='alipay'){
	    	$this->payWithAlipay(); 
	    }
	    if($payment=='wxpay'){
	    	$this->payWithWxPay();
	    } 
	    if($payment=='yuepay'){
	    	$this->yuepay();
	    }
	}
	
	function yuepay(){
		 if(IS_POST){
	    	$userid=sp_get_current_userid();
	    	$user=$this->user_obj->where(array("id"=>$userid))->find();
	    	$totalmoney=$_POST['totalmoney'];
	    	$out_trade_no=$_POST['orderId'];
	    	$viptimes=$_POST['viptimes'];
	    	$this->assign("totalmoney",$totalmoney);
	    	$check=$this->vipuser->where(array("uid"=>$userid,"state"=>1))->find(); 
	    	if(!$check){
				if($user['coin']<$_POST['totalmoney']){
		    		 $this->error("您的账户余额不足！");
				}else{
					$result=1;
					$u_data['coin']=($user['coin'])-($totalmoney);
					$o_data['state']=1;
					$o_data['pay']="余额";
					$orderId=$_POST['orderId'];
					$this->order_obj->where(array("order"=>$orderId))->save($o_data);
					$this->user_obj->where(array("id"=>$userid))->save($u_data);
					$user_data['uid']=$userid;
					$user_data['vipcard']="在线支付";
					$user_data['state']=1;
					$user_data['startime']=date('Y-m-d H:i:s');
					$user_data['endtime']=date('Y-m-d H:i:s',strtotime("+".$viptimes."month"));  
					$user_data['vipprice'] =$totalmoney; 
					$user_data['duration'] =$viptimes;
					$message="您的订单".$out_trade_no."已成功支付,购买VIP会员".$viptimes."个月，到期时间为".$user_data['endtime']."快去学习吧！";
				    send_message($user_data['uid'],'0','1',$message);
					if($this->vipuser->add($user_data)){
						$this->success("支付成功,恭喜您成为VIP会员!",U("User/center/associator"));
					}                            
				}
	    	}else{
	    	   $this->error("您已经是VIP会员，请不要重复下单！",U("User/center/associator"));
	    	}
	   }
	}
	function payWithWxPay(){
		$time=time();
		session("url",null);
		$out_trade_no = $_POST['orderId'];
        $subject = $_POST['ordsubject'];  
        $total_fee = $_POST['totalmoney']; 
        $body = $_POST['ordbody'];  
        $show_url = $_POST['ordshow_url'];
		$userid=sp_get_current_userid();
		$check=$this->vipuser->where(array("uid"=>$userid,"state"=>1))->find(); 
		if(!$check){		
			if(sp_is_mobile()){ 
				Vendor('Weixinpay.wechatH5Pay');
				$appid = C('wx_APPID');
				$mch_id = C('wx_MCHID');
				$key = C('wx_KEY');
				$notify_url = sp_get_host().U('course/course/wxh5notify',array('out_trade_no'=>$out_trade_no));
				$redirect_url=sp_get_host().U('user/center/associator');
				$name="微信支付";
				$wechatAppPay = new \wechatAppPay($appid, $mch_id, $notify_url, $key);
				$order=array(
					'body'=>$subject,
					'total_fee'=>$total_fee*100,
					'out_trade_no'=>$out_trade_no,
					'trade_type'=>'MWEB',
					'scene_info'=>'{"h5_info": {"type":"Wap","wap_url": "'.sp_get_host().'","wap_name": "'.$name.'"}}'
				); 
				$result = $wechatAppPay->unifiedOrder($order);
				$url_encode_redirect=urlencode($redirect_url);
				$url = $result['mweb_url'].'&redirect_url='.$url_encode_redirect;
				echo "<script>window.location.href='".$url."';</script>";
				exit();
			}else{
				$order=array(
					'body'=>$subject,
					'total_fee'=>$total_fee*100,
					'out_trade_no'=>$out_trade_no,
					'product_id'=>$body
				); 
				$url= weixinpay($order);
				$_SESSION["url"]=$url;
				$this->assign("cid",$body);
				$this->assign("out_trade_no",$out_trade_no);
				$this->display(":payWithWxPay");
			}
		}else{
	    	   $this->error("您已经是VIP会员，请不要重复下单！",U("User/center/associator"));
	    }	
	}
	 public function qrcode(){
		 $url=$_SESSION["url"];
		 $size=8;
		 qrcode($url);
	 }
	
	function payWithAlipay(){
		$userid=sp_get_current_userid();
		$check=$this->vipuser->where(array("uid"=>$userid,"state"=>1))->find(); 
		if(!$check){
			 
			$alipay_config=array(
			   'partner' => C('partner'),
			   'key' => C('key'),
			   'sign_type' => C('sign_type'),
			   'input_charset' => C('input_charset'),
			   'cacert' => C('cacert'),
			   'transport' => 'http',
			 );
			$payment_type = "1"; 
			$notify_url = sp_get_host().U('user/center/notifyurl');
			$return_url = sp_get_host().'/index.php?g=user&m=center&a=returnurl';
			$seller_email = C('seller_email');
			$out_trade_no = $_POST['orderId'];
			$subject = $_POST['ordsubject'];  
			$total_fee = $_POST['totalmoney']; 
			$body = $_POST['ordbody'];  
			$show_url = $_POST['ordshow_url'];  
			$anti_phishing_key = "";
			$exter_invoke_ip = get_client_ip(); 
			$parameter = array(
				"service" => "create_direct_pay_by_user",
				"partner" => trim($alipay_config['partner']),
				"payment_type"    => $payment_type,
				"notify_url"    =>$notify_url,
				"return_url"    => $return_url,
				"seller_email"    => $seller_email,
				"out_trade_no"    => $out_trade_no,
				"subject"    => $subject,
				"total_fee"    => $total_fee,
				"body"            => $body,
				"show_url"    => $show_url,
				"anti_phishing_key"    => $anti_phishing_key,
				"exter_invoke_ip"    => $exter_invoke_ip,
				"_input_charset"    => trim(strtolower($alipay_config['input_charset']))
			);	
			$alipaySubmit = new \ AlipaySubmit($alipay_config);
			$html_text = $alipaySubmit->buildRequestForm($parameter,"post", "确认");
			echo $html_text;
		}else{
	    	$this->error("您已经是VIP会员，请不要重复下单！",U("User/center/associator"));
	    }		
	}
    function notifyurl(){
		$alipay_config=array(
           'partner' => C('partner'),
           'key' => C('key'),
           'sign_type' => C('sign_type'),
           'input_charset' => C('input_charset'),
           'cacert' => C('cacert'),
           'transport' => 'http',
         );
        $alipayNotify = new  \  AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify();
        if($verify_result) {
           $out_trade_no   = $_POST['out_trade_no'];      
           $trade_no       = $_POST['trade_no'];         
           $trade_status   = $_POST['trade_status'];     
           $total_fee      = $_POST['total_fee'];        
           $notify_id      = $_POST['notify_id'];         
           $notify_time    = $_POST['notify_time'];       
           $buyer_email    = $_POST['buyer_email']; 
		   $body           = $_POST['body'];  		   
           $parameter = array(
				 "out_trade_no"     => $out_trade_no, 
				 "trade_no"         => $trade_no,    
				 "total_fee"        => $total_fee,   
				 "trade_status"     => $trade_status, 
				 "notify_id"        => $notify_id,    
				 "notify_time"      => $notify_time,  
				 "buyer_email"      => $buyer_email, 
				 "body"             => $body, 
           );
           if($_POST['trade_status'] == 'TRADE_FINISHED' || $_POST['trade_status'] == 'TRADE_SUCCESS') {		   
	     		if(!checkorderstatus($out_trade_no)){
				   orderhandle($parameter); 
				   $user_data['uid']=sp_get_current_userid();
				   $user_data['vipcard']="在线支付";
				   $user_data['state']=1;
				   $user_data['startime']=date('Y-m-d H:i:s');
				   $user_data['endtime']=date('Y-m-d H:i:s',strtotime("+".$body."month"));  
				   $user_data['vipprice'] =$total_fee;
				   $user_data['duration'] =$body;
				   $message="您的订单".$out_trade_no."已成功支付,购买VIP会员".$body."个月，到期时间为".$user_data['endtime']."快去学习吧！";
				   send_message($user_data['uid'],'0','1',$message);
				   $this->vipuser->add($user_data);
	            }
            }
            echo "success";      
         }else {
            echo "fail";
        }    
    }
    function returnurl(){
        $alipay_config=array(
           'partner' => C('partner'),
           'key' => C('key'),
           'sign_type' => C('sign_type'),
           'input_charset' => C('input_charset'),
           'cacert' => C('cacert'),
           'transport' => 'http',
         );
        $alipayNotify = new  \ AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyReturn();
        if($verify_result) {
			$out_trade_no   = $_GET['out_trade_no'];     
			$trade_no       = $_GET['trade_no'];        
			$trade_status   = $_GET['trade_status'];     
			$total_fee      = $_GET['total_fee'];       
			$notify_id      = $_GET['notify_id'];        
			$notify_time    = $_GET['notify_time'];      
			$buyer_email    = $_GET['buyer_email'];      
			$body           = $_GET['body'];  
			$parameter = array(
				 "out_trade_no"     => $out_trade_no, 
				 "trade_no"         => $trade_no,    
				 "total_fee"        => $total_fee,   
				 "trade_status"     => $trade_status, 
				 "notify_id"        => $notify_id,    
				 "notify_time"      => $notify_time,  
				 "buyer_email"      => $buyer_email, 
				 "body"             => $body, 
			);
			if($_GET['trade_status'] == 'TRADE_SUCCESS') {
				if(!checkorderstatus($out_trade_no) || !$res=$this->usercourse_obj->where(array('user_id'=>sp_get_current_userid(),'course_id'=>$body))->find()){
				   orderhandle($parameter);  
				   $user_data['uid']=sp_get_current_userid();
			       $user_data['vipcard']="在线支付";
			       $user_data['state']=1;
			       $user_data['startime']=date('Y-m-d H:i:s');
			       $user_data['endtime']=date('Y-m-d H:i:s',strtotime("+".$body."month"));  
			       $user_data['vipprice'] =$total_fee;
			       $user_data['duration'] =$body;
				   $message="您的订单".$out_trade_no."已成功支付,购买VIP会员".$body."个月，到期时间为".$user_data['endtime']."快去学习吧！";
				   send_message($user_data['uid'],'0','1',$message);
			       $this->vipuser->add($user_data);
				 }
			    $this->redirect("User/center/associator");
			 }else {
				 echo "trade_status=".$_GET['trade_status'];
				 $this->redirect("User/center/associator");
			 }
		  }else {
			$this->redirect("User/center/associator");
			echo "支付失败！";
	  	}
	 }
	function payresult(){
		$c_id=  intval(I("get.id"));
		$trade_no=I("get.order");
		$userid=sp_get_current_userid();
		$csdata=$this->course_obj->where("id=$c_id")->find();
        $check=$this->usercourse_obj->where(array("user_id"=>$userid,"course_id"=>$c_id))->find();
		$payinfo=$this->order_obj->where(array('order'=>$trade_no))->find();
		if($check and $payinfo['state']==1){
			$message='支付成功！';
			$result=1;
		}else{
			$message='支付失败！';
			$result=0;
		}
		$this->assign("message",$message);
		$this->assign("time",$check['addtime']);
		$this->assign("result",$result);
		$this->assign("cs_data",$csdata);
		$this->assign("payinfo",$payinfo);
		$this->assign("trade_no",$trade_no);
		$this->display();
	}
	function chcckCoursePay(){
		$trade_no= I('post.trade_no');
		$data=$this->order_obj->where(array("order"=>$trade_no))->find();
		$check=$this->vipuser->where(array("uid"=>$data['user_id'],"state"=>1))->find(); 
	
		if($data['state']==1 and $check){
			$result['states']=true;
		}else{
			$result['states']=false;
		}
		$json_string = json_encode($result);
        echo $json_string;
		
	}
    public function coupon(){
    	$mycoupon=$this->mycoupon->where(array('userid'=>sp_get_current_userid()))->select();
    	foreach($mycoupon as $n=> $val){   
    		$mycoupon[$n]['coupon']=$this->coupon->where(array('id'=>$mycoupon[$n]['couponid'],'used_state'=>0))->find();
    		if($mycoupon[$n]['coupon']['timelimit'] < date('Y-m-d H:i:s')){
    			 $mycoupon[$n]['coupon']['state']=2;
    			}
    		}
    	$this->assign('mycoupon',$mycoupon);
    	$this->display(':coupon');
    }
	public function associator(){
		 $where['uid']=sp_get_current_userid(); 
		 $associatorlist=$this->vipuser->where($where)->select();
		 if($this->vipuser->where(array("uid"=>sp_get_current_userid(),"state"=>1))->find()){
		 	  $isvip=true;
		 } else{
		 		$isvip=false;
		 }
		  $this->assign('isvip',$isvip);
		 $this->assign('associatorlist',$associatorlist);
		 $this->display(':associator');
	}
     public function card_post(){
     	if(!sp_check_verify_code()){
    		$this->error("验证码错误！");
    	}
    	$rules = array(
    		array('card_name', 'require', '请输入点卡卡号', 1 ),
    	);
    	if($this->card_obj->validate($rules)->create()===false){
    		$this->error($this->card_obj->getError());
    	}else{
    		$map['card_name']=I("post.card_name");
    		if($this->card_obj->where($map)->find()==false){
    			$this->error("输入的卡号错误！");
    		}else{
    			$carddata=$this->card_obj->where($map)->find();
				if($carddata['type_id']!=1){
				   $this->error("此卡号不是充值卡,请确认后再充值！");
				}
    		   if($carddata['use_state']==1 or $carddata['card_state']==1){
    		      $this->error("卡号已经被使用，或卡号被锁定！");
    		   }else{
    		     $userid=sp_get_current_userid(); 
    		   	 $state['use_state']=1;
    		   	 $state['user_id']=$userid;
    		     $this->card_obj->where($map)->save($state);
    		     $user=$this->users_model->where(array("id"=>$userid))->find();
    		     $userdata['coin']=$user['coin']+$carddata['card_price'];
    		     if($this->users_model->where(array('id'=>$userid))->save($userdata)){
					$message="点卡充值成功，充值卡号为：".$map['card_name'].",充值金额为:".$carddata['card_price']."元";
				    send_message($userid,'0','1',$message);
    		     	$this->success('充值成功',U("User/center/count"));
    		     }                            
    		   } 
    		}
    	}  	
    }
	public function vipcard_post(){
		if(!sp_check_verify_code()){
    		$this->error("验证码错误！");
    	}
    	$rules = array(
    			array('card_name', 'require', '请输入点卡卡号', 1 ),
    	);
    	if($this->card_obj->validate($rules)->create()===false){
    		$this->error($this->card_obj->getError());
    	}else{
    		$map['card_name']=I("post.card_name");
    		if($this->card_obj->where($map)->find()==false){
    			$this->error("输入的卡号错误！");
    		}else{
    			$carddata=$this->card_obj->where($map)->find();
				if($carddata['type_id']!=3){
				   $this->error("此卡号不是VIP激活卡,请确认后再充值！");
				}
    		   if($carddata['use_state']==1 or $carddata['card_state']==1){
    		      $this->error("卡号已经被使用，或卡号被锁定！");
    		   }else{
    		   	 $isvip=$this->vipuser->where(array("uid"=>sp_get_current_userid(),"state"=>1))->find(); 
    		     if($isvip){
    		     	 $this->error("您已经是VIP会员，无需激活！");
    		     	 exit();
    		     	}else{
    		     		   $userid=sp_get_current_userid(); 
			    		   	 $state['use_state']=1;
			    		   	 $state['user_id']=$userid;
			    		     $this->card_obj->where($map)->save($state);
			    		     $user_data['uid']=$userid;
			    		     $user_data['vipcard']=$carddata['card_name'];
			    		     $user_data['state']=1;
			    		     $user_data['startime']=date('Y-m-d H:i:s');
			    		     $user_data['endtime']=date('Y-m-d H:i:s',strtotime("+".$carddata['viptime']."month"));  
			    		     $user_data['vipprice'] =$carddata['card_price']; 
			    		     $user_data['duration'] =$carddata['viptime'];
			    		     if($this->vipuser->add($user_data)){
								$message="恭喜您成为本站VIP会员，VIP期限为：".$carddata['viptime']."个月,VIP会员期限内,站内所有课程免费学习!";
								send_message($userid,'0','1',$message);			    		   
			    		     	$this->success('VIP会员激活成功',U("User/center/associator"));
			    		     }                            
    		     	}
    		   } 
    		}
    	}  	
		
	}
    public function order(){
				$state=ReplaceSpecialChar(I("get.state"));
				$user_id=sp_get_current_userid();
				$where=empty($state)?array("user_id = $user_id"):array("user_id = $user_id and state=$state");
				$count=$this->order_obj->where($where)->count();
				$page = $this->page($count, 10);
				$data=$this->order_obj->limit($page->firstRow . ',' . $page->listRows)->where($where)->order('addtime desc')->select();
				foreach($data as $n=> $val){           
		            $data[$n]['coursename']=$this->course_obj->where(array('id'=>$data[$n]['course_id']))->getField('cs_name');
					$data[$n]['coursepic']=$this->course_obj->where(array('id'=>$data[$n]['course_id']))->getField('cs_picture');
					$data[$n]['coursetype']=$this->course_obj->where(array('id'=>$data[$n]['course_id']))->getField('course_type');
			  }  
				$num=$this->order_obj->where(array('state'=>2,'user_id'=>$user_id))->count();
		    $this->assign('num',$num);
		    $this->assign('order',$data);
		    $this->assign('state',$state);
			  $this->assign("Page", $page->show('Admin'));
		    $this->display(':order');
		}
		function avatar(){
		    $this->display();
    }
    function avatar_upload(){
    	$config=array(
    			'rootPath' => './'.C("UPLOADPATH"),
    			'savePath' => './avatar/',
    			'maxSize' => 3024000,
    			'saveName'   =>    array('uniqid',''),
    			'exts'       =>    array('jpg', 'png', 'jpeg'),
    			'autoSub'    =>    false,
    	);
    	$driver_type = sp_is_sae()?"Sae":'Local';
    	$upload = new \Think\Upload($config,$driver_type);//
    	$info=$upload->upload();
    	if ($info) {
    		$first=array_shift($info);
    		$file=$first['savename'];
    		$_SESSION['avatar']=$file;
    		$this->ajaxReturn(sp_ajax_return(array("file"=>$file),"上传成功！",1),"AJAX_UPLOAD");
    	} else {
    		$this->ajaxReturn(sp_ajax_return(array(),$upload->getError(),0),"AJAX_UPLOAD");
    	}
    }
    
    function avatar_update(){
    	if(!empty($_SESSION['avatar'])){
    		$targ_w = intval($_POST['w']);
    		$targ_h = intval($_POST['h']);
    		$x = $_POST['x'];
    		$y = $_POST['y'];
    		$jpeg_quality = 90;
    		
    		$avatar=$_SESSION['avatar'];
    		$avatar_dir=C("UPLOADPATH")."avatar/";
    		if(sp_is_sae()){
    			$src=C("TMPL_PARSE_STRING.__UPLOAD__")."avatar/$avatar";
    		}else{
    			$src = $avatar_dir.$avatar;
    		}
    		
    		$avatar_path=$avatar_dir.$avatar;
    		
    		
    		if(sp_is_sae()){
    			$img_data = sp_file_read($avatar_path);
    			$img = new \SaeImage();
    			$size=$img->getImageAttr();
    			$lx=$x/$size[0];
            	$rx=$x/$size[0]+$targ_w/$size[0];
            	$ty=$y/$size[1];
            	$by=$y/$size[1]+$targ_h/$size[1];
    			
    			$img->crop($lx, $rx,$ty,$by);
    			$img_content=$img->exec('png');
    			sp_file_write($avatar_dir.$avatar, $img_content);
    		}else{
    			$image = new \Think\Image();
    			$image->open($src);
    			$image->crop($targ_w, $targ_h,$x,$y);
    			$image->save($src);
    		}
    		
    		$userid=sp_get_current_userid();
    		$result=$this->users_model->where(array("id"=>$userid))->save(array("avatar"=>$avatar));
    		$_SESSION['user']['avatar']=$avatar;
    		if($result){
    			$this->success("头像更新成功！");
    		}else{
    			$this->error("头像更新失败！");
    		}
    		
    	}
    }
    function application(){
    	$isapp=$this->application_obj->where(array('user_id'=>sp_get_current_userid()))->find();
        $this->assign('isapp',$isapp);
        $this->display(':application');
    }
   function application_post(){
     if(IS_POST){
		 $data=I('post.');
     	 $data['user_id']=sp_get_current_userid(); 
         $data['state']=0;
         $data['addtime']=date('Y-m-d H:i:s');
         if(empty($data['t_name'])){
			 $this->error("请填写用户名！");
		 }
		 if(empty($data['sex'])){
			 $this->error("请填写性别！");
		 }
		 if(empty($data['nianling'])){
			 $this->error("请填写年龄！");
		 }
		 if(empty($data['xueli'])){
			 $this->error("请填写最高学历");
		 }
		 if(empty($data['school'])){
			 $this->error("请填写毕业学校");
		 }
		 if(empty($data['tel'])){
			 $this->error("请填写联系电话");
		 }
		 if(empty($data['signature'])){
			 $this->error("请填写个人简介");
		 }
		  if(empty($data['zigezheng'])){
			 $this->error("请上传职称证书");
		 }
         $result=$this->application_obj->add($data);
			if ($result) {
				
					$this->success("提交成功！");
				}else{
					$this->error("提交失败！");
				}			
        }
    }
	function myeaxm(){
		$userid=sp_get_current_userid();
		$count=$this->userpapers_obj->where(array('userid'=>$userid))->count();
		$page = $this->page($count, 10);
		$myexam=$this->userpapers_obj->limit($page->firstRow . ',' . $page->listRows)->where(array('userid'=>$userid))->select();
		foreach($myexam as $n=> $val){           
            $myexam[$n]['title']=$this->papers_obj->where(array('id'=>$myexam[$n]['papersid']))->getField('title');
			$myexam[$n]['cs_id']=$this->papers_obj->where(array('id'=>$myexam[$n]['papersid']))->getField('cs_id');
			$myexam[$n]['nianyue']=date('Y-m-d',strtotime($myexam[$n]['addtime']));
			$myexam[$n]['time']=date('H:i:s',strtotime($myexam[$n]['addtime']));
	      }  
		$this->assign("Page", $page->show('Admin'));
		$this->assign("myexam", $myexam);
        $this->display(':myexam');
	}
	function myerrors(){
		$userid=sp_get_current_userid();
		$myerrorids=json_decode($this->myerrors->where(array('uid'=>$userid))->getField('shitiid'));
		if($myerrorids){
			$result=1;
			$ids=join(",",$myerrorids);
			$count=$this->shiti_obj->where("id in ($ids)")->count();
			$page = $this->page($count, 10);
			$myerrors=$this->shiti_obj->limit($page->firstRow . ',' . $page->listRows)->where("id in ($ids)")->select();
			$this->assign("Page", $page->show('Admin'));
			$this->assign("myerrors", $myerrors);
		}else{
			$result=0;
		}
		$this->assign("result", $result);
        $this->display(':myerrors');
	}
	function message(){
		$type=empty(I("get.option"))?1:I("get.option");
		$userid=sp_get_current_userid();
		$message=$this->message_obj->where(array('touid'=>$userid,'type'=>$type))->order('id desc')->select();
		foreach($message as $n=> $val){     
			$message[$n]['tempread']=$message[$n]['isread'];
			$message[$n]['avatar']=$this->users_model->where(array('id'=>$message[$n]['fromuid']))->getField('avatar');
			$message[$n]['username']=$this->users_model->where(array('id'=>$message[$n]['fromuid']))->getField('user_nicename');
			$this->message_obj->where(array('id'=>$message[$n]['id'],'isread'=>'0'))->setField('isread','1');
		}
		$this->assign("type", $type);
		$this->assign("message", $message);
		$this->display(':message');
	}
	function delMessage(){
		$id=I("post.id");
		if($this->message_obj->where(array('id'=>$id))->delete()){
			$res['message']='success';
		}else{
			$res['message']=false;
		}
		$this->ajaxReturn($res);	
	}
	function sentMessage(){
		$id=I("get.id");
		if(empty(!$id)){
			$Info=$this->users_model->where(array('id'=>$id))->find();
			$this->assign("Info", $Info);
		}
		$this->display(':sentmessage');
	}
	function sendMessage_post(){
		$data=I("post.");
		
		if(empty($data['content'])){
			$this->error('请填写内容！');
		}
		if(empty($data['uid'])){
			if(empty($data['name'])){
				$this->error('请填写用户名！');
				exit();
			}
			if(preg_match("/^1[34578]{1}\d{9}$/",$data['name'])){  
				$data['uid']=$this->users_model->where(array('mobile'=>$data['name']))->getField('id');
			}else{  
			    $data['uid']=$this->users_model->where(array('user_nicename'=>$data['name']))->getField('id');
			}
		}
		if(empty($data['uid'])){
			$this->error('查无此人！');
		}
		$fromId=sp_get_current_userid();
		$res=send_message($data['uid'],$fromId,'2',$data['content']);
	    if($res){
			$this->success('发送成功',U('User/Center/sentmessage'));
		}else{
			$this->error('发送失败',U('User/Center/sendMessage'));
		}
	}
	function conversation(){
		$messageId=I('get.id');
		$messageDate=$this->message_obj->where(array('id'=>$messageId))->find();
		$messageDate['avatar']=$this->users_model->where(array('id'=>$messageDate['fromuid']))->getField('avatar');
		$messageDate['username']=$this->users_model->where(array('id'=>$messageDate['fromuid']))->getField('user_nicename');
		$this->assign("messageDate", $messageDate);
		$this->display(':conversation');
	}
       
}