<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/**
 * 标签零售首页
 */

class tag_index_zhou extends MY_Controller{
    
    private $broker;
    private $info;
    private $uid;
    private $config_cityflag;


    public function __construct($type = NULL) 
    {
        parent::__construct($type);
		
        $this->initUserInfo();
        $this->checkAuth();
        $this->config_cityflag = 'nj';
        $this->load->model('broker_model');
		
        $this->growthBrokerCredit = new GrowthBrokerCredit($this->broker);
        $this->initGrowthBrokerBidBlockExpert();
        $this->initGrowthBrokerBidHouse();
    }
    
    public function index(){
        //用户信息初始化
        //$this->initUserInfo();
		
        $groupId = $this->info['package_id'];//套餐
        $brokerType = $this->info['groupid'];//免费or付费
        //特权
        $my_privilege= $this->my_privilege($this->info['level'],$brokerType,  $this->info['credit'],$groupId);
        $this->load->model('payment_model');
		//print_r($this->info);exit;

        /**标签零售信息 2015-5-16 zhou start  **/
		$this->load->model('house_tag_price_model');
		$house_tag_info =$this->house_tag_price_model->findByAll();
		$house_tag_num  =count($house_tag_info);
	
		$viewData['house_tag_num'] = $house_tag_num ;
		$viewData['house_tag_info'] = $house_tag_info ;

		/**标签零售信息 2015-5-16 zhou end  **/

		// 2016-1-14 添加星级数据 -----------start -------->
		
		$this->load->model('broker_zhou_model');
		//echo $uid;die;
		$broker_new_info =$this->broker_zhou_model->get_broker_info_by_uid($this->info['uid']);
		// 2016-1-14 添加星级数据 -----------end -------->

        $documentation = $this->config->item('documentation');
        $viewData['page_title'] = '营销中心-首页';
        $viewData['js'] = load_js('zsb/js/v1.0/js2.js,common/js/jquery.jcountdown.js');   
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css');
        $viewData['broker'] = $this->broker;
        $viewData['info'] = $this->info;
        $viewData['my_privilege'] = $my_privilege;
        $viewData['documentation'] = $documentation;

		$viewData['broker_new_info'] = $broker_new_info;

        $viewData['payment_url'] = $this->payment_model->get_module_url('recharge');
		$viewData['google_analytics'] = get_ga_js_code('/营销中心/标签零售/');
        $this->view('market','tag_index_zhou',$viewData);
    }


	public function addcart()
	{
		
		$id			=$_GET['id'];
		$tag_price  =$_GET['tag_price'];
		$tag_num    =$_GET['tag_num'];
		
		if($tag_num==0)
		{
			$result['is_ok'] = 0;
            $result['msg'] = iconv( 'gb2312' , 'utf-8',  '购买标签包数量不对!' );
			print_r(json_encode($result));
			exit;
		}
		
		$this->initUserInfo();
		
        $groupId = $this->info['package_id'];//套餐
        $brokerType = $this->info['groupid'];//免费or付费


		$result['is_ok'] = 1;
        $result['msg']   = '购买成功!';

		// 判断账号是否有效
		if ($this->info['valid_flag']==0) 
		{
			$result['is_ok'] = 0;
            $result['msg'] = '您账号无效,无法购买标签包！';
           
        }
		// 判断账号是否大于购买上限(套餐标签的60%)
		
		$this->load->model('house_tag_price_model');
		$broker_package_info  =$this->house_tag_price_model->findBrokerPageById($groupId);

		$date_now = strtotime("now");
		$date_expire = strtotime($this->info['expiredate']);
		
		if($date_now>$date_expire)
		{
			$result['is_ok'] = 0;
            $result['msg'] = '您的账号已经过期，无法购买!';
			$result['msg'] = iconv( 'gb2312' , 'utf-8',  $result['msg'] ); 
			print_r(json_encode($result));
			exit;
		}
		if($broker_package_info[0]['package_tag_num']==0)
		{
			$result['is_ok'] = 0;
            $result['msg'] = '您的套餐不含标签，所以无法购买，请联系客户经理开通带标签的套餐.';
			$result['msg'] = iconv( 'gb2312' , 'utf-8',  $result['msg'] ); 
			print_r(json_encode($result));
			exit;
		}
		$current_total_num =$this->house_tag_price_model->findTagNumByUid($this->info['uid']);//当月买的标签数
		
	
		$house_tag_price_info = $this->house_tag_price_model->findById($id);

		$tag_num_total        =$tag_num*$house_tag_price_info[0]['tag_num'];
		if ($tag_num_total>$broker_package_info[0]['package_tag_num']*0.6  || ($current_total_num+$tag_num_total)>$broker_package_info[0]['package_tag_num']*0.6) 
		{
			$result['is_ok'] = 0;
            $result['msg'] = '超过套餐购买上限，您无法购买！';
        }
		
		// 判断账户所剩房豆值是否超过所选的标签包所需的房豆值
		
		if($tag_price*$tag_num>$this->info['credit'])
		{
			$result['is_ok'] = 0;
            $result['msg'] = '您的房豆值不够，请充值!';
		}
		
		if($result['is_ok'])
		{
			$house_tag_price_info = $this->house_tag_price_model->findById($id);
			$tag_name             =$house_tag_price_info[0]['tag_name'];
			$tag_valid            =$house_tag_price_info[0]['tag_valid'];
			$uid                  =$this->info['uid'];
			$username             =$this->info['username'];
			$truename             =$this->info['truename'];
			$telno				  =$this->info['telno'];
			
			$home_auth_info		  =$this->house_tag_price_model->findByMaster($this->info['master']);
			if(is_array($home_auth_info) && !empty($home_auth_info))
			{
				$master               =$home_auth_info[0]['truename'];	
			}
			else
			{
				$master ='';
			}
			$broker['id']		  =$this->info['uid'];
			$broker['groupid']    =$this->info['package_id'];
			$price                =$tag_price*$tag_num;
			
			$time=time()+$tag_valid*24*3600;
			$date_end=date('Y-m-d',$time);
			$GrowthBrokerCredit   = new GrowthBrokerCredit($broker);
			//$pay_order = $GrowthBrokerCredit->reduce('HouseTagPrice', '标签零售', $price);
			$pay_order = $GrowthBrokerCredit->reduce('tagSale', '该标签包中未使用标签的到期时间为 '.$date_end, $price);
			$transaction_id       =$pay_order['transaction_id'];
			
			/**    标签零售记录表里面插入记录      **/
			$this->load->model('house_tag_record_model');
			
			
			
			$this->house_tag_record_model->insertdata($id,$tag_num,$tag_name,$uid,$username,$truename,$telno,$master,$transaction_id,time());

			$this->load->model('house_tag_package_model');
		    $this->house_tag_package_model->add_tag_pacakage($id,$tag_num*$house_tag_price_info[0]['tag_num'],$tag_valid,$uid);

			//清楚到期缓存
			//$this->load->model("house_tag_package_model");
			$this->house_tag_package_model->get_tag_valid($uid,1);
			
		}
		
		$result['msg'] = iconv( 'gb2312' , 'utf-8',  $result['msg'] ); 
        print_r(json_encode($result));
        exit;
		

	
	}

	//标签零售购买记录页面2015-5-18 zhou
	public function record()
	{

		$this->_limit       =10;
		$this->_offset      =0;
		$this->initUserInfo();
		$post_param			= array();
        $post_param['page'] ='';
        $post_param			= $this->input->post(NULL , TRUE);
        $current_page		= $post_param['page'] != '' ? intval($post_param['page']) : 1;
        $cond_where			= "uid = ".$this->info['uid'];
		$this->load->model('house_tag_record_model');
		//参数初始化
        $this->_init_pagination($current_page);
        //符合条件的总行数
        $this->_total_count	 = $this->house_tag_record_model->findNumberBy($cond_where);
        //计算总页数
        $pages				 = $this->_total_count > 0 ? ceil( $this->_total_count / $this->_limit ) : 0;
        //获取数据源
		

		$data_info = $this->house_tag_record_model->findBy($cond_where ,'date_add', 'DESC', $this->_limit, $this->_offset);
		
		for($i=0;$i<count($data_info);$i++)
		{
			$this->load->model('house_tag_price_model');
			$house_tag_price_info  =$this->house_tag_price_model->findById($data_info[$i]['tag_price_id']);
			$data_info[$i]['tag_total_price']    = $house_tag_price_info[0]['tag_discount_price'] * $data_info[$i]['tag_num'];
			$data_info[$i]['expire_time']        = date('Y-m-d',$data_info[$i]['date_add']+($house_tag_price_info[0]['tag_valid']*3600*24));	
		}

			
 
        //是否显示分页
        $pagination = NULL;
        if( $this->_total_count > $this->_limit)
        {
            $pagination = helper_pagination( $current_page , $pages , $this->_total_count );
        }
        
		
		
        $groupId = $this->info['package_id'];//套餐
        $brokerType = $this->info['groupid'];//免费or付费
        //特权
        $my_privilege= $this->my_privilege($this->info['level'],$brokerType,  $this->info['credit'],$groupId);
        $this->load->model('payment_model');

        $documentation = $this->config->item('documentation');
        $viewData['page_title'] = '营销中心-标签零售记录';
		$viewData['data_info']  = $data_info;
		$viewData['page']  = $current_page;
        $viewData['pagination'] = $pagination;
        $viewData['total'] = $this->_total_count;
        $viewData['js'] = load_js('zsb/js/v1.0/js2.js,common/js/jquery.jcountdown.js');   
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css');
        $viewData['broker'] = $this->broker;
        $viewData['info'] = $this->info;
        $viewData['my_privilege'] = $my_privilege;
        $viewData['documentation'] = $documentation;
        $viewData['payment_url'] = $this->payment_model->get_module_url('recharge');
		$viewData['google_analytics'] = get_ga_js_code('/营销中心/标签零售记录/');
        $this->view('market','tag_record',$viewData);
	
		
	}


	//标签零售购买记录页面2015-5-26 zhou
	public function buy_person_num()
	{

		//参数初始化
		$this->load->model('house_tag_record_model');
		
        //符合条件的总行数
        $total_info	 = $this->house_tag_record_model->findPersonNum();
		return  $total_info[0]['number'];
		
       
	
		
	}


    
    
   
    /**
    * 初始化分页参数
    *
    * @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());
        }
    }
    
    
    /**
     * 初始化经纪人信息
     */
    private function initUserInfo() {
        $info = $this->broker_model->get_user_session();
        
        $groupId = $info['package_id']; //套餐
        $brokerType = $info['groupid'];//免费or付费
        $gbe = new GrowthBrokerExp(array('id' => $info['uid'], 'groupid' => $groupId));
        $gbc = new GrowthBrokerCredit(array('id' => $info['uid'], 'groupid' => $groupId));
        $broker_detail = $this->broker_model->get_broker_detail();//经纪人详细信息
        if($broker_detail['master']){
            $accout_manager = $this->broker_model->get_account_manager($broker_detail['master']);//客户经理
            if (isset($accout_manager) && !empty($accout_manager)) {
                $info['accout_manager'] = $accout_manager['truename'];
                $info['manager_tel'] = $accout_manager['telno'];
            }
        }
        //等级
        $info['level'] = $gbe->getLevel(2);
        //经验
        $info['exp'] = $gbe->getExp();
        //成长值线        
        $allLevel = $this->allLevel();
        $growthAllLevelNum = count($allLevel);
        $info['level_num'] = intval(substr($info['level'],2));
	$info['level_line'] = ceil($info['level_num']/$growthAllLevelNum*100);
        //房豆
        $info['credit'] = $gbc->getValidCredit();
        $this->info = $info;
        $this->uid = $info['uid'];
        
        $broker['smallphoto'] = $info['smallphoto'] ? $info['smallphoto'] : "http://esf.fz.house365.com/zsb/images/v1.0/defaultface.jpg";
        $broker['id'] = $this->uid;
        $broker['level'] = 'LV'.$this->info['level'];
        $broker['credit'] = $this->info['credit'];
        $broker['groupid'] = $groupId;
        $broker['is_pay'] = $this->info['is_pay'];
        $this->broker = $broker;
    }
    
    
   

    //特权
    private function my_privilege($brokerLevel,$brokerType,$brokerCredit,$packageid) {
        $privilege = array();
        //$privilege[] = $this->getPrivilegeBlockExpert($brokerLevel, $brokerType, $brokerCredit,$packageid);
        //$privilege[] = $this->getPrivilegeBuy($brokerLevel, $brokerType, $brokerCredit,$packageid);
        //$privilege[] = $this->getPrivilegeRent($brokerLevel, $brokerType, $brokerCredit,$packageid);
        $this->load->library('TeQuan');
        $privilege = $this->tequan->init($brokerLevel,$brokerType,$brokerCredit,$packageid)->getAll();
        //var_dump($x);exit;
        $data = array();
        $data['privilege'] = $privilege;
    
        return $this->load->view('ucenter/my_privilege.php',$data,true);
    }
    
    
   /**
     * 初始化成长体系-经纪人小区专家竞投类
     */
    private function initGrowthBrokerBidBlockExpert() {
        $growthConfig = $this->config->item('growth');
        $mode = $growthConfig['mode'];
        $this->growthBrokerBidBlockExpert = new GrowthBrokerBidBlockExpert($this->broker, $this->growthBrokerCredit, $mode);
        //$this->growthBrokerBidHouse->setCheckStar(true);
        $additionalScore = $growthConfig['additionalScore']['block'];
        $this->growthBrokerBidBlockExpert->setAdditionalScore($additionalScore);
    }
    
    /**
     * 初始化成长体系类
     */
    private function initGrowthBrokerBidHouse() {
        $growthConfig = $this->config->item('growth');
        $mode = $growthConfig['mode'];
        $this->growthBrokerBidHouse = new GrowthBrokerBidHouse($this->broker, $this->growthBrokerCredit,$mode);
        $this->growthBrokerBidHouse->setCheckStar(true);
        $additionalScore = $growthConfig['additionalScore']['house'];
        $this->growthBrokerBidHouse->setAdditionalScore($additionalScore);
    }
    
        /**
     * 返回全部等级数组
     * @return type
     */
    private function allLevel() {
        $key = $this->config_cityflag."_growth_level_data";
        $allLevel = $this->mc->get($key);
        if($allLevel === false) {
            $growthLevel = new GrowthLevel();
            $allLevel = $growthLevel->findAllLevelData();
            $this->mc->set($key,$allLevel,600);	
        }
        return $allLevel;
    }

	private function checkAuth() {
        if($this->info['is_pay']){
            $this->jump('/', '您当前套餐没有此功能的权限，请联系客户经理开通！');
            exit;
        }
    }
    
    
      
}