<?php if (!defined('BASEPATH'))exit('No direct script access allowed');

/**
 * statistics_analysis Class
 *
 * 租售宝二手房数据统计模块
 *
 * @package		zsb
 * @subpackage	Controllers
 * @category	Controllers
 * @author      liuhu
 */

class statistics_analysis extends MY_Controller {
    
	/**
	*
	* @var Statistics 
	*/
    public $stat;

	/**
    * 当前用户uid
    *
    * @access private
    * @var int
    */
    private $uid;


    private $info;

	/**
    * 当前页码
    *
    * @access private
    * @var string
    */
    private $_current_page = 1;

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

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

    /**
    * 条目总数
    *
    * @access private
    * @var int
    */
    private $_total_count = 0;

    public function __construct() 
	{
        parent::__construct();

        $this->load->model('statistics_model','stat');
        $this->load->model('broker_check');
        $this->load->library('TabPage');
        $this->load->library('statistics_plus');
		$this->load->model('reserve_model');
        $info = $this->broker_model->get_user_session();
        $this->info = $info;
        $this->uid = $info['uid'];
    }

	
	/**
    * 初始化分页参数
    *
    * @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());
        }
    }

    
    public function index() 
    {
        $this->today();
    }


    /**
     * 使用概况 今日
     */
    public function today() 
    {
        $viewData = array();
        $groupId = $this->info['package_id'];//套餐
        $brokerType = $this->info['groupid'];//免费or付费
        
        //时间
        $data['time'] = date("Y-m-d H:i");

        //今日概况
        $overViewToday = $this->stat->overViewToday($this->uid,$groupId);

        $data = array_merge($data, $overViewToday);

        $viewData['data'] = $data;
        //tab页
        $curPage = 'today';
        $viewData['tab'] = $this->overViewTab($curPage);
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css');
        $viewData['page_title'] = '租售宝-使用概况-今日';
		$viewData['google_analytics'] = get_ga_js_code('/统计分析/使用概况/今日概况/');

		// 是否能够发全景房
		$config = $this->config->item('is_publish_360');
		if($config === false){
			$config = true;
		}else{
			if($config == 1){
				$config = true;
			}else{
				$config = false;
			}
		}
		$viewData['is_publish_360'] = $config;


        $this->view('statics', 'statistics_analysis/today', $viewData);
    }
    
    /**
     * 使用概况 历史
     */
    public function history()
    {
        $viewData = array();
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');

        //默认一周
		$stime = $this->input->post('stime', TRUE);
        if($stime === FALSE) 
		{
            $stime = date("Y-m-d",strtotime("-7days"));
        }
        $viewData['stime'] = $stime;

        $etime = $this->input->post('etime',TRUE);
        if($etime === FALSE) 
		{
            $etime = date("Y-m-d",strtotime("-1days"));
        }
        $viewData['etime'] = $etime;


		/** 分页参数 */
		$page = $this->input->post( 'page' , TRUE);
        $page = (isset($page)&& intval($page) > 0) ? intval($page) : 1;
        $this->_init_pagination($page);

        $this->_total_count = $this->stat->historyCount($this->uid, $stime, $etime);
		$pages  = $this->_total_count > 0 ? ceil( $this->_total_count / $this->_limit ) : 0;

        $viewData['list'] = $this->stat->historyList($this->uid, $stime, $etime, $this->_offset , $this->_limit);
        //print_r($viewData['list']);die;
        foreach ($viewData['list'] as &$value)
		{
            $value['house_add'] = $value['sell_add'] + $value['rent_add'];
            $value['house_add_valid'] = $value['sell_add_valid'] + $value['rent_add_valid'];
            $value['remain_refresh'] = $value['total_refresh'] >= $value['refresh'] ?
				$value['total_refresh'] - $value['refresh'] : 0;
            $value['remain_tag_num'] = $value['package_tag_num'] >= $value['is_tag_num'] ?
				$value['package_tag_num'] - $value['is_tag_num'] : 0;
            $value['remain_nofee_num'] = $value['nofee_limit'] - $value['nofee_num'];
        }

		//是否显示分页
        $pagination = NULL;
        if( $this->_total_count > $this->_limit)
        {	
            $pagination = helper_pagination( $this->_current_page , $pages , $this->_total_count );
        }

        //tab页
        $curPage = 'history';
        $viewData['tab'] = $this->overViewTab($curPage);
        
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css');
        //js
        $viewData['js'] = load_js('common/js/My97DatePicker/WdatePicker.js');
        $viewData['page_title'] = '租售宝-使用概况-历史';
		$viewData['google_analytics'] = get_ga_js_code('/统计分析/使用概况/历史概况/');
		$viewData['page']  = $this->_current_page;
        $viewData['pagination'] = $pagination;
		
		// 是否能够发全景房
		$config = $this->config->item('is_publish_360');
		if($config === false){
			$config = true;
		}else{
			if($config == 1){
				$config = true;
			}else{
				$config = false;
			}
		}
		$viewData['is_publish_360'] = $config;

        $this->view('statics', 'statistics_analysis/history', $viewData);
    }

	
	/**
     * 使用概况 历史下载
     */
    public function history_download()
    {
		$broker_info = array();

        //默认一周
		$stime = $this->input->post('stime', TRUE);
        if($stime === FALSE) 
		{
            $stime = date("Y-m-d",strtotime("-7days"));
        }
        $viewData['stime'] = $stime;

        $etime = $this->input->post('etime',TRUE);
        if($etime === FALSE) 
		{
            $etime = date("Y-m-d",strtotime("-1days"));
        }
        $viewData['etime'] = $etime;


		/** 分页参数 */
        $broker_info = $this->stat->historyList($this->uid, $stime, $etime, 0 , 60);

		/** PHPExcel_IOFactory */
		$this->load->library('PHPExcel');
		$this->load->library('PHPExcel/IOFactory');

		//初始化类库
		$objReader = new IOFactory('Excel5');

		//引用模版
		if(!empty($broker_info))
		{
			$tplname =	APPPATH.'views/nj/statistics_analysis/broker_use_statistic_temp.xls' ;
		}
		else
		{
			$tplname =	APPPATH.'views/nj/statistics_analysis/broker_use_statistic_temp_nodata.xls' ;
		}
		$objPHPExcel = $objReader->load($tplname);

		//给单元格赋值
		$baseRow = 3;
		if(is_array($broker_info) && !empty($broker_info))
		{
			foreach($broker_info as $r => $dataRow) 
			{	
				$remain_refresh = $dataRow['total_refresh'] >= $dataRow['refresh'] ?
				$dataRow['total_refresh'] - $dataRow['refresh'] : 0;
				$remain_tag_num = $dataRow['package_tag_num'] >= $dataRow['is_tag_num'] ?
				$dataRow['package_tag_num'] - $dataRow['is_tag_num'] : 0;
				$remain_nofee_num = $dataRow['nofee_limit'] - $dataRow['nofee_num'];

				$row = $baseRow + $r;
				$objPHPExcel->getActiveSheet()->insertNewRowBefore($row,1);
				$objPHPExcel->getActiveSheet()->setCellValue('A'.$row, $dataRow['stattime'])
					  ->setCellValue('B'.$row, intval( $dataRow['sell_house_num'] ) )
					  ->setCellValue('C'.$row, $dataRow['rent_house_num'])
					  ->setCellValue('D'.$row, intval($dataRow['sell_star_num']) )
					  ->setCellValue('E'.$row, intval($dataRow['rent_star_num']) )
					  ->setCellValue('F'.$row, intval( $dataRow['sell_add']+$dataRow['rent_add'] ) )
					  ->setCellValue('G'.$row, intval( $dataRow['sell_add_valid']+$dataRow['rent_add_valid'] ) )
					  ->setCellValue('H'.$row, intval( $dataRow['refresh'] ) )
					  ->setCellValue('I'.$row, intval( $remain_refresh ) )
					  ->setCellValue('J'.$row, intval( $dataRow['is_tag_num'] ) )
					  ->setCellValue('K'.$row, $remain_tag_num)
                      ->setCellValue('L'.$row, intval( $dataRow['is_tag_num'] ) )
                      ->setCellValue('M'.$row, $remain_tag_num)
					  /*->setCellValue('L'.$row, intval( $dataRow['nofee_num'] ))
					  ->setCellValue('M'.$row, intval( $dataRow['nofee_limit'] ))
					  ->setCellValue('N'.$row, intval( $dataRow['click_num'] ) );*/
					  ->setCellValue('N'.$row, intval( $dataRow['click_num'] ) );
			}
		}

		$outputFileName = '使用统计下载.xls';
		header('Content-Type: application/vnd.ms-excel');
		header("Content-Disposition: attachment;filename=".$outputFileName."");
		header('Cache-Control: max-age=0');
		$objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
		exit;
    }


    /**
     * 使用日志
     */
    public function log()
    {

        $viewData = array();
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $app	= '';
        //房源编号
        $houseid = $this->input->post('houseid', TRUE);
        //类型
        $type = $this->input->post( 'type' , TRUE);

        if($type === FALSE)
        {
            $type = 0;
        }

        /** 分页参数 */
        $page = $this->input->post( 'page' , TRUE);
        $page = (isset($page)&& intval($page) > 0) ? intval($page) : 1;
        $this->_init_pagination($page);

        $types = array(0 => '全部', 1 => '新增',2 => '刷新',3 => '删除',4 => '失效',5 => '激活');
        if( !in_array( $type , array_keys($types)) )
        {
            $type = 0;
        }

        $viewData['types'] = $types;
        $viewData['type'] = $type;
        $viewData['houseid'] = $houseid;

        //统计的日期，默认是昨天的日期
        $count_day = $this->input->post('count_day', TRUE);

        if($count_day === FALSE)
        {
            $yesterday  = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')));
            $count_day = $yesterday;
        }

//        $this->uid = 827249; //TODO 测试

        $viewData['count_day'] = $count_day;
        $day	= date('Ymd' , strtotime($count_day));
        $total_num_array =$this->statistics_plus->getOperateCount($day , $this->uid , $type , $app, $houseid);
        if(!empty($total_num_array))
        {
            $this->_total_count = $total_num_array[$this->uid];
        }
        else
        {
            $this->_total_count =0;
        }
        $this->_total_count = $total_num_array[$this->uid];

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

        $viewData['list'] = $this->statistics_plus->getOperateListByType( $day , $this->uid ,'' , $this->_offset, $this->_limit , 0 , $type, $houseid);

        //是否显示分页
        $pagination = NULL;
        if( $this->_total_count > $this->_limit)
        {
            $pagination = helper_pagination( $this->_current_page , $pages , $this->_total_count );
        }

        $curPage = 'log';
        $viewData['tab'] = $this->logTab($curPage);
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css');
        $viewData['js'] = load_js('common/js/My97DatePicker/WdatePicker.js');
        $viewData['page_title'] = '租售宝-统计分析-使用日志';
        $viewData['google_analytics'] = get_ga_js_code('/统计分析/使用日志/房源操作/');
        $viewData['page']  = $this->_current_page;
        $viewData['pagination'] = $pagination;
        $this->view('statics', 'statistics_analysis/log', $viewData);
    }

	
    
    /**
     * 标签使用
     */
    public function label() 
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $this->load->model('house_tag');
        $this->load->model('real_house_set_log');
        $viewData = array();
        
        //时间默认一周
		$stime = $this->input->post('stime', TRUE);
        if($stime === FALSE) 
		{
            $stime = date("Y-m-d",strtotime("-7days"));
        }
        $viewData['stime'] = $stime;

        $etime = $this->input->post('etime',TRUE);
        if($etime === FALSE) 
		{
            $etime = date("Y-m-d",strtotime("-1days"));
        }
        //TODO 测试中数据可以看今天
//        $etime = date("Y-m-d",time());
//        var_dump($etime);die;
        $viewData['etime'] = $etime;
        //房源编号
        $houseid = $this->input->post('houseid',TRUE);
        $viewData['houseid'] = $houseid;
        //类型
        //类型，默认急推
        $type = $this->input->post( 'type' , TRUE);
        if($type === FALSE)
        {
            $type = 2;
        }

        $types = array(1 => '放心看',2 => '急推');
        if( !in_array( $type , array_keys($types)) )
        {
            $type = 2;
        }

        $viewData['types'] = $types;
        $viewData['type'] = $type;
        $viewData['realhousereason'] = $this->config->item('realhouse_operation_status');
        $viewData['jituireason'] = $this->config->item('jitui_operation_status');

		/** 分页参数 */
		$page = $this->input->post('page' , TRUE);
        $page = (isset($page)&& intval($page) > 0) ? intval($page) : 1;
        $this->_init_pagination($page);

        if($type == 1){  //放心看
            $this->_total_count = $this->real_house_set_log->findCountByUidTime($this->uid, $stime, $etime,$houseid);
            $viewData['list'] = $this->_total_count ? $this->real_house_set_log->findByUidTime($this->uid, $stime, $etime, $this->_offset, $this->_limit,$houseid):array();
        }else{      //急推
            $this->_total_count = $this->house_tag->findCountByUidTime($this->uid, $stime, $etime,$houseid);
            $viewData['list'] = $this->_total_count ? $this->house_tag->findByUidTime($this->uid, $stime, $etime, $this->_offset, $this->_limit,$houseid):array();
        }

        $pages  = $this->_total_count > 0 ? ceil( $this->_total_count / $this->_limit ) : 0;

		//是否显示分页
        $pagination = NULL;
        if( $this->_total_count > $this->_limit)
        {
            $pagination = helper_pagination( $this->_current_page , $pages , $this->_total_count );
        }
        
        $curPage = 'label';
        $viewData['tab'] = $this->logTab($curPage);
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css');
        $viewData['js'] = load_js('common/js/My97DatePicker/WdatePicker.js');
        $viewData['page_title'] = '租售宝-统计分析-标签使用';
		$viewData['google_analytics'] = get_ga_js_code('/统计分析/使用日志/标签使用/');
		$viewData['page']  = $this->_current_page;
        $viewData['pagination'] = $pagination;
        $this->view('statics', 'statistics_analysis/label', $viewData);
    }

    /**
     * 登录历史
     */
    public function login_history()
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $viewData = array();

        //统计的日期，默认是昨天的日期
        $count_day = $this->input->post('count_day', TRUE); // 
        if($count_day === FALSE) {
            $yesterday  = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')));
            $count_day = $yesterday;
        }
        $viewData['count_day'] = $count_day;

        /** 分页参数 */
        $page = $this->input->post( 'page' , TRUE);
        $page = (isset($page)&& intval($page) > 0) ? intval($page) : 1;
        $this->_init_pagination($page);

        $day	= date('Ymd',strtotime($count_day));
        $total_count_array  =$this->statistics_plus->getLoginCount($day, $this->uid);
        if(!empty($total_count_array))
        {
            $this->_total_count = $total_count_array[$this->uid];
        }
        else
        {
            $this->_total_count = 0;
        }

        $viewData['list'] = $this->statistics_plus->getLoginList($day,$this->uid,'sell',$this->_offset, $this->_limit);

        $pages  = !empty($this->_total_count) ? ceil( $this->_total_count / $this->_limit ) : 0;

        //是否显示分页
        $pagination = NULL;
        if( $this->_total_count > $this->_limit)
        {
            $pagination = helper_pagination( $this->_current_page , $pages , $this->_total_count );
        }

        $curPage = 'login_history';
        $viewData['tab'] = $this->logTab($curPage);
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css');
        $viewData['js'] = load_js('common/js/My97DatePicker/WdatePicker.js');
        $viewData['page_title'] = '租售宝-统计分析-登录历史';
        $viewData['google_analytics'] = get_ga_js_code('/统计分析/使用日志/登录历史/');
        $viewData['page']  = $this->_current_page;
        $viewData['pagination'] = $pagination;
        $this->view('statics', 'statistics_analysis/login_history', $viewData);
    }
    
    /**
     * 违规记录
     */
    public function violation() 
    {
        $viewData = array();
        
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        //类型
        $type = $this->input->post('type',TRUE);
        if($type === FALSE) {
            $type = 'frozen';
        }
        $types = array('frozen'=>'房源违规','pic'=>'图片违规',);
        if(!in_array($type, array_keys($types))) {
            show_404();
        }
        $viewData['types'] = $types; 
        $viewData['type'] = $type;
        
        //时间默认一周
        $etime = $this->input->post('etime',TRUE);
        if($etime === FALSE) {
            $etime = date("Y-m-d",strtotime("-1days"));
        }
        $viewData['etime'] = $etime;

        $stime = $this->input->post('stime', TRUE);
        if($stime === FALSE) {
            $stime = date("Y-m-d",strtotime("-7days"));
        }
        $viewData['stime'] = $stime;
        
		/** 分页参数 */
		$page = $this->input->post( 'page' , TRUE);
        $page = (isset($page)&& intval($page) > 0) ? intval($page) : 1;
        $this->_init_pagination($page);
        $this->_total_count = $this->getVTotal($type,$stime, $etime);
        
        $viewData['list'] = $this->_total_count ? $this->getVList($type, $stime, $etime, $this->_offset, $this->_limit) : array();

		$pages  = $this->_total_count > 0 ? ceil( $this->_total_count / $this->_limit ) : 0;

		//是否显示分页
        $pagination = NULL;
        if( $this->_total_count > $this->_limit)
        {
            $pagination = helper_pagination( $this->_current_page , $pages , $this->_total_count );
        }
        
        $curPage = 'violation';
        $viewData['tab'] = $this->logTab($curPage);
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css');
        $viewData['js'] = load_js('common/js/My97DatePicker/WdatePicker.js');
        $viewData['page_title'] = '租售宝-统计分析-违规记录';
		$viewData['google_analytics'] = get_ga_js_code('/统计分析/使用日志/违规记录/');
		$viewData['page']  = $this->_current_page;
        $viewData['pagination'] = $pagination;
        $this->view('statics', 'statistics_analysis/violation', $viewData);
    }


    /**
     * 点击量统计
     */
    public function click()
    {
        $viewData = array();

        //统计的日期，默认是昨天的日期
        $yesterday  = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 1, date("Y")));

        $start_day = $this->input->post('start_day',TRUE);
        $end_day = $this->input->post('end_day',TRUE);

        $start_day  = !empty($start_day) ? $start_day : $yesterday;
        $end_day    = !empty($end_day) ? $end_day : $yesterday;

        //判断时间，是否需要交换起始日期
        $start_time = strtotime($start_day);
        $end_time   = strtotime($end_day);

        if($start_time > $end_time)
        {
            $temp_day   = $end_day;
            $end_day    = $start_day;
            $start_day  = $temp_day;
            //显示统计日期
            $viewData['day_show']   = $start_day .' 至 '. $end_day ;
        }
        else if($start_time == $end_time)
        {
            $viewData['day_show']   = $start_day ;
        }
        else
        {
            $viewData['day_show']   = $start_day .' 至 '. $end_day ;
        }

        //相差天数
        $diff_count = ($end_time - $start_time) / 86400 ;
        $i = 0;
        do{
            $countday_arr[$i] = date('Ymd',$start_time + (86400 * $i) );
            $countday_arr_Day[$i] = date('Y-m-d',$start_time + (86400 * $i) ) ;
            -- $diff_count;
            ++ $i;
        }while( $diff_count >= 0);

        //按天统计、按小时统计
        $countType  = $this->input->post('countType' , TRUE);
        $countType  = in_array($countType, array('Hour','Day')) ? $countType : 'Hour';

        //显示类型 all-全部、sell-二手房、rent-租房
        $showType  = $this->input->post('showType',TRUE);
        $showType   = in_array($showType,array('all','sell','rent')) ? $showType : 'all';

        //经纪人编号
        $uid = $this->user_arr['uid'];

        //加载统计类
        $this->load->library('statistics');

        //通过统计类获取总点击量
        $this->load->model('statistics_model');
        $click_info = $this->statistics_model->get_broker_clickdata($uid , $start_day , $end_day );

        if( $countType == 'Hour' )
        {
            //各时段房源点击量数据
            $arr_sell   = array();
            $arr_rent   = array();
            $sellClickBYHour    = array();
            $rentClickBYHour    = array();
            $houseClickBYHour	= array();

            if( $showType == 'all' )
            {
                //全部点击量累加
                if( is_array($countday_arr) && !empty($countday_arr) )
                {
                    //循环选中日期内的点击总数
                    foreach( $countday_arr as $key => $day )
                    {
                        $arr_sell[$day]   = $this->statistics->get_dayclickcount( $day, $uid , 'sell' );
                        $arr_rent[$day]   = $this->statistics->get_dayclickcount( $day, $uid , 'rent' );
                    }
                }
            }
            else if( $showType == 'sell' )
            {

                //二手房源点击量累加
                if(is_array($countday_arr) && !empty($countday_arr))
                {
                    //循环选中日期内的点击总数
                    foreach( $countday_arr as $key => $day )
                    {
                        $arr_sell[$day]   = $this->statistics->get_dayclickcount( $day, $uid , 'sell' );
                    }
                }
            }
            else if($showType == 'rent')
            {
                //出租房源点击量累加
                if(is_array($countday_arr) && !empty($countday_arr))
                {
                    //循环选中日期内的点击总数
                    foreach( $countday_arr as $key => $day )
                    {
                        $arr_rent[$day]   = $this->statistics->get_dayclickcount( $day, $uid , 'rent' );
                    }
                }
            }

            for ($i = 0 ; $i < 24 ; $i++)
            {
                //循环计算二手房各时段点击量之和
                if( $showType == 'all' || $showType == 'sell' )
                {
                    foreach($arr_sell as $key=>$value)
                    {

                        if(isset($sellClickBYHour[$i]))
                        {
                            $sellClickBYHour[$i]  += isset($value[$i]['count']) ? intval($value[$i]['count']) : 0;
                        }
                        else
                        {
                            $sellClickBYHour[$i]  = isset($value[$i]['count']) ? intval($value[$i]['count']) : 0;
                        }
                    }
                }

                //循环计算租房各时段点击量之和
                if( $showType == 'all' || $showType == 'rent' )
                {
                    foreach($arr_rent as $key=>$value)
                    {
                        if(isset($rentClickBYHour[$i]))
                        {
                            $rentClickBYHour[$i]  += isset($value[$i]['count']) ? intval($value[$i]['count']) : 0;
                        }
                        else
                        {
                            $rentClickBYHour[$i]  = isset($value[$i]['count']) ? intval($value[$i]['count']) : 0;
                        }
                    }
                }

                //各小时点击量总和
                if( $showType == 'all' )
                {
                    $houseClickByHour[$i]  = $sellClickBYHour[$i] + $rentClickBYHour[$i];
                }
                else if($showType == 'sell')
                {
                    $houseClickByHour[$i]  = $sellClickBYHour[$i];
                }
                else if($showType == 'rent')
                {
                    $houseClickByHour[$i]  = $rentClickBYHour[$i];
                }

                $xAxis[$i] = $i;
            }

            //准备显示数据
            $viewData['clickNum_json']  = json_encode($houseClickByHour);
            $viewData['xAxis_json'] = json_encode($xAxis);
            $viewData['unit']   = '时';
        }
        else if( $countType == 'Day' )
        {
            if(is_array($countday_arr_Day) && !empty($countday_arr_Day))
            {
                $click_info_day = array();
                if(is_array($click_info) && !empty($click_info))
                {
                    foreach( $click_info as $key=>$value)
                    {
                        $click_info_day[$value['stattime']]	= $value;
                    }
                }

                //循环选中日期内的点击总数
                $count_day_num = count($countday_arr_Day);
                for( $i = 0; $i <  $count_day_num ; $i++ )
                {
                    //X轴
                    $xAxis[$i]  = date( 'd',strtotime($countday_arr_Day[$i]));
                    $day_key    = $countday_arr_Day[$i];
                    //各小时点击量总和
                    if( $showType == 'all' )
                    {
                        $house_click[$i]    = isset($click_info_day[$day_key]['click_num']) ?
                            intval($click_info_day[$day_key]['click_num']) : 0;
                    }
                    else if($showType == 'sell')
                    {
                        $house_click[$i]    = isset($click_info_day[$day_key]['sell_click']) ?
                            intval($click_info_day[$day_key]['sell_click']) : 0;
                    }
                    else if($showType == 'rent')
                    {
                        if(isset($click_info_day[$day_key]['click_num']) && isset($click_info_day[$day_key]['sell_click']))
                        {
                            $house_click[$i]    =
                                intval($click_info_day[$day_key]['click_num']) - intval($click_info_day[$day_key]['sell_click']);
                        }
                        else if(isset($click_info_day[$day_key]['click_num']))
                        {
                            $house_click[$i]    = intval($click_info_day[$day_key]['click_num']);
                        }
                        else
                        {
                            $house_click[$i]    =  0;
                        }
                    }
                }
            }

            //准备显示数据
            $viewData['clickNum_json']  = json_encode($house_click);
            $viewData['xAxis_json'] = json_encode($xAxis);
            $viewData['unit']   = '日';
        }

        $viewData['showType']	= $showType;
        $viewData['countType']	= $countType;
        $viewData['start_day']	= $start_day;
        $viewData['end_day']	= $end_day;

        //计算点击总和
        $viewData['house_clickcount']	= 0;
        $viewData['house_starclick']	= 0;
        $viewData['sell_total_click']	= 0;
        if(is_array($click_info) && !empty($click_info))
        {
            foreach($click_info as $key => $value)
            {
                $viewData['house_clickcount']   += intval($value['click_num']);
                $viewData['house_starclick']    += intval($value['sell_star_click']) + intval($value['rent_star_click']);
                $viewData['sell_total_click']   += intval($value['sell_click']) ;
            }
        }

        $viewData['rent_total_click']   = intval($viewData['house_clickcount']) - intval($viewData['sell_total_click']) ;

        $viewData['css'] = load_css('zsb/css/v1.0/style1.css');
        $viewData['js'] = load_js('common/js/My97DatePicker/WdatePicker.js,common/js/Highcharts/js/highcharts.js');
        $viewData['page_title'] = '租售宝-统计分析-点击量统计';
        $viewData['google_analytics'] = get_ga_js_code('/统计分析/点击统计/');
        $this->view('statics', 'statistics_analysis/click', $viewData);
    }
    
    
    /**
     * 房源刷新
     */
    public function refresh() 
    {
        $viewData = array();

        //经纪人信息
        $uid  = intval( $this->user_arr['uid']);

        //经纪人门店账号
        $agentcode = strip_tags($this->user_arr['agentcode']);

        //显示类型 all-全部、sell-二手房、rent-租房
        $showType  = $this->input->post('showType',TRUE);
        $showType   = in_array($showType,array('all','sell','rent')) ? $showType : 'all';

        //统计的日期，默认是昨天的日期
        $count_day  = $this->input->post('count_day',TRUE);
        $count_day   = !empty ($count_day) ? $count_day : date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 1, date("Y")));

        //统计时间
        $day    = date('Ymd', strtotime($count_day));

        $refresh_info	= array();
        $app	= $showType != 'all' ? $showType : '' ;
        $kind	= 2;	//刷新

        //获得经纪人刷新记录
        $this->load->library('statistics_plus');
        $refresh_info = $this->statistics_plus->getOperateListByType($day,$uid,$app,0,0,0,$kind);

        //循环24小时各时段刷新总和
        $refreshu_sell = 0;
        $refreshu_rent = 0;
        $houseRefreshByHour   = array();

        //刷新数量
        $refresh_sell_array = $this->statistics_plus->getOperateCount($day,$uid,$kind,'sell');
        if(!empty($refresh_sell_array))
        {
            $refresh_sell       =$refresh_sell_array[$uid];
        }else
        {
            $refresh_sell       =0;
        }

        $refresh_rent_array = $this->statistics_plus->getOperateCount($day,$uid,$kind,'rent');
        if(!empty($refresh_rent_array))
        {
            $refresh_rent       =$refresh_rent_array[$uid];
        }
        else
        {
            $refresh_rent       =0;
        }

        //加载统计类
        $this->load->library('statistics');
        $agentinfo = array();
        $search = array();
        if($agentcode != '')
        {
            $this->load->model('agency_model');
            $agentinfo = $this->agency_model->get_company_info_by_code($agentcode);
            $search['streetid'] = $agentinfo['streetid'];
        }

        //循环显示各小时的刷新数量
        $search_data = array();

        $houseRefreshByHour = array();
        if(is_array($refresh_info) && !empty($refresh_info) )
        {
            foreach ($refresh_info as $key=>$value){
                $hour = $value['hour'];

                $houseRefreshByHour[$hour] = empty($houseRefreshByHour[$hour])? 1: ++$houseRefreshByHour[$hour];
            }
        }

        for ($i = 0 ; $i < 24 ;$i++)
        {
            $xAxis[$i] = $i;
            $houseRefreshByHour[$i] = empty($houseRefreshByHour[$i])? 0: $houseRefreshByHour[$i];
        }
        ksort($houseRefreshByHour);


        /*for ($i = 0 ; $i < 24 ;$i++)
        {
            $xAxis[$i] = $i;
            if(is_array($refresh_info) && !empty($refresh_info) )
            {
                foreach ($refresh_info as $key =>$value)
                {
                    if( $value['hour'] == $i )
                    {
                        $houseRefreshByHour[$i] = isset($houseRefreshByHour[$i]) ?
                            $houseRefreshByHour[$i] + 1 : 1;
                    }
                    else
                    {
                        $houseRefreshByHour[$i] = isset($houseRefreshByHour[$i]) ?
                            $houseRefreshByHour[$i] : 0;
                    }
                }
            }
            else
            {
                $houseRefreshByHour[$i] = 0;
            }


        }*/
        //网友搜索次数数组
        if($agentcode != '')
        {
            $search['hour'] = $i;

            if($showType == 'all')
            {
                $search_data_sell = $this->statistics->get_searchcount_bak($day,'sell',$search);

                $search_data_rent = $this->statistics->get_searchcount_bak($day,'rent',$search);

                for($i=0;$i<24;$i++) {
                    $search_data_sell[$i] = isset($search_data_sell[$i]) && $search_data_sell[$i] > 0 ? intval($search_data_sell[$i]) : 0;

                    $search_data_rent[$i] = isset($search_data_rent[$i]) && $search_data_rent[$i] > 0 ? intval($search_data_rent[$i]) : 0;

                    #########屏蔽凌晨0-6点的点击量  ---start----###############
                    //if (0) {
                    if ($i <= 6) {
                        if ($search_data_sell[$i] >= 100) {
                            $search_data_sell[$i] = 0;
                        }
                        if ($search_data_rent[$i] >= 50) {
                            $search_data_rent[$i] = 0;
                        }

                    }

                    #########屏蔽凌晨0-6点的点击量 ----end-------###############

                    $search_data[$i] = $search_data_sell[$i] + $search_data_rent[$i];

                }
            }
            else if($showType == 'sell')
            {
                for($i=0;$i<24;$i++) {
                    $search_data_sell = $this->statistics->get_searchcount_bak($day, 'sell', $search);
                    $search_data[$i] = isset($search_data_sell[$i]) && $search_data_sell[$i] > 0 ? intval($search_data_sell[$i]) : 0;

                    #########屏蔽凌晨0-6点的点击量  ---start----###############
                    if ($i <= 6) {
                        if ($search_data[$i] >= 100) {
                            $search_data[$i] = 0;
                        }
                    }
                }

                #########屏蔽凌晨0-6点的点击量 ----end-------###############
            }
            else if($showType == 'rent')
            {
                for($i=0;$i<24;$i++) {
                    $search_data_rent = $this->statistics->get_searchcount_bak($day, 'rent', $search);
                    $search_data[$i] = isset($search_data_rent[$i]) && $search_data_rent[$i] > 0 ? intval($search_data_rent[$i]) : 0;

                    #########屏蔽凌晨0-6点的点击量  ---start----###############
                    if ($i <= 6) {
                        if ($search_data[$i] >= 50) {
                            $search_data[$i] = 0;
                        }
                    }
                }

                #########屏蔽凌晨0-6点的点击量 ----end-------###############
            }
        }
        $viewData['count_day'] = $count_day;
        $viewData['showType'] = $showType;
        $viewData['refresh_sell']  = $refresh_sell;
        $viewData['refresh_rent']  = $refresh_rent;
        $viewData['refresh_total']  = $refresh_sell + $refresh_rent;
        $viewData['RefreshNum_json']    = json_encode($houseRefreshByHour);
        $viewData['SearchNum_json']    = json_encode($search_data);
        $viewData['xAxis_json'] = json_encode($xAxis);

        $viewData['css'] = load_css('zsb/css/v1.0/style1.css');
        $viewData['js'] = load_js('common/js/My97DatePicker/WdatePicker.js,common/js/Highcharts/js/highcharts.js');
        $viewData['page_title'] = '租售宝-统计分析-刷新量统计';
        $viewData['google_analytics'] = get_ga_js_code('/统计分析/刷新量统计/');
        $this->view('statics', 'statistics_analysis/refresh', $viewData);
    }
    
    
    /**
     * 使用概况标签页
     * @param type $curPage
     * @return type
     */
    private function overViewTab($curPage) {
        $tabData = array();
        $tabData['today'] = array('url'=>'/statistics_analysis/today/','name'=>'今日概况');
        $tabData['history'] = array('url'=>'/statistics_analysis/history/','name'=>'历史概况');
        return $this->tabpage->generate($tabData,$curPage);
    }
    
    /**
     * 使用日志标签页
     * @param type $curPage
     * @return type
     */
    private function logTab($curPage) {
        $tabData = array();
        $tabData['log'] = array('url'=>'/statistics_analysis/log/','name'=>'房源操作');
		if(GB_CITY=='nj'){
           $tabData['label'] = array('url'=>'/statistics_analysis/label/','name'=>'标签使用');
		}
        $tabData['login_history'] = array('url'=>'/statistics_analysis/login_history/','name'=>'登录历史');
        $tabData['violation'] = array('url'=>'/statistics_analysis/violation/','name'=>'违规记录');
		$tabData['reserve_refresh_log'] = array('url'=>'/statistics_analysis/reserve_refresh_log/','name'=>'预约刷新');
        //array('statistics_analysis/log','statistics_analysis/label','statistics_analysis/login_history','statistics_analysis/violation')
        return $this->tabpage->generate($tabData,$curPage);
    }
    
    public function etime_check($etime,$stime) {
        $time = strtotime($etime);
        if(!$time) {
            $this->form_validation->set_message('etime_check', '%s 格式错误！');
            return FALSE;
        }
        if($time < strtotime($stime)) {
            $this->form_validation->set_message('etime_check', '%s 不能在开始时间之前！');
            return FALSE;
        }
        /*
        $int = $time - strtotime($stime);
        if($int/(3600*24)>7) {
            $this->form_validation->set_message('etime_check', '最多一周');
            return FALSE;
        }*/
        return TRUE;
    }
    
    public function stime_check($stime,$etime) {
        $time = strtotime($etime);
        if(!$time) {
            $this->form_validation->set_message('stime_check', '%s 格式错误！');
            return FALSE;
        }
        if($time > strtotime($etime)) {
            $this->form_validation->set_message('stime_check', '%s 不能在开始时间之后！');
            return FALSE;
        }

        return TRUE;
    }
    
    /**
     * 违规总数
     * @param type $type
     * @param type $stime
     * @param type $etime
     */
    private function getVTotal($type,$stime,$etime)  
	{
        if($type=='frozen') {
            $this->load->model("house_frozen");
            $total = $this->house_frozen->findCountByUidTime($this->uid,$stime,$etime);
        } 
		else if ($type=='pic') 
		{
            $this->load->model("upload_log");
            $total = $this->upload_log->findCountByUidTime($this->uid,$stime,$etime);
        }

        return $total;
    }
    

    /**
     * 违规记录
     * @param type $type
     * @param type $stime
     * @param type $etime
     * @param type $start
     * @param type $number
     * @return int
     */
    private function getVList($type,$stime,$etime,$start,$number)  
	{
        if($type=='frozen') 
		{
            $this->load->model("house_frozen");
            $list = $this->house_frozen->findByUidTime($this->uid,$stime,$etime,$start,$number);
        } 
		elseif ($type=='pic') 
		{
            $this->load->model("upload_log");
            $list = $this->upload_log->findByUidTime($this->uid,$stime,$etime,$start,$number);
        }

        return $list;
    }


	    /**
     * 违规记录
     */
    public function reserve_refresh_log() 
    {
        $viewData = array();
        
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        //类型
        $tbl = $this->input->post('tbl',TRUE);
		$rowid = $this->input->post('rowid',TRUE);
        if($tbl === FALSE) {
            $tbl = '1';
        }
		
        $tbls = array('1'=>'出售','2'=>'出租');
		$viewData['typeArr'] = array('1'=>'设置','2'=>'更新','3'=>'取消');
        if(!in_array($tbl, array_keys($tbls))) {
            show_404();
        }
        $viewData['tbls'] = $tbls; 
        $viewData['tbl'] = intval($tbl);
        $viewData['rowid'] = $rowid;
        //时间默认一周
        $etime = $this->input->post('etime',TRUE);
        if($etime === FALSE) {
            $etime = date("Y-m-d");
        }
        $viewData['etime'] = $etime;

        $stime = $this->input->post('stime', TRUE);
        if($stime === FALSE) {
            $stime = date("Y-m-d",strtotime("-7days"));
        }
        $viewData['stime'] = $stime;
        
		/** 分页参数 */
		$page = $this->input->post( 'page' , TRUE);
        $page = (isset($page)&& intval($page) > 0) ? intval($page) : 1;
        $this->_init_pagination($page);
        $this->_total_count = $this->reserve_model->count_reserve_refresh_log($this->uid, $tbl, $rowid, $stime, $etime);
        
        $viewData['list'] = $this->_total_count ? $this->reserve_model->get_reserve_refresh_log($this->uid, $tbl, $rowid, $stime, $etime, $this->_offset, $this->_limit) : array();
		
		$pages  = $this->_total_count > 0 ? ceil( $this->_total_count / $this->_limit ) : 0;

		//是否显示分页
        $pagination = NULL;
        if( $this->_total_count > $this->_limit)
        {
            $pagination = helper_pagination( $this->_current_page , $pages , $this->_total_count );
        }
        $curPage = 'reserve_refresh_log';
        $viewData['tab'] = $this->logTab($curPage);
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css');
        $viewData['js'] = load_js('common/js/My97DatePicker/WdatePicker.js');
        $viewData['page_title'] = '租售宝-统计分析-预约刷新';
		$viewData['google_analytics'] = get_ga_js_code('/统计分析/使用日志/预约刷新/');
		$viewData['page']  = $this->_current_page;
        $viewData['pagination'] = $pagination;
        $this->view('statics', 'statistics_analysis/reserve_refresh_log', $viewData);
    }
}
?>