<?php

class Vas_set_promot extends MY_Controller {
    
    
     /**
    * 当前页码
    *
    * @access private
    * @var string
    */
    private $_current_page = 1;

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

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

    /**
    * 条目总数
    *
    * @access private
    * @var int
    */
    private $_total_count = 0;
    
    /**
     * 解析函数
     *
     * @access public
     * @return void
     */
    public function __construct($type = NULL) {
        parent::__construct($type);
        $this->config_cityflag = 'nj';
        $this->load->model('broker_model');
        $this->load->model('payment_model');
        $this->load->model('school_model');
        $this->VasPrice = new VasPrice(); 
        $this->house = $this->config->item('house');
        $this->load->helper('common_url_helper');
          //用户信息初始化
        $info = $this->broker_model->get_user_session();

        $groupId = $info['package_id']; //套餐
        $gbc = new GrowthBrokerCredit(array('id' => $info['uid'], 'groupid' => $groupId));
        $gbe = new GrowthBrokerExp(array('id' => $info['uid'], 'groupid' => $groupId));
        //房豆
        $info['credit'] = $gbc->getValidCredit();
        //等级
        $info['level'] = $gbe->getLevel(2);
        //经验
        $info['exp'] = $gbe->getExp();
        $this->info = $info;
    }
    
    
    
    /**
     * 学区房tab
     */
    public function schoolHouse(){
        //经纪人等级是否符合               
        $check = $this->checkVasLevel();
        if ($check!==true) {
            $page_text = "您升级至&nbsp;<span style='color:green;'>{$check}</span>&nbsp;级就可以使用此功能哦 ！<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;先去升级吧，加油！";
            $this->jump('/', $page_text, 4000);
            return;
        }
       
        $ASchoolNowPrice = $this->getTruthPrice('ASchool');//黄金实际价格
        $BSchoolNowPrice = $this->getTruthPrice('BSchool');//白银实际价格
        $ASchoolPrice = $this->getPrice('ASchool');//黄金
        $BSchoolPrice = $this->getPrice('BSchool');//白银
        $SchoolArr = $this->judgeSchool();
        
        $viewData['info'] = $this->info;
        $viewData['documentation'] = $this->config->item('documentation');
        $viewData['ASchoolNowPrice']  = $ASchoolNowPrice;
        $viewData['BSchoolNowPrice'] =  $BSchoolNowPrice;//白银
        $viewData['ASchoolPrice']  = $ASchoolPrice;
        $viewData['BSchoolPrice'] =  $BSchoolPrice;//白银
        $viewData['SchoolArr'] = $SchoolArr;
        $viewData['page_title'] = "定投推广-学区房定投";
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css');
        $viewData['payment_url'] = $this->payment_model->get_module_url('recharge');
		$viewData['google_analytics'] = get_ga_js_code('/营销中心/定投推广/我要购买/');
        $this->view('market','vas/school_house', $viewData);
    }
    
    /**
     * 学区选择
     */
    public function choiceSchool(){        
        //经纪人等级是否符合
        $check = $this->checkVasLevel();
        if ($check!==true) {
            $page_text = "您升级至&nbsp;<span style='color:green;'>{$check}</span>&nbsp;级就可以使用此功能哦 ！<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;先去升级吧，加油！";
            $this->jump('/', $page_text, 4000);
            return;
        }
      
        //配置文件数据
        $schoolTypeArr = $this->config->item('set_promot_school_type');
        $setPromotType = $this->config->item('set_promot_type');
        array_pop($setPromotType);
        //学区新数组
        if(CommonBase::isFullArray($schoolTypeArr)){
            foreach ($schoolTypeArr as $value){
                $newsShoolTypeArr[$value['sid']] = $value;
                $schoolIdArr[] = $value['sid'];
            }            
        }
        
        
        
        //获取的数据   
        $schoolId = $this->input->get('sid',TRUE);
        $schoolSubType = $this->input->get('type',TRUE);
        
        
        //类型判断
        if(in_array($schoolSubType, $setPromotType) ){
          $schoolType = substr($schoolSubType, 0,7);     
          $schoolAB = array('ASchool','BSchool');
          if(in_array($schoolType, $schoolAB)){
              $isParameter = TRUE;
          }else{
              $isParameter = FALSE;
          }
                  
        }else{
            $isParameter = FALSE;
        }
        
  
        //参数错误处理
        if(!$isParameter || !in_array($schoolId, $schoolIdArr)){
            $page_text = "对不起，参数错误，请重新定投！";
            $this->jump('/', $page_text, 4000);
            return;
        }
        
        //判断该学区下有无房源 
        //学校下面的小区
        $schoolBlock = $this->school_model->getBlockIdBySchoolId($schoolId);//学校下面的小区
        //该学区下经纪人是否有房源
        $isEstaSchool = $this->school_model->isEstHouseInSchoolByUid($this->info['uid'],$schoolBlock);
          if ($check!==true) {
            $page_text = "对不起，您该学区下没有房源 ！<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;快去发布学区房源吧！";
            $this->jump('/', $page_text, 4000);
            return;
        }
        
        $price = $this->getTruthPrice($schoolType);
        
        $houseList = $this->school_model->getSchoolHouseByUid($this->info['uid'],$schoolBlock);//该学区下的房源
        
        $blockName = $newsShoolTypeArr[$schoolId]['name'];
        
        
        $viewData['page_title'] = "定投推广-学区房定投";
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css,zsb/css/v1.0/jquery.mCustomScrollbar.css');
        $viewData['houseList'] = $houseList;
        $viewData['blockName']= $blockName;
        $viewData['price'] = $price; 
        $viewData['subType'] = $schoolSubType;
        $viewData['sid'] = $schoolId;
        $this->view('market','vas/select_house', $viewData);
        
    }
    
    
    /**
     * 学区购买订单处理
     */    
    public function schoolHouseBuy(){
        //获取类型
        $subType = $this->input->post('subType',TRUE);
        //获取房源ID
        $houseId = $this->input->post('houseid',TRUE);
        //学校ID
        $sid = $this->input->post('sid',TRUE);
        
        //判断类型
        $setPromotType = $this->config->item('set_promot_type');
        array_pop($setPromotType);        
       
        //判断房源id是否是学区房
        $isSchoolHouse = $this->isSchoolHouse($houseId,$sid);
       
        if(!$isSchoolHouse || !in_array($subType, $setPromotType)){
            echo json_encode(array('status'=>'2','msg'=>'参数错误,请重新选择学区定投房源！'));exit;
        }        
        
        //获取排队人数
        $VasQueueLimit  = new  VasQueueLimit();        
        $BuyNum  =   $VasQueueLimit->findtypenum($subType);//购买人数               
        $LimitNum =  $VasQueueLimit->findtypelimitnum($subType);//限制人数
        if($BuyNum>=$LimitNum){            
            echo json_encode(array('status'=>'3','msg'=>'超过最大购买次数！'));exit;            
        }
        
        //价格
        $schoolType = substr($subType,0,7);     
        $truthPrice = $this->getTruthPrice($schoolType);
        //房豆
        $myDou = $this->info['credit'];
        if($myDou<$truthPrice){
            echo json_encode(array('status'=>'4','msg'=>'对不起，您的房豆不足，请充值！'));exit;            
        }
        
        
        $broker['id'] = $this->info['uid'];
        $broker['groupid'] = $this->info['package_id'];
        $GrowthBrokerCredit = new GrowthBrokerCredit($broker);
        $pay_order  = $GrowthBrokerCredit->reduce('setPromot','学区房定投推广',$truthPrice);
        if($pay_order['status']==1){
            //记录详细信息
           $fieldData=array('type'=>$subType,'uid'=>$this->info['uid'],'houseid'=>$houseId,'order_id'=>$pay_order['transaction_id'],'cost'=>$truthPrice,'status'=>1);
           $VasSetPromotRecord = new VasSetPromotRecord('vas_set_promot_record');
           $record_id = $VasSetPromotRecord->insert($fieldData);
     
           //更新购买次数          
           $VasQueueLimit->addNumberToOneType($subType,1);
           
           //增加经纪人购买记录
           $vasBroker = new VasBroker();
           $vasBroker->addJoinSetPromotRecord($broker['id']);

        }
        print json_encode($pay_order);
        
    }
    
   


    /**
     * 优秀经纪人tab
     */
    public function greatBroker(){
        
        
        $GreatBrokerNowPrice = $this->getTruthPrice('GreatBroker');//实际价格        
        $GreatBrokerPrice = $this->getPrice('GreatBroker');//价格
        $judgeGradeBroker = $this->judgeGradeBroker($GreatBrokerNowPrice,$GreatBrokerPrice);
        
        $viewData['info'] = $this->info;
        $viewData['documentation'] = $this->config->item('documentation');
        $viewData['GreatBrokerPrice']  = $GreatBrokerPrice;
        $viewData['GreatBrokerNowPrice']  = $GreatBrokerNowPrice;  
        $viewData['judgeGradeBroker'] = $judgeGradeBroker;
        $viewData['page_title'] = "定投推广-优秀经纪人定投";
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css,zsb/css/v1.0/jquery.mCustomScrollbar.css');
        $viewData['payment_url'] = $this->payment_model->get_module_url('recharge');
        $this->view('market','vas/great_broker', $viewData);
        
    }
    
    
    
    
     /**
     * 优秀经纪人购买
     */
    public function gradeBrokerBuy(){
        
        $type = "GreatBroker";
        //获取排队人数
        $VasQueueLimit  = new  VasQueueLimit();        
        $BuyNum  =   $VasQueueLimit->findtypenum($type);//购买人数               
        $LimitNum =  $VasQueueLimit->findtypelimitnum($type);//限制人数
        if($BuyNum>=$LimitNum){            
            echo json_encode(array('status'=>'2','msg'=>'超过最大购买次数！'));exit;            
        }
        
        //价格        
        $truthPrice = $this->getTruthPrice($type);
        //房豆
        $myDou = $this->info['credit'];
        if($myDou<$truthPrice){
            echo json_encode(array('status'=>'3','msg'=>'对不起，您的房豆不足，请充值！'));exit;            
        }
        
        
        $broker['id'] = $this->info['uid'];
        $broker['groupid'] = $this->info['package_id'];
        $GrowthBrokerCredit = new GrowthBrokerCredit($broker);
        $pay_order  = $GrowthBrokerCredit->reduce('setPromot','优秀经纪人定投推广',$truthPrice);
        if($pay_order['status']==1){
            //记录详细信息
           $fieldData=array('type'=>$type,'uid'=>$this->info['uid'],'order_id'=>$pay_order['transaction_id'],'cost'=>$truthPrice,'status'=>1);
           $VasSetPromotRecord = new VasSetPromotRecord('vas_set_promot_record');
           $record_id = $VasSetPromotRecord->insert($fieldData);
     
           //更新购买次数          
           $VasQueueLimit->addNumberToOneType($type,1);
           
           //增加经纪人购买记录
           $vasBroker = new VasBroker();
           $vasBroker->addJoinSetPromotRecord($broker['id']);

        }
        print json_encode($pay_order);
        
    }
    

    
    /**
     * 购买记录list
     */
    public function myList(){
               
        $post_param = array();
        $post_param['page'] ='';
        $post_param = $this->input->post(NULL , TRUE);
        $current_page = $post_param['page'] != '' ? intval($post_param['page']) : 1;
    
        $status = $post_param['status'];
  
      //  exit();
        $allStatus = $this->config->item('packing_house_staus');
        
        $cond_where = "uid = ".$this->info['uid'];
        if($status){           
            $cond_where .= " and status=".$status;
        }
                
        //参数初始化
        $this->_init_pagination($current_page);
        
        
        $vasRecord = new VasSetPromotRecord();      
        
         //符合条件的总行数
        $this->_total_count = $vasRecord->findNumberBy($cond_where);
     

        //计算总页数
        $pages  = $this->_total_count > 0 ? ceil( $this->_total_count / $this->_limit ) : 0;

        //获取数据源($conf,$order='',$limit='',$offset='') 
        $data_info = $vasRecord->findBy( $cond_where ,'buy_time DESC', $this->_limit, $this->_offset  );
        
        
        
        //是否显示分页
        $pagination = NULL;
        if( $this->_total_count > $this->_limit)
        {
            $pagination = helper_pagination( $current_page , $pages , $this->_total_count );
        }
        
        
        $data_info = $this->myRecordListData($data_info, $allStatus);
        
          /** 页面初始化 */
        $viewData['page_title'] = '定投推广-我的购买记录';
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css'); //需要加载的css
       
        $viewData['post_param']  = $post_param;
        $viewData['data_info']  = $data_info;
        $viewData['page']  = $current_page;
        $viewData['pagination'] = $pagination;
        $viewData['total'] = $this->_total_count;
        $viewData['documentation'] = $this->config->item('documentation');
        $viewData['allStatus'] = $allStatus;
        $viewData['status'] = $status;
        $viewData['info'] = $this->info;
        $viewData['payment_url'] = $this->payment_model->get_module_url('recharge');
		$viewData['google_analytics'] = get_ga_js_code('/营销中心/定投推广/我的购买记录/');
        //加载模板
        $this->view('market','vas/set_promot_list',$viewData);         
        
    }
    
    
    //房源记录数据处理
    private function myRecordListData($data_info,$allStatus){
        if(CommonBase::isFullArray($data_info)){
            foreach ($data_info as $key=>$value){                
                $data_info[$key]['status'] = $allStatus[$value['status']];
                $data_info[$key]['start_time'] = $value['start_time'] == "0000-00-00 00:00:00" ? "" : date('Y-m-d',  strtotime($value['start_time']));
                $data_info[$key]['end_time'] = $value['end_time'] == "0000-00-00 00:00:00" ? "" : date('Y-m-d',  strtotime($value['end_time']));
                $data_info[$key]['houseid'] = $value['houseid']!=0 ? $value['houseid'] : '——';                
                $data_info[$key]['type'] = $value['type'] == 'GreatBroker' ? "优秀经纪人定投" : $this->getSchoolAndDisplayByType($value['type']);
                
                
            }
            return $data_info;
            
        }
    
    }
    
    //根据定投类型获取房源的学校和展位
    private function getSchoolAndDisplayByType($type){
        $set_promot_school_type = $this->config->item('set_promot_school_type');
        if(CommonBase::isFullArray($set_promot_school_type)){
            foreach ($set_promot_school_type as $value){
                if($type == $value['A']){   
                    return "学区房定投-".$value['name']."-黄金展位";
                }elseif($type == $value['B']){
                    return "学区房定投-".$value['name']."-白银展位";
                }
            }
        }
    }






    /**
     * 是否有三条店铺推荐房源
     * 
     */
    public function isTopHouse(){       
        $this->load->model('shop_model');            
        $sell_shop_num =  $this->shop_model->use_rec_count('sell',$this->info['uid']); 
		$rent_shop_num =  $this->shop_model->use_rec_count('rent',$this->info['uid']);
		$total = $sell_shop_num + $rent_shop_num;
        if($total>=3){
            $return['status'] = 1;
        }else{
            $return['status'] = 0;
        }
        
        return print json_encode($return);;
    }
    
    /**
     * 是否是某学校学区房
     */
    private function isSchoolHouse($houseId,$sid){
        $blockArr = $this->school_model->getBlockIdBySchoolId($sid);
        $this->load->model('sell_model');      
        $cond_where = "id = ".$houseId;
        $houseInfo =  $this->sell_model->find_one_by($cond_where);  
        
        if(in_array($houseInfo['blockid'], $blockArr)){
            return TRUE;
        }else{
            return FALSE;
        }
       
    }

        /**
     * 优秀经纪人判断
     */
    private function judgeGradeBroker($GreatBrokerNowPrice){
        //房豆
        $myDou = $this->info['credit'];
        //排队人数
        $VasQueueLimit  = new  VasQueueLimit();        
        $BuyNum  =   $VasQueueLimit->findtypenum('GreatBroker');//购买人数               
        $LimitNum =  $VasQueueLimit->findtypelimitnum('GreatBroker');//限制人数
        
        if($myDou>$GreatBrokerNowPrice && $BuyNum<$LimitNum){
            //可以购买
            $arr = array('status'=>1,'msg'=>'可以购买');
        }elseif($myDou<$GreatBrokerNowPrice){
            //房豆少
            $arr = array('status'=>2,'msg'=>'您的房豆余额不够哦，<a href="'.$this->payment_model->get_module_url('recharge').'" target="_blank">去充值>></a>');
        }else{
            //排队人数多
            $arr = array('status'=>3,'msg'=>'购买的人太多了，稍后再来吧！');
        }
        return $arr;
    }




    /**
     * 学区判断
     */
    private function judgeSchool(){
        //学校具体类别
        $schoolType = $this->config->item('set_promot_school_type');
      
        $ASchoolNowPrice = $this->getTruthPrice('ASchool');//黄金实际价格
        $BSchoolNowPrice = $this->getTruthPrice('BSchool');//白银实际价格
        //房豆
        $myDou = $this->info['credit'];
        
        //排队人数
        $VasQueueLimit  = new  VasQueueLimit();
        if(CommonBase::isFullArray($schoolType)){
            foreach ($schoolType as $key=>$value){
                $aBuyNum  =   $VasQueueLimit->findtypenum($value['A']);//A类购买人数
               
                $aLimitNum =  $VasQueueLimit->findtypelimitnum($value['A']);//A类限制人数
                $bBuyNum  =   $VasQueueLimit->findtypenum($value['B']);//B类购买人数
                $bLimitNum =  $VasQueueLimit->findtypelimitnum($value['B']);//B类限制人数
                //学校下面的小区
                $schoolBlock = $this->school_model->getBlockIdBySchoolId($value['sid']);//学校下面的小区
          
                //该学区下经纪人是否有房源
                $isEstaSchool = $this->school_model->isEstHouseInSchoolByUid($this->info['uid'],$schoolBlock);
                
                $aSchoolStatus = $this->schoolBeforeBuy($myDou, $ASchoolNowPrice, $aBuyNum, $aLimitNum);
                $bSchoolStatus = $this->schoolBeforeBuy($myDou, $BSchoolNowPrice, $bBuyNum, $bLimitNum);              
                
                $temp[$key] = array('aschool'=>$aSchoolStatus,'bschool'=>$bSchoolStatus,'isesta'=>$isEstaSchool,'schoolname'=>$value['name'],'sid'=>$value['sid'],'typeA'=>$value['A'],'typeB'=>$value['B']);     
                
            }
            $schoolArr = $temp;
        }
        
        return $schoolArr;        
       
    }
    
    /**
     * 学区购买之前场景处理
     */
    private function schoolBeforeBuy($myDou,$price,$BuyNum,$LimitNum){
    
        if($myDou>=$price&&$LimitNum>$BuyNum){
            //可以购买
            $arr = array('status'=>1,'msg'=>'可以购买');
        }elseif($myDou<$price){
            //房豆少
            $arr = array('status'=>2,'msg'=>'您的房豆余额不够哦，<a href="'.$this->payment_model->get_module_url('recharge').'" target="_blank">去充值>></a>');
        }else{
            //排队人数太多
            $arr = array('status'=>3,'msg'=>'购买的人太多了，稍后再来吧！');
        }
        
        return $arr;
        
        
    }
    
    /**
     * 获取价格
     */
    private function getPrice($type){
        $key = $this->config_cityflag."_vas_set_promot_price_".$type;
        $SchoolPrice = $this->mc->get($key);
        if($SchoolPrice === false) {
            $SchoolPrice = $this->VasPrice->findByType($type);
            $this->mc->set($key,$SchoolPrice,600);	
        }
        return $SchoolPrice; 
    }
    
    /**
     * 获取最终价格
     */
    private function getTruthPrice($type){
        $key = $this->config_cityflag."_vas_set_promot_truth_price_".$type;
        $SchoolNowPrice = $this->mc->get($key);
        if($SchoolNowPrice === false) {
            $SchoolNowPrice = $this->VasPrice->ServicePrice($type);//黄金实际价格
            $this->mc->set($key,$SchoolNowPrice,600);	
        }
        return $SchoolNowPrice;      
    }
    
    
    /**
     * 
     * @return boolean 成功时返回true，失败时返回等级
     */
    private function checkVasLevel() {
        //判断有无权访问
        $brokerLevel = $this->info['level'];        
        //经纪人操作等级最低权限
        $permi = new GrowthLevelWayPermission();
        $minLevel = $permi->findMinLevelByWayAliasAndType('setPromot',2);       
     
        if ($brokerLevel < $minLevel || $minLevel == '') {
            return "Lv".$minLevel;
        } else {
            return true;
        }
    }
    
    
    



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

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

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

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





}