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

/**
 * Rent Class
 *
 * 租售宝租房管理模块
 *
 * @package     zsb
 * @subpackage      Controllers
 * @category        Controllers
 * @author      liuhu
 */
class Rent_xiao extends MY_Controller {
    
    /**
    * 城市参数
    *
    * @access private
    * @var string
    */
    protected  $_city = GB_CITY;
    
    /**
     * 房源模板模块
     * @var type 
     */
    private $_house_template_module = 'rent';

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

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

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

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

    /**
    * 条目总数
    *
    * @access private
    * @var int
    */
    private $_total_count = 0;
    
    
    /**
    * 解析函数
    *
    * @access public
    * @return void
    */
    public function __construct()
    {     
        parent::__construct();
        //加载房源模型类
        $this->load->model('rent_model');
        $this->load->helper('common_house_helper');
        //可发出售和出租的权限 @todo
        $is_permission = $this->rent_model->get_public_permission($this->user_arr['package_id']);
		//增加判断开通时间是否小于等于当前时间，是则可发，否则不可发布
		$this->load->model('broker_model');
		$info_extra = $this->broker_model->get_broker_detail($this->user_arr['uid']);
		//print_r($info_extra);die;
		if(time()-strtotime($info_extra['usetime'])<0){
			//$use_access	= true;
			$is_permission = false;
			//var_dump($is_permission);die;
		}

        if ($is_permission === false && (GB_CITY=='nj' && GB_CITY=='hf')) 
        {
            $this->jump(GB_WO_URL);
            exit;
        }
    }
    
    
    /**
    * 初始化分页参数
    *
    * @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());
        }
    }
    
    /**
     * 渲染房源信息
     * @param type $data_page
     */
    private function render_publish($data_page = array())
    {   
        //页面加载需要的数据
        $data_page['page_js'] = load_js('common/js/swf/swfupload.js,'
                . 'zsb/js/v1.0/uploadpic.js,common/js/jquery.validate.min.js,'
                . 'common/js/jquery_ui_autocomplete/ui/jquery.ui.core.js,'
                . 'common/js/jquery_ui_autocomplete/ui/jquery.ui.position.js,'
                . 'common/js/jquery_ui_autocomplete/ui/jquery.ui.widget.js,'
                . 'common/js/jquery_ui_autocomplete/ui/jquery.ui.autocomplete.js,'
                . 'common/js/jquery.ui.mouse.min.js,'
                . 'common/js/jquery.ui.sortable.min.js,'
                . 'zsb/js/v1.0/house_xiao.js,'
				. 'zsb/js/v1.0/jquery.jsonp.js,zsb/js/v1.0/wechatUploadImage.js');

        $data_page['css'] = load_css('zsb/css/v1.0/style1.css,zsb/css/v1.0/autocomlete_xiao.css');
        $data_page['house'] = $this->config->item('house');

		// 2016-1-15 添加星级数据 -----------start -------->
		$uid = $this->user_arr['uid'];
		$data_page['house']['broker_new_info'] =$this->broker_model->get_broker_info_by_uid($uid);
		
		// 2016-1-15 添加星级数据 -----------end -------->

        $data_page['upload_pic_url'] = $this->config->item('base_url') . 'pic/house/';

		//微信类
		$this->load->model('wechat_model');
		
		//微信上传室内图
		$data_page['wechatDoorinData'] = $this->wechat_model->get_wechat_info($this->_city);
		
		//微信上传室外图
		$data_page['wechatDooroutData'] = $this->wechat_model->get_wechat_info($this->_city);

		//微信上传户型图
		$data_page['wechatLayoutData'] = $this->wechat_model->get_wechat_info($this->_city);

        $this->view('house_manage', 'rent_modify_xiao', $data_page);
    }
    
    /**
     * 默认首页
     */
    public function index()
    {
        $this->manage();
    }
    
    /**
     * 发布房源页面
     */
    public function add() 
    { 
        $uid = $this->user_arr['uid'];
        $package_id = $this->user_arr['package_id'];
        //可发出售和出租的权限 加到__construct
        //判断库存是否已满 房源列表页地址，用于跳转的
        $url_manage = $this->rent_model->find_func_url();
        $this->load->model('broker_model');
        $this->load->model('package_model');
        $package = $this->package_model->find_by_id($package_id);
        //判断库存量和套餐库存量
        $stock_house_num = $this->broker_model->stock_house_num();
        if ($stock_house_num >= $package["package_stock_num"])
        {
            $this->jump($url_manage, "对不起,已超过帐号房源库存量上限("
                    . "上限{$package['package_stock_num']},已用$stock_house_num) 
                        请到您的房源管理里删除过期房源!");
            return;
        }
        $data_page = array();
        //读取房源模板信息
        $template_module = $this->_house_template_module;
        $this->load->model('house_template_model');
        //房源模板数量
        $data_page['template_num'] = $this->house_template_model->
                find_count_by_module($template_module, $uid);
        //模板数 > 0 跳转列表，否则跳转添加页
        if ($data_page['template_num'] > 0)
        {
            //还可保存多少套模板
            $data_page['remain_num'] = $this->house_template_model->template_num 
                    - $data_page['template_num'];
            //模板列表
            $data_page['template_list'] = $this->house_template_model->
                    find_by_module($template_module, $uid);
            $data_page['url_template_manage'] = $this->house_template_model->
                    find_func_url('manage') . $template_module . '/';
        }
        else
        {
            //添加模板
            $data_page['url_template_manage'] = $this->house_template_model->
                    find_func_url('add') . $template_module . '/';
        }
        $data_page['url_template_add'] = $this->house_template_model->
                 find_func_url('add') . $template_module . '/'; 
        //获取发布过房源历史小区信息
        $this->rent_model->set_select_fields(array('blockid', 'blockshowname'));
        $data_page['publish_block'] = $this->rent_model->find_publish_block($uid);
        //发布多图和普通房源添加成长值的分值
        $gcep = new GrowthExpWayPackage();
        $starScore = $gcep->findScoreByWayAliasAndPackageId('pStarHouse', $package_id);
        $noStarScore = $gcep->findScoreByWayAliasAndPackageId('pNoStarHouse', $package_id);
        $data_page['star_score'] = $starScore;
        $data_page['no_star_score'] = $noStarScore;
        //允许发布的房源类型
        $data_page['allow_publish_infotype'] = $this->rent_model->
                get_public_infotype_permission($package_id);
        //当天发布共获得多少成长值
        $growthExpDayCount = new GrowthExpDayCount();
        $publishEventArray = array('pQualityHouse','pStarHouse','pNoStarHouse');
        $exp_rank_day = $growthExpDayCount->getExpAndRank($uid, $publishEventArray);
        $data_page['growthDaySum'] = $exp_rank_day['exp'];
        //当前用的排序名次百分比
        $data_page['rankRate'] = $exp_rank_day['rate'];
        //页面基本参数
        $data_page['method'] = 'add';
        $data_page['url_house_submit'] = $this->rent_model->find_func_url('insert');
        //测试地址-xiao
        $data_page['url_house_submit'] = '/rent_xiao/insert/';
        //帮助文档
        $data_page['documentation'] = $this->config->item('documentation');
        //统计代码
        $data_page['page_title'] = '房源管理-发布出租';
		$data_page['google_analytics'] = get_ga_js_code('/房源管理/发布出租/');
		//提交验证随机码
		$data_page['post_rand'] = $this->broker_model->get_rand_post();

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


        //加载模板
        $this->render_publish($data_page);
    }
    
    /**
     * 插入房源数据 model
     */
    public function insert() 
    {      
        //一、获取经纪人UID
		$this->load->model('broker_model');
		$session_info = $this->broker_model->get_user_session();	
        $uid = $this->user_arr['uid'];
        $package_id = $this->user_arr['package_id'];
        $companycode = $this->user_arr['agentcode'];
        $tbl = $this->rent_model->get_tbl();
        $nowtime = time();
        //二、发布出租权限
        //房源列表页地址，用于跳转的
        $url_manage = $this->rent_model->find_func_url();
        //控制发布房源的时间限制
        $session_key = $uid . '_last_rent_add_time';
        $session_value = $this->session->userdata($session_key);
        if ($session_value > 0 && $nowtime - $session_value <= 5) {
            $this->session->set_userdata(array($session_key => $nowtime));
            $this->jump($url_manage, "服务器正忙，请稍后再试");
            return;
        } else {
            $this->session->set_userdata(array($session_key => $nowtime));
        }
        $this->load->model('broker_model');
        $this->load->model('package_model');
        $package = $this->package_model->find_by_id($package_id);

        //防止模拟提交房源数据 xue 2015-06-16
        //提交验证随机码
		$post_rand = $this->broker_model->get_rand_post();
        $post_value = $this->input->post($post_rand['post_key'], true);
        if($post_rand['post_value']!=$post_value){
		//    echo "<script>alert('参数错误！');history.go(-1);</script>";
             //   exit;		
		}

        //四、判断源活房源是否有否超过上限
        $valid_house_num = $this->broker_model->valid_house_num();
        $esta = $valid_house_num >= $package["package_valid_num"] ? 2 : 1;
        if ($esta == 1) //激活房源判断是否刷新超过上限
        {
            $this->load->model('log_refresh');
            $total_refresh_num = $this->log_refresh->findTodayNumberByBrokerId($uid);
            $esta = $total_refresh_num >= $package["package_refresh_num"] ? 2 : 1;
        }
        if ($esta == 2) //失效房源判断库存量和套餐库存量
        {
            $stock_house_num = $this->broker_model->stock_house_num();
            if ($stock_house_num >= $package["package_stock_num"])
            {
                $this->jump($url_manage, "对不起,已超过帐号房源库存量上限("
                        . "上限{$package['package_stock_num']},已用$stock_house_num) 
                            请到您的房源管理里删除过期房源!");
                return;
            }
        }
        //五、插入房源信息
        //经纪人发布房源的默认agentcode
        $agentcode = 'B000';
        $this->load->helper('common_string_helper');
        //房源参数
        $fields_values = array();
        /* 前台客户端已验证小区文本框填写的内容是否有效小区，这里根据输入框的值，
        * 来获取小区相关信息，而不是通过post方式提交
        */
        $blockshowname = trim($this->input->post('blockshowname', true));
        if($blockshowname != '')
        {
            $this->load->model('block_model');
            $this->block_model->set_select_fields(array('id','blockname','district','streetid'));
            $block = $this->block_model->find_by_blockname($blockshowname);

            if( !empty($block)) {
                $blockid = $block['id'];
                $district = $block['district'];
                $streetid = $block['streetid'];
                $blockshowname = $block['blockname'];
            }else{
                echo "<script>alert('小区不存在，请重新输入小区名称或添加新小区后在小区列表中选择！');history.go(-1);</script>";
                exit;
            }
        }
        else
        {
            echo "<script>alert('请填写小区！');history.go(-1);</script>";
            exit;
        }
        /*******************基本信息开始***************************/
        $fields_values['infotype'] = intval($this->input->post('infotype', true));
        $fields_values['agentcode'] = $agentcode;
        $fields_values['infofrom'] = get_infofrom_by_agentocde($agentcode);
        $fields_values['uid'] = $uid;
        $fields_values['esta'] = $esta;
        $fields_values['district'] = str_replace('"','',$district);
        $fields_values['streetid'] = $streetid;
        $fields_values['blockid'] = $blockid;
        $fields_values['blockshowname'] = csubstr($this->input->post('blockshowname', true), 20);
        $fields_values['price'] = $this->input->post('price', true);
        $fields_values['priceunit'] = $this->input->post('priceunit', true);
        $fields_values['renttype'] = $this->input->post('renttype', true);
        if ($fields_values['renttype'] == '合租')
        {
            $fields_values['rentremark'] = $this->input->post('rentremark', true);
            $fields_values['rentroom'] = $this->input->post('rentroom', true);
        } 
        $fields_values['payment'] = $this->input->post('payment', true);
        $fields_values['buildarea'] = $this->input->post('buildarea', true);
        //只有物业类型 住宅 别墅 有室、厅等参数
        if ($fields_values['infotype'] == 1 || $fields_values['infotype'] == 2) 
        {
            $fields_values['room'] = $this->input->post('room', true);
            $fields_values['hall'] = $this->input->post('hall', true);
            $fields_values['toilet'] = $this->input->post('toilet', true);
            $fields_values['kitchen'] = $this->input->post('kitchen', true);
            $fields_values['balcony'] = $this->input->post('balcony', true);
        }       
        else
        {
            //其它类型强制设为0
            $fields_values['room'] = '';
            $fields_values['hall'] = '';
            $fields_values['toilet'] = '';
            $fields_values['kitchen'] = '';
            $fields_values['balcony'] = '';
        }
        //物业类型为车库车位没有楼层
        if ($fields_values['infotype'] == 6)
        {
            $fields_values['subfloor'] = '';
            $fields_values['floor'] = '';
            $fields_values['totalfloor'] = '';
            $fields_values['fitment'] = '';
            $fields_values['forward'] = '';
        }
        else
        {
            //楼层判断
            $lctype = $this->input->post('lctype', true);
            if ($lctype == 1) //单层
            { 
                $floor = $this->input->post('floor', true);
                $totalfloor = $this->input->post('totalfloor', true);
                if ($floor > $totalfloor) 
                {
                    //跳转页面
                    echo "<script>alert('总楼层不能小于当前楼层!');history.go(-1);</script>";
                    return;
                }
                $fields_values['subfloor'] = 0;
                $fields_values['floor'] = $floor;
                $fields_values['totalfloor'] = $totalfloor;
            }   
            if ($lctype == 2) //跃层
            { 
                $subfloor = $this->input->post('subfloor', true);
                $floor2 = $this->input->post('floor2', true);
                $totalfloor2 = $this->input->post('totalfloor2', true);
                if ($subfloor > $totalfloor2 || $floor2 > $totalfloor2) 
                {
                    echo "<script>alert('总楼层不能小于当前楼层!');history.go(-1);</script>";
                    return;
                }
                $fields_values['subfloor'] = $subfloor;
                $fields_values['floor'] = $floor2;
                $fields_values['totalfloor'] = $totalfloor2;
            }
            $fields_values['fitment'] = $this->input->post('fitment', true);
            $fields_values['forward'] = $this->input->post('forward', true);
        }
        $fields_values['contactor'] = $this->user_arr['truename'];
        $fields_values['telno'] = $session_info['telno'];
        $fields_values['creattime'] = time();
        if ($fields_values['infotype'] == 1)
        {
			if(GB_CITY=='nj')
			{
				$fields_values['expiretime'] = strtotime("+30 days");
			}
			else
			{
				$fields_values['expiretime'] = strtotime("+45 days");
			}
        }
        else
        {
			if(GB_CITY=='nj')
			{
				$fields_values['expiretime'] = strtotime("+90 days");
			}
			else
			{
				$fields_values['expiretime'] = strtotime("+60 days");
			}
        }
		if(GB_CITY=='wh')
		{
			$fields_values['expiretime'] = strtotime("+30 days");
		}
        $fields_values['updatetime'] = time();
        $fields_values['lucupdatetime'] = $fields_values['updatetime'];
        $fields_values['ip'] = get_ip();
        /*******************基本信息结束***************************/
        
        //暂时记录日志
		$msg = date('y-m-d H:i:s')."::".print_r($_POST,true)." \n";
		$log = './applications/zsb/logs/rent'."_".date('y-m-d');
		file_put_contents($log,$msg,FILE_APPEND );

        /*******************补充信息开始***************************/
        $housekind = $this->input->post('housekind', true);
        if (isset($housekind) && $housekind != '')
        {
            //物业类型 厂房车库代表车位属性
            //物业类型 物业类型代表别墅类型
            $fields_values['housekind'] = $housekind;
        }
        //商业分类
        $tradeclass = $this->input->post('tradeclass', true);
        if (isset($tradeclass) && $tradeclass != '')
        {
            $fields_values['tradeclass'] = $tradeclass;
        }
        //物业费
        $fee = $this->input->post('fee', true);
        if (isset($fee) && $fee != '')
        {
            $fields_values['strata_fee'] = $fee;
        }
        //房屋设备
        $equipment = $this->input->post('equipment', true);
        if ($equipment)
        {
            $fields_values['equipment'] = implode(",", $equipment);
        }
        $fields_values['ownid'] = trim($this->input->post('ownid', true));
        /*******************补充信息结束***************************/
        
        /*******************详细信息开始***************************/
        $fields_values['address'] = htmlspecialchars(csubstr(trim(
                filterSpace($this->input->post('address', true))),60));
		
		//敏感词过滤
		if(!empty($fields_values['address']))
		{
			$this->load->model('ajax_model');
			$sensitive_word = $this->ajax_model->check_sensitive_word($fields_values['address']);
			
			if(!empty($sensitive_word))
			{
				echo "<script>alert('含有敏感词：".$fields_values['address']."');history.go(-1);</script>";
                return;
			}
		}

        //$fields_values['remark'] = $this->input->post('remark');
		$fields_values['remark'] = check_word($this->input->post('remark'),STATIC_BADWORD_URL);

       /*******************详细信息结束***************************/
        //插入房源信息，并返回房源编号
        $house_id = $this->rent_model->insert($fields_values);
        if ($house_id)
        {
            //房源封面图
            $pic1 = $this->input->post('pic1', true);
            if($pic1 == '')
            {
                $pic1 = '';
            }
            else
            {
                $pic1 = preg_match("#\?#", $pic1) ? substr($pic1, 0, strpos($pic1, '?')) : $pic1;
            }
            //四、处理房源图片
            $this->load->model('admin_check');
            $pics = array();
            $pfile_name = $this->input->post('p_filename', true);
            if (isset($pfile_name) && $pfile_name != '') 
            {
                $pics = array(
                    'p_filename' => $pfile_name,
                    'p_sort' => $this->input->post('p_sort', true),
                    'p_title' => $this->input->post('p_title', true),
                    'infotype' => $fields_values['infotype']
                );
            }

            //判断有无外景图 1为经纪人上传图片 10为图库图片
            if(!in_array(1,$pics['p_sort']) && !in_array(10,$pics['p_sort']))
            {
                //获取小区外景图
                $this->load->model('block_xiao_model');
                $imageUrl = $this->block_xiao_model->getBlockImg($blockid);
                if($imageUrl)
                {
                    $pics['p_filename'][] = $imageUrl.'?pid=123170';
                    $pics['p_sort'][] = 10;
                    $pics['p_title'][] = '系统默认外景图';
                    $pics['infotype'] = $fields_values['infotype'];
                }
            }

            if (!empty($pics) && is_array($pics)) 
            {
                $pic_check = $this->rent_model->insert_house_pic($pics,
                $tbl, $house_id, $pic1, $blockid);
                $pic_check_arr = $pic_check['pic_check'];
                //更新封面图
                $this->rent_model->update(array('pic1' => $pic_check['indexpic']), $house_id);
                //审核图片入库
                
                if(isset($pic_check_arr) && is_array($pic_check_arr) 
                        && !empty($pic_check_arr) && $uid > 0)
                {
                    foreach($pic_check_arr as $key => $val)
                    {
                        $infotype = $fields_values['infotype'];
                        $fitment = $fields_values['fitment'];
                        $pic_check_arr[$key]['uid'] = $uid;
                        $pic_check_arr[$key]['housetbl'] = $tbl;
                        $pic_check_arr[$key]['houseid'] = $house_id;
                        $pic_check_arr[$key]['fitment'] = $fitment == "简装" ? 2 : ($fitment == "毛坯" ? 3 : 1);
                        $pic_check_arr[$key]['infotype'] = $infotype == 3 ? 4 : ($infotype == 4 ? 3 : $infotype);//商铺、写字楼互换
                        $pic_check_arr[$key]['dateline'] = $nowtime;
                        //进入审核附属表待夜间JOB过滤入库
                        $this->admin_check->insert_check_pic_sub($pic_check_arr[$key]);
                        //来自设备的图片只入待审核库、不入审核库
                        if($pic_check_arr[$key]['surface'] == 0 && $pic_check_arr[$key]['from_device'] == 1)
                        {
                            unset($pic_check_arr[$key]);
                        }
                        unset($pic_check_arr[$key]['from_device']);
                        //封面图入审核表
                        if($pic_check_arr[$key]['surface'] == 1)
                        {
                            $this->admin_check->insert_check_pic($pic_check_arr[$key]);
                        }
                    }
                }
            }
            //审核房源描述
            /***
            $remark = $fields_values['remark'];
            $check_remark = preg_replace("/[\s*\t\n\r&nbsp;]/", "", strip_tags($remark));
            if($check_remark != '')
            {
                $remark_check_arr['uid'] = $uid;
                $remark_check_arr['housetbl'] = $tbl;
                $remark_check_arr['houseid'] = $house_id;
                $remark_check_arr['blockname'] = $blockshowname;
                $remark_check_arr['remark'] = $check_remark;
                $remark_check_arr['dateline'] = $nowtime;
                $remark_check_arr['file_md5'] = md5($check_remark);
                $this->admin_check->insert_check_remark_sub($remark_check_arr);
            }***/
            /**
             * 对房成长值的操作
             * 每天成长值的上限；成长值操作房源条数的上限
             */
            /***
            $startTime = strtotime(date('Y-m-d',time()));//当天零点时间戳
            $growthHouseLog = new GrowthHouseLog();
            $publishHouseNum = $growthHouseLog->findCountBy($uid, $startTime);
            $expControllPackage = new GrowthExpControllPackage();                 
            $upperLimitNum = $expControllPackage->findScoreByWayAliasPackageId(
               'dayHouseNum', $package_id);
            $upperFlag = $publishHouseNum < $upperLimitNum ? 1 : 0;**/
            $gbe  = new GrowthBrokerExp(array('id' => $uid, 'groupid' => $package_id));			
            $gewp = new GrowthExpWayPackage();
            $ghl  = new GrowthHouseLog();
            //判断优质，多图 先有多图再有优质
            $fields_values['id'] = $house_id;
            $this->load->model('rent_star_model');
            $this->rent_star_model->set_houseinfo($fields_values);
            //$this->sell_star_model->set_rowid($house_id);
            $is_star_house = $this->rent_star_model->check_star_standard();
            //日志记录房源状态
            $logesta = $fields_values['esta'];
            if ($is_star_house)
            {
                $exp = $gewp->findScoreByWayAliasAndPackageId('pStarHouse', $package_id);					 
                $inExpStatus = $gbe->increase('pStarHouse','发布多图房源',$exp);
                $ghl->insertHouseGradeLog($house_id, $tbl, 2, $uid);
                $logesta = $fields_values['esta'] == 1 ? 5 : 6;
                //设置房源属性为多图@todo
                $this->rent_star_model->set_star();
            } 
            else 
            {
                //普通房源
                $exp = $gewp->findScoreByWayAliasAndPackageId('pNoStarHouse', $package_id);					 
                $inExpStatus = $gbe->increase('pNoStarHouse','发布非多图房源',$exp); 
                $ghl->insertHouseGradeLog($house_id, $tbl, 1, $uid);
            }
            $growthMessage = '';
            if($inExpStatus['status'] == 2 ){
                $growthMessage = "您今天的成长值已达峰值！";
            } elseif($inExpStatus['status'] == 1){
                $growthMessage = "成长值+" . $exp;
            }
            //记录用户行为
            $this->rent_model->action_log($companycode, $uid, $tbl, $house_id, $logesta);
            if ($fields_values['esta'] == 1) {
                //刷新房源
				if(GB_CITY == 'nj')
				{
					refresh_house($uid, $tbl, $house_id);
				}
                $this->rent_model->action_log($companycode, $uid, $tbl, $house_id, 7);
            }
            //中间件数据提交接口
            $this->load->library('statistics');

            //加载门店类
            $this->load->model('agency_model');
            $relation_info = array();
            $relation_info = $this->agency_model->get_relation_by_agentcode($companycode);
            $domain = isset($relation_info['cat_id']) ? $relation_info['cat_id'] : 0;
            $parentcode = '';
            if( is_array($relation_info) && !empty($relation_info))
            {	 
                $parentcode = isset($relation_info['parentcode']) ? $relation_info['parentcode'] : '';
            }
            else
            {	
                $parentinfo = array();
                $select_array = array('parentcode');
                $this->agency_model->set_select_fields($select_array);
                $parentinfo = $this->agency_model->get_company_info_by_code($companycode);
                $parentcode = isset($parentinfo['parentcode']) ? $parentinfo['parentcode'] : '';
            }
            $this->statistics->sub_operatecount($uid,$companycode,1,$house_id,
                    '', $tbl, $domain, $parentcode);
            //$page_text = "房源发布成功!" . $growthMessage;
            $page_text = "房源发布成功!" ;
        }
        else
        {
            $page_text = "抱歉，房源发布失败!";
        }
        $this->jump($this->rent_model->find_func_url(), $page_text, 3000);
    }
    
    /**
     * 展示房源修改页面
     */
    public function modify($id, $tab = '') 
    {
        $uid = $this->user_arr['uid'];
        $package_id = $this->user_arr['package_id'];
        $tbl = $this->rent_model->get_tbl();
        //房源列表页地址
        $url_manage_module = $this->rent_model->find_func_url();
        if (!$id)
        {
            $this->jump($url_manage_module, '参数不合法');
            return;
        }
		
        //查找有无此房源记录，没有则转到列表页
        $house_detail = $this->rent_model->find_by_uid_id($uid, $id);
        if (!$house_detail)
        {
            $this->jump($url_manage_module, '没有发现您查询的记录');
            return;
        }
        $data_page = array();
        $this->load->model('block_model');
        //查找房源的板块名称、查找房源的小区地址

        $block = $this->block_model->base_info_by_id($house_detail['blockid']);
        if ($block)
        {
            $house_detail['streetname'] = $block['streetname'];
            $house_detail['blockaddress'] = $block['address'];
        }

        //房源图片
        $this->load->model('pic_model');

        //室内图 2
        $house_detail['house_pic2'] = $this->pic_model->find_house_pic_by($tbl, $id, 2);

        //外景图 1
        $house_detail['house_pic1'] = $this->pic_model->find_house_pic_by($tbl, $id, 1);
        //户型图 0
        $house_detail['house_pic0'] = $this->pic_model->find_house_pic_by($tbl, $id, 0);
        $data_page['house_detail'] = $house_detail;
        //房源模板
        $this->load->model('house_template_model');
        $data_page['url_template_add'] = $this->house_template_model->
                 find_func_url('add') . $this->_house_template_module . '/';

        //发布多图和普通房源添加成长值的分值
        $gcep = new GrowthExpWayPackage();
        $starScore = $gcep->findScoreByWayAliasAndPackageId('pStarHouse', $package_id);
        $noStarScore = $gcep->findScoreByWayAliasAndPackageId('pNoStarHouse', $package_id);
        $data_page['star_score'] = $starScore;
        $data_page['no_star_score'] = $noStarScore;
        //当天发布共获得多少成长值
        $growthExpDayCount = new GrowthExpDayCount();
        $publishEventArray = array('pQualityHouse','pStarHouse','pNoStarHouse');
        $exp_rank_day = $growthExpDayCount->getExpAndRank($uid, $publishEventArray);
        $data_page['growthDaySum'] = $exp_rank_day['exp'];
        //当前用的排序名次百分比
        $data_page['rankRate'] = $exp_rank_day['rate'];
       
        //允许发布的房源类型
        $data_page['allow_publish_infotype'] = $this->rent_model->
                get_public_infotype_permission($package_id);
        //帮助文档
        $data_page['documentation'] = $this->config->item('documentation');
        $data_page['method'] = 'modify';
        $data_page['url_house_submit'] = $this->rent_model->find_func_url('update');
        $data_page['tab'] = $tab;
        $data_page['page_title'] = '房源管理-修改出租';
		$data_page['google_analytics'] = get_ga_js_code('/房源管理/修改出租/');
		//提交验证随机码
		$data_page['post_rand'] = $this->broker_model->get_rand_post();

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


        //渲染页面
        $this->render_publish($data_page);
    }
    
    /**
     * 修改房源 model
     */
    public function update()
    {
        //一、获取经纪人UID
		$this->load->model('broker_model');
		$session_info = $this->broker_model->get_user_session();
        $uid = $this->user_arr['uid'];
        $tbl = $this->rent_model->get_tbl();
        $package_id = $this->user_arr['package_id'];    //套餐
        $house_id = $this->input->post('id', true);
        //查询房源没修改之前的信息
        $this->rent_model->set_select_fields(array('isstar', 'esta'));
        $before_info = $this->rent_model->find_by_id($house_id);
         //防止模拟提交房源数据 xue 2015-06-16
        //提交验证随机码
		$post_rand = $this->broker_model->get_rand_post();
        $post_value = $this->input->post($post_rand['post_key'], true);
        if($post_rand['post_value']!=$post_value){
		    echo "<script>alert('参数错误！');history.go(-1);</script>";
                exit;		
		}

        //冻结房源不允许修改
        if ($before_info['esta'] == 5) 
        {
            echo "<script>alert('冻结房源不允许修改!');history.go(-1);</script>";
            return;
        }
        //二、更新房源信息
        $this->load->helper('common_string_helper');
        //房源参数
        $fields_values = array();
        /*******************基本信息开始***************************/
        $fields_values['infotype'] = intval($this->input->post('infotype', true));
        /***
        $fields_values['district'] = str_replace('"','',$district);
        $fields_values['streetid'] = $streetid;
        $fields_values['blockid'] = $blockid;
        $fields_values['blockshowname'] = csubstr($this->input->post('blockshowname'), 20);***/
        $fields_values['price'] = $this->input->post('price', true);
        $fields_values['priceunit'] = $this->input->post('priceunit', true);
        $fields_values['priceterm'] = $this->input->post('priceterm', true);
        $fields_values['pricetype'] = $this->input->post('pricetype', true);
        $fields_values['buildarea'] = $this->input->post('buildarea', true);
        $fields_values['renttype'] = $this->input->post('renttype', true);
		$fields_values['payment'] = $this->input->post('payment', true);
        if ($fields_values['renttype'] == '合租')
        {
            $fields_values['rentremark'] = $this->input->post('rentremark', true);
            $fields_values['rentroom'] = $this->input->post('rentroom', true);
        } 
        //只有物业类型 住宅 别墅 有室、厅等参数
        if ($fields_values['infotype'] == 1 || $fields_values['infotype'] == 2) 
        {
            $fields_values['room'] = $this->input->post('room', true);
            $fields_values['hall'] = $this->input->post('hall', true);
            $fields_values['toilet'] = $this->input->post('toilet', true);
            $fields_values['kitchen'] = $this->input->post('kitchen', true);
            $fields_values['balcony'] = $this->input->post('balcony', true);
        }       
        else
        {
            //其它类型强制设为0
            $fields_values['room'] = '';
            $fields_values['hall'] = '';
            $fields_values['toilet'] = '';
            $fields_values['kitchen'] = '';
            $fields_values['balcony'] = '';
        }
        //物业类型为车库车位没有楼层
        if ($fields_values['infotype'] == 6)
        {
            $fields_values['subfloor'] = '';
            $fields_values['floor'] = '';
            $fields_values['totalfloor'] = '';
            $fields_values['fitment'] = '';
            $fields_values['forward'] = '';
        }
        else
        {
            //楼层判断
            $lctype = $this->input->post('lctype', true);
            if ($lctype == 1) //单层
            { 
                $floor = $this->input->post('floor', true);
                $totalfloor = $this->input->post('totalfloor', true);
                if ($floor > $totalfloor) 
                {
                    //跳转页面
                    echo "<script>alert('总楼层不能小于当前楼层!');history.go(-1);</script>";
                    return;
                }
                $fields_values['subfloor'] = 0;
                $fields_values['floor'] = $floor;
                $fields_values['totalfloor'] = $totalfloor;
            }   
            if ($lctype == 2) //跃层
            { 
                $subfloor = $this->input->post('subfloor', true);
                $floor2 = $this->input->post('floor2', true);
                $totalfloor2 = $this->input->post('totalfloor2', true);
                if ($subfloor > $totalfloor2 || $floor2 > $totalfloor2) 
                {
                    echo "<script>alert('总楼层不能小于当前楼层!');history.go(-1);</script>";
                    return;
                }
                $fields_values['subfloor'] = $subfloor;
                $fields_values['floor'] = $floor2;
                $fields_values['totalfloor'] = $totalfloor2;
            }
            $fields_values['fitment'] = $this->input->post('fitment', true);
            $fields_values['forward'] = $this->input->post('forward', true);
        }
        $fields_values['mright'] = $this->input->post('mright', true);
        $fields_values['buildyear'] = $this->input->post('buildyear', true);
        $fields_values['contactor'] = $this->user_arr['truename'];
        $fields_values['telno'] = $session_info['telno'];
        $fields_values['ip'] = get_ip();
        /*******************基本信息结束***************************/
        
        //暂时记录日志
		$msg = date('y-m-d H:i:s')."::".print_r($_POST,true)." \n";
		$log = './applications/zsb/logs/rentupdate'."_".date('y-m-d');
		file_put_contents($log,$msg,FILE_APPEND );


        /*******************补充信息开始***************************/
        $housekind = $this->input->post('housekind', true);
        if (isset($housekind) && $housekind != '')
        {
            //物业类型 厂房车库代表车位属性
            //物业类型 物业类型代表别墅类型
            $fields_values['housekind'] = $housekind;
        }
        //商业分类
        $tradeclass = $this->input->post('tradeclass', true);
        if (isset($tradeclass) && $tradeclass != '')
        {
            $fields_values['tradeclass'] = $tradeclass;
        }
        //物业费
        $fee = $this->input->post('fee', true);
        if (isset($fee) && $fee != '')
        {
            $fields_values['strata_fee'] = $fee;
        }
        //房屋设备
        $equipment = $this->input->post('equipment', true);
        if ($equipment)
        {
            $fields_values['equipment'] = implode(",", $equipment);
        }
        $fields_values['ownid'] = trim($this->input->post('ownid', true));
        /*******************补充信息结束***************************/
        
        /*******************详细信息开始***************************/
        $fields_values['address'] = htmlspecialchars(csubstr(trim(
                filterSpace($this->input->post('address', true))),60));

		//敏感词过滤
		if(!empty($fields_values['address']))
		{
			$this->load->model('ajax_model');
			$sensitive_word = $this->ajax_model->check_sensitive_word($fields_values['address']);
			
			if(!empty($sensitive_word))
			{
				echo "<script>alert('含有敏感词：".$fields_values['address']."');history.go(-1);</script>";
                return;
			}
		}
  
        //$fields_values['remark'] = $this->input->post('remark');
		$fields_values['remark'] = check_word($this->input->post('remark'),STATIC_BADWORD_URL);

        //房源封面图
        $pic1 = $this->input->post('pic1', true);
        if($pic1 == '')
        {
            $pic1 = '';
        }
        else
        {
            $pic1 = preg_match("#\?#", $pic1) ? substr($pic1, 0, strpos($pic1, '?')) 
                    : $pic1;
        }
        //四、处理房源图片
        $pics = array();
        $pfile_name = $this->input->post('p_filename', true);
        if (isset($pfile_name) && $pfile_name != '') 
        {
            $pics = array(
                'p_filename' => $pfile_name,
                'p_sort' => $this->input->post('p_sort', true),
                'p_title' => $this->input->post('p_title', true),
                'infotype' => $fields_values['infotype']
            );
            $pic_check = $this->rent_model->insert_house_pic($pics,
                    $tbl, $house_id, $pic1, $this->input->post('block_id', true), 1);
            $pic_check_arr = $pic_check['pic_check'];
            //更新封面图
            $fields_values['pic1'] = $pic_check['indexpic'];
        }
        //update rent set esta = 5 where id in(33899521, 37700775) and uid = 10000040;
        $affected_rows = $this->rent_model->update($fields_values, $house_id, $uid);
        if ($affected_rows > 0)
        {
            
            $this->load->model('admin_check');
            $delpic = $this->input->post('delpic', true);
            //把删除的图片从审核库中删除
            if($delpic != '')
            {
                $delpicarr = explode(",", $delpic);
                if(is_array($delpicarr) && !empty($delpicarr))
                {
                    foreach($delpicarr as $val)
                    {
                        $val = intval($val);
                        if($val)
                        {
                            //貌似不太好判断入了哪个库，一起删除吧
                            $this->admin_check->delete_check_pic($tbl, $house_id, $val);
                            $this->admin_check->delete_check_pic_sub($tbl, $house_id, $val);
                        }
                    }
                }
            }
            $nowtime = time();
            //审核图片入库
            /***
            if(isset($pic_check_arr) && is_array($pic_check_arr) 
                    && !empty($pic_check_arr) && $uid > 0)
            {
                $this->load->model('admin_check');
                foreach($pic_check_arr as $key => $val)
                {
                    $infotype = $fields_values['infotype'];
                    $fitment = $fields_values['fitment'];
                    $pic_check_arr[$key]['uid'] = $uid;
                    $pic_check_arr[$key]['housetbl'] = $tbl;
                    $pic_check_arr[$key]['houseid'] = $house_id;
                    $pic_check_arr[$key]['fitment'] = $fitment == "简装" ? 2 : ($fitment == "毛坯" ? 3 : 1);
                    $pic_check_arr[$key]['infotype'] = $infotype == 3 ? 4 : ($infotype == 4 ? 3 : $infotype);//商铺、写字楼互换
                    $pic_check_arr[$key]['dateline'] = $nowtime;
                    //进入审核附属表待夜间JOB过滤入库
                    $this->admin_check->insert_check_pic_sub($pic_check_arr[$key]);
                    //来自设备的图片只入待审核库、不入审核库
                    if($pic_check_arr[$key]['surface'] == 0 && $pic_check_arr[$key]['from_device'] == 1)
                    {
                        unset($pic_check_arr[$key]);
                    }
                    unset($pic_check_arr[$key]['from_device']);
                    //封面图入审核表
                    if($pic_check_arr[$key]['surface'] == 1)
                    {
                        $this->admin_check->insert_check_pic($pic_check_arr[$key]);
                    }
                }
            }***/
            //判断优质，多图 先有多图再有优质
            $this->load->model('rent_star_model');
            $fields_values['id'] = $house_id;
            $fields_values['uid'] =  $this->user_arr['uid'];
            $this->rent_star_model->set_houseinfo($fields_values);
            $is_star_house = $this->rent_star_model->check_star_standard();
            $growthMessage = '';
            if ($is_star_house)
            {
                if ($before_info['isstar'] != 3) {
                    //房源标签的级别
                    $gradeLog = $before_info['isstar'] == 3 ? 2 : 1;
                    $ghl  = new GrowthHouseLog();
                    $houseGradeLog = $ghl->findHouseGradeLog($house_id, $tbl, $gradeLog, $uid);
                    if ($houseGradeLog['grade'] == 1 && $before_info['isstar'] != 3) 
                    {
                        $gbe  = new GrowthBrokerExp(array('id' => $uid, 'groupid' => $package_id));			
                        $gewp = new GrowthExpWayPackage();
                        $exp = $gewp->findScoreByWayAliasAndPackageId('pStarHouse', $package_id);					 
                        $inExpStatus = $gbe->increase('pStarHouse','发布多图房源',$exp);
                        $ghl->updateHouseGradeLog($house_id, $tbl, 2, $uid);
                        if($inExpStatus['status'] == 2 ){
                            $growthMessage = "您今天的成长值已达峰值！";
                        } elseif($inExpStatus['status'] == 1){
                            $growthMessage = "成长值+" . $exp;
                        }
                    }
                    //判断原来是否为图
                    if ($before_info['isstar'] != 3)
                    {
                        $this->rent_star_model->set_star();
                    }
                }
            } 
            else 
            {
                //设置房源属性为多图
                $this->rent_star_model->remove_star();
                $this->load->model('rent_tag_model');
                $this->rent_tag_model->set_houseinfo($fields_values);
                //2011-11-30 同步设置标签失效
				$this->rent_tag_model->remove_tag();
            }
            //$page_text = '房源修改成功!' . $growthMessage;
            $page_text = '房源修改成功!' ;
        }
        else 
        {
            $page_text = '抱歉，修改房源信息失败!';
        }
        $this->jump($this->rent_model->find_func_url(), $page_text, 3000);
    }

    /**
     * 物理删除房源，如需更改房源状态为删除，请调用update方法
     */
    public function delete()
    {
        //delete from  rent where id = 33899521 and uid = 10000040;
        $this->rent_model->delete(33899521, 10000040);
    }
    
    
    /**
     * 房源列表页
     *
     * @access public
     * @param  string $esta 房源状态字符串
	 * @param  int $page 跳转页数(特殊跳转使用)
     * @return void
     */
    public function manage( $house_esta = 'active' , $page = 1)
    {   
        //post参数
        $post_param = $this->input->post( NULL , TRUE );
        
        /** 分页参数 */
        $page = isset($post_param['page']) ? intval($post_param['page']) : intval($page);
        $this->_init_pagination($page);
        
        //经纪人账号信息
        $uid = $this->user_arr['uid'];  //账号
        $package_id = $this->user_arr['package_id'];    //套餐

        /*** 经纪人信息 ****/
        $broker_info = array();
        $this->load->model('broker_model');
        $this->broker_model->set_uid($uid);
        $broker_info = $this->user_arr;
        
        //房源核心数组
        $house = $this->config->item('house');
        $house['roomcategory'] = array('1' => '非多图' , '2' => '多图', '3' => '急推');

        //加载房源类
        $this->load->model('rent_model');
        $esta_arr = array(); //房源状态数组
        $esta_arr = $this->rent_model->get_house_esta();
        /* 'active' => 1 , 'invalid' => 2 , 'delete' => 4 , 'frozen' => 5 */
        $esta = ( isset($house_esta) && isset($esta_arr[$house_esta]) && $house_esta != 'delete' ) ? 
                $esta_arr[$house_esta] : 1 ;
        
        //查询房源条件
        $cond_where = "uid = '".$uid."' AND esta = $esta  AND infofrom = '5' ";
        //表单提交参数组成的查询条件
        $cond_where_ext = $this->_get_cond_str($post_param);
        $cond_where .= $cond_where_ext;
        //排序字段
        $roomorder = isset($post_param['roomorder']) ? $post_param['roomorder'] : array();
        $order_arr = $this->_get_orderby_arr($roomorder);

        //符合条件的总行数
        $this->_total_count = $this->rent_model->find_count_by($cond_where);

        //计算总页数
        $pages  = $this->_total_count > 0 ? ceil( $this->_total_count / $this->_limit ) : 0;
        
        //获取数据源
        $data_info = array ();
        if($this->_total_count > 0 )
        {
            $select_fields = array ('id','ownid','infotype','infofrom','agentcode','uid','esta','district','address',
			'streetid','blockid','isreal','blockshowname','buildyear','buildarea',
			'subfloor','floor','totalfloor','room','hall','toilet','kitchen','balcony',
			'forward','price','priceunit','priceterm','pricetype','fitment','contactor',
			'telno','creattime','updatetime','expiretime','ischarge','istop','isstar','renttype','istag');
            $this->rent_model->set_select_fields($select_fields);
            $data_info = $this->rent_model->find_all_by( $cond_where , $this->_offset ,
                $this->_limit , $order_arr['order_key'] , $order_arr['order_by'] );
        }
        $row_num =  count($data_info);
        
        //加载新房直售属性类
        $this->load->model('sell_nofee_model');
        //加载立减属性类
        //$this->load->model('rent_reduce_model');
        //预约方案
        $reserve_info = array();
        if( $row_num > 0 )
        {   
            //加载辅助函数
            $this->load->helper('common_url');
            $this->load->helper('common_house');
			$this->load->helper('common_string');
            
            //昨天的日期
            $yesterday = date( 'Ymd' , time() - 86400 );
            
            //实例化经纪人统计类(原中间件提供数据统计类)
            $this->load->library( 'statistics');
            
            //加载多图属性类
            $this->load->model('rent_star_model');
            
            if( $house_esta == 'active')
            {   
				if(!$_SESSION['rent_token_value']){
			     $_SESSION['rent_token_value'] = md5(getRandChar(10));

			    }
                //加载刷新日志类
                $this->load->model('log_refresh');
            
                //加载急推属性类
                $this->load->model('rent_tag_model');

                //加载预约方案模型类
                $this->load->model('reserve_model');
                $this->reserve_model->set_uid($uid);
                
                //竞投期限类
                $growthBidPeriods = new GrowthBidPeriods();

                //小区专家
                $periodsBlockExpert = $growthBidPeriods->currentBidPeriods(1);

                //获取最新一期小区专家等级
                $bidBlockExpertPeriodsId = $periodsBlockExpert['id'];
                $growthBidBlockExpert = new GrowthBidBlockExpert();
            }

			if($house_esta == 'active' || $house_esta == 'invalid')
			{
				//我发布的小区
				$block_fields = array('blockid','blockshowname');
				$this->rent_model->set_select_fields($block_fields);
				$publish_block = $this->rent_model->find_publish_block($uid , $house_esta);
			}
            
             //冻结房源类
            if( $house_esta == 'frozen')
            {
                $this->load->model('rent_freeze_model');
                $house['freeze_esta'] = $this->rent_freeze_model->get_freeze_esta();
            }
            
            //房源信息数组
            $house_info = array();
            for( $i = 0 ; $i < $row_num ; $i ++ )
            {   
                //房源地址
                $data_info[$i]['info_url'] =  get_rentinfo_url($data_info[$i]['id']);

				//房源小区地址
				$data_info[$i]['block_url'] =  get_blockinfo_url($data_info[$i]['blockid']);

				//房源地址
				$data_info[$i]['address_str'] =  csubstr($data_info[$i]['address'],60);

				//面积
				$data_info[$i]['buildarea'] =  strip_end_0($data_info[$i]['buildarea']);

				//价格
				$data_info[$i]['price'] =  strip_end_0($data_info[$i]['price']);

				//楼层
				if(empty($data_info[$i]['subfloor']))
				{
					$data_info[$i]['floor_str'] = $data_info[$i]['floor'].'/'.$data_info[$i]['totalfloor']; 
				}
				else
				{
					$data_info[$i]['floor_str'] = $data_info[$i]['subfloor'].'-'.$data_info[$i]['floor'].'/'.$data_info[$i]['totalfloor'];
				}
                
                //房源修改地址
                $data_info[$i]['modify_url'] =  $this->rent_model->get_modify_house_url($data_info[$i]['id']);
                
                //是否为多图房源
                $this->rent_star_model->set_houseinfo($data_info[$i]);
                $data_info[$i]['is_star_result'] = $this->rent_star_model->is_star();
                
                //激活房源页面数据
                if( $house_esta == 'active')
                {
                    //是否为急推房源
                    $this->rent_tag_model->set_houseinfo($data_info[$i]);
                    $data_info[$i]['is_tag_result'] = $this->rent_tag_model->is_tag();
                    //急推标准
                    if($data_info[$i]['is_tag_result'] === FALSE)
                    {
                        $data_info[$i]['tag_standard'] = $this->rent_tag_model->check_tag_standard();
						$data_info[$i]['house_tag_info'] = array();
						$data_info[$i]['tag_exipire_days'] = '';
                    }
					else
					{
						//急推标签剩余日期
						$data_info[$i]['house_tag_info'] = $this->rent_tag_model->get_tag_record() ;
						if(isset($data_info[$i]['house_tag_info']) && !empty($data_info[$i]['house_tag_info']))
						{
							$data_info[$i]['tag_exipire_days'] = 
								$this->rent_tag_model->tag_exipire_days($data_info[$i]['house_tag_info']['expiretime']);
						}
					}

                    //预约方案
                    $data_info[$i]['reserve_info'] = $this->reserve_model->get_project_by_tblrowid('rent',$data_info[$i]['id']);

                    //小区专家等级
                    /*$memkey = "nj_block_heat_" . $bidBlockExpertPeriodsId . '_' . $data_info[$i]['blockid'];
                    $cache = $this->mc->get($memkey);
                    $blockLevelInfo = array();
                    if ($cache['isok'] == 1 ) 
                    {
                        $blockLevel = $cache['data'];
                    } 
                    else 
                    {
                        $conf = "bid_periods_id = $bidBlockExpertPeriodsId AND block_id=".$data_info[$i]['blockid'];
                        $blockLevelInfo = $growthBidBlockExpert->findOneBy($conf);
                        $blockLevel = isset($blockLevelInfo['broker_level']) ? 
                                $blockLevelInfo['broker_level'] : '';
                       $this->mc->add($memkey, array('isok'=>1,'data'=>$blockLevel),  3600);
                    }
                    if (isset($blockLevel) && $blockLevel != '') 
                    {   
                        $bidBlockLevels = rtrim(str_replace('LV', '', $blockLevel), ',');
                        $minBidBlockLevel = min(explode(',', $bidBlockLevels));
                        $data_info[$i]['block_level'] = $minBidBlockLevel;
                    }
                    else 
                    {
                        $data_info[$i]['block_level'] = '';
                    }*/
                    
                    //刷新次数
                    $data_info[$i]['refresh_num'] = 
                    $this->log_refresh->refresh_num_by_id( $data_info[$i]['id'] , 'rent' , $data_info[$i]['updatetime']);
                } 
                
                //到期天数
                $data_info[$i]['exipire_days'] = to_expire_day_new($data_info[$i]['expiretime']);
                
                //昨日点击量
                //$data_info[$i]['click_num_y'] = 
                   // $this->statistics->get_fidclickcount( $yesterday , $data_info[$i]['id'] , 'rent');
				//$data_info[$i]['click_num_y'] =0;//xue



				$fid_click_count_key = "nj_statistics_get_fidclickcount_new".$yesterday."_rent_".$data_info[$i]['id'];
				
				$fid_click_count = $this->mc->get($fid_click_count_key);
			
				
				if($fid_click_count === false) {
				   $click_id_arr[$i] = $data_info[$i]['id'];
				   $house_key[$data_info[$i]['id']] = $i;
				   //echo "12312";exit();
					
				}else{
				   $data_info[$i]['click_num_y'] = $fid_click_count;
				}
                
                if( $house_esta == 'frozen')
                {
                    //冻结信息
                    $this->rent_freeze_model->set_select_fields(array('id','esta','rowid','reason','freezetime'));
                    $data_info[$i]['freeze_info'] = $this->rent_freeze_model->get_freeze_by_rowid($data_info[$i]['id']);
                }
                
                $arr_rowid[] = $data_info[$i]['id'];
            }
            
            //批量查询房源预约方案
            if( $house_esta == 'active')
            {
                $reserve_info = $this->reserve_model->get_project_by_rowids('rent' , $arr_rowid);
            }
        }


		//获取房源昨日点击量
		if(is_array($click_id_arr)&&!empty($click_id_arr)){

			foreach($click_id_arr as $key=>$value){
				$fids .= $value.",";
			}
			$fids = rtrim($fids,",");			
			$click_data_str = $this->statistics->getfidsclickcountnew( $yesterday , $fids , 'rent');
			
			$click_data_str = rtrim($click_data_str,'}');
			$click_data_str = ltrim($click_data_str,'{');
			$click_data_arr = explode(",",$click_data_str);
			
			foreach($click_data_arr as $value){
				$house_click = explode("=",$value);
				
                $click_house_id= trim($house_click[0]);
				$click_house_num= trim($house_click[1]);
				//房源在数据的编号
                $iid = $house_key[$click_house_id];		
				if($iid>0){
				   $data_info[$iid]['click_num_y'] = $click_house_num;
				}
				
				$fid_click_count_key = "nj_statistics_get_fidclickcount_new".$yesterday."_rent_".$click_house_id;
				//echo $fid_click_count_key;echo "<br/>";
			    $this->mc->set($fid_click_count_key,$click_house_num,6000);	
			}
			

		}
        
        //是否显示分页
        $pagination = NULL;
        if( $this->_total_count > $this->_limit)
        {
            $pagination = helper_pagination( $this->_current_page , $pages , $this->_total_count );
        }
        
        /*** 经纪人今日使用统计 ***/
        $statistic_data = array();
        $this->load->model('statistics_model' ,'stat');
        $this->load->model('broker_package_model','broker_package');
        
        //套餐房源个数
        $post_limit = intval($this->user_arr['postlimit']);
        //激活出售
        $statistic_data['sell_count'] = $this->stat->sellCount($uid);
        //激活出租
        $statistic_data['rent_count'] = $this->stat->rentCount($uid);
        $house_count = $statistic_data['sell_count'] + $statistic_data['rent_count'];

		//激活全景图房源总量
		$statistic_data['sell360Count'] = $this->stat->sell360Count($uid);
        $statistic_data['rent360Count'] = 0;

		 //当前有效激活总量
        $statistic_data['sellCountStar'] = $this->stat->sellCountStar($uid);
        $statistic_data['rentCountStar'] = $this->stat->rentCountStar($uid);

        //剩余套餐数
        $statistic_data['package_valid_num_limit'] = $post_limit > $house_count ? 
        $post_limit - $house_count : 0;
        $package_info = array();
        $package_info = $this->broker_package->find_by_id($package_id);
		$broker_info['package_info'] = $package_info;
        //库存量总量
        $statistic_data['package_stock_num'] = $package_info['package_stock_num'];
        //当前库存房源量
        $statistic_data['stock_house_num'] = $this->broker_model->stock_house_num();
        //剩余库存量
        $statistic_data['package_stock_num_limit'] = 
                $statistic_data['package_stock_num'] >=  $statistic_data['stock_house_num']?
        $statistic_data['package_stock_num'] - $statistic_data['stock_house_num'] : 0;

		//当日刷新
        $statistic_data['refresh_limit'] = $this->stat->refreshNumber($package_id);
        $statistic_data['refresh_today'] = $this->stat->refreshNumberToday($uid);
        
        //预约未执行个数
        $this->load->model('reserve_model');
        $statistic_data['refresh_not_do'] = $this->reserve_model->get_reserve_remain_num();
        if ($statistic_data['refresh_not_do'] >= $statistic_data['refresh_limit']) 
        {
            $statistic_data['refresh_not_do'] = $statistic_data['refresh_limit'] - $statistic_data['refresh_today'];
        }
        //此处逻辑是为了让预约未执行与已执行之和等于刷新总量
        $need2reserveRefreshNum = $statistic_data['refresh_limit'] - $statistic_data['refresh_today'];
        $statistic_data['refresh_not_do'] = $statistic_data['refresh_not_do'] >= $need2reserveRefreshNum ? $need2reserveRefreshNum : $statistic_data['refresh_not_do'];
        $statistic_data['refresh_remain'] = $statistic_data['refresh_limit'] - $statistic_data['refresh_today'] - $statistic_data['refresh_not_do'];
        $statistic_data['refresh_remain'] = $statistic_data['refresh_remain'] > 0 ? $statistic_data['refresh_remain'] : 0;

        //急推标签使用情况
        if($package_info['package_tag_num'] > 0)
        {
           // $statistic_data['tag_limit'] = $this->stat->jtLabelNumber($package_id);
            //$statistic_data['tag_count_today'] = $this->stat->jtLabelCount($uid);
            //$statistic_data['tag_remain'] = $statistic_data['tag_limit'] > $statistic_data['tag_count_today'] ? $statistic_data['tag_limit'] - $statistic_data['tag_count_today'] : 0;

            $this->load->model("house_tag_package_model");
			//$statistic_data['tag_count_today'] = $this->house_tag_package_model->get_used_tag_valid_num($uid,1);
		    $statistic_data['tag_remain'] = $this->house_tag_package_model->get_tag_valid_num($uid,1);
			$statistic_data['tag_count_today'] = $this->stat->jtLabelCount($uid);
        }
        else
        {
            $statistic_data['tag_limit'] = '--';
            $statistic_data['tag_count_today'] = '--';
            $statistic_data['tag_remain'] = '--';
        }

		//冻结房源个数
		$cond_where_forzen = "uid = '".$uid."' AND esta = 5  AND infofrom = '5'";
		$statistic_data['forzen_house_num'] = $this->rent_model->find_count_by($cond_where_forzen);
        /*** 经纪人今日使用统计结束 ***/
        
        //经纪人今日刷新成长值
        $growthExpDayCount = new GrowthExpDayCount();
        $refreshEventArray = array('refreshHouse');
        $exp_rank_day = $growthExpDayCount->getExpAndRank($uid, $refreshEventArray);
        $statistic_data['growthDaySum'] = $exp_rank_day['exp'];
        //当前用的排序名次百分比
        $statistic_data['rankRate'] = $exp_rank_day['rate'];

        /** 页面初始化 */
        $data['page_title'] = '房源管理-管理出租';

		$data['css'] = load_css('zsb/css/v1.0/style1.css,zsb/css/v1.0/autocomlete.css');


        $data['js'] = load_js('zsb/js/v1.0/js2.js,zsb/js/v1.0/cp.js,common/js/swf/swfupload.js,'
                . 'zsb/js/v1.0/upload_real.js');   //需要加载的JS
        $data['house']  = $house;
        if (isset($publish_block) && $publish_block != '') 
        {
            $data['publish_block']  = $publish_block;
        }
        $data['post_param']  = $post_param;
        $data['data_info']  = $data_info;
        $data['broker_info']  = $broker_info;
        $data['reserve_info']  = $reserve_info;
        $data['statistic_data']  = $statistic_data;//今日使用统计
        $data['upload_pic_url'] = $this->config->item('base_url') . 'pic/common/';
        $data['documentation'] = $this->config->item('documentation');//帮助文档
        $data['page']  = $this->_current_page;
        $data['pagination'] = $pagination;
        $data['total_count'] = $this->_total_count;
		switch ($house_esta){
			case 'active' :
				$ga_title = '激活房源';
				break;
			case 'invalid' :
				$ga_title = '失效房源';
				break;
			case 'frozen' :
				$ga_title = '违规房源';
				break;
		}
		$data['google_analytics'] = get_ga_js_code('/房源管理/管理出租/'.$ga_title.'/');
        //引导
        $this->load->library('guide');
        $data['guide_show'] = $this->guide->check_guide($uid, 'zsb_refresh');
        // 2016-1-15 添加星级数据 -----------start -------->
	
		 $data['broker_new_info'] =$this->broker_model->get_broker_info_by_uid($uid);

		// 2016-1-15 添加星级数据 -----------end -------->

		// 数据过滤
		if($house_esta == 'frozen'){
			if(!empty($data_info)){
				$this->load->model('house_freeze_base_model');
				$databaseSellWarning = mysql_connect('172.17.1.153', 'root', 'idontcare');
				mysql_query('set names gbk');
				mysql_select_db('esfpublic');
				foreach($data_info as $key => $value){
					$databaseFreezeBase = $this->house_freeze_base_model->database();
					$databaseFreezeBase->select(array('rowid', 'remark', 'freezetime', 'appealtime', 'thawtime'));
					$databaseFreezeBase->where('rowid', $value['id']);
					$resultFreezeBase = $databaseFreezeBase->get('house_freeze')->row_array();
					// 违规处理
					//$data_info[$key]['freeze_info']['esta'] = $value['esta'];
					// 违规原因
					if(empty($value['freeze_info']['reason'])){
						$data_info[$key]['freeze_info']['reason'] = '房源违规';
						// 如果违规处理是删除，展示删除的原因
						if(intval($value['esta']) == 4){
							if(!empty($resultFreezeBase)){
								$data_info[$key]['freeze_info']['reason'] = $resultFreezeBase['remark'];
							}
						}
						// 如果违规处理是冻结
						if(intval($value['esta']) == 5){
							// 查找疑似价格虚假房源库有没有，有就展示“价格虚假”
							$row = null;
							$sql1 = sprintf('select * from sell_price_warning where id=%s', $value['id']);
							$result1 = mysql_query($sql1, $databaseSellWarning);
							$row1 = mysql_fetch_array($result1);
							if($row1){
								$row = $row1;
							}
							$sql2 = sprintf('select * from sell_price_warning_pass where id=%s', $value['id']);
							$result2 = mysql_query($sql2, $databaseSellWarning);
							$row2 = mysql_fetch_array($result2);
							if($row2){
								$row = $row2;
							}
							$sql3 = sprintf('select * from sell_price_warning_refuse where id=%s', $value['id']);
							$result3 = mysql_query($sql3, $databaseSellWarning);
							$row3 = mysql_fetch_array($result3);
							if($row3){
								$row = $row3;
							}
							if($row){
								$data_info[$key]['freeze_info']['reason'] = '价格虚假';
							}
						}
					}
					// 处理时间
					$time = array();
					array_push($time, intval($value['updatetime']));
					array_push($time, intval($value['freeze_info']['freezetime']));
					if($resultFreezeBase){
						array_push($time, intval($resultFreezeBase['freezetime']));
						array_push($time, intval($resultFreezeBase['appealtime']));
						array_push($time, intval($resultFreezeBase['thawtime']));
					}
					$pos = array_search(max($time), $time);
					$data_info[$key]['freeze_info']['freezetime'] = $time[$pos];
				}
				// Order By Time
				$array = array();
				foreach($data_info as $value){
					if(!empty($value['freeze_info']['freezetime'])){
						$array[intval($value['freeze_info']['freezetime'])] = $value;
					}
				}
				foreach($data_info as $value){
					if(empty($value['freeze_info']['freezetime'])){
						array_push($array, $value);
					}
				}
				krsort($array);
				$data_info = $array;
			}
		}
		$data['data_info'] = $data_info;
		
		// 是否能够发全景房
		$config = $this->config->item('is_publish_360');
		if($config === false){
			$config = true;
		}else{
			if($config == 1){
				$config = true;
			}else{
				$config = false;
			}
		}
		$data['is_publish_360'] = $config;

        //加载模板
        $template_name = $esta == 1 ? 'rent_manage' : 'rent_manage_'.$house_esta;
        $this->view( 'house_manage' , $template_name , $data);
    }
    
    
     /* 列表页房源操作入口
     * @param   string $actiontype 操作类型
     * @param   string $rowid_str 操作房源编号
     * @param   int $page 操作页数
     * @param   string $referer 操作后跳转的页面
    */
    public function do_action()
    {   
        //操作类型
        $actiontype = $this->input->post( 'actiontype' , TRUE );
        
        //房源编号
        $rowid_str = $this->input->post( 'actionid' , TRUE );
        $rowid = $this->input->post( 'rowid' , TRUE );
        
        //当前页数
        $page = $this->input->post( 'pg' , TRUE );
        
        //跳转地址
        $referer = $this->input->post( 'referer' , TRUE );
        $referer = (isset($referer) && $referer != '')  ? $referer : $_SERVER['HTTP_REFERER'];
        
        //房源编号字符串转化为数组
        $arr_id = explode( ',' , $rowid_str );
        
        //经纪人账号uid
        $uid = $this->user_arr['uid'];
        //门店账号
        $agentcode = $this->user_arr['agentcode'];
        
        //房源类型
        $tbl = 'rent';
        
        //分发处理
        switch ($actiontype) 
        {
            case 'invalid_house':
                $invalid_num = 0;
                
                //初始化房源操作类
                $this->load->model('rent_operate_model');
                
                /*** 1、失效房源 ***/
                $invalid_num = $this->rent_operate_model->invalid_house($arr_id);
                if( $invalid_num > 0 )
                {   
                    //加载中间件统计类
                    $this->load->library('statistics');
                    
                    //加载房源急推属性类
                    $this->load->model('rent_tag_model');
                    
                    //加载Real房属性类
                    //$this->load->model('rent_reduce_model');
                    
                    //加载门店类
                    $this->load->model('agency_model');
                    $relation_info = array();
                    $relation_info = $this->agency_model->get_relation_by_agentcode($agentcode);
                    $domain = isset($relation_info['cat_id']) ? $relation_info['cat_id'] : 0;
                    if( is_array($relation_info) && !empty($relation_info))
                    {	 
                        $parentcode = isset($relation_info['parentcode']) ? $relation_info['parentcode'] : '';
                    }
                    else
                    {	
                        $parentinfo = array();
                        $select_array = array('parentcode');
                        $this->agency_model->set_select_fields($select_array);
                        $parentinfo = $this->agency_model->get_company_info_by_code($agentcode);
                        $parentcode = isset($parentinfo['parentcode']) ? $parentinfo['parentcode'] : '';
                    }
                    
                    foreach( $arr_id as $rowid )
                    {   
                        /*** 2、失效标签、Real房 ****/
                        $house_info = array('id'=> $rowid);
                        $this->rent_tag_model->set_houseinfo($house_info);
                        $this->rent_tag_model->remove_tag();
                        //$this->rent_reduce_model->set_houseinfo($house_info);
                        //$this->rent_reduce_model->remove_reduce();
                        
                        /*** 3、取消预约刷新 ***/
                        $this->load->model('reserve_model');
                        $result = $this->reserve_model->delete_projecthouse($uid , $tbl , $rowid);
                        
                        /*** 4、通过接口提交操作日志给中间件，operatetype 1:新增 2刷新 3删除 4失效 5再发布 ***/
                        $msg = 4;
                        $this->statistics->sub_operatecount( $uid , $agentcode , $msg , $rowid , '' , $tbl , $domain , $parentcode );
                        
                        /*** 5、提交房源操作日志给MYSQL(经纪人日志查询),[$msg:4-失效房源] ***/
                        $this->rent_model->action_log( $agentcode , $uid , $tbl , $rowid , $msg);
                    }
                    
                    $page_text = '操作成功，共失效了'.$invalid_num.'条房源';
                }
                else
                {
                    $page_text = '失效房源失败';
                }
                break;
            case 'multi_delete_house':
                $delete_num = 0;
                
                //初始化房源操作类
                $this->load->model('rent_operate_model');
                
                /*** 1、删除房源 ***/
                $delete_num = $this->rent_operate_model->delete_house($arr_id);
                if( $delete_num > 0 )
                {   
                    //加载中间件统计类
                    $this->load->library('statistics');
                    
                    //加载门店类
                    $this->load->model('agency_model');
                    $relation_info = array();
                    $relation_info = $this->agency_model->get_relation_by_agentcode($agentcode);
                    $domain = isset($relation_info['cat_id']) ? $relation_info['cat_id'] : 0;
                    if( is_array($relation_info) && !empty($relation_info))
                    {	 
                        $parentcode = isset($relation_info['parentcode']) ? $relation_info['parentcode'] : '';
                    }
                    else
                    {	
                        $parentinfo = array();
                        $select_array = array('parentcode');
                        $this->agency_model->set_select_fields($select_array);
                        $parentinfo = $this->agency_model->get_company_info_by_code($agentcode);
                        $parentcode = isset($parentinfo['parentcode']) ? $parentinfo['parentcode'] : '';
                    }
                    
                    foreach( $arr_id as $rowid )
                    {   
                        $tbl = 'sell';
                        /*** 4、通过接口提交操作日志给中间件，operatetype 1:新增 2刷新 3删除 4失效 5再发布 ***/
                        $this->statistics->sub_operatecount( $uid , $agentcode , 3 , $rowid , '' , $tbl , $domain , $parentcode );
                        
                        /*** 5、提交房源操作日志给MYSQL(经纪人日志查询),[$msg:4-失效房源] ***/
                        $this->rent_model->action_log( $agentcode , $uid , $tbl , $rowid , 0);
                    }
                    $page_text = '操作成功，共删除了'.$delete_num.'条房源';
                }
                else
                {
                    $page_text = '删除了房源失败。';
                }
                break;    
            case 'refresh':
                if(is_array($arr_id) && !empty($arr_id) )
                {
				    $token_rent = $this->input->post( 'rent_token' , TRUE );
                    $errornum = 0;
					if($uid==850507){
					//	VAR_DUMP($_SESSION['rent_token_value']);
					//	var_dump($_POST);EXIT();
					 //  var_dump($token_sell);exit();
					}
					 if($token_rent!=$_SESSION['rent_token_value']){
					    $this->jump($url_manage, "服务器正忙，请稍后再试");
                        return;				
					}
                    
                    //加载刷新函数文件
                    $this->load->helper('common_house');
                    
                    //套餐ID
                    $package_id = $this->user_arr['package_id'];
                    
                    //刷新总量限制
                    $package_info = array();
                    $this->load->model('package_base_model');
                    $this->package_base_model->set_select_fields(array('package_refresh_num'));
					$package_info = $this->package_base_model->find_by_id($package_id);
                    $refresh_limit =  intval($package_info['package_refresh_num']);
                    //今日已刷新数量
                    $this->load->model("log_refresh");
                    $refreshnum = $this->log_refresh->findTodayNumberByBrokerId($uid);
                    
                    foreach( $arr_id as $key => $value )
                    {
                        $cb = refresh_house( $uid ,$tbl , $value);
                        
                        if( trim($cb) == 'error')
                        {
                            $errornum ++ ;
                            unset( $arr_id[$key] );
                        }
                        else
                        {   
                            $msg = 7;/*** 提交房源操作日志给MYSQL(经纪人日志查询),[$msg:7-刷新房源] ***/
                            $this->rent_model->action_log( $agentcode , $uid , $tbl , $value , $msg);
                        }
                    }
                    
                    $errornum = intval($errornum);
                    $sum = count($arr_id);
                    
                    //经纪人成长体系
                    if( $sum > 0 )
                    {   
                        $arrBroker = array(
                            'id' => $uid,
                            'groupid' => $package_id,
                        );
                        
						//成长值
                        $gbe  = new GrowthBrokerExp($arrBroker);		
                        $gewp = new GrowthExpWayPackage();
						$exp = 0;	
                        $exp = $gewp->findScoreByWayAliasAndPackageId('refreshHouse',$package_id);

                        if( $sum > 1)
                        {
                            $log_tip = '批量刷新房源';
                            $exp = $exp * $sum;
                        }
                        else
                        {
                            $log_tip = '刷新单条房源';
                        }
                        $inExpStatus = $gbe->increase('refreshHouse' , $log_tip ,$exp);
                        /*
                        if($inExpStatus['status'] == 2)
                        {
                            $growthMessage = "<div style='text-align:center;margin:0px 10px;'>"
                                    . "</div>";
                        }
                        else if($inExpStatus['status'] == 1)
                        {
                            $growthMessage = "<div style='text-align:center;margin:0px 10px;'>"
                                    . "成长值+".$exp."</div>";
                        }
						*/
                        
                        //清除今日刷新总量[清除缓存用，勿删 add xz]
                        $this->load->model('log_refresh');
                        $this->log_refresh->findTodayNumberByBrokerId( $uid , 1);
                    }
                    
                    //今日剩余刷新量
                    $refresh_left = 0;
                    $refresh_left = intval($refresh_limit) - intval($refreshnum) - intval($sum) ;
                    if( $sum > 0 && $errornum == 0) 
                    {   
                        $page_text = '操作成功，共刷新了'.$sum.'条房源';
                        $page_text .= "，今日剩余刷新".$refresh_left."次。";
                        $page_text .= $growthMessage;
                    }
                    else if($sum > 0 && $errornum > 0)
                    {
                        $page_text = '您成功刷新了'.$sum.'条房源，';
                        $page_text .= "今日剩余刷新".$refresh_left."次。";
                        $page_text .= $growthMessage;
                    }
                    else if ($sum == 0 && $errornum > 0 && $refresh_left > 0) 
                    {
                        $page_text = "对不起，您选定的房源今日刷新次数已经达到上限。";
                    }
                    else if($sum == 0 && $errornum > 0)
                    {
                        $page_text = '对不起，刷新超限';
                    }
                    else
                    {
                        $page_text = '刷新失败';
                    }
                }
                break;
        }
        
       $this->jump( $referer , $page_text , 1000);
    }
    
    
    /**
     * 设置急推房源
     */
    public function house_tag_set()
    {   
        //房源编号
        $rowid = $this->input->get( 'rowid' , TRUE );
        $secret_key = $this->input->get( 'secret_key' , TRUE );
        $result = array();
        
        //验证房源编号和提交验证码
        if( intval($rowid) > 0 && md5('HOUSE365_TAG_SET_'.$rowid) == $secret_key )
        {
            //经纪人账号uid
            $uid = $this->user_arr['uid'];

            //初始化房源操作类
            $this->load->model('rent_model');
            $houseinfo = array();
            $houseinfo = $this->rent_model->find_by_id($rowid);
            
            if( is_array( $houseinfo ) && !empty($houseinfo)    )
            {
                //加载房源急推属性类
                $this->load->model('rent_tag_model');
                $this->rent_tag_model->set_houseinfo($houseinfo);

                //检查此房源是否符合设置急推房源的标准
                $result = $this->rent_tag_model->check_tag_standard();

                if( isset($result) && $result['is_ok'] == 1 )
                {
                    $set_result = $this->rent_tag_model->set_tag();
                    
                    if($set_result)
                    {
                        $result['is_ok'] = 1;
                        $result['msg'] = '标签设置成功';
                        
                        //清理已用标签个数缓存
                        $this->load->model('statistics_model');
                        $this->statistics_model->jtLabelCount( $uid , 1);
					    //清到期缓存
						$this->load->model("house_tag_package_model");
						$this->house_tag_package_model->get_tag_valid($uid,1);
						$this->house_tag_package_model->get_tag_valid_num($uid,1);
                    }
                    else
                    {
                        $result['is_ok'] = 0;
                        $result['msg'] = '标签设置失败';
                    }
                }
            }
            else
            {
                $result['is_ok'] = 0;
                $result['msg'] = '房源信息不存在';  
            }
        }
        else
        {
            $result['is_ok'] = 0;
            $result['msg'] = '参数错误'; 
        }

        $result['msg'] = iconv( 'gb2312' , 'utf-8',  $result['msg'] ); 
        print_r(json_encode($result));
        exit;
    }
    
    
    /**
     * 设置急推房源
     */
    public function house_tag_cancel()
    {
        //房源编号
        $rowid = $this->input->get( 'rowid' , TRUE );
        $secret_key = $this->input->get( 'secret_key' , TRUE );
        $result = array();
        //验证房源编号和提交验证码
        if( intval($rowid) > 0  &&  md5('HOUSE365_TAG_SET_'.$rowid) == $secret_key )
        {
            //经纪人账号uid
            $uid = $this->user_arr['uid'];

            //初始化房源操作类
            $this->load->model('rent_model');
            $houseinfo = array();
            $this->rent_model->set_select_fields(array('id','uid','esta','istag'));
            $houseinfo = $this->rent_model->find_by_id($rowid);
            
            if( is_array( $houseinfo ) && !empty($houseinfo)    )
            {
                //加载房源急推属性类
                $this->load->model('rent_tag_model');
                $this->rent_tag_model->set_houseinfo($houseinfo);
                $set_result = $this->rent_tag_model->remove_tag();
                
                if($set_result)
                {
                    $result['is_ok'] = 1;
                    $result['msg'] = '取消标签成功';
                }
                else
                {
                    $result['is_ok'] = 0;
                    $result['msg'] = '取消标签失败';
                }
            }
            else
            {
                $result['is_ok'] = 0;
                $result['msg'] = '房源信息不存在';  
            }
        }
        else
        {   
            $result['is_ok'] = 0;
            $result['msg'] = '参数错误'; 
        }

        $result['msg'] = iconv( 'gb2312' , 'utf-8',  $result['msg'] ); 
        print_r(json_encode($result));
        exit;
    }
    
    
    /**
     * 设置立减标签
     */
    public function house_reduce_set()
    {
        //房源编号
        $rowid = $this->input->get( 'rowid' , TRUE );
        $secret_key = $this->input->get( 'secret_key' , TRUE );
        
        $result = array();
        //验证房源编号和提交验证码
        if( intval($rowid) > 0  &&  md5('HOUSE365_REDUCE_SET_'.$rowid) == $secret_key )
        {
            //经纪人账号uid
            $uid = $this->user_arr['uid'];

            //初始化房源操作类
            $this->load->model('rent_model');
            $houseinfo = array();
            $this->rent_model->set_select_fields(array('id','uid','esta','istag'));
            $houseinfo = $this->rent_model->find_by_id($rowid);
            
            if( is_array( $houseinfo ) && !empty($houseinfo)    )
            {
                //加载房源REAL房属性类
                $this->load->model('rent_reduce_model');
                $this->rent_reduce_model->set_houseinfo($houseinfo);
                $set_result = $this->rent_reduce_model->set_reduce();
                
                if($set_result)
                {
                    $result['is_ok'] = 1;
                    $result['msg'] = '设置立减标签成功';
                }
                else
                {
                    $result['is_ok'] = 0;
                    $result['msg'] = '设置立减标签失败';
                }
            }
            else
            {
                $result['is_ok'] = 0;
                $result['msg'] = '房源信息不存在';  
            }
        }
        else
        {   
            $result['is_ok'] = 0;
            $result['msg'] = '参数错误'; 
        }

        $result['msg'] = iconv( 'gb2312' , 'utf-8',  $result['msg'] ); 
        print_r(json_encode($result));
        exit;
    }
    
    /**
     * 取消立减标签
     */
    public function house_reduce_cancel()
    {
        //房源编号
        $rowid = $this->input->get( 'rowid' , TRUE );
        $secret_key = $this->input->get( 'secret_key' , TRUE );
        
        $result = array();
        //验证房源编号和提交验证码
        if( intval($rowid) > 0  &&  md5('HOUSE365_REDUCE_SET_'.$rowid) == $secret_key )
        {
            //经纪人账号uid
            $uid = $this->user_arr['uid'];

            //初始化房源操作类
            $this->load->model('rent_model');
            $houseinfo = array();
            $this->rent_model->set_select_fields(array('id','uid','esta','istag'));
            $houseinfo = $this->rent_model->find_by_id($rowid);
            
            if( is_array( $houseinfo ) && !empty($houseinfo)    )
            {
                //加载房源REAL房属性类
                $this->load->model('rent_reduce_model');
                $this->rent_reduce_model->set_houseinfo($houseinfo);
                $set_result = $this->rent_reduce_model->remove_reduce();
                
                if($set_result)
                {
                    $result['is_ok'] = 1;
                    $result['msg'] = '取消立减标签成功';
                }
                else
                {
                    $result['is_ok'] = 0;
                    $result['msg'] = '取消立减标签失败';
                }
            }
            else
            {
                $result['is_ok'] = 0;
                $result['msg'] = '房源信息不存在';  
            }
        }
        else
        {   
            $result['is_ok'] = 0;
            $result['msg'] = '参数错误'; 
        }

        $result['msg'] = iconv( 'gb2312' , 'utf-8',  $result['msg'] ); 
        print_r(json_encode($result));
        exit;
    }
    
    
    /**
     * 激活房源
     */
    public function active_house()
    {
        //房源编号
        $rowid = $this->input->get( 'rowid' , TRUE );
        $secret_key = $this->input->get( 'secret_key' , TRUE );
        $result = array();
        //验证房源编号和提交验证码
        if( intval($rowid) > 0  &&  md5('HOUSE365_ACTIVE_HOUSE_'.$rowid) == $secret_key )
        {
            //经纪人账号uid
            $uid = $this->user_arr['uid'];
			$agentcode = $this->user_arr['agentcode'];
            $package_id = $this->user_arr['package_id'];
            
            $this->load->model('broker_model');
            $this->load->model('package_model');
            $package = $this->package_model->find_by_id($package_id);
            
            //判断源活房源是否有否超过上限
            $valid_house_num = $this->broker_model->valid_house_num();
            
            if($valid_house_num < $package["package_valid_num"])
            {
                //初始化房源操作类
                $this->load->model('rent_model');
                $houseinfo = array();
                $this->rent_model->set_select_fields(array('id','esta'));
                $houseinfo = $this->rent_model->find_by_id($rowid);

                if( is_array( $houseinfo ) && !empty($houseinfo)    )
                {
                    //加载房源急推属性类
                    $this->load->model('rent_operate_model'); 
                    $set_result = $this->rent_operate_model->active_house($rowid);

                    if($set_result)
                    {	
                        //加载门店类
                        $this->load->model('agency_model');
                        $relation_info = array();
                        $relation_info = $this->agency_model->get_relation_by_agentcode($agentcode);
                        $domain = isset($relation_info['cat_id']) ? $relation_info['cat_id'] : 0;
                        $parentcode = '';
                        if( is_array($relation_info) && !empty($relation_info))
                        {	 
                            $parentcode = isset($relation_info['parentcode']) ? $relation_info['parentcode'] : '';
                        }
                        else
                        {	
                            $parentinfo = array();
                            $select_array = array('parentcode');
                            $this->agency_model->set_select_fields($select_array);
                            $parentinfo = $this->agency_model->get_company_info_by_code($agentcode);
                            $parentcode = isset($parentinfo['parentcode']) ? $parentinfo['parentcode'] : '';
                        }
                        $tbl = 'rent';
						/***提交房源操作日志给MYSQL(经纪人日志查询),[$msg:3-房源再发布] ***/
						$this->rent_model->action_log( $agentcode , $uid , $tbl , $rowid , 3);
                        //加载中间件统计类
                        $this->load->library('statistics');
                        /***通过接口提交操作日志给中间件，operatetype 1:新增 2刷新 3删除 4失效 5再发布 ***/
                        $this->statistics->sub_operatecount( $uid , $agentcode , 5 , $rowid , '' , $tbl , $domain , $parentcode );

                        $result['is_ok'] = 1;
                        $result['msg'] = '激活房源成功';
                    }
                    else
                    {
                        $result['is_ok'] = 0;
                        $result['msg'] = '激活房源失败';
                    }
                }
                else
                {
                    $result['is_ok'] = 0;
                    $result['msg'] = '房源信息不存在';  
                }
            }
            else
            {
                $result['is_ok'] = 0;
                $result['msg'] = '激活房源已满';  
            }
        }
        else
        {   
            $result['is_ok'] = 0;
            $result['msg'] = '参数错误'; 
        }

        $result['msg'] = iconv( 'gb2312' , 'utf-8',  $result['msg'] ); 
        print_r(json_encode($result));
        exit;
    }
    
    
    /**
     * 删除房源
     */
    public function delete_house()
    {
        //房源编号
        $rowid = $this->input->get( 'rowid' , TRUE );
        $secret_key = $this->input->get( 'secret_key' , TRUE );
        $result = array();
        
        //验证房源编号和提交验证码
        if( intval($rowid) > 0  &&  md5('HOUSE365_DELETE_HOUSE_'.$rowid) == $secret_key )
        {
            //经纪人账号uid
            $uid = $this->user_arr['uid'];

			//门店账号
			$agentcode = $this->user_arr['agentcode'];

            //初始化房源操作类
            $this->load->model('rent_model');
            $houseinfo = array();
            $this->rent_model->set_select_fields(array('id','esta'));
            $houseinfo = $this->rent_model->find_by_id($rowid);
            
            if( is_array( $houseinfo ) && !empty($houseinfo)    )
            {
                //加载房源急推属性类
                $this->load->model('rent_operate_model'); 
                $set_result = $this->rent_operate_model->delete_house($rowid);
                
                if($set_result)
                {	
                    //加载门店类
                    $this->load->model('agency_model');
                    $relation_info = array();
                    $relation_info = $this->agency_model->get_relation_by_agentcode($agentcode);
                    $domain = isset($relation_info['cat_id']) ? $relation_info['cat_id'] : 0;
                    if( is_array($relation_info) && !empty($relation_info))
                    {	 
                        $parentcode = isset($relation_info['parentcode']) ? $relation_info['parentcode'] : '';
                    }
                    else
                    {	
                        $parentinfo = array();
                        $select_array = array('parentcode');
                        $this->agency_model->set_select_fields($select_array);
                        $parentinfo = $this->agency_model->get_company_info_by_code($agentcode);
                        $parentcode = isset($parentinfo['parentcode']) ? $parentinfo['parentcode'] : '';
                    }

                    $tbl = 'rent';
                    //加载中间件统计类
                    $this->load->library('statistics');
                    /***通过接口提交操作日志给中间件，operatetype 1:新增 2刷新 3删除 4失效 5再发布 ***/
                    $this->statistics->sub_operatecount( $uid , $agentcode , 3 , $rowid , '' , $tbl , $domain , $parentcode );

                    /***提交房源操作日志给MYSQL(经纪人日志查询),[$msg:4-失效房源] ***/
                    $this->rent_model->action_log( $agentcode , $uid , $tbl , $rowid , 0);

                    $result['is_ok'] = 1;
                    $result['msg'] = '删除房源成功';
                }
                else
                {
                    $result['is_ok'] = 0;
                    $result['msg'] = '删除房源失败';
                }
            }
            else
            {
                $result['is_ok'] = 0;
                $result['msg'] = '房源信息不存在';  
            }
        }
        else
        {   
            $result['is_ok'] = 0;
            $result['msg'] = '参数错误'; 
        }

        $result['msg'] = iconv( 'gb2312' , 'utf-8',  $result['msg'] ); 
        print_r(json_encode($result));
        exit;
    }
    
    
    /**
     * 房源申诉
     */
    function house_appeal()
    {   
        //房源编号
        $rowid = $this->input->get( 'rowid' , TRUE );
        $reason = $this->input->get( 'reason' , TRUE );
        $secret_key = $this->input->get( 'secret_key' , TRUE );

		//2015-7-22 zhou添加申诉图片 ------------start------->
		$p_filenames = $this->input->get( 'p_filenames' , TRUE );
		
		$pics_arr =explode(',',substr($p_filenames,0,strlen($p_filenames)-1));
		//2015-7-22 zhou添加申诉图片 ------------end------->	
        $result = array();
        //验证房源编号和提交验证码
        if( intval($rowid) > 0  &&  md5('HOUSE365_SELL_APPEAL_'.$rowid) == $secret_key )
        {
            if ( $reason != "" ) 
            {
                $data_info = array();
                $reason = urldecode($reason);
                $data_info['appeal'] = iconv( "UTF-8" , "GBK" , $reason);
                $data_info['appealtime'] = time();
                $data_info['esta'] = 2;
				$data_pic_info['pics_arr']= $pics_arr;
                $this->load->model('rent_freeze_model');
                $app_result = FALSE;
                $app_result = $this->rent_freeze_model->house_appeal ( $rowid , $data_info);
				if(is_array($pics_arr) && $pics_arr[0])
				{
					$pic_result = FALSE;
					$pic_result = $this->rent_freeze_model->house_pic_insert ( 'rent',$rowid , $data_pic_info);
				}
				else
				{	
					
					$pic_result = $this->rent_freeze_model->house_pic_delete ('rent',$rowid);
					$pic_result = TRUE;
				}
                if($app_result && $pic_result)
                {
                    $result['is_ok'] = 1;
                    $result['msg'] = '申诉提交成功，工作人员会第一时间处理您的申诉';
                }
                else
                {
                    $result['is_ok'] = 0;
                    $result['msg'] = '提交失败，请致电客服热线'; 
                }
            }
            else
            {
                $result['is_ok'] = 0;
                $result['msg'] = '请填写申诉理由';
            }
        }
        else
        {
            $result['is_ok'] = 0;
            $result['msg'] = '参数错误'; 
        }
        
        $result['msg'] = iconv( 'gb2312' , 'utf-8',  $result['msg'] ); 
        print_r(json_encode($result));
        exit;
    }
    
    
    /**
    * 根据表单提交参数，获取查询条件
    */
    private function _get_cond_str( $form_param )
    {   
        $cond_where = '';
        
        //房源类型
        if( isset($form_param['infotype']) && !empty($form_param['infotype']) )
        {
           $cond_where .= " AND infotype = '".intval($form_param['infotype'])."'";
        }
        
        //房源价格参数
        if ( isset($form_param["price_rent"]) && !empty($form_param["price_rent"]) ) 
        {  
            switch($form_param["price_rent"])
            {
                case 1:	
                    $cond_where .= " AND price <= '800' ";
                    break;
                case 2:
                    $cond_where .= " AND price > '800' and price <= '1200' ";
                    break;
                case 3:
                    $cond_where .= " AND price > '1200' and price <= '2000' ";
                    break;
                case 4:
                    $cond_where .= " AND price > '2000' and price <= '3000' ";
                    break;
                case 5:
                    $cond_where .= " AND price > '3000' and price <= '5000' ";
                    break;
                case 6:
                    $cond_where .= " AND price > '5000' and price <= '10000' ";
                    break;
                case 7:
                    $cond_where .= " AND price > '10000'";
                    break;
            }       
        }
        
        //面积条件
        if (isset($form_param["buildarea"]) && !empty($form_param["buildarea"])) 
        {
            switch($form_param["buildarea"])
            {
                case 1:	
                    $cond_where .= " AND buildarea <= '40' ";
                    break;
                case 2:
                    $cond_where .= " AND buildarea > '40' AND buildarea <= '60' ";
                    break;
                case 3:
                    $cond_where .= " AND buildarea > '60' AND buildarea <= '80' ";
                    break;
                case 4:
                    $cond_where .= " AND buildarea > '80' AND buildarea <= '100' ";
                    break;
                case 5:
                    $cond_where .= " AND buildarea > '100' AND buildarea <= '120' ";
                    break;
                case 6:
                    $cond_where .= " AND buildarea > '120' AND buildarea <= '144' ";
                    break;
                case 7:
                    $cond_where .= " AND buildarea > '144'  AND  buildarea <= '200' ";
                    break;
                case 8:
                    $cond_where .= " AND buildarea > '200'  AND  buildarea <= '400' ";
                    break;
                case 9:
                    $cond_where .= " AND buildarea > '400' ";
                    break;
            }       
        }
        
        //房型条件
        if (isset($form_param['roomtype']) && !empty($form_param['roomtype'])) 
        {
            switch ($form_param['roomtype']) 
            {
              case 1:
                    $cond_where .= " AND  room = '1'";
                    break;
              case 2:
                    $cond_where .= " AND   room = '2' ";
                    break;
              case 3:
                    $cond_where .= " AND  room = '3' ";
                    break;
              case 4:
                    $cond_where .= " AND  room = '4' ";
                    break;
              case 5:
                    $cond_where .= " AND  room = '5' ";
                    break;
			case 6:
                    $cond_where .= " AND  room > '5' ";
                    break;
            }
        }
        
        //关键词条件
        if (isset($form_param['keywords']) && !empty($form_param['keywords']) && $form_param['k_id']) 
        {   
            $keyword = trim(strip_tags($form_param['keywords']));
            switch ($form_param['k_id']) 
            {
                case 1:
                    $cond_where .= " AND blockshowname LIKE '%".$keyword."%'";
                    break;
                case 2:
                    $cond_where .= " AND id = '".$keyword."'";
                    break;
                case 3:
                    $cond_where .= " AND ownid = '".$keyword."'";
                    break;
            }
        }

		//小区编号
		if (isset($form_param['blockid']) && !empty($form_param['blockid']) && $form_param['blockid'] > 0) 
        {	
			$blockid = intval($form_param['blockid']);
			$cond_where .= " AND blockid = '".$blockid."'";
		}

        //全部房源条件
        if ( isset($form_param['roomcategory']) && !empty($form_param['roomcategory']) ) 
        {
            switch ($form_param['roomcategory']) 
            {
                case 1:
                    $cond_where .= ' AND  isstar = 0 ';
                    break;
                case 2:
                    $cond_where .= ' AND  isstar = 3 ';
                    break;
                case 3:
                    $cond_where .= ' AND  istag = 1 ';
                    break;
                case 4:
                    $cond_where .= ' AND  isreal = 1 ';
                    break;
            }
        }
        return $cond_where;
    }
    
    
    //获取排序字符串
    private function _get_orderby_arr( $order_val ) 
    {   
        $arr_order = array();
        
        switch ($order_val) 
        {
            case 1:
                $arr_order['order_key'] = 'updatetime' ;
                $arr_order['order_by'] = 'DESC';
                break;
            case 2:
                $arr_order['order_key'] = 'updatetime' ;
                $arr_order['order_by'] = 'ASC';
                break;
            case 3:
                $arr_order['order_key'] = 'creattime' ;
                $arr_order['order_by'] = 'DESC';
                break;
            case 4:
                $arr_order['order_key'] = 'creattime' ;
                $arr_order['order_by'] = 'ASC';
                break;
            case 5:
                $arr_order['order_key'] = 'price' ;
                $arr_order['order_by'] = 'ASC';
                break;
            case 6:
                $arr_order['order_key'] = 'price' ;
                $arr_order['order_by'] = 'DESC';
                break;
            case 7:
                $arr_order['order_key'] = 'buildarea' ;
                $arr_order['order_by'] = 'ASC';
                break;
            case 8:
                $arr_order['order_key'] = 'buildarea' ;
                $arr_order['order_by'] = 'DESC';
                break;
            default:
                $arr_order['order_key'] = 'updatetime' ;
                $arr_order['order_by'] = 'DESC';
        }

        return $arr_order;
    }

    /**
     * 加载swfupload上传文件组件
     */
    public function swf_upload()
    {
        $this->load->view('pic_inc');
    }
}
/* End of file rent.php */
/* Location: ./application/zsb/controllers/rent.php */