<?php
namespace Course\Controller;
use Common\Controller\HomebaseController;
header("Content-Type: text/html; charset=utf-8");
class CourseController extends HomebaseController {
	protected $course_obj;
	protected $courseview_obj;
	protected $coursetype_obj;
	protected $usercourse_obj;
	protected $section_obj;
	protected $order_obj;
	protected $user_obj;
	protected $label_obj;
	protected $user_favorites_obj;
	function _initialize() {
		parent::_initialize();
		vendor('Alipay.Corefunction');
		vendor('Alipay.Md5function');
		vendor('Alipay.Notify');
		vendor('Alipay.Submit');
		$this->course_obj = D("Common/Course");
		$this->coursetype_obj = D("Common/coursetype");
		$this->section_obj = D("Common/Section");
		$this->livesection_obj= D("Common/Livesection");
		$this->courseview_obj = D("Common/CourseView");
		$this->usercourse_obj = D("Common/Usercourse");
		$this->order_obj = D("Common/Order");
		$this->user_obj = D("Common/Users");
		$this->label_obj = D("Common/Label");
		$this->live_obj = D("Common/Live");
		$this->material_obj = D("Common/Material");
		$this->user_favorites_obj = D("Common/user_favorites");
		$this->teacher_order = D("Common/Teacher_order");
		$this->papers_obj = D("Common/Exam_papers");
		$this->userpapers_obj = D("Common/Exam_userpapers");
		$this->slide_obj = D("Common/Slide");
		$this->notes_obj = D("Common/notest");
		$this->comments_obj = D("Common/comments");
		$this->playpoint_obj = D("Common/playpoint");
		$this->vipuser=D("Common/Vipuser");
		$this->discount=D("Common/Discount");
		$this->mycoupon=M("Mycoupon");
		$this->coupon=M("Coupon");
		$this->isvip();
	}
	
	public function coursecenter(){
		if(C('dianboIsOpen')==0){
			$this->error('录播模块未开启');
		}
		$toptype=$this->coursetype_obj->where('parent=0')->order('listorder asc')->select();
		$topid=intval(I("get.topid"));
		$childid= intval(I("get.childid"));
		$thirdid= intval(I("get.thirdid"));
		$labelid= intval(I("get.labelid"));
		$labelid= intval(I("get.labelid"));
		$filter['cs_price']= I("get.cs_price");
		$filter['stu_numbers']= I("get.stu_numbers");
		if(!empty($topid)){
			if(!empty($childid)){
				if(!empty($thirdid)){
					if(!empty($labelid)){
						$map=array("cs_state"=>1,"course_type"=>array('NEQ','live'),"ty_id"=>$thirdid,"labelid"=>$labelid);
						$childtype=$this->coursetype_obj->where('parent='.$topid)->order('listorder asc')->select();
						$thirdtype=$this->coursetype_obj->where('parent='.$childid)->order('listorder asc')->select();
						$label=$this->label_obj->where('c_id='.$thirdid)->order('listorder asc')->select();	
						//$topid不空，$childid不空，$thirdid不空,$labelid不空
					}else{
						$map=array("cs_state"=>1,"course_type"=>array('NEQ','live'),"ty_id"=>$thirdid);
						$childtype=$this->coursetype_obj->where('parent='.$topid)->order('listorder asc')->select();
						$thirdtype=$this->coursetype_obj->where('parent='.$childid)->order('listorder asc')->select();
						$label=$this->label_obj->where('c_id='.$thirdid)->order('listorder asc')->select();	
						//$topid不空，$childid不空，$thirdid不空 $labelid 空
					}
				}else{
					$childtype=$this->coursetype_obj->where('parent='.$topid)->order('listorder asc')->select();
					$thirdtype=$this->coursetype_obj->where('parent='.$childid)->order('listorder asc')->select();
					$label=$this->label_obj->where('c_id='.$childid)->order('listorder asc')->select();
					if(!empty($thirdtype)){
						foreach($thirdtype as $n=> $val){
								$child1Ids[] = $thirdtype[$n]['term_id'];
						}	
						$map=array("cs_state"=>1,"course_type"=>array('NEQ','live'),"ty_id"=>array(in,$child1Ids));
					}else{
						$map=array("cs_state"=>1,"course_type"=>array('NEQ','live'),"ty_id"=>$childid);
					}
					//$topid不空，$childid不空，$thirdid空
			  }
			}else{
				$child1=$this->coursetype_obj->where('parent='.$topid)->order('listorder asc')->select();
				$label=$this->label_obj->where('c_id='.$topid)->order('listorder asc')->select();
				$childtype=$child1;
				if(!empty( $child1)){
						foreach($child1 as $n=> $val){
							$child1Ids[] = $child1[$n]['term_id'];
						}
						$map1['parent']= array('in',$child1Ids);
					  $child2=$this->coursetype_obj->where($map1)->order('listorder asc')->select();
						foreach($child2 as $n=> $val){
							$child2Ids[] = $child2[$n]['term_id'];
				 		}
				 		if(!empty($child2Ids)){
								$childs= array_merge($child1Ids,$child2Ids);
						}else{
								$childs=$child1Ids;
						}	
						$map=array("cs_state"=>1,"course_type"=>array('NEQ','live'),"ty_id"=>array(in,$childs));
				}else{
					  $map=array("cs_state"=>1,"course_type"=>array('NEQ','live'),"ty_id"=>$topid);
				}
				//$topid不空，$childid空
			}
			
		}else{
			$map=array("cs_state"=>1,"course_type"=>array('NEQ','live'));
				//$topid空
		}
		$discount=$this->discount->find();
		$discount['ids']=json_decode($discount['c_ids'],true);
		$count=$this->course_obj->where($map)->count();
		$page = $this->page($count, 16);
		if(!empty($filter['cs_price'])){
			$order=array('cs_price'=>$filter['cs_price']);
		}elseif(!empty($filter['stu_numbers'])){
			$order=array('stu_numbers'=>$filter['stu_numbers']);
		}else{
			$order=array('listorder'=>'asc','id'=>'desc');
		}
		$map2['course_type']=array('not in','live,ftf');
		$csdata=$this->course_obj->limit($page->firstRow . ',' . $page->listRows)->order($order)->where($map)->where($map2)->select();
		foreach($csdata as $n=> $val){
			$csdata[$n]['xueyuannum']=$this->usercourse_obj->where('course_id=\''.$val['id'].'\'')->count()+$val['cs_xuni'];
			$csdata[$n]['pinglununm']=$this->usercourse_obj->where(array('course_id'=>$val['id'],'pinglun'=>array('NEQ','NULL')))->count();
			if(in_array($csdata[$n]['id'], $discount['ids'])  and   strtotime($discount['starttime']) <strtotime(date('Y-m-d H:i:s',time()))  and strtotime(date('Y-m-d H:i:s',time())) < strtotime($discount['endtime'])){
				$csdata[$n]['discount']=1;
			}
		}
		$this->assign("topid",$topid);
		$this->assign("childid",$childid);
		$this->assign("thirdid",$thirdid);
		$this->assign("labelid",$labelid);
		$this->assign("toptype",$toptype);
		$this->assign("childtype",$childtype);
		$this->assign("thirdtype",$thirdtype);
		$this->assign("label",$label);
		$this->assign("name",'课程中心');
		$this->assign("csdata",$csdata);
		$this->assign("Page", $page->show('Admin'));
	    $this->display();
	}
	public function ftfcourse(){
		if(C('xianxiaIsOpen')==0){
			$this->error('线下模块未开启');
		}
		$toptype=$this->coursetype_obj->where('parent=0')->order('listorder asc')->select();
		$topid=intval(I("get.topid"));
		$childid= intval(I("get.childid"));
		$thirdid= intval(I("get.thirdid"));
		$labelid= intval(I("get.labelid"));
		$labelid= intval(I("get.labelid"));
		$filter['cs_price']= I("get.cs_price");
		$filter['stu_numbers']= I("get.stu_numbers");
		if(!empty($topid)){
			if(!empty($childid)){
				if(!empty($thirdid)){
					if(!empty($labelid)){
						$map=array("cs_state"=>1,"course_type"=>array('NEQ','live'),"ty_id"=>$thirdid,"labelid"=>$labelid);
						$childtype=$this->coursetype_obj->where('parent='.$topid)->order('listorder asc')->select();
						$thirdtype=$this->coursetype_obj->where('parent='.$childid)->order('listorder asc')->select();
						$label=$this->label_obj->where('c_id='.$thirdid)->order('listorder asc')->select();	
						//$topid不空，$childid不空，$thirdid不空,$labelid不空
					}else{
						$map=array("cs_state"=>1,"course_type"=>array('NEQ','live'),"ty_id"=>$thirdid);
						$childtype=$this->coursetype_obj->where('parent='.$topid)->order('listorder asc')->select();
						$thirdtype=$this->coursetype_obj->where('parent='.$childid)->order('listorder asc')->select();
						$label=$this->label_obj->where('c_id='.$thirdid)->order('listorder asc')->select();	
						//$topid不空，$childid不空，$thirdid不空 $labelid 空
					}
				}else{
					$childtype=$this->coursetype_obj->where('parent='.$topid)->order('listorder asc')->select();
					$thirdtype=$this->coursetype_obj->where('parent='.$childid)->order('listorder asc')->select();
					$label=$this->label_obj->where('c_id='.$childid)->order('listorder asc')->select();
					if(!empty($thirdtype)){
						foreach($thirdtype as $n=> $val){
								$child1Ids[] = $thirdtype[$n]['term_id'];
						}	
						$map=array("cs_state"=>1,"course_type"=>array('NEQ','live'),"ty_id"=>array(in,$child1Ids));
					}else{
						$map=array("cs_state"=>1,"course_type"=>array('NEQ','live'),"ty_id"=>$childid);
					}
					//$topid不空，$childid不空，$thirdid空
			  }
			}else{
				$child1=$this->coursetype_obj->where('parent='.$topid)->order('listorder asc')->select();
				$label=$this->label_obj->where('c_id='.$topid)->order('listorder asc')->select();
				$childtype=$child1;
				if(!empty( $child1)){
						foreach($child1 as $n=> $val){
							$child1Ids[] = $child1[$n]['term_id'];
						}
						$map1['parent']= array('in',$child1Ids);
					  $child2=$this->coursetype_obj->where($map1)->order('listorder asc')->select();
						foreach($child2 as $n=> $val){
							$child2Ids[] = $child2[$n]['term_id'];
				 		}
				 		if(!empty($child2Ids)){
								$childs= array_merge($child1Ids,$child2Ids);
						}else{
								$childs=$child1Ids;
						}	
						$map=array("cs_state"=>1,"course_type"=>array('NEQ','live'),"ty_id"=>array(in,$childs));
				}else{
					  $map=array("cs_state"=>1,"course_type"=>array('NEQ','live'),"ty_id"=>$topid);
				}
				//$topid不空，$childid空
			}
			
		}else{
			$map=array("cs_state"=>1,"course_type"=>array('NEQ','live'));
				//$topid空
		}
		$discount=$this->discount->find();
		$discount['ids']=json_decode($discount['c_ids'],true);
		$count=$this->course_obj->where($map)->count();
		$page = $this->page($count, 16);
		if(!empty($filter['cs_price'])){
			$order=array('cs_price'=>$filter['cs_price']);
		}elseif(!empty($filter['stu_numbers'])){
			$order=array('stu_numbers'=>$filter['stu_numbers']);
		}else{
			$order=array('listorder'=>'asc','id'=>'desc');
		}
		$map2['course_type']=array('EQ','ftf');
		$csdata=$this->course_obj->limit($page->firstRow . ',' . $page->listRows)->order($order)->where($map)->where($map2)->select();
		foreach($csdata as $n=> $val){
			$csdata[$n]['xueyuannum']=$this->usercourse_obj->where('course_id=\''.$val['id'].'\'')->count()+$val['cs_xuni'];
			$csdata[$n]['pinglununm']=$this->usercourse_obj->where(array('course_id'=>$val['id'],'pinglun'=>array('NEQ','NULL')))->count();
			if(in_array($csdata[$n]['id'], $discount['ids'])  and   strtotime($discount['starttime']) <strtotime(date('Y-m-d H:i:s',time()))  and strtotime(date('Y-m-d H:i:s',time())) < strtotime($discount['endtime'])){
				$csdata[$n]['discount']=1;
			}
		}
		$this->assign("topid",$topid);
		$this->assign("childid",$childid);
		$this->assign("thirdid",$thirdid);
		$this->assign("labelid",$labelid);
		$this->assign("toptype",$toptype);
		$this->assign("childtype",$childtype);
		$this->assign("thirdtype",$thirdtype);
		$this->assign("label",$label);
		$this->assign("name",'课程中心');
		$this->assign("csdata",$csdata);
		$this->assign("Page", $page->show('Admin'));
	    $this->display();
	} 
	public function livecourse(){
		if(C('zhiboIsOpen')==0){
			$this->error('直播模块未开启');
		}
		$alllessoon=$this->livesection_obj->select();
		$nowlesson=array();
		$recentlylesson=array();
		foreach($alllessoon as $n=> $val){
			if(strtotime($alllessoon[$n]['starttime'])< strtotime(date('Y-m-d H:i:s',time())) and strtotime(date('Y-m-d H:i:s',time()))< strtotime($alllessoon[$n]['endtime'])){
				array_push($nowlesson,$alllessoon[$n]['csid']);
				$tids=join(",",$nowlesson);
				$nowcourse=$this->course_obj->where("id in ($tids)")->select();
				$now=array_unset_tt($nowcourse,id);
			}
			if(strtotime(date('Y-m-d H:i:s', time()))< strtotime($alllessoon[$n]['starttime'])){
			  array_push($recentlylesson,$alllessoon[$n]['csid']);
				$tids=join(",",$recentlylesson);
				$recently=$this->course_obj->where("id in ($tids)")->select();
				$recently=array_unset_tt($recently,id);
			}
		}
		foreach($recently as $n=> $val){
			$map['csid']=$recently[$n]['id'];
			$map['type_id']=1;
			$map['state']=1;
			$map['starttime']=array('gt',(date('Y-m-d H:i:s',time())));
			 $recently[$n]['les']=$this->livesection_obj->where($map)->order('starttime asc')->limit(1)->getField("starttime");
			}
 		$recently=$this->arr_sort($recently,'recently_starttime');
		$recently=array_slice($recently, 0, 3);
		$now=$this->arr_sort($now,'recently_starttime');
		$now=array_slice($now, 0, 3);
		$slide=$this->slide_obj->where(array('slide_cid'=>2,'slide_status'=>1))->select();
		$this->assign("slide",$slide);
		$this->assign("recently",$recently);
		$this->assign("now",$now);
		$this->assign("name",'直播课程');
	    $this->display();
	}
	public function  livecoursecenter(){
		if(C('zhiboIsOpen')==0){
			$this->error('直播模块未开启');
		}
		$toptype=$this->coursetype_obj->where('parent=0')->order('listorder asc')->select();
		$topid=intval(I("get.topid"));
		$childid= intval(I("get.childid"));
		$thirdid= intval(I("get.thirdid"));
		$labelid= intval(I("get.labelid"));
		if(!empty($topid)){
			if(!empty($childid)){
				if(!empty($thirdid)){
					if(!empty($labelid)){
						$map=array("cs_state"=>1,"course_type"=>array('EQ','live'),"ty_id"=>$thirdid,"labelid"=>$labelid);
						$childtype=$this->coursetype_obj->where('parent='.$topid)->order('listorder asc')->select();
						$thirdtype=$this->coursetype_obj->where('parent='.$childid)->order('listorder asc')->select();
						$label=$this->label_obj->where('c_id='.$thirdid)->order('listorder asc')->select();	
						//$topid不空，$childid不空，$thirdid不空,$labelid不空
					}else{
						$map=array("cs_state"=>1,"course_type"=>array('EQ','live'),"ty_id"=>$thirdid);
						$childtype=$this->coursetype_obj->where('parent='.$topid)->order('listorder asc')->select();
						$thirdtype=$this->coursetype_obj->where('parent='.$childid)->order('listorder asc')->select();
						$label=$this->label_obj->where('c_id='.$thirdid)->select();	
						//$topid不空，$childid不空，$thirdid不空 $labelid 空
					}
				}else{
					$childtype=$this->coursetype_obj->where('parent='.$topid)->order('listorder asc')->select();
					$thirdtype=$this->coursetype_obj->where('parent='.$childid)->order('listorder asc')->select();
					if(!empty($thirdtype)){
						foreach($thirdtype as $n=> $val){
								$child1Ids[] = $thirdtype[$n]['term_id'];
						}	
						$map=array("cs_state"=>1,"course_type"=>array('EQ','live'),"ty_id"=>array(in,$child1Ids));
					}else{
						$map=array("cs_state"=>1,"course_type"=>array('EQ','live'),"ty_id"=>$childid);
					}
					//$topid不空，$childid不空，$thirdid空
			  }
			}else{
				$child1=$this->coursetype_obj->where('parent='.$topid)->order('listorder asc')->select();
				$childtype=$child1;
				if(!empty( $child1)){
						foreach($child1 as $n=> $val){
							$child1Ids[] = $child1[$n]['term_id'];
						}
						$map1['parent']= array('in',$child1Ids);
					  $child2=$this->coursetype_obj->where($map1)->order('listorder asc')->select();
						foreach($child2 as $n=> $val){
							$child2Ids[] = $child2[$n]['term_id'];
				 		}
				 		if(!empty($child2Ids)){
								$childs= array_merge($child1Ids,$child2Ids);
						}else{
								$childs=$child1Ids;
						}	
						$map=array("cs_state"=>1,"course_type"=>array('EQ','live'),"ty_id"=>array(in,$childs));
				}else{
					  $map=array("cs_state"=>1,"course_type"=>array('EQ','live'),"ty_id"=>$topid);
				}
				//$topid不空，$childid空
			}
			
		}else{
			$map=array("cs_state"=>1,"course_type"=>array('EQ','live'));
				//$topid空
		}
		$discount=$this->discount->find();
		$discount['ids']=json_decode($discount['c_ids'],true);
		$count=$this->course_obj->where($map)->count();
		$page = $this->page($count, 16);
		$csdata=$this->course_obj->limit($page->firstRow . ',' . $page->listRows)->order(array('listorder'=>'asc','id'=>'desc'))->where($map)->select();
		foreach($csdata as $n=> $val){
			$csdata[$n]['xueyuannum']=$this->usercourse_obj->where('course_id=\''.$val['id'].'\'')->count()+$val['cs_xuni'];
			$csdata[$n]['pinglununm']=$this->usercourse_obj->where(array('course_id'=>$val['id'],'pinglun'=>array('NEQ','NULL')))->count();
			if(in_array($csdata[$n]['id'], $discount['ids'])  and   strtotime($discount['starttime']) <strtotime(date('Y-m-d H:i:s',time()))  and strtotime(date('Y-m-d H:i:s',time())) < strtotime($discount['endtime'])){
				$csdata[$n]['discount']=1;
			}
		}
		$this->assign("topid",$topid);
		$this->assign("childid",$childid);
		$this->assign("thirdid",$thirdid);
		$this->assign("labelid",$labelid);
		$this->assign("toptype",$toptype);
		$this->assign("childtype",$childtype);
		$this->assign("thirdtype",$thirdtype);
		$this->assign("label",$label);
		$this->assign("name",'直播课程');
		$this->assign("csdata",$csdata);
		$this->assign("Page", $page->show('Admin'));
	  $this->display();
	}
	public function search(){
		if(IS_POST){
			$key=I("post.keywords");
			if(empty($key)){
				$map['cs_state'] = 1;
			}else{
				$map['cs_state'] = 1;
				$map['cs_name'] = array('like','%'.$key.'%');
			}
			$count=$this->course_obj->where($map)->count();
			$page = $this->page($count, 16);
			$course = $this->course_obj->where($map)->select();
			$this->assign("course",$course);
			$this->assign("name",'搜索结果');
			$this->assign("Page", $page->show('Admin'));
			$this->display();
		}
		
	}
	
	public function  selectcourse(){
	   $type_id=I("get.id");
       $course = $this->course_obj->order(array("id"=>"asc"))->where(array('ty_id'=>$type_id))->select();
       $json_string = json_encode($course);
       echo $json_string;
		
	}
	public function isbuy(){
		$map['user_id']=sp_get_current_userid();
		$map['course_id']=I("post.cid");
		$sid=I("post.sid");
		$teacherid=$this->course_obj->where(array('id'=>$map['course_id']))->getField('cs_teacher');
		$isfree1=$this->section_obj->where(array('id'=>$sid))->getField('is_free');
		$isfree2=$this->livesection_obj->where(array('id'=>$sid))->getField('isfree');
		$isvip=$this->isvip();
		if($buyinfo=$this->usercourse_obj->where($map)->find() or $teacherid==$map['user_id'] or $isfree1==1 or $isfree2==1 or $isvip){
		    $isbuy['states']=true;
		}else{
			  $isbuy['states']=false;
		}
		$this->ajaxReturn($isbuy);
	}
	public function getchildtype(){
		$id=intval(I("post.id"));
		$data=$this->coursetype_obj->where(array('parent'=>$id))->select();
		if($data){
			$data['states']=true;
		}else{
			$data['states']=false;
		}
		$json_string = json_encode($data);
		echo $json_string;
	}
	
	public function courseinfo(){
		$c_id=  intval(I("get.id"));
		$cs_data=$this->course_obj->where("id=$c_id")->find();
		$hdata['stu_numbers']=$cs_data['stu_numbers']+1;
		$this->course_obj->where(array('id'=>$c_id))->save($hdata);
		$teacher=$this->user_obj->where(array('id'=>$cs_data['cs_teacher']))->find();
		$course_type=$this->coursetype_obj->where(array('term_id'=>$cs_data['ty_id']))->find();
		$map['user_id']=sp_get_current_userid();
		$map['course_id']=$c_id;
		$isvip=$this->isvip();
		if($buyinfo=$this->usercourse_obj->where($map)->find() or $isvip or $cs_data['cs_teacher']==$map['user_id']){
		    $isbuy=1;
		    if($buyinfo['pinglun']==''){
		    	$ispinglun=0;
		    }else{
		    	$ispinglun=1;
		    	$mypinglun=$buyinfo;
		      }
		}else{
			$isbuy=0;
		}
		if($cs_data['cs_price']==0){
		    $isfree=0;
		}else{
		    $isfree=1;
		}
		$check=$this->usercourse_obj->where(array("user_id"=>$map['user_id'],"course_id"=>$c_id))->find();
	    $urlArr = explode("|",$check['studied']);
		$exam=$this->papers_obj->where(array('cs_id'=>$c_id,'state'=>1))->order('id desc')->select();
		foreach($exam as $n=> $val){
			if($this->userpapers_obj->where(array('userid'=>$map['user_id'],'papersid'=>$exam[$n]['id']))->find()){
				$exam[$n]['ustate']=1;
			}else{
				$exam[$n]['ustate']=0;
			}
		}
		if(empty($cs_data['markedid'])){
			$sc_list=$this->section_obj->where(array('cs_id'=>$c_id,'type_id'=>0,'state'=>1))->order('id desc')->select();
		}else{
			$url=$this->marketUrl."/index.php?g=market&m=market&a=getMyMarketCourseSection";
			$date['marketId']=$cs_data['markedid'];
			$date['marketcount']=$this->user_obj->where(array('id'=>$cs_data['cs_teacher']))->getField('marketcount');
			$date['marketpass'] =$this->user_obj->where(array('id'=>$cs_data['cs_teacher']))->getField('marketpass');
			$sc_list=json_decode(post_curl($url,$date),true);
		}
		if($cs_data['course_type']=='live'){
			foreach($sc_list as $n=> $val){
				$sc_list[$n]['channelid']=$this->live_obj->where('sectionid=\''.$val['id'].'\'')->getField('channelid');    	
			}
		}
		$firstid = $this->section_obj->where(array('cs_id'=>$c_id,'state'=>1))->min('id');
		$sc_num=$this->section_obj->where(array('cs_id'=>$c_id))->count();
		$map2['course_id']=$c_id;
		$map2['pinglun']=array('neq','');
		if (sp_get_current_userid()!=''){
		  $map2['user_id']=array('not in',sp_get_current_userid());
		}
		$pcount=$pinglunlist=$this->usercourse_obj->where($map2)->count();
		$page = $this->page($pcount, 20);
		$pinglunlist=$this->usercourse_obj->limit($page->firstRow . ',' . $page->listRows)->where($map2)->select();
	     foreach($pinglunlist as $n=> $val){
			$pinglunlist[$n]['avatar']=$this->user_obj->where('id=\''.$val['user_id'].'\'')->getField('avatar');
		}
		$buynum=$this->usercourse_obj->where(array("course_id"=>$c_id))->count()+$cs_data['cs_xuni'];
		
		$newstud=$this->usercourse_obj->order('id desc')->where(array("course_id"=>$c_id))->limit(15)->select();
	    foreach($newstud as $n=> $val){
			$newstud[$n]['avatar']=$this->user_obj->where('id=\''.$val['user_id'].'\'')->getField('avatar');
			$newstud[$n]['user_nicename']=$this->user_obj->where('id=\''.$val['user_id'].'\'')->getField('user_nicename');
		}
		$dongtai=$this->usercourse_obj->order('id desc')->limit(10)->select();
		foreach($dongtai as $n=>$val){
		    $dongtai[$n]['username']=$this->user_obj->where('id=\''.$val['user_id'].'\'')->getField('user_nicename');
			$dongtai[$n]['coursename']=$this->course_obj->limit(6)->where('id=\''.$val['course_id'].'\'')->getField('cs_name');
			$dongtai[$n]['courseid']=$this->course_obj->limit(6)->where('id=\''.$val['course_id'].'\'')->getField('id');
		 }
		$name=$cs_data[cs_name];
		if(empty($cs_data['markedid'])){
			$material=$this->material_obj->where(array('cs_id'=>$c_id))->select();
		}else{
			$url=$this->marketUrl."/index.php?g=market&m=market&a=getMarketCourseMaterial";
			$date['marketId']=$cs_data['markedid'];
			$material=json_decode(post_curl($url,$date),true);
		}
		$favorite=$this->user_favorites_obj->where(array('uid'=>sp_get_current_userid(),'object_id'=>$c_id))->find();
		$tuijiancourselist=$this->course_obj->where('is_tuijian=1')->order('rand()')->limit(2)->select();
		$commentsCount=$this->comments_obj->where(array('post_id'=>$c_id,'status'=>1))->count();
		$cpage = $this->page($commentsCount, 10);
		$comments=$this->comments_obj->where(array('post_id'=>$c_id,'status'=>1))->limit($cpage->firstRow . ',' . $cpage->listRows)->order('id desc')->select();
		foreach($comments as $n=> $val){
			$comments[$n]['avatar']=$this->user_obj->where('id=\''.$val['uid'].'\'')->getField('avatar');
		}
		$cs_data['y_cs_price']=$cs_data['cs_price'];
		$playpoint=$this->playpoint_obj->where(array('uid'=>sp_get_current_userid(),'cid'=>$c_id))->find();
		if($discount=$this->discount->find()){
			$discount['ids']=json_decode($discount['c_ids'],true);
			if(in_array($cs_data['id'], $discount['ids'])  and   strtotime($discount['starttime']) <strtotime(date('Y-m-d H:i:s',time()))  and strtotime(date('Y-m-d H:i:s',time())) < strtotime($discount['endtime'])){
				$cs_data['discount']=$discount['discount'];
				$cs_data['cs_price']=round(($discount['discount']*$cs_data['cs_price']),2);
				$cs_data['endtime']=$discount['endtime'];
			}
		}
		$this->assign("playpoint",$playpoint);
		$this->assign("cpage",$cpage->show('Admin'));
		$this->assign("comments",$comments);
		$this->assign("firstid",$firstid);
		$this->assign("buynum",$buynum);
		$this->assign("dongtai",$dongtai);
		$this->assign("newstud",$newstud);
		$this->assign("teacher",$teacher);
		$this->assign("pinglunlist",$pinglunlist);
		$this->assign("mypinglun",$mypinglun);
		$this->assign("c_id",$c_id);
		$this->assign("u_id",sp_get_current_userid());
		$this->assign("ispinglun",$ispinglun);
	    $this->assign("isfree",$isfree);
		$this->assign("isbuy",$isbuy);
		$this->assign("cs_data",$cs_data);
		$this->assign("sc_list",$sc_list);
		$this->assign("sc_num",$sc_num);
		$this->assign("name",$name);
		$this->assign("course_type",$course_type);
		$this->assign("buyinfo",$buyinfo);
		$this->assign("material",$material);
		$this->assign("favorite",$favorite);
		$this->assign("exam",$exam);
		$this->assign("tuijiancourselist",$tuijiancourselist);
		$this->assign("Page", $page->show('Admin'));
		if($cs_data['course_type']=='ftf'){
			$this->display(ftfcourseinfo);
		}else{
			$this->display(courseinfo);
		}
	}
	public function livecourseinfo(){
		if(C('zhiboIsOpen')==0){
			$this->error('直播模块未开启');
		}
		$c_id=  intval(I("get.id"));
		$cs_data=$this->course_obj->where("id=$c_id")->find();
		$hdata['stu_numbers']=$cs_data['stu_numbers']+1;
		$this->course_obj->where(array('id'=>$c_id))->save($hdata);
		$teacher=$this->user_obj->where(array('id'=>$cs_data['cs_teacher']))->find();
		$course_type=$this->coursetype_obj->where(array('term_id'=>$cs_data['ty_id']))->find();
		$map['user_id']=sp_get_current_userid();
		$map['course_id']=$c_id;
		$isvip=$this->isvip();
		if($buyinfo=$this->usercourse_obj->where($map)->find() or $isvip){
		    $isbuy=1;
		    if($buyinfo['pinglun']==''){
		    	$ispinglun=0;
		    }else{
		    	$ispinglun=1;
		    	$mypinglun=$buyinfo;
		      }
		}else{
			$isbuy=0;
		}
		if($cs_data['cs_price']==0){
		    $isfree=0;
		}else{
		    $isfree=1;
		}
		$check=$this->usercourse_obj->where(array("user_id"=>$map['user_id'],"course_id"=>$c_id))->find();
	    $urlArr = explode("|",$check['studied']);
		
		$sc_list=$this->livesection_obj->where(array('csid'=>$c_id,'type_id'=>1,'state'=>1))->order('id desc')->select();
		
		$sc_num=$this->livesection_obj->where(array('csid'=>$c_id,'type_id'=>1,'state'=>1))->count();
		$isstrat=false;
		foreach($sc_list as $n=> $val){
			 $sc_list[$n]['endtimeyr']=date('H:i:s', strtotime($sc_list[$n]['endtime']));
			if(strtotime(date('Y-m-d H:i:s', time()))< strtotime($sc_list[$n]['starttime'])){
				$sc_list[$n]['livestate']=0;
			};
			if(strtotime($sc_list[$n]['starttime'])< strtotime(date('Y-m-d H:i:s',time())) and strtotime(date('Y-m-d H:i:s',time()))<strtotime($sc_list[$n]['endtime'])){
				$sc_list[$n]['livestate']=1;
			}; 
			if(strtotime(date('Y-m-d H:i:s', time()))>strtotime($sc_list[$n]['endtime'])){
				
				$sc_list[$n]['livestate']=2;
			};
			
		}
		$exam=$this->papers_obj->where(array('cs_id'=>$c_id,'state'=>1))->order('id asc')->select();
		foreach($exam as $n=> $val){
			if($this->userpapers_obj->where(array('userid'=>$map['user_id'],'papersid'=>$exam[$n]['id']))->find()){
				$exam[$n]['ustate']=1;
			}else{
				$exam[$n]['ustate']=0;
			}
		}
   	    $map2['course_id']=$c_id;
		$map2['pinglun']=array('neq','');
		if (sp_get_current_userid()!=''){
		  $map2['user_id']=array('not in',sp_get_current_userid());
		}
		$pcount=$pinglunlist=$this->usercourse_obj->where($map2)->count();
		$page = $this->page($pcount, 20);
		$pinglunlist=$this->usercourse_obj->limit($page->firstRow . ',' . $page->listRows)->where($map2)->select();
	
	     foreach($pinglunlist as $n=> $val){
		  	$pinglunlist[$n]['avatar']=$this->user_obj->where('id=\''.$val['user_id'].'\'')->getField('avatar');
		}
		$buynum=$this->usercourse_obj->where(array("course_id"=>$c_id))->count()+$cs_data['cs_xuni'];
		
		$newstud=$this->usercourse_obj->order('id desc')->where(array("course_id"=>$c_id))->limit(15)->select();
	    foreach($newstud as $n=> $val){
			$newstud[$n]['avatar']=$this->user_obj->where('id=\''.$val['user_id'].'\'')->getField('avatar');
			$newstud[$n]['user_nicename']=$this->user_obj->where('id=\''.$val['user_id'].'\'')->getField('user_nicename');
		}
		$dongtai=$this->usercourse_obj->order('id desc')->limit(10)->select();
		foreach($dongtai as $n=>$val){
		  $dongtai[$n]['username']=$this->user_obj->where('id=\''.$val['user_id'].'\'')->getField('user_nicename');
			$dongtai[$n]['coursename']=$this->course_obj->limit(6)->where('id=\''.$val['course_id'].'\'')->getField('cs_name');
			$dongtai[$n]['courseid']=$this->course_obj->limit(6)->where('id=\''.$val['course_id'].'\'')->getField('id');
		 }
		$name=$cs_data[cs_name];
		$material=$this->material_obj->where(array('cs_id'=>$c_id))->select();
		$favorite=$this->user_favorites_obj->where(array('uid'=>sp_get_current_userid(),'object_id'=>$c_id))->find();
		$tuijiancourselist=$this->course_obj->where('is_tuijian=1')->order('rand()')->limit(2)->select();
		$commentsCount=$this->comments_obj->where(array('post_id'=>$c_id,'status'=>1))->count();
		$cpage = $this->page($commentsCount,7);
		$comments=$this->comments_obj->where(array('post_id'=>$c_id,'status'=>1))->limit($cpage->firstRow . ',' . $cpage->listRows)->order('id desc')->select();
		foreach($comments as $n=> $val){
			$comments[$n]['avatar']=$this->user_obj->where('id=\''.$val['uid'].'\'')->getField('avatar');
		}
		if(sp_get_current_userid()==$cs_data['cs_teacher']){
			$isteacher=true;
		}
		$cs_data['y_cs_price']=$cs_data['cs_price'];
		if($discount=$this->discount->find()){
			$discount['ids']=json_decode($discount['c_ids'],true);
			if(in_array($cs_data['id'], $discount['ids'])  and   strtotime($discount['starttime']) <strtotime(date('Y-m-d H:i:s',time()))  and strtotime(date('Y-m-d H:i:s',time())) < strtotime($discount['endtime'])){
				$cs_data['discount']=$discount['discount'];
				$cs_data['cs_price']=round(($discount['discount']*$cs_data['cs_price']),2);
				$cs_data['endtime']=$discount['endtime'];
			}
		}
		
		$this->assign("cpage",$cpage->show('Admin'));
		$this->assign("comments",$comments);
		$this->assign("isteacher",$isteacher);
		$this->assign("buynum",$buynum);
		$this->assign("dongtai",$dongtai);
		$this->assign("newstud",$newstud);
		$this->assign("teacher",$teacher);
		$this->assign("pinglunlist",$pinglunlist);
		$this->assign("mypinglun",$mypinglun);
		$this->assign("c_id",$c_id);
		$this->assign("u_id",sp_get_current_userid());
		$this->assign("ispinglun",$ispinglun);
	    $this->assign("isfree",$isfree);
		$this->assign("isbuy",$isbuy);
		$this->assign("cs_data",$cs_data);
		$this->assign("sc_list",$sc_list);
		$this->assign("sc_num",$sc_num);
		$this->assign("name",$name);
		$this->assign("course_type",$course_type);
		$this->assign("buyinfo",$buyinfo);
		$this->assign("material",$material);
		$this->assign("favorite",$favorite);
		$this->assign("exam",$exam);
		$this->assign("tuijiancourselist",$tuijiancourselist);
		$this->assign("Page", $page->show('Admin'));
		$this->display();
		
	}
	function downmaterial(){
		 $this->check_login();
		 $id=  intval(I("get.id"));
		 $materialInfo=$this->material_obj->where(array('id'=>$id))->find(); 
		 $course=$this->course_obj->where(array("id"=>$materialInfo['cs_id']))->find();
		 if(!empty($course['markedid']) or empty($course)){
			$url=$this->marketUrl."/index.php?g=market&m=market&a=getMarketCourseMaterialInfo";
			$date['materialId']=$id;
			$materialInfo=json_decode(post_curl($url,$date),true);
			$course=$this->course_obj->where(array("markedid"=>$materialInfo['cs_id']))->find();
		 }
		 $map['user_id']=sp_get_current_userid();
		 $map['course_id']=$course['id'];
		 $teacherid=$course['cs_teacher'];
		 $isvip=$this->isvip();
		 if($this->usercourse_obj->where($map)->find() or $map['user_id']==$teacherid or $isvip){
		    $file_name = $materialInfo['downname']; 
			$file_dir =$materialInfo['url']; 
			$file = @ fopen($file_dir,"r"); 
			if (!$file) { 
				echo "文件找不到"; 
			}else{ 
				ob_start(); 
				$filename=$materialInfo['url'];
				header( "Content-type:  application/octet-stream "); 
				header( "Accept-Ranges:  bytes "); 
				header( "Content-Disposition:  attachment;  filename= $filename"); 
				$size=readfile($filename); 
				header( "Accept-Length: " .$size);
			}
		 }else{
			 exit();
		 }
      }
    function favorite(){
		if(IS_POST){ 
			$data['object_id']=(int)$_POST['cid'];
			$data['uid']=sp_get_current_userid();
			$model = M('user_favorites'); 
			if($model->add($data)){
				$result['states']=true;
			} else{
				$result['states']=false;
			}
			 $json_string = json_encode($result);
			 echo $json_string;
		}
    }
	function unfavorite(){
		if(IS_POST){ 
			$map['uid']=sp_get_current_userid();
			$map['object_id']=(int)$_POST['cid'];
			$model = M('user_favorites'); 
			if($model->where($map)->delete()){
				$result['states']=true;
			} else{
				$result['states']=false;
			}
			$json_string = json_encode($result);
		    echo $json_string;
		}
	}
	function pinglunadd(){
	   $this->check_login();
	   $cid=  intval(I("post.c_id"));
	   $user_id=sp_get_current_userid();
	   $content=I("post.pinglun");
	   $data['pinglun'] =  $content;
	   $data['pingluntime']=date('Y-m-d H:i:s');
	   if(empty($content)){
	       $this->error('请填写评论内容！');
	   }
       if($this->usercourse_obj->where(array('course_id'=>$cid,'user_id'=>$user_id))->save($data)){
           $this->success('评论成功！');
       }
	}
	function ajaxpinglunadd(){
	   $content=I("post.pinglun");
	   $data['post_id']= intval(I("post.c_id"));
	   $data['parentid']= intval(I("post.s_id"));
	   $data['uid']=sp_get_current_userid();
	   $data['content'] = $this->_safe($content);
	   $data['createtime']=date('Y-m-d H:i:s');
	   if($this->comments_obj->add($data)){
		   $result['success']=true;
		   $result['message']='评论成功！';
	   }else{
		   $result['success']=false;
		   $result['message']='评论失败！';
	   }
	     $json_string = json_encode($result);
       echo $json_string;
	   
	}
	function ajaxpinglunselect(){
		$cid=  intval(I("post.c_id"));
		$sid=  intval(I("post.s_id"));
		if(empty($sid)){
			$sid=0;
		}
		if($res=$this->comments_obj->where(array('post_id'=>$cid,'parentid'=>$sid))->order('id desc')->limit(1)->find()){
		  	$res['success']=true;
		  	$res['avatar']=$this->user_obj->where('id=\''.$res['uid'].'\'')->getField('avatar');
		  	$res['username']=$this->user_obj->where('id=\''.$res['uid'].'\'')->getField('user_nicename');
		}else{
				$res['success']=false;
				$res['message']="数据查询失败";
		}
		$json_string = json_encode($res);
        echo $json_string;
	   
	}
	public function buycourse(){
	    $id=  intval(I("get.id"));
	    $cs_data=$this->course_obj->where("id=$id")->find();
		$teacher=$this->user_obj->where(array('id'=>$cs_data['cs_teacher']))->find();
		$this->assign("cs_data",$cs_data);
		$this->assign("teacher",$teacher);
	    if($cs_data['cs_price']==0){
			$this->display(buycourse_free);
	    }else{
			$this->display(buycourse);
	    }
	}
	function addcourse(){
		$c_id=  intval(I("get.id"));
        $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();
		if($userid==''){
				$this->error("请登陆！",U("User/Login/index"));
			}
        if($cs_data['cs_price']==0){
        	if($check){
        		$message='您已经购买了此课程，请不要重复购买';
				$result='添加失败';
        	}else{
        		$c_data['user_id']=$userid;
	    	    $c_data['course_id']=$c_id;
				$c_data['teacher_id']=$csdata['cs_teacher'];
				$c_data['course_price']=0;
	    	    $c_data['addtime']=date('Y-m-d H:i:s');
	    	    $c_data['state']=1;
				$message="您已成功添加课程".$csdata['cs_name']."，快去学习吧！";
				send_message($userid,'0','1',$message);
             	$this->usercourse_obj->add($c_data);
             	$message='添加课程成功';
				$result='添加成功';
        	}
        }else{
			$this->message='此课程不是免费课程，请到前台购买';
			$result='添加失败';
        }
		$this->assign("message",$message);
		$this->assign("time",$c_data['addtime']);
		$this->assign("result",$result);
		$this->assign("cs_data",$csdata);
		$this->display();
	}
	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('orderid'=>$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();
	}
	public function order(){
		$this->check_login();
		$id=  intval(I("get.id"));
	    $cs_data=$this->course_obj->where("id=$id")->find();
	    if($discount=$this->discount->find()){
			$discountInfo=true;
			$discount['ids']=json_decode($discount['c_ids'],true);
			if(in_array($cs_data['id'], $discount['ids'])  and   strtotime($discount['starttime']) <strtotime(date('Y-m-d H:i:s',time()))  and strtotime(date('Y-m-d H:i:s',time())) < strtotime($discount['endtime'])){
				$cs_data['cs_price']=round(($discount['discount']*$cs_data['cs_price']),2);
			}
		}
		$mycoupon=$this->mycoupon->where(array('userid'=>sp_get_current_userid()))->select();
		foreach($mycoupon as $n=> $val){ 
			$map['id']=$mycoupon[$n]['couponid'];
			$map['used_state']=0; 
			$map['state']=1;   
			$map['timelimit']=array('gt',date('Y-m-d H:i:s'));
			$mycoupon[$n]['coupon']=$this->coupon->where($map)->find();
		}
		$teacher=$this->user_obj->where(array('id'=>$cs_data['cs_teacher']))->find();
		$this->assign("mycoupon",$mycoupon);
		$this->assign("cs_data",$cs_data);
		$this->assign("discountInfo",$discountInfo);
		$this->assign("teacher",$teacher);
		$this->display();
	}
	function getCouponInfo(){
		$map['id']=intval(I("post.id"));
		$map['used_state']=0; 
		$map['state']=1;   
		$map['timelimit']=array('gt',date('Y-m-d H:i:s'));
		$res=$this->coupon->where($map)->find();
	    if($res){
		   $result['success']=true;
		   $result['discount']=$res['discount'];
	    }else{
		   $result['success']=false;
	    }
	   $json_string = json_encode($result);
       echo $json_string;
	}
	public function payorder(){
		$this->check_login();
	    $data['uid']=  I("get.uid");
	    $data['cid']=  I("get.cid");
	    $out_trade_no=I("get.cn");
		$option=I("post.option");
		$userid=sp_get_current_userid();
		if($data['cid']=='-1'){
			$cs_data['cs_name']="VIP会员购买";
		}else{
			$cs_data=$this->course_obj->where(array('id'=>$data['cid']))->find();
		}
		$out_trade_no_info=$this->order_obj->where(array('orderid'=>$out_trade_no))->find();
		$user=$this->user_obj->where(array("id"=>$userid))->find();
		$this->assign("data",$data);
		$this->assign("out_trade_no_info",$out_trade_no_info);
		$this->assign("cs_data",$cs_data);
		$this->assign("user",$user);
		$this->display();
	}
	function delorder(){
		$id=I("post.id");
		if($this->order_obj->where(array('id'=>$id))->delete()){
			$res['message']='success';
		}else{
			$res['message']="删除成功！";
		}
		$this->ajaxReturn($res);	
	}
	public function createorder(){
		$this->check_login();
		$id=  intval(I("get.id"));
		$mycouponId= intval(I("post.mycouponId"));
	    $cs_data=$this->course_obj->where("id=$id")->find();
	    if($cs_data['cs_price']==0){
			$this->assign("cs_data",$cs_data);
			$this->display(buycourse_free);
	    }else{
			$out_trade_no = date('Ymdhms').rand(100,999);
			$userid=sp_get_current_userid();
			$course_id=  intval(I("get.id"));
			$cs_data=$this->course_obj->where(array("id"=>$course_id))->find();
			if($discount=$this->discount->find()){
				$discount['ids']=json_decode($discount['c_ids'],true);
				if(in_array($cs_data['id'], $discount['ids'])  and   strtotime($discount['starttime']) <strtotime(date('Y-m-d H:i:s',time()))  and strtotime(date('Y-m-d H:i:s',time())) < strtotime($discount['endtime'])){
					$cs_data['cs_price']=round(($discount['discount']*$cs_data['cs_price']),2);
				}
			}
		    if(!empty($mycouponId)){
				$map['id']=$mycouponId;
				$map['used_state']=0; 
				$map['state']=1;   
				$map['timelimit']=array('gt',date('Y-m-d H:i:s'));
				$mycoupon=$this->coupon->where($map)->find();
				$cs_data['cs_price']=$mycoupon['discount']*$cs_data['cs_price']/10;
				$date['used_state']=1;
				$date['user_id']=sp_get_current_userid();
				$this->coupon->where(array('id'=>$mycouponId))->save($date);
			} 
			
			$user=$this->user_obj->where(array("id"=>$userid))->find();
			$order['user_id']=sp_get_current_userid();
			$order['orderid']=$out_trade_no;
			$order['course_id']=$course_id;
			$order['state']=2;
			$order['total']=$cs_data['cs_price'];
			$order['addtime']=date('Y-m-d H:i:s');
			$check=$this->order_obj->where(array("user_id"=>$userid,"course_id"=>$course_id))->find();
			if(!$check){
				$this->order_obj->add($order);
				$this->assign("out_trade_no",$out_trade_no);
			}else{
				$this->assign("out_trade_no",$check['orderid']);
			}
			$this->assign("cs_data",$cs_data);
			$this->assign("user",$user);
			$this->assign("course_id",$course_id);
			$this->display();
	    }
	}
	public function myorder(){
		$this->check_login();
		$userid=sp_get_current_userid();
		$order=$this->order_obj->where(array("user_id"=>$userid))->order('addtime desc')->select();
		$count=$this->order_obj->where(array("user_id"=>$userid))->count();
		foreach($order as $n=> $val){  
			$course= $this->course_obj->where(array("id"=>$order[$n][course_id]))->find();        
            $order[$n]['course_name']=$course['cs_name'];
	      }  
	    $this->assign("order",$order);
	    $this->display();
	}
   
	public function myclass(){
		$this->check_login();
		$c_id=  intval(I("get.id"));
		$cs_data=$this->course_obj->where("id=$c_id")->find();
		$lession=$this->section_obj->where(array("cs_id"=>$cs_data['id']))->select();
		$this->assign("cs_data",$cs_data);
		$this->assign("lession",$lession);
		$this->display();
	}
    public function geturl(){
		$c_id= I('post.id');
		$data=$this->section_obj->where(array("id"=>$c_id))->find();
		if($data){
			$result['states']=true;
			$result['url']=$data['yun_url'];
		}
		$json_string = json_encode($result);
        echo $json_string;
	}
	public function isvip(){
		$isvip=$this->vipuser->where(array("uid"=>sp_get_current_userid() ,"state"=>1))->find();
	  if($isvip){
	  	$now=date("Y-m-d H:i:s"); 
	  	$vip=true;        
	  	if(strtotime($isvip['endtime'])-strtotime($now)<0){
	  		 $data['state']=2;
	  		 $vip=false;  
	  		 $this->vipuser->where(array("uid"=>$userid))->save($data);
	  	}
		} else{
			$vip=false;  
		}
		return $vip;
		}
	public function study(){
		$this->check_login();
	    $c_id=  intval(I("get.id"));
		$lession=$this->section_obj->where(array("id"=>$c_id))->find();
		$course=$this->course_obj->where(array("id"=>$lession['cs_id']))->find();
		if(!empty($course['markedid']) or empty($course)){
			$url=$this->marketUrl."/index.php?g=market&m=market&a=getMarketSectionInfo";
			$date['sectionId']=$c_id;
			$lession=json_decode(post_curl($url,$date),true);
			$course=$this->course_obj->where(array("markedid"=>$lession['cs_id']))->find();
			$isMarket=true;
		}else{
			$isMarket=false;
		}
		$cs_id=$course['id'];
		$map['user_id']=sp_get_current_userid();
		$map['course_id']=$cs_id;
		$isvip=$this->isvip();
		$type=$this->course_obj->where(array("id"=>$cs_id))->getField('course_type');
		$teacherid=$this->course_obj->where(array("id"=>$cs_id))->getField('cs_teacher');
		$course_price=$this->course_obj->where(array("id"=>$cs_id))->getField('cs_price');
		$psc_list=$this->section_obj->where(array('cs_id'=>$cs_id,'type_id'=>0,'state'=>1))->order('id desc')->select();
		$isbuy=$this->usercourse_obj->where(array('user_id'=>sp_get_current_userid(),'course_id'=>$cs_id))->find();
		if($isvip and !$isbuy){
			$indata['course_id']=$cs_id;
			$indata['user_id']=sp_get_current_userid();
			$indata['addtime']=date('Y-m-d H:i:s');
			$indata['teacher_id']=$teacherid;
			$indata['course_price']=$course_price;
			$this->usercourse_obj->add($indata);
		}
		$lession['pic']=$this->course_obj->where(array("id"=>$cs_id))->getField('cs_picture');
		$lession['csname']=$this->course_obj->where(array("id"=>$cs_id))->getField('cs_name');
		if(!empty($course['markedid'])){
			$url=$this->marketUrl."/index.php?g=market&m=market&a=getMyMarketCourseSection";
			$date['marketId']=$course['markedid'];
			$date['marketcount']=$this->user_obj->where(array('id'=>$teacherid))->getField('marketcount');
			$date['marketpass'] =$this->user_obj->where(array('id'=>$teacherid))->getField('marketpass');
			$sc_list=json_decode(post_curl($url,$date),true);
			
		}else{
			$sc_list=$this->section_obj->where(array('cs_id'=>$cs_id,'type_id'=>0,'state'=>1))->order('id desc')->select();
		}
	    $count=count($sc_list);
		if($data=$this->usercourse_obj->where($map)->find() or $map['user_id']==$teacherid or $lession['is_free']=='1' or $isvip){
			$isbuy=1;
			$playdata['uid']=$map['user_id'];
			$playdata['cid']=$map['course_id'];
			$playdata['sid']=$c_id;
			$pointmap['uid']=$map['user_id'];
			$pointmap['cid']=$map['course_id'];
			if($point=$this->playpoint_obj->where($pointmap)->find()){
				$this->playpoint_obj->where(array('uid'=>$map['user_id'],'cid'=>$map['course_id']))->save($playdata);
			}else{
				$this->playpoint_obj->add($playdata);
			}
			
		}else{
			$isbuy=2;
			$this->error('此为收费课程，请购买后再来学习！');
			exit();
		}
		$yuouxiaoqi=$this->course_obj->where(array("id"=>$cs_id))->getField('youxiaoqi');
		$end=subDate($yuouxiaoqi,$data['addtime']);
		if($yuouxiaoqi==0){
			$isover=false;
		}else{
			if((strtotime($end)-strtotime(date('Y-m-d H:i:s')))<0){
				$isover=true;
				$this->error('你购买的课程有限期已过,无法继续学习！');
				exit();
			}else{
				$isover=false;
			}
		}
		$notes=$this->notes_obj->where(array('c_id'=>$cs_id,'s_id'=>$c_id,'u_id'=>$map['user_id']))->order('id desc')->select();
		$comments=$this->comments_obj->where(array('parentid'=>$c_id,'status'=>1))->order('id desc')->select();
		foreach($comments as $n=> $val){
			$comments[$n]['avatar']=$this->user_obj->where('id=\''.$val['uid'].'\'')->getField('avatar');
		}
		$this->assign("isover",$isover);
		$this->assign("isMarket",$isMarket);
		$this->assign("isbuy",$isbuy);
		$this->assign("psc_list",$psc_list);
		$this->assign("sc_list",$sc_list);
		$this->assign("cid",$c_id);
		$this->assign("cs_id",$cs_id);
		$this->assign("count",$count);
		$this->assign("notes",$notes);
		$this->assign("comments",$comments);
		if($type=='normal'){
            $postdata=$this->Ali_info();
            $postdata['VideoId']=$lession['yun_url'];
            $url = $postdata['server'] . "/api/educloud/getaliplayertoken";
            $res=json_decode(post_curl($url,$postdata),true);
            $lession['PlayAuth']=$res['PlayAuth'];
			$this->assign("lession",$lession);
			if(sp_is_mobile()){
			   	$this->display('mobilestudy');
			}else{
				$this->display();
			}
		}
		if($type=='doc'){
			$lession['doccontent']=htmlspecialchars_decode($lession['doccontent']);
		    $this->assign("lession",$lession);
			$this->display("docstudy");
		}
	}  
	public function livestudy(){
		$this->check_login();
        $this->baijiayunlive();
	}
	/* function marketstudy(){
		$markerSectionId=I('get.id');
		$server=I('get.server');
		$url=$server."index.php?g=market&m=market&a=getMarketSectionInfo";
		$date['id']=$markerSectionId;
		$sectioin=post_curl($url,$date);
		dump($sectioin);
	} */
	function baijiayunlive(){
		$c_id=  intval(I("get.id"));
		$lession=$this->livesection_obj->where(array("id"=>$c_id))->find();
		$map['user_id']=sp_get_current_userid();
		$map['course_id']=$lession['csid'];
		$lession['pic']=$this->course_obj->where(array("id"=>$lession['csid']))->getField('cs_picture');
		$lession['csname']=$this->course_obj->where(array("id"=>$lession['csid']))->getField('cs_name');
		$lession['teacher_id']=$this->course_obj->where(array("id"=>$lession['csid']))->getField('cs_teacher');
		$lession['course_price']=$this->course_obj->where(array("id"=>$lession['csid']))->getField('cs_price');
		$room_id=$lession['url'];
		$user_number=sp_get_current_userid();
		$user_name=$this->user_obj->where(array('id'=>$user_number))->getField('user_nicename');
		$user_name_url=urlencode($user_name);
		$starttime=$lession['starttime'];
		$endtime=$lession['endtime'];
		$isvip=$this->isvip();
		$isbuy=$this->usercourse_obj->where(array('user_id'=>sp_get_current_userid(),'course_id'=>$lession['csid']))->find();
        $info=$this->get_site_info();
		if($isvip and !$isbuy){
			$indata['course_id']=$lession['csid'];
			$indata['user_id']=sp_get_current_userid();
			$indata['addtime']=date('Y-m-d H:i:s');
			$indata['teacher_id']=$lession['teacher_id'];
			$indata['course_price']=$lession['course_price'];
			$this->usercourse_obj->add($indata);
		}
		if($user_number==$lession['teacherid']){
			$user_role=1;
		}else{
			$user_role=0;
		}
		if($data=$this->usercourse_obj->where($map)->find() or $map['user_id']==$lession['teacherid'] or $lession['isfree']=='1' or $isvip){
			$isbuy=1;
		}else{
			$isbuy=2;
			$this->error('此为收费课程，请购买后再来学习！');
			exit();
		}
		if(strtotime(date('Y-m-d H:i:s', time()))<strtotime($starttime)){
			$isstrat=0;
			$isover=0;
		};
        $pic=$this->user_obj->where(array('id'=>$user_number))->getField('avatar');
        if($pic){
            $user_avatar=sp_get_host().sp_get_user_avatar_url($this->user_obj->where(array('id'=>$user_number))->getField('avatar'));
        }else{
            $user_avatar=sp_get_host().'/public/simplebootx/public/images/093958e59110293063.jpg';
        }
        $user_avatar_url=urlencode($user_avatar);
        $postdata=$info;
        $postdata['room_id']=$room_id;
        $postdata['user_number']=$user_number;
        $postdata['user_name']=$user_name;
        $postdata['user_role']=$user_role;
        $postdata['user_avatar']=$user_avatar;
        $url=$info['server']."/api/educloud/remotegetsign";
        $res=json_decode(post_curl($url,$postdata),true);
        $inurl=$res['inurl'];
		if(strtotime(date('Y-m-d H:i:s',time()))<=strtotime($endtime)){
			$isstrat=1;
			$isover=0;
            $sign=$res['sign'];
			if(sp_is_mobile()){
				if(C('BJ_APP')==1){
					$query = array(
						"roomId" => $room_id,
						"userNumber" => $user_number,
						"userName"=>$user_name,
						"userType"=>$user_role,
						"userAvatar"=>$user_avatar,
						"sign"=>$sign
					);
					$this->assign("query",$query);
				}else{
					$student_code=$lession['student_code'];
					$url=$inurl.'/room/quickenter?code='.$student_code.'&user_name='.$user_name;
                    $xml_arr['url']=$url;
				}
				$this->assign("appon",C('BJ_APP'));
				$ismobile=true;
			}else{
				$ismobile=false;
				$url=$inurl."/room/enter?room_id=".$room_id."&user_number=".$user_number."&user_name=".$user_name_url."&user_role=".$user_role."&user_avatar=".$user_avatar_url."&sign=".$sign;
                $xml_arr['url']=$url;
			}
		};
		if(strtotime(date('Y-m-d H:i:s', time()))>strtotime($endtime)){
			$isstrat=1;
			$isover=1;
            $postdata=$info;
            $postdata['room_id']=$room_id;
            $postdata['user_number']=$user_number;
            $postdata['user_name']=$user_name;
            $postdata['user_role']=$user_role;
            $postdata['user_avatar']=$user_avatar;
            $url=$info['server']."/api/educloud/getPlaybackToken";
            $data=json_decode(post_curl($url,$postdata),true);
			if($data['code']!=0){
				$this->error($data['msg']);
			}else{
				$tep=$data['data'];
				$token=$tep['token'];
				$tourl=$inurl."/playback/index?classid=".$room_id."&token=".$token;
			}
		};
		$sc_list=$this->livesection_obj->where(array('csid'=>$lession['csid'],'state'=>1))->order('id desc')->select();
		foreach($sc_list as $n=> $val){
			if(strtotime(date('Y-m-d H:i:s', time()))<strtotime($sc_list[$n]['starttime'])){
				$sc_list[$n]['livestate']=0;
			};
			if(strtotime($sc_list[$n]['starttime'])<strtotime(date('Y-m-d H:i:s',time())) and strtotime(date('Y-m-d H:i:s',time()))<strtotime($sc_list[$n]['endtime'])){
				$sc_list[$n]['livestate']=1;
			}; 
			if(strtotime(date('Y-m-d H:i:s', time()))>strtotime($sc_list[$n]['endtime'])){
				$sc_list[$n]['livestate']=2;
		   };
	    }
	    $notes=$this->notes_obj->where(array('c_id'=>$lession['csid'],'s_id'=>$c_id,'u_id'=>$map['user_id']))->order('id desc')->select();
		$comments=$this->comments_obj->where(array('parentid'=>$c_id,'status'=>1))->order('id desc')->select();
		foreach($comments as $n=> $val){
			$comments[$n]['avatar']=$this->user_obj->where('id=\''.$val['uid'].'\'')->getField('avatar');
		}
        $this->assign("notes",$notes);
		$this->assign("comments",$comments);
		$this->assign("ismobile",$ismobile);
		$this->assign("isstrat",$isstrat);
		$this->assign("isover",$isover);
		$this->assign("sc_list",$sc_list);
		$this->assign("isbuy",$isbuy);
		$this->assign("lession",$lession);
		$this->assign("count",$count);
		$this->assign("xml_arr",$xml_arr);
		$this->assign("tourl",$tourl);
		$this->assign("cid",$c_id);
		$this->display('zhibo');
	}
	function video(){
		$id=$_GET['sid'];
		$data = $this->section_obj->getById ($id );
		echo $data['yun_url'];
		
	}
	function getlivetoken(){
		$room_id=I('post.roomid');
		$partner_key=C('BJ_Partner_Key');
		$partner_id=C('BJ_Partner_ID');
		$timestamp=time();
		$expires_in=3600;
		$params = array(
			"partner_id"=>$partner_id,
			"room_id" => $room_id,
			"expires_in"=>$expires_in,
			"timestamp"=>$timestamp
			);
			
		$sign=$this->getSign($params,$partner_key);
		$url="https://api.baijiacloud.com/openapi/video/getPlayerToken";
		$postdata="expires_in=".$expires_in."&room_id=".$room_id."&partner_id=".$partner_id."&timestamp=".$timestamp."&sign=".$sign;
		echo post_curl($url,$postdata);
	}
	function chekbuy(){
		$id=I('post.id');
		$section = $this->section_obj->where(array('id'=>$id))->find();
		$teacherid=$this->course_obj->where(array('id'=>$section['cs_id']))->getField('cs_teacher');
		$userid=sp_get_current_userid();
		$result=$this->usercourse_obj->where(array("course_id"=>$section['cs_id'],'user_id'=>$userid))->find();
		$isvip=$this->isvip();
		if($result or $isvip){
			$res['isbuy']=1;
		}else{
			$res['isfree']=$section['is_free'];
			if($teacherid==$userid){
			  $res['isteacher']=1;
			}
		}
		echo json_encode($res);
	}
	public function play(){
		$this->check_login();
	    $id=  intval(I("get.id"));
	    $section=$this->section_obj->where(array("id"=>$id))->find();
	}
	public  function studied(){
	   $sc_id=  intval(I("post.sc_id"));
	   $cs_id=  intval(I("post.cs_id"));
	   $userid=sp_get_current_userid();
	   $check=$this->usercourse_obj->where(array("user_id"=>$userid,"course_id"=>$cs_id))->find();
	   $urlArr = explode("|",$check['studied']);  
	  if(!in_array($sc_id ,$urlArr)){                
             $data['studied'] =$check['studied'].$sc_id.'|';
             $this->usercourse_obj->where(array("user_id"=>$userid,"course_id"=>$cs_id))->save($data);  
            }
		$this->success('设置成功！');	
     	}
   public function pay_free (){
        $c_id=  intval(I("get.id"));
        $userid=sp_get_current_userid();
        $cs_data=$this->course_obj->where("id=$c_id")->find();
        $check=$this->usercourse_obj->where(array("user_id"=>$userid,"course_id"=>$c_id))->find();
		if($userid==''){
				$this->error("请登陆！",U("User/Login/index"));
			}
        if($cs_data['cs_price']==0){
        	if($check){
        		$this->error('您已经购买了此课程，请不要重复购买');
        	}else{
        		$c_data['user_id']=$userid;
	    	    $c_data['course_id']=$c_id;
	    	    $c_data['addtime']=date('Y-m-d H:i:s');
	    	    $c_data['state']=1;
             	$this->usercourse_obj->add($c_data);
				$message="您已成功添加课程,".$cs_data['cs_name']."，快去学习吧！";
				send_message($userid,'0','1',$message);
             	$this->success('添加成功',U("course/course/courseinfo",array('id'=>$c_id)));
        	}
        }else{
         $this->error('此课程不是免费课程，请到前台购买');
        }
    }  
	
	public function payment(){
	  	$this->check_login();
		$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(){
		$out_trade_no=I("post.orderId");
		$orderInfo=$this->order_obj->where(array("orderid"=>$out_trade_no))->find();
		$c_id=$orderInfo['course_id'];
		$cs_data=$this->course_obj->where("id=$c_id")->find();
		$totalmoney=$orderInfo['total'];
		$userid=sp_get_current_userid();
		$user=$this->user_obj->where(array("id"=>$userid))->find();
		$this->assign("totalmoney",$totalmoney);
		$check=$this->usercourse_obj->where(array("user_id"=>$userid,"course_id"=>$c_id))->find();
		if(!$check){
		  if($user['coin']<$totalmoney){
			$result=0;
			$this->assign("result",$result);
			$this->assign("cs_data",$cs_data);
			$this->assign("yue",$user['coin']);
			$this->assign("out_trade_no",$out_trade_no);
			$this->display(":Course/doyue");
		  }else{
			$result=1;
			$u_data['coin']=($user['coin'])-($totalmoney);
			$o_data['state']=1;
			$o_data['pay']="余额";
			$orderId=$out_trade_no;
			$this->order_obj->where(array("orderid"=>$orderId))->save($o_data);
			$this->user_obj->where(array("id"=>$userid))->save($u_data);
			$c_data['user_id']=$userid;
			$c_data['course_id']=$c_id;
			$c_data['addtime']=date('Y-m-d H:i:s');
			$c_data['state']=1;
			$c_data['teacher_id']=$cs_data['cs_teacher'];
			$c_data['course_price']=$cs_data['cs_price'];
			$sailes['u_id']=$cs_data['cs_teacher'];
			$sailes['c_id']=$c_id;
			$sailes['money']=round($totalmoney*C('cardbili') ,2);
			$sailes['addtime']=date('Y-m-d H:i:s');
			$message="您的订单".$out_trade_no."已成功支付,购买课程".$cs_data['cs_name']."，快去学习吧！";
			send_message($userid,'0','1',$message);
			$this->teacher_order->add($sailes);
			$this->usercourse_obj->add($c_data);
			$this->user_favorites_obj->where(array('uid'=>$userid,'object_id'=>$c_id))->delete();
			$this->assign("result",$result);
			$this->assign("out_trade_no",$out_trade_no);
			$this->assign("totalmoney",$totalmoney);
			$this->assign("cs_data",$cs_data);
			$this->assign("yue",$u_data['coin']);
			$this->assign("c_id",$c_id);
			$this->display(":Course/doyue");
		  }
		}else{
		   $result=2;
		   $this->assign("cs_data",$cs_data);
		   $this->assign("out_trade_no",$out_trade_no);
		   $this->assign("result",$result);
		   $this->assign("yue",$user['coin']);
		   $this->display(":Course/doyue");
		}
	}
	function payWithWxPay(){
		$payment=I("post.payment");
		$out_trade_no=I("post.orderId");
		$orderInfo=$this->order_obj->where(array("orderid"=>$out_trade_no))->find();
		$c_id=$orderInfo['course_id'];
		$cs_data=$this->course_obj->where("id=$c_id")->find();
		$totalmoney=$orderInfo['total'];
		$userid=sp_get_current_userid();
	    $user=$this->user_obj->where(array("id"=>$userid))->find();
		$time=time();
		session("url",null);
        $subject = $cs_data['cs_name'];  
        $total_fee = $totalmoney; 
        $body = $c_id;  
		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/index');
			$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(":Course/payWithWxPay");
		}
		
	}
	 public function qrcode(){
		 $url=$_SESSION["url"];
		 $size=8;
		 qrcode($url);
	 }
	 public function wxh5notify(){
		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));
		$out_trade_no=I('get.out_trade_no');
		$wechatAppPay = new \wechatAppPay($appid, $mch_id, $notify_url, $key);
		$result=$wechatAppPay->orderQuery($out_trade_no);
		if ($result['trade_state']=='SUCCESS') {
			$orderinfo['alipayorder']=$result['transaction_id'];
			$orderinfo['state']=1;
			$orderinfo['pay']="微信";
			$this->order_obj->where(array('orderid'=>$result['out_trade_no']))->save($orderinfo);
			$info=$this->order_obj->where(array('orderid'=>$result['out_trade_no']))->find();
			if($info['course_id']==-1){
				  $user_data['uid']=$info['user_id'];
				  $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("+".$info['viptimes']."month"));  
				  $user_data['vipprice'] =$info['total'];
				  $user_data['duration'] =$info['viptimes'];
				  $message="您的订单".$out_trade_no."已成功支付,购买VIP会员".$info['viptimes']."个月，到期时间为".$user_data['endtime']."快去学习吧！";
				  send_message($user_data['uid'],'0','1',$message);
				  $this->vipuser->add($user_data);
				  $this->redirect(("User/center/associator"), 2, '页面跳转中...');
			}else{
				$cs_data=$this->course_obj->where(array('id'=>$info['course_id']))->find(); 
				$c_data['user_id']=$info['user_id'];
				$c_data['course_id']=$info['course_id'];
				$c_data['addtime']=date('Y-m-d H:i:s');
				$c_data['state']=1;
				$c_data['teacher_id']=$cs_data['cs_teacher'];
				$c_data['course_price']=$info['total'];
				$sailes['u_id']=$info['user_id'];
				$sailes['c_id']=$info['course_id'];
				$sailes['money']=round($info['total']*C('alipaybili') ,2); 
				$sailes['addtime']=date('Y-m-d H:i:s');	
			if(!$this->teacher_order->where(array('u_id'=>$sailes['u_id'],'c_id'=>$sailes['c_id']))->find()){
				$this->teacher_order->add($sailes);
			}
			if(!$this->usercourse_obj->where(array('user_id'=>$c_data['user_id'],'course_id'=>$c_data['course_id']))->find()){
				$message="您的订单".$out_trade_no."已成功支付,购买课程".$cs_data['cs_name']."，快去学习吧！";
				send_message($c_data['user_id'],'0','1',$message);
				$this->usercourse_obj->add($c_data);
			  }
			M(User_favorites)->where(array('object_id'=>$c_data['course_id']))->delete();
			$this->redirect(U('course/Course/addcourse'), array('id' => $info['course_id']), 5, '页面跳转中...');
				
			}
        }
	 }
	 public function wxnotify(){
        Vendor('Weixinpay.Weixinpay');
        $wxpay=new \Weixinpay();
        $result=$wxpay->notify();
        if ($result) {
			$orderinfo['alipayorder']=$result['transaction_id'];
			$orderinfo['state']             =1;
			$orderinfo['pay']="微信";
			$this->order_obj->where(array('orderid'=>$result['out_trade_no']))->save($orderinfo);
			$info=$this->order_obj->where(array('orderid'=>$result['out_trade_no']))->find();
			if($info['course_id']==-1){
			  $user_data['uid']=$info['user_id'];
			  $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("+".$info['viptimes']."month"));  
			  $user_data['vipprice'] =$info['total'];
			  $user_data['duration'] =$info['viptimes'];
			  $message="您的订单".$out_trade_no."已成功支付,购买VIP会员".$info['viptimes']."个月，到期时间为".$user_data['endtime']."快去学习吧！";
		      send_message($user_data['uid'],'0','1',$message);
			  $this->vipuser->add($user_data);
			  $this->redirect(("User/center/associator"), 2, '页面跳转中...');
			}else{
				$cs_data=$this->course_obj->where(array('id'=>$info['course_id']))->find(); 
				$c_data['user_id']=$info['user_id'];
				$c_data['course_id']=$info['course_id'];
				$c_data['addtime']=date('Y-m-d H:i:s');
				$c_data['state']=1;
				$c_data['teacher_id']=$cs_data['cs_teacher'];
				$c_data['course_price']=$info['total'];
				$sailes['u_id']=$info['user_id'];
				$sailes['c_id']=$info['course_id'];
				$sailes['money']=round($info['total']*C('alipaybili') ,2); 
				$sailes['addtime']=date('Y-m-d H:i:s');	
			if(!$this->teacher_order->where(array('u_id'=>$sailes['u_id'],'c_id'=>$sailes['c_id']))->find()){
				$this->teacher_order->add($sailes);
			}
			if(!$this->usercourse_obj->where(array('user_id'=>$c_data['user_id'],'course_id'=>$c_data['course_id']))->find()){
				$message="您的订单".$out_trade_no."已成功支付,购买课程".$cs_data['cs_name']."，快去学习吧！";
				send_message($c_data['user_id'],'0','1',$message);
				$this->usercourse_obj->add($c_data);
			  }
			M(User_favorites)->where(array('object_id'=>$c_data['course_id']))->delete();
			$this->redirect(U('course/Course/addcourse'), array('id' => $info['course_id']), 5, '页面跳转中...');
				
			}
					  
        }
    }
	function payWithAlipay(){
	    $payment=I("post.payment");
		$out_trade_no=I("post.orderId");
		$orderInfo=$this->order_obj->where(array("orderid"=>$out_trade_no))->find();
		$c_id=$orderInfo['course_id'];
		$cs_data=$this->course_obj->where("id=$c_id")->find();
		$totalmoney=$orderInfo['total'];
		$userid=sp_get_current_userid();
	    $user=$this->user_obj->where(array("id"=>$userid))->find();
        $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('course/course/notifyurl');
        $return_url = sp_get_host().U('course/course/returnurl');
        $seller_email = C('seller_email');
        $subject = $cs_data['cs_name'];  
        $show_url = sp_get_host();  
        $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"    => $totalmoney,
			"body"            => $c_id,
			"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;
	}
    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);  
					$cs_data=$this->course_obj->where("id=$body")->find();
					$c_data['user_id']=sp_get_current_userid();
					$c_data['course_id']=$body;
					$c_data['addtime']=date('Y-m-d H:i:s');
					$c_data['state']=1;
					$c_data['teacher_id']=$cs_data['cs_teacher'];
					$c_data['course_price']=$total_fee;
					$sailes['u_id']=sp_get_current_userid();
					$sailes['c_id']=$body;
					$sailes['money']=round($total_fee*C('alipaybili') ,2); 
					$sailes['addtime']=date('Y-m-d H:i:s');
					$this->teacher_order->add($sailes);
					$this->usercourse_obj->add($c_data);
					M(User_favorites)->where(array('object_id'=>$c_data['course_id']))->delete();
               }
            }
            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);  
				   $cs_data=$this->course_obj->where("id=$body")->find();
				   $c_data['user_id']=sp_get_current_userid();
				   $c_data['course_id']=$body;
				   $c_data['addtime']=date('Y-m-d H:i:s');
				   $c_data['state']=1;
				   $c_data['teacher_id']=$cs_data['cs_teacher'];
				   $c_data['course_price']=$total_fee;
					$sailes['u_id']=sp_get_current_userid();
					$sailes['c_id']=$body;;
					$sailes['money']=round($total_fee*0.5 ,2); 
					$sailes['addtime']=date('Y-m-d H:i:s');
					$message="您的订单".$out_trade_no."已成功支付,购买课程".$cs_data['cs_name']."，快去学习吧！";
				    send_message($c_data['user_id'],'0','1',$message);
					$this->teacher_order->add($sailes);
					$this->usercourse_obj->add($c_data);
					M(User_favorites)->where(array('object_id'=>$c_data['course_id']))->delete();
				 }
			    $this->redirect('/user/center/order');
			 }else {
				 echo "trade_status=".$_GET['trade_status'];
				 $this->redirect('/user/center/order');
			 }
		}else {
			$this->redirect(U(user/center/order));
			echo "支付失败！";
		}
	}
	function chcckCoursePay(){
		$trade_no= I('post.trade_no');
		$data=$this->order_obj->where(array("orderid"=>$trade_no))->find();
		$check=$this->usercourse_obj->where(array("user_id"=>$data['user_id'],"course_id"=>$data['course_id']))->find();
		
		if($data['state']==1 and $check){
			$result['states']=true;
		}else{
			$result['states']=false;
		}
		$json_string = json_encode($result);
        echo $json_string;
		
	}
    function zhibo(){
		$appid=C('AppId');
		$this->assign("appid",$appid);
		$this->display();
	}

	function arr_sort($array,$key,$order="desc"){
		$arr_nums=$arr=array();
		foreach($array as $k=>$v){
			$arr_nums[$k]=$v[$key];
		}
		if($order=='asc'){
			asort($arr_nums);
		}else{
			arsort($arr_nums);
		}
		foreach($arr_nums as $k=>$v){
			$arr[$k]=$array[$k];
		}
		return $arr;
	}
	function getbaijiayuntoken(){
		$video_id=$_POST['video_id'];
		//$isMarket=$_POST['isMarket'];
        $isMarket=false;
		if($isMarket){
			$marketConfig=$this->getMarketConfig();
			$partner_key=$marketConfig['BJ_Partner_Key'];
		    $partner_id=$marketConfig['BJ_Partner_ID'];
		}else{
            $info=$this->get_site_info();
            $postdata['domain']=$this->get_domain();
            $postdata['authorcode']=$info['author_code'];
            $postdata['video_id']=$video_id;
            $postdata['expires_in']=3600;
            $url=$info['server']."/api/educloud/getPlayerToken";
            $restemp=post_curl($url,$postdata);
            echo $restemp;
		}
	}
    function get_site_info(){
        $info['authorcode']=C('authoCode');
        $info['Partner_ID']=C('BJ_Partner_ID');
        $info['Partner_Key']=C('BJ_Partner_Key');
        $info['Secret_Key']=C('BJ_Secret_Key');
        $info['private_domain']=C('BJ_private_domain');
        $info['server']=C('server');
        $info['domain']=$this->get_domain();
        return $info;
    }
    function get_domain(){

        $host=$_SERVER["HTTP_HOST"];
        return $host;
    }

	function addNotest(){
		$data['c_id']=$_POST['courseId'];
		$data['s_id']=$_POST['sectionId'];
		$data['u_id']=sp_get_current_userid();
		$data['content']=$_POST['content'];
		$data['addtime']=date('Y-m-d H:i:s');
		if($this->notes_obj->add($data)){
			  $result['message']='success';
		  }else{
			  $result['message']='false';
	 	  }
	 	 echo json_encode($result); 
	}
	function queryNote(){
		$map['c_id']=$_POST['courseid'];
		$map['s_id']=$_POST['sectionid'];
		$map['u_id']=sp_get_current_userid();
	    $notes=$this->notes_obj->where($map)->order('id desc')->find();
	    echo json_encode($notes); 
	}
	function delNote(){
		$map['id']=$_POST['noteid'];
	    if($this->notes_obj->where($map)->delete()){
		   $result['state']='sucess';
	    } 
	    echo json_encode($result); 
	}
	function getMarketConfig(){
		$url=$this->marketUrl."/index.php?g=market&m=market&a=getMarketConfig";
		$MarketConfig=json_decode(post_curl($url),true);
		return $MarketConfig;
	}
    function Ali_info(){
        $info['KeyID']=C('Ali_KeyID');
        $info['keySecret']=C('Ali_KeySecret');
        $info['Bucket']=C('Ali_Bucket');
        $info['EndPoint']=C('Ali_EndPoint');
        $info['UserId']=C('Ali_UserId');
        $info['server']=C('server');
        $info['domain']=$this->get_domain();
        $info['authorcode']=C('authoCode');
        return $info;
    }
}