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

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

    /**
    * 当前用户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('sell_model');
        $this->load->helper('common_house_helper');

        //可发出售和出租的权限 @todo
        $is_permission = $this->sell_model->get_public_permission($this->user_arr['package_id']);

        if ($is_permission === false) 
        {
            $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['css'] = load_css('zsb/css/v1.0/style1.css,zsb/css/v1.0/autocomlete.css');
        
        //页面加载需要的数据
        $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.js');
        $data_page['house'] = $this->config->item('house');
        $data_page['upload_pic_url'] = $this->config->item('base_url') . 'pic/house/';
        
        $this->view('house_manage', 'sell_modify', $data_page);
    }
    
    /**
     * 默认首页
     */
    public function index()
    {
        $this->manage();
    }
    
    /**
     * 发布房源页面
     */
    public function add() 
    { 
        $uid = $this->user_arr['uid'];
        $package_id = $this->user_arr['package_id'];
        $tbl = $this->sell_model->get_tbl();
        //可发出售和出租的权限 加到__construct
        //判断库存是否已满 房源列表页地址，用于跳转的
        $url_manage = $this->sell_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->sell_model->set_select_fields(array('blockid', 'blockshowname'));
        $data_page['publish_block'] = $this->sell_model->find_publish_block($uid);
        //房源特色
        $this->load->model('house_feature');
        $data_page['feature_arr'] = $this->house_feature->find_feature($tbl, 1);
        $data_page['feature'] = $this->house_feature->find_house_feature('', $tbl);
        //发布多图和普通房源添加成长值的分值
        $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->sell_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['documentation'] = $this->config->item('documentation');
        //页面基本参数
        $data_page['method'] = 'add';
        $data_page['url_house_submit'] = $this->sell_model->find_func_url('insert');
        //统计代码
        $data_page['page_title'] = '房源管理-发布出售';
		$data_page['google_analytics'] = get_ga_js_code('/房源管理/发布出售/');
        //加载模板
        $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->sell_model->get_tbl();
        $nowtime = time();
        //二、发布出售权限
        //房源列表页地址，用于跳转的
        $url_manage = $this->sell_model->find_func_url();
        //控制发布房源的时间限制
        $session_key = $uid . '_last_sell_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);
        //四、判断源活房源是否有否超过上限
        $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方式提交
         * update 2012-5-7 xz
         */
        $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));
        $allow_infotype = $this->sell_model->get_public_infotype_permission($package_id);
        if (!in_array($fields_values['infotype'], $allow_infotype)) 
        {
            echo "<script>alert('没有权限发布此类型房源，请重新选择');history.go(-1);</script>";
            exit;
        }
        $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['priceterm'] = $this->input->post('priceterm', true);
        $fields_values['pricetype'] = $this->input->post('pricetype', true);
        $fields_values['buildarea'] = $this->input->post('buildarea', true) 
                ? $this->input->post('buildarea', true) : 1;
        if( 3 > $fields_values['buildarea'] || $fields_values['buildarea'] > 150000)
        {
            echo "<script>alert('面积必须在3-150000平米之间');history.go(-1);</script>";
            exit;
        }
        $fields_values['averprice'] = round(10000 * $fields_values['price'] 
                / $fields_values['buildarea'], 2);
        if (500 > $fields_values['averprice'] || $fields_values['averprice'] > 250000) {
            echo "<script>alert('当前单价为：" . $fields_values['averprice'] 
                    . "元/平米，单价必须在2000-300000元/平米之间');history.go(-1);</script>";
            exit;
        }
        //只有物业类型 住宅 别墅 有室、厅等参数
        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);
        if ($fields_values['infotype'] == 6)
        {
            $fields_values['buildyear'] = $this->input->post('buildyear1', true);
        } 
        else
        {
            $fields_values['buildyear'] = $this->input->post('buildyear', true);
        }
        $fields_values['contactor'] = $this->user_arr['truename'];
        $fields_values['telno'] = $session_info['telno'];
        $fields_values['creattime'] = time();
        $fields_values['expiretime'] = $fields_values['infotype'] == 1 ? strtotime("+60 days") : strtotime("+90 days");
        $fields_values['updatetime'] = time();
        $fields_values['lucupdatetime'] = $fields_values['updatetime'];
        $fields_values['ip'] = get_ip();
        /*******************基本信息结束***************************/
        
        /*******************补充信息开始***************************/
        if ($fields_values['infotype'] == 2) 
        {
            $housekind = $this->input->post('housekind', true);
        } 
        else if ($fields_values['infotype'] == 6)
        {
            $housekind = $this->input->post('housekindname', true);
        }
        else
        {
            $fields_values['housekind'] = '';
        }
        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;
        }
        //基础设施
        $baseservice = $this->input->post('baseservice', true);
        if ($baseservice)
        {
            $fields_values['baseservice'] = implode(",", $baseservice);
        }
        $fields_values['ownid'] = trim($this->input->post('ownid', true));
        /*******************补充信息结束***************************/
        
        /*******************详细信息开始***************************/
        $fields_values['address'] = htmlspecialchars(csubstr(trim(
                filterSpace($this->input->post('address', true))),60));
        $fields_values['remark'] = $this->input->post('remark');
        //房源特色
        $fields_values['feature'] = '';
        $feature = $this->input->post('feature', true);
        if(is_array($feature) && !empty($feature))
        {
            $this->load->model('house_feature');
            $feature_arr = $this->house_feature->find_feature($tbl, $fields_values['infotype']);
            foreach($feature as $val)
            {	
                $val = intval($val);
                if($feature_arr[$val] != '')
                {
                    $fields_values['feature'] .= '$'.$val;
                }
            }
            if($fields_values['feature'] != '')
            {
                $fields_values['feature'] .= '$';
            }
        }
       /*******************详细信息结束***************************/
        //插入房源信息，并返回房源编号
        $house_id = $this->sell_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']
                );
                $pic_check = $this->sell_model->insert_house_pic($pics,
                $tbl, $house_id, $pic1, $blockid);
                $pic_check_arr = $pic_check['pic_check'];
                //更新封面图
                $this->sell_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('sell_star_model');
            $this->sell_star_model->set_houseinfo($fields_values);
            //$this->sell_star_model->set_rowid($house_id);
            $is_star_house = $this->sell_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;
                //设置房源属性为多图
                $this->sell_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->sell_model->action_log($companycode, $uid, $tbl, $house_id, $logesta);
            if ($fields_values['esta'] == 1) {
                //刷新房源
                refresh_house($uid, $tbl, $house_id);
                $this->sell_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;
        }
        else
        {
            $page_text = "抱歉，房源发布失败!";
        }
        $this->jump($url_manage, $page_text, 3000);
    }
    
    /**
     * 展示房源修改页面
     */
    public function modify($id, $tab = '') 
    {
        $uid = $this->user_arr['uid'];
        $package_id = $this->user_arr['package_id'];
        $tbl = $this->sell_model->get_tbl();
        
        //房源列表页地址
        $url_manage_module = $this->sell_model->find_func_url();
        if (!$id)
        {
            $this->jump($url_manage_module, '参数不合法');
            return;
        }
        //查找有无此房源记录，没有则转到列表页
        $house_detail = $this->sell_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['block'] = $block;
        } 
        else
        {
            $this->load->model('street_model');
            $street = $this->street_model->find_by_id($house_detail['streetid']);
            $house_detail['block'] = array(
                'district' => $house_detail['district'],
                'blockname' => $house_detail['blockshowname'],
                'streetid' => $house_detail['streetid'],
                'streetname' => $street['streetname'],
                'address' =>  $house_detail['address'],
                'blockid' => 0
            );
        }
        //房源图片
        $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 . '/';
        $data_page['method'] = 'modify';
        $data_page['url_house_submit'] = $this->sell_model->find_func_url('update');
        //发布多图和普通房源添加成长值的分值
        $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->sell_model->
                get_public_infotype_permission($package_id);
        //房源特色
        $this->load->model('house_feature');
        $data_page['feature_arr'] = $this->house_feature->find_feature($tbl, $house_detail['infotype']);
        $data_page['feature'] = $this->house_feature->
                find_house_feature($house_detail['feature'], $tbl);
        $data_page['tab'] = $tab;
        
        //当天发布共获得多少成长值
        $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['documentation'] = $this->config->item('documentation');
        //渲染页面
        $data_page['page_title'] = '房源管理-修改出售';
		$data_page['google_analytics'] = get_ga_js_code('/房源管理/修改出售/');
        $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->sell_model->get_tbl();
        $package_id = $this->user_arr['package_id'];
        $house_id = $this->input->post('id', true);
        //查询房源没修改之前的信息
        $this->sell_model->set_select_fields(array('isstar', 'esta'));
        $before_info = $this->sell_model->find_by_id($house_id);
        //冻结房源不允许修改
        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));
        $allow_infotype = $this->sell_model->get_public_infotype_permission($package_id);
        if (!in_array($fields_values['infotype'], $allow_infotype)) 
        {
            echo "<script>alert('没有权限发布此类型房源，请重新选择');history.go(-1);</script>";
            exit;
        }
        /***
        $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['priceterm'] = $this->input->post('priceterm', true);
        $fields_values['pricetype'] = $this->input->post('pricetype', true);
        $fields_values['buildarea'] = $this->input->post('buildarea', true) 
                ? $this->input->post('buildarea', true) : 1;
        if(3>$fields_values['buildarea'] || $fields_values['buildarea']>150000)
        {
            echo "<script>alert(面积必须在3-150000平米之间');history.go(-1);</script>";
            exit;
        }
        $fields_values['averprice'] = round(10000 * $fields_values['price'] 
                / $fields_values['buildarea'], 2);
        if (500 > $fields_values['averprice'] || $fields_values['averprice'] > 250000) {
            echo "<script>alert('当前单价为：" . $fields_values['averprice'] 
                    . "元/平米，单价必须在2000-300000元/平米之间');history.go(-1);</script>";
            exit;
        }
        //只有物业类型 住宅 别墅 有室、厅等参数
        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);
        if ($fields_values['infotype'] == 6)
        {
            $fields_values['buildyear'] = $this->input->post('buildyear1', true);
        } 
        else
        {
            $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();
        /*******************基本信息结束***************************/
        
        /*******************补充信息开始***************************/
        if ($fields_values['infotype'] == 2) 
        {
            $housekind = $this->input->post('housekind', true);
        } 
        else if ($fields_values['infotype'] == 6)
        {
            $housekind = $this->input->post('housekindname', 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;
        }
        //基础设施
        $baseservice = $this->input->post('baseservice', true);
        if ($baseservice)
        {
            $fields_values['baseservice'] = implode(",", $baseservice);
        }
        $fields_values['ownid'] = trim($this->input->post('ownid', true));
        /*******************补充信息结束***************************/
        
        /*******************详细信息开始***************************/
        $fields_values['address'] = htmlspecialchars(csubstr(trim(
                filterSpace($this->input->post('address', true))),60));
        $fields_values['remark'] = $this->input->post('remark');
        //房源特色
        $fields_values['feature'] = '';
        $feature = $this->input->post('feature', true);
        if(is_array($feature) && !empty($feature))
        {
            $this->load->model('house_feature');
            $feature_arr = $this->house_feature->find_feature($tbl, $fields_values['infotype']);
            foreach($feature as $val)
            {	
                $val = intval($val);
                if($feature_arr[$val] != '')
                {
                    $fields_values['feature'] .= '$'.$val;
                }
            }
            if($fields_values['feature'] != '')
            {
                $fields_values['feature'] .= '$';
            }
        }
        //房源封面图
        $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->sell_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 sell set esta = 5 where id in(33899521, 37700775) and uid = 10000040;
        $affected_rows = $this->sell_model->update($fields_values, $house_id, $uid);     
        //设置多图、标签、real房
        $fields_values['id'] = $house_id;
        $fields_values['uid'] =  $this->user_arr['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('sell_star_model');
            $this->sell_star_model->set_houseinfo($fields_values);
            $is_star_house = $this->sell_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)
                    {
                        $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->sell_star_model->set_star();
                    }
                }
            } 
            else 
            {
                //设置房源属性为多图
                $this->sell_star_model->remove_star(); 
                $this->load->model('sell_tag_model');
                $this->sell_tag_model->set_houseinfo($fields_values);
                //2011-11-30 同步设置标签失效
				$this->sell_tag_model->remove_tag();
                //取消REAL房
                $this->load->model('sell_real_model');
                $this->sell_real_model->set_houseinfo($fields_values);
                $this->sell_real_model->remove_real();
                //取消新房直售
                $this->load->model('sell_nofee_model');
                $this->sell_nofee_model->set_houseinfo($fields_values);
                $this->sell_nofee_model->remove_nofee();
            }
            $page_text = '房源修改成功!' . $growthMessage;
        }
        else 
        {
            $page_text = '抱歉，修改房源信息失败!';
        }
        //跳转到之前修改的页面
        $tab = $this->input->post('tab', true);
        $this->jump($this->sell_model->find_func_url() . $tab, $page_text, 3000);
    }

    /**
     * 物理删除房源，如需更改房源状态为删除，请调用update方法
     */
    public function delete()
    {
        //delete from  sell where id = 33899521 and uid = 10000040;
        $this->sell_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;
        
        //客户经理
        if( isset($broker_info) && isset($broker_info['master']) && $broker_info['master'] != '')
        {
            $broker_info['accout_manager'] = $this->broker_model->get_account_manager($broker_info['master']);
        }
        
        //房源核心数组
        $house = $this->config->item('house');
        $house['roomcategory'] = array( 
                                '1' => '非多图' , '2' => '多图', '3' => '急推', 
                                '4' => 'REAL房' , '5' => '新房直售'
                                );
        //加载房源类
        $this->load->model('sell_model');
        $esta_arr = array(); //房源状态数组
        $esta_arr = $this->sell_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->sell_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','averprice','priceterm','pricetype','fitment','contactor',
               'telno','creattime','updatetime','expiretime','isstar','istag','nofee');
            $this->sell_model->set_select_fields($select_fields);
            $data_info = $this->sell_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');
        
        //预约方案
        $reserve_info = array();
		$publish_block = array();
        //加载二手房Real房属性类
        $this->load->model('sell_real_model');
        $broker_info['limit_apply_real_num'] = $this->sell_real_model->get_today_apply_num();  
        $broker_info['apply_real_num'] = $this->sell_real_model->apply_real_num_today($uid , 1);
        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('sell_star_model');

            if( $house_esta == 'active')
            {
                //加载刷新日志类
                $this->load->model('log_refresh');
                
                //加载急推属性类
                $this->load->model('sell_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();

                //经纪人竞投房源
                $grow_bid_house_record = new GrowthBidHouseRecordFinish();
                $bidHouseRecord = $grow_bid_house_record->getBidFinishByBorkerId($uid);
            }
			
			if($house_esta == 'active' || $house_esta == 'invalid')
			{
				//我发布的小区
				$block_fields = array('blockid','blockshowname');
				$this->sell_model->set_select_fields($block_fields);
				$publish_block = $this->sell_model->find_publish_block($uid , $house_esta);
			}


            //冻结房源类
            if( $house_esta == 'frozen')
            {
                $this->load->model('sell_freeze_model');
                $house['freeze_esta'] = $this->sell_freeze_model->get_freeze_esta();
            }

            //房源信息数组
            $house_info = array();
            for( $i = 0 ; $i < $row_num ; $i ++ )
            {   
                //房源地址
                $data_info[$i]['info_url'] =  get_sellinfo_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->sell_model->get_modify_house_url($data_info[$i]['id']);
                
                //是否为多图房源
                $this->sell_star_model->set_houseinfo($data_info[$i]);
                $data_info[$i]['is_star_result'] = $this->sell_star_model->is_star();
                
                //激活房源页面数据
                if( $house_esta == 'active')
                {
                    //是否为急推房源
                    $this->sell_tag_model->set_houseinfo($data_info[$i]);
                    $data_info[$i]['is_tag_result'] = $this->sell_tag_model->is_tag();
                    
                    //急推标准
                    if($data_info[$i]['is_tag_result'] === FALSE)
                    {
                        $data_info[$i]['tag_standard'] = $this->sell_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->sell_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->sell_tag_model->tag_exipire_days($data_info[$i]['house_tag_info']['expiretime']);
						}
					}	

                    //是否新房直售
                    $this->sell_nofee_model->set_houseinfo($data_info[$i]);
                    $data_info[$i]['is_nofee_result'] = $this->sell_nofee_model->is_nofee();
                    
                    //新房直售标准
                    if($data_info[$i]['is_nofee_result'] === FALSE)
                    {   
                        $data_info[$i]['nofee_standard'] = $this->sell_nofee_model->check_nofee_standard();
                    }

                    //是否Real房
                    $this->sell_real_model->set_houseinfo($data_info[$i]);
                    $data_info[$i]['is_real_result'] =  $this->sell_real_model->is_real();
                    
                    //REAL房标准
                    if($data_info[$i]['is_real_result'] === FALSE)
                    {   
                        $data_info[$i]['real_standard'] = $this->sell_real_model->check_real_standard();
                    }
                    
                    //刷新次数
                    $data_info[$i]['refresh_num'] = 
                    $this->log_refresh->refresh_num_by_id( $data_info[$i]['id'],'sell', $data_info[$i]['updatetime']);
					
                    //是否成功参加竞投
                    $data_info[$i]['is_bidhouse_result'] = FALSE;
                    if (is_array($bidHouseRecord) && !empty($bidHouseRecord)) 
                    {
                        foreach($bidHouseRecord as $v) 
                        {   
                            if($v['house_id'] == $data_info[$i]['id'] )
                            {
                                $data_info[$i]['is_bidhouse_result'] = TRUE;
                            }
                        }
                    }

					//今天是否在竞投房源日
					$periodsHouse = $growthBidPeriods->currentBidPeriods(2);
					if ($periodsHouse['status'] == 1) //竞投日
					{
						//获取经纪人竞投的房源
						$growth_bid_house_on = GrowthBidRecordFactory::getRecordClassByTime('house', $periodsHouse['status']);
						$bid_house_on = $growth_bid_house_on->getBidHouseByBrokerId($uid, $periodsHouse['id']);
						if (isset($bid_house_on) && !empty($bid_house_on)) {
							$bid_house_on = SqlCombinHelper::changeToKeyArray($bid_house_on, 'house_id');
						} else {
							$bid_house_on = array(); 
						}
					}

                    //小区专家等级
                    /*$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'] = '';
                    }*/
					//房源是否在竞投中
                    if (isset($bid_house_on) && !empty($bid_house_on) 
                        && isset($bid_house_on[$data_info[$i]['id']])) 
                    {
                        $data_info[$i]['is_bidon_house'] = TRUE;
                    }
                }
                
                //到期天数
                $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'] , 'sell');//xue
                 // $data_info[$i]['click_num_y'] = 0;
                
                if( $house_esta == 'frozen')
                {
                    //冻结信息
                    $this->sell_freeze_model->set_select_fields(array('id','esta','rowid','reason','freezetime'));
                    $data_info[$i]['freeze_info'] = $this->sell_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('sell' , $arr_rowid);
            }
        }

        //是否显示分页
        $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['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;
        }
        else
        {
            $statistic_data['tag_limit'] = '--';
            $statistic_data['tag_count_today'] = '--';
            $statistic_data['tag_remain'] = '--';
        }

        //新房直售
        if($broker_info['nofee_num'] > 0)
        {
            $statistic_data['nofee_limit'] = $this->sell_nofee_model->get_nofee_num_limit($uid);
            $statistic_data['nofee_today'] = $this->sell_nofee_model->get_nofee_num_by_uid($uid);
            $statistic_data['nofee_limit'] = $statistic_data['nofee_limit'] > $statistic_data['nofee_today'] ?
            $statistic_data['nofee_limit'] - $statistic_data['nofee_today'] : 0;
        }
        else
        {
            $statistic_data['nofee_limit'] = '--';
            $statistic_data['nofee_today'] = '--';
            $statistic_data['nofee_limit'] = '--';
        }

        //Real房
        if($broker_info['real_limit'] > 0)
        {
            $statistic_data['real_limit'] = $this->stat->real_num_limit($uid);
            $statistic_data['real_today'] = $this->stat->real_num_today($uid);
            $statistic_data['real_remain'] = $statistic_data['real_today'] <= $statistic_data['real_limit'] ? 
            $statistic_data['real_limit'] - $statistic_data['real_today'] : 0 ;
        }
        else
        {
            $statistic_data['real_limit'] = '--';
            $statistic_data['real_today'] = '--';
            $statistic_data['real_remain'] = '--';
        }

		//冻结房源个数
		$cond_where_forzen = "uid = '".$uid."' AND esta = 5  AND infofrom = '5'";
		$statistic_data['forzen_house_num'] = $this->sell_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'); //需要加载的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;
        $data['post_param']  = $post_param;
		$data['publish_block']  = $publish_block;
        $data['data_info']  = $data_info;
        $data['reserve_info']  = $reserve_info;
        $data['broker_info']  = $broker_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');
        
        //加载模板
        $template_name = $esta == 1 ? 'sell_manage' : 'sell_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 = 'sell';
        
        //分发处理
        switch ($actiontype) 
        {
            case 'invalid_house':
                $invalid_num = 0;
                
                //初始化房源操作类
                $this->load->model('sell_operate_model');
                
                /*** 1、失效房源 ***/
                $invalid_num = $this->sell_operate_model->invalid_house($arr_id);
                if( $invalid_num > 0 )
                {   
                    //加载中间件统计类
                    $this->load->library('statistics');
                    
                    //加载房源急推属性类
                    $this->load->model('sell_tag_model');
                    
                    //加载Real房属性类
                    $this->load->model('sell_real_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;
                    $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'] : '';
                    }
                    
                    foreach( $arr_id as $rowid )
                    {   
                        /*** 2、失效标签、Real房 ****/
                        $house_info = array('id'=> $rowid);
                        $this->sell_tag_model->set_houseinfo($house_info);
                        $this->sell_tag_model->remove_tag();
                        
                        $this->sell_real_model->set_houseinfo($house_info);
                        $this->sell_real_model->remove_real();
                        
                        /*** 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->sell_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('sell_operate_model');
                
                /*** 1、删除房源 ***/
                $delete_num = $this->sell_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;
                    $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'] : '';
                    }
                    
                    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->sell_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) )
                {
                    $errornum = 0;
                    
                    //加载刷新函数文件
                    $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->sell_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,
                        );
                        
                        $ctime = date('Y-m-d');
						//成长值
                        $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>";
                        }
                        
                        //清除今日刷新总量
                        $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('sell_model');
            $houseinfo = array();
            $houseinfo = $this->sell_model->find_by_id($rowid);
            
            if( is_array( $houseinfo ) && !empty($houseinfo)    )
            {
                //加载房源急推属性类
                $this->load->model('sell_tag_model');
                $this->sell_tag_model->set_houseinfo($houseinfo);

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

                if( isset($result) && $result['is_ok'] == 1 )
                {
                    $set_result = $this->sell_tag_model->set_tag();
                    
                    if($set_result)
                    {
                        $result['is_ok'] = 1;
                        $result['msg'] = '标签设置成功';
                        
                        //清理已用标签个数缓存
                        $this->load->model('statistics_model');
                        $this->statistics_model->jtLabelCount( $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_nofee_set()
    {
        //房源编号
        $rowid = $this->input->get( 'rowid' , TRUE );
        $secret_key = $this->input->get( 'secret_key' , TRUE );
        $result = array();
        
        //验证房源编号和提交验证码
        if( intval($rowid) > 0 && md5('HOUSE365_NOFEE_SET_'.$rowid) == $secret_key )
        {   
            //经纪人账号uid
            $uid = $this->user_arr['uid'];

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

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

                if( isset($result) && $result['is_ok'] == 1 )
                {
                    $set_result = $this->sell_nofee_model->set_nofee();
                    
                    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;
    }
    
    
    /**
     * 设置REAL房
     */
    public function house_real_set()
    {
        $after = $this->input->post( 'after' , TRUE );
        $p_filename = $this->input->post( 'p_filename' , TRUE );
        $pic_title = $this->input->post( 'pic_title' , TRUE );
        //认证方式 0 
        $pic_type = $this->input->post( 'pic_type' , TRUE );
        
        //房源编号
        $rowid = $this->input->post( 'rowid' , TRUE );
        $secret_key = $this->input->post( 'secret_key' , TRUE );
        $result = array();
        
        //验证房源编号和提交验证码
        if( intval($rowid) > 0 && md5('HOUSE365_REAL_SET_'.$rowid) == $secret_key )
        {   
            //经纪人账号uid
            $uid = $this->user_arr['uid'];
            $isreal = $this->user_arr['isreal'];
            
            //条件判断
            if( $isreal == '1' || $pic_title != '' || !empty($p_filename) )
            {
                //初始化房源操作类
                $this->load->model('sell_model');
                $houseinfo = array();
                $houseinfo = $this->sell_model->find_by_id($rowid);

                if( is_array( $houseinfo ) && !empty($houseinfo) )
                {   
                    //加载房源急推属性类
                    $this->load->model('sell_real_model');
                    $this->sell_real_model->set_houseinfo($houseinfo);

                    //检查此房源是否符合设置急推房源的标准
                    $result = $this->sell_real_model->check_real_standard();
                    if( isset($result) && $result['is_ok'] == 1 )
                    {   
                        if(is_array($pic_type) && !empty($pic_type))
                        {
                            if(isset($pic_type[0]) && $pic_type[0] == '1' )
                            {   
                                //如果是第二种方式就设置房产证参数
                                $this->sell_real_model->set_pic_title($pic_title);
                                $this->sell_real_model->set_pic_url($p_filename[0]);
                            }
                            else if( isset($pic_type[0]) && $pic_type[0] == 2)
                            {
                                //如果第三种方式就设置委托协议参数
                                $this->sell_real_model->set_real_pics($p_filename);
                            }
                        }

                        //设置REAL房属性
                        $set_result = $this->sell_real_model->set_real();

                        if($set_result)
                        {
                            $result['is_ok'] = 1;
                            $result['msg'] = 'Real房设置成功';
                            
                            //清除已申请REAL房个数和已存在的REAL记录个数缓存
                            $this->sell_real_model->apply_real_num_today( $uid , 1);
                            $this->sell_real_model->get_real_num_by_uid( $uid , 1);
                        }
                        else
                        {
                            $result['is_ok'] = 0;
                            $result['msg'] = 'Real房设置失败';
                        }
                    }
                }
                else
                {
                    $result['is_ok'] = 0;
                    $result['msg'] = '房源信息不存在';  
                }
            }
            else
            {
                $result['is_ok'] = 0;
                $result['msg'] = '请满足real房三条件之一';
            }
        }
        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('sell_model');
            $houseinfo = array();
            $this->sell_model->set_select_fields(array('id','uid','esta','istag'));
            $houseinfo = $this->sell_model->find_by_id($rowid);
            
            if( is_array( $houseinfo ) && !empty($houseinfo)    )
            {
                //加载房源急推属性类
                $this->load->model('sell_tag_model');
                $this->sell_tag_model->set_houseinfo($houseinfo);
                $set_result = $this->sell_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_nofee_cancel()
    {
        //房源编号
        $rowid = $this->input->get( 'rowid' , TRUE );
        $secret_key = $this->input->get( 'secret_key' , TRUE );
        $result = array();
        //验证房源编号和提交验证码
        if( intval($rowid) > 0  &&  md5('HOUSE365_NOFEE_SET_'.$rowid) == $secret_key )
        {
            //经纪人账号uid
            $uid = $this->user_arr['uid'];

            //初始化房源操作类
            $this->load->model('sell_model');
            $houseinfo = array();
            $this->sell_model->set_select_fields(array('id','uid','esta','istag'));
            $houseinfo = $this->sell_model->find_by_id($rowid);
            
            if( is_array( $houseinfo ) && !empty($houseinfo)    )
            {
                //加载房源急推属性类
                $this->load->model('sell_nofee_model');
                $this->sell_nofee_model->set_houseinfo($houseinfo);
                $set_result = $this->sell_nofee_model->remove_nofee();
                
                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;
    }
    
    
    /**
     * 取消Real房
     */
    public function house_real_cancel()
    {
        //房源编号
        $rowid = $this->input->get( 'rowid' , TRUE );
        $secret_key = $this->input->get( 'secret_key' , TRUE );
        
        $result = array();
        //验证房源编号和提交验证码
        if( intval($rowid) > 0  &&  md5('HOUSE365_REAL_SET_'.$rowid) == $secret_key )
        {
            //经纪人账号uid
            $uid = $this->user_arr['uid'];

            //初始化房源操作类
            $this->load->model('sell_model');
            $houseinfo = array();
            $this->sell_model->set_select_fields(array('id','uid','esta','istag'));
            $houseinfo = $this->sell_model->find_by_id($rowid);
            
            if( is_array( $houseinfo ) && !empty($houseinfo)    )
            {
                //加载房源REAL房属性类
                $this->load->model('sell_real_model');
                $this->sell_real_model->set_houseinfo($houseinfo);
                $set_result = $this->sell_real_model->remove_real();
                
                if($set_result)
                {
                    $result['is_ok'] = 1;
                    $result['msg'] = '取消REAL房成功';
                }
                else
                {
                    $result['is_ok'] = 0;
                    $result['msg'] = '取消REAL房失败';
                }
            }
            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'];
            $package_id = $this->user_arr['package_id'];
			$agentcode = $this->user_arr['agentcode'];
            
            $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('sell_model');
                $houseinfo = array();
                $this->sell_model->set_select_fields(array('id','esta'));
                $houseinfo = $this->sell_model->find_by_id($rowid);

                if( is_array( $houseinfo ) && !empty($houseinfo)    )
                {
                    //加载房源急推属性类
                    $this->load->model('sell_operate_model'); 
                    $set_result = $this->sell_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 = 'sell';
						/***提交房源操作日志给MYSQL(经纪人日志查询),[$msg:3-房源再发布] ***/
						$this->sell_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('sell_model');
            $houseinfo = array();
            $this->sell_model->set_select_fields(array('id','esta'));
            $houseinfo = $this->sell_model->find_by_id($rowid);
           
            if( is_array( $houseinfo ) && !empty($houseinfo)    )
            {	
                //加载房源急推属性类
                $this->load->model('sell_operate_model'); 
                $set_result = $this->sell_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;
                    $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 = 'sell';
                    //加载中间件统计类
                    $this->load->library('statistics');
                    /***通过接口提交操作日志给中间件，operatetype 1:新增 2刷新 3删除 4失效 5再发布 ***/
                    $this->statistics->sub_operatecount( $uid , $agentcode , 3 , $rowid , '' , $tbl , $domain , $parentcode );

                    /***提交房源操作日志给MYSQL(经纪人日志查询),[$msg:0-删除房源] ***/
                    $this->sell_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 );

        $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;
                $this->load->model('sell_freeze_model');
                $app_result = FALSE;
                $app_result = $this->sell_freeze_model->house_appeal ( $rowid , $data_info);
                if($app_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_sell"]) && !empty($form_param["price_sell"]) ) 
        {   
            switch($form_param["price_sell"])
            {
                case 1:	
                    $cond_where .= " AND price <= '40' ";
                    break;
                case 2:
                    $cond_where .= " AND price > '40' and price <= '60' ";
                    break;
                case 3:
                    $cond_where .= " AND price > '60' and price <= '90' ";
                    break;
                case 4:
                    $cond_where .= " AND price > '90' and price <= '120' ";
                    break;
                case 5:
                    $cond_where .= " AND price > '120' and price <= '150' ";
                    break;
                case 6:
                    $cond_where .= " AND price > '150' and price <= '200' ";
                    break;
                case 7:
                    $cond_where .= " AND price > '200' and price <= '300' ";
                    break;
                case 8:
                    $cond_where .= " AND price > '300' and price <= '500' ";
                    break;
                case 9:
                    $cond_where .= " AND price > '500'";
                    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;
            }
        }
        
        //关键词条件
        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;
                case 5: //新房直售
                    $cond_where .= ' AND  nofee = 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 sell.php */
/* Location: ./application/zsb/controllers/sell.php */