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

class Reserve_Wang extends MY_Controller {
    
    /**
    * 经纪人账号编号
    *
    * @access private
    * @var string
    */
    private $_uid = 0;
    
    /**
     * 设置预约刷新SESSION的KEY值
     * @access 
     * @var const
     */
    const SET_SESSION_KEY = 'project_house_set';
    
    /**
    * 解析函数
    *
    * @access public
    * @return void
    */
    public function __construct()
    {
        parent::__construct();

        //加载预约方案模型类
        $this->load->model('reserve_model');
		$this->load->helper('common_house_helper');
		$this->_uid = $this->user_arr['uid'];
        $this->reserve_model->set_uid($this->_uid);

		$this->load->helper('common_string');
    }
    
    
    /**
     * Index Page for this controller.
     */
    public function index()
    {
        $this->project_manage();
    }
    
    /**
     * 预约方案添加页面
     * @param string $add_house 标识是否添加方案时候添加房源到预约方案，
     *                           默认不添加，等于add时添加房源
     * @param void
     */
    public function project_new( $add_house = '')
    {   
        if($add_house == 'add')
        {
            //存取SESSION，处理切换多个预约方案
            $project_house_session = $this->session->userdata(self::SET_SESSION_KEY);
            if( isset($project_house_session) && !empty($project_house_session) )
            {
                $tbl = $project_house_session['tbl'];
                $actionid = $project_house_session['actionid'];
            }
        }

        $rowid_arr = isset($actionid) && $actionid != false ?  explode(',',$actionid) : array();
        
        $uid = $this->user_arr['uid'];
        $tbl = (isset($tbl) && in_array($tbl,array('sell','rent') ) ) ? $tbl : '';
        //提交设置的房源个数
        $set_house_num = count($rowid_arr);
        //有效房源数组
        $project_houses_arr = array();
        //有效房源个数
        $project_house_num = 0;
        //过滤有效房源
        if( $set_house_num > 0)
        {   
            $this->load->helper('common_url');
            
            //加载房源MODEL
            if($tbl == 'sell')
            {
                $this->load->model('sell_model');
            }
            else if($tbl == 'rent')
            {
                $this->load->model('rent_model');
            }

			$house = $this->config->item('house');
            foreach($rowid_arr as $key=>$val)
            {
                $rowid = intval($val);
                if($rowid > 0)
                {   
                    $cond_where = "id = '".$rowid."' AND uid = '".$uid."'";
                    
                    if($tbl == 'sell')
                    {	
						$select_filed = array('esta','blockshowname','room','hall','buildarea','price');
                        $this->sell_model->set_select_fields($select_filed);
                        $house_arr = $this->sell_model->find_one_by($cond_where);
                    }
                    else if($tbl == 'rent')
                    {	
						$select_filed = array('esta','blockshowname','room','hall','buildarea','price','priceunit');
                        $this->rent_model->set_select_fields($select_filed);
                        $house_arr = $this->rent_model->find_one_by($cond_where);
                    }
                    
                    //记录有效房源信息
                    if( isset ($house_arr['esta']) && $house_arr['esta'] == 1)
                    {
                        //处理房源标题和小区标题截取
                        $house_arr['tbl'] = $tbl;
                        $house_arr['rowid'] = $rowid;
						$house_arr['price'] = strip_end_0($house_arr['price']);
						$house_arr['buildarea'] = strip_end_0($house_arr['buildarea']);
						$house_arr['price_unit'] = $tbl == 'sell' ? '万' : $house['shoppriceunit'][$house_arr['priceunit']];
                        $house_arr['blockshowname'] = $house_arr['blockshowname'];
                        $house_arr['url'] = $tbl == "sell" ? get_sellinfo_url($rowid) : get_rentinfo_url($rowid);
                        $project_houses_arr[]['houseinfo'] = $house_arr;
                    }
                }
            }
            
            //如果设置的房源全部都是非有效房源，还设置了干嘛。
            $project_house_num = count($project_houses_arr);
        }
        
        /** 页面初始化 */
        $data['page_title'] = '房源管理-预约刷新';
        //需要加载的css
        $data['css'] = load_css('zsb/css/v1.0/style1.css,zsb/css/v1.0/style2.css');
        //需要加载的JS
        $data['js'] = load_js('zsb/js/v1.0/js3.js');
        $data['project_house_num'] = $project_house_num;
        $data['project_houses_arr'] = $project_houses_arr;
        $data['house_tbl'] = $tbl;
        $data['project_times_num'] = 0;
		$data['documentation'] = $this->config->item('documentation');//帮助文档
        $data['project_times_max_days'] = $this->reserve_model->get_project_times_max_days();
        
        //加载模板
        $this->view( 'house_manage' , 'project_new_wang' , $data);
    }
    
    
    /**
     * 预约方案管理页面
     * @param int $project_id 预约方案编号
     */
    public function project_manage( $project_id = '' )
    {   
        //预约方案编号
        $id = isset($project_id) ? intval($project_id) : 0;
        
        //根据方案ID获取该方案名称
        $project_name = $this->reserve_model->get_projectname_by_pid($id);
        
        //获取我的全部预约刷新方案
        $project_arr = $this->reserve_model->get_myprojects(1);
        $project_num = count($project_arr);

        //没有该方案跳转到添加页面
        if( $project_name == '' )
        {
            if($project_num == 0)
            {
                $page_text = '您还没有设置过任何的预约刷新方案，请先添加！';
                $this->jump("/reserve/project_new/", $page_text , 1000);
            }
            else
            {
                $first_project_id = isset($project_arr[0]['id']) ? intval($project_arr[0]['id']) : 0;
                if( $first_project_id > 0)
                {
                    echo "<script>window.location.href='/reserve/project_manage/".$first_project_id."/';</script>";   
                }
                else
                {
                    echo "<script>window.location.href='/reserve/project_new/';</script>";
                }
            }
            exit;
        }
        
        //根据方案ID获取该方案时间点
        $project_times_arr = $this->reserve_model->get_projecttimes_by_pid($id);
        $project_times_num = count($project_times_arr);
        $project_times_str = '';
        
        if($project_times_num > 0)
        {
            foreach($project_times_arr as $key=>$val)
            {   
                $time = date("H:i", strtotime($val['time']));
                $project_times_str .= $time.",";
            }
        }
        
        //拆分时间点
        $ptime_arr = $this->reserve_model->deal_strtime_2_arr($project_times_arr);
        
        //根据方案ID获取该方案参与房源
        $project_houses_arr = $this->reserve_model->get_projecthouses_by_pid($id, true);
        $project_houses_num = count($project_houses_arr);
        //经纪人编号
        $uid = $this->user_arr['uid'];
        if( $project_houses_num > 0)
        {   
            $this->load->helper('common_url');
			$house = $this->config->item('house');
            foreach( $project_houses_arr as $key=>$val)
            {
                $house_esta = 0;
                if(in_array($val['tbl'], array('sell','rent')) && $val['rowid'] > 0)
                {   
                    $cond_where = "id = '".$val['rowid']."' AND uid = '".$uid."'";
                    if($val['tbl'] == 'sell')
                    {	
						$select_filed = array('esta','blockshowname','room','hall','buildarea','price');
                        $this->load->model('sell_model');
                        $this->sell_model->set_select_fields($select_filed);
                        $house_arr = $this->sell_model->find_one_by($cond_where);
                    }
                    else if($val['tbl'] == 'rent')
                    {	
						$select_filed = array('esta','blockshowname','room','hall','buildarea','price','priceunit');
                        $this->load->model('rent_model');
                        $this->rent_model->set_select_fields($select_filed);
                        $house_arr = $this->rent_model->find_one_by($cond_where);
                    }
                    $house_esta = isset($house_arr['esta']) ? isset($house_arr['esta']) : 2;
                }

                if( $house_esta != 1)
                {
                    unset($project_houses_arr[$key]);
                }
                else
                {	
                    $house_arr['tbl'] = $val['tbl'];
                    $house_arr['rowid'] = $val['rowid'];
					$house_arr['price'] = strip_end_0($house_arr['price']);
					$house_arr['buildarea'] = strip_end_0($house_arr['buildarea']);
					$house_arr['price_unit'] = $val['tbl'] == 'sell' ? '万' : $house['shoppriceunit'][$house_arr['priceunit']];
                    $house_arr['url'] = $val['tbl'] == "sell" ? 
                        get_sellinfo_url($val['rowid']) : get_rentinfo_url($val['rowid']);
                    $project_houses_arr[$key]['houseinfo'] = $house_arr;
                }
            }
        }
        
        //方案编号
        $data['id'] = $id;
        //方案名称
        $data['project_name'] = $project_name;
        //方案数量
        $data['project_num'] = $project_num;
        //最大方案个数
        $project_max_num = $this->reserve_model->get_project_max_num();
        $data['project_max_num'] = $project_max_num;
        //方案时间个数
        $data['project_times_num'] = $project_times_num;
        //方案时间数组
        $data['ptime_arr'] = $ptime_arr;
        //方案时间点字符串
        $data['project_times_str'] = $project_times_str;
        //方案数组
        $data['project_arr'] = $project_arr;
        //方案房源信息
        $data['project_houses_num'] = count($project_houses_arr);
        $data['project_houses_arr'] = $project_houses_arr;
        
        /** 页面初始化 */
        $data['page_title'] = '房源管理-预约刷新';
        //需要加载的css
        $data['css'] = load_css('zsb/css/v1.0/style1.css,zsb/css/v1.0/style2.css');
        //需要加载的JS
        $data['js'] = load_js('zsb/js/v1.0/js3.js');
		//帮助文档
		$data['documentation'] = $this->config->item('documentation');
        //加载模板
        $this->view( 'house_manage' , 'project_manage_wang' , $data);
    }
    
    
    //表单跳转处理
    public function do_action()
    {
        $actiontype = $this->input->post('actiontype',TRUE);
        switch ($actiontype)
        {
            case 'project_house_set':
                $this->project_house_set();
                break;
            case 'project_house_cancel':
                $this->project_house_cancel();
                break;
        }
    }
    
    /*
     * 预约方案房源设置
     */
    public function project_house_set($id = '')
    {   
        //获取表单提交信息
        $tbl = $this->input->post('tbl',TRUE);
        $actionid = $this->input->post('actionid',TRUE);
        $secret_key = $this->input->post('secret_key',TRUE);
        
        //存取SESSION，处理切换多个预约方案
        $app_key = self::SET_SESSION_KEY;
        if(isset($actionid) && $actionid != false)
        {   
            $session_data = array( 'actionid' => $actionid , 'tbl' => $tbl );
            $this->session->set_userdata(array($app_key => $session_data));
        }
        else
        {
            $project_house_session = $this->session->userdata($app_key);
            if( isset($project_house_session) && !empty($project_house_session) )
            {
                $tbl = $project_house_session['tbl'];
                $actionid = $project_house_session['actionid'];;
            }
        }
        
        $rowid_arr = isset($actionid) && $actionid != false ?  explode(',',$actionid) : array();

        //获取我的全部预约刷新方案
        $project_arr = $this->reserve_model->get_myprojects(1);
        $project_num = count($project_arr);
        //没有该方案跳转到添加页面
        if($project_num == 0)
        {
            $page_text = '您还没有设置过任何的预约刷新方案，请先添加！';
            $this->jump("/reserve/project_new/", $page_text , 1000);
            exit;
        }
        
        if( isset($id) && $id !='')
        {
            $id = $id;
        }
        else
        {
            $id = isset($project_arr[0]['id']) ? intval($project_arr[0]['id']) : 0;
        }
        
        if( $id <= 0)
        {
            echo "<script>window.location.href='/reserve/project_new/';</script>";
            exit;
        }
        
        //根据方案ID获取该方案名称
        $project_name = $this->reserve_model->get_projectname_by_pid($id);
        
        //根据方案ID获取该方案时间点
        $project_times_arr = $this->reserve_model->get_projecttimes_by_pid($id);
        $project_times_num = count($project_times_arr);
        $project_times_str = '';
        if($project_times_num > 0)
        {
            foreach($project_times_arr as $key=>$val)
            {   
                $time = date("H:i", strtotime($val['time']));
                $project_times_str .= $time.",";
            }
        }  
        //拆分时间点
        $ptime_arr = $this->reserve_model->deal_strtime_2_arr($project_times_arr);
        
        $uid = $this->user_arr['uid'];
        $set_tbl = (isset($tbl) && in_array($tbl,array('sell','rent') ) ) ? $tbl : '';
        $set_houses_arr = isset($rowid_arr) ? $rowid_arr : array();
        //提交设置的房源个数
        $set_house_num = count($set_houses_arr);
        $project_houses_arr = array();
        //过滤有效房源
        if( $set_house_num > 0)
        {   
            $this->load->helper('common_url');
            
            //加载房源MODEL
            if($set_tbl == 'sell')
            {
                $this->load->model('sell_model');
            }
            else if($set_tbl == 'rent')
            {
                $this->load->model('rent_model');
            }

			$house = $this->config->item('house');

            foreach($set_houses_arr as $key=>$val)
            {
                $rowid = intval($val);
                
                if($rowid > 0)
                {   
                    $cond_where = "id = '".$rowid."' AND uid = '".$uid."'";
                    
                    if($set_tbl == 'sell')
                    {	
						$select_filed = array('esta','blockshowname','room','hall','buildarea','price','expiretime');
                        $this->sell_model->set_select_fields($select_filed);
                        $house_arr = $this->sell_model->find_one_by($cond_where);
                    }
                    else if($set_tbl == 'rent')
                    {	
						$select_filed = array('esta','blockshowname','room','hall','buildarea','price','priceunit','expiretime');
                        $this->rent_model->set_select_fields($select_filed);
                        $house_arr = $this->rent_model->find_one_by($cond_where);
                    }
                    
                    //记录有效房源信息
                    if( isset ($house_arr['esta']) && $house_arr['esta'] == 1)
                    {
                        //处理房源标题和小区标题截取
                        $house_arr['tbl'] = $set_tbl;
                        $house_arr['rowid'] = $rowid;
						$house_arr['price'] = strip_end_0($house_arr['price']);
						$house_arr['buildarea'] = strip_end_0($house_arr['buildarea']);
						$house_arr['price_unit'] = $set_tbl == 'sell' ? '万' : $house['shoppriceunit'][$house_arr['priceunit']];
                        $house_arr['blockshowname'] = $house_arr['blockshowname'];
						//获取房源过期时间
						$days = intval(to_expire_day_new($house_arr['expiretime']));
						$house_arr['expiretime'] = $days;
                        $house_arr['url'] = $set_tbl == "sell" ? get_sellinfo_url($rowid) : get_rentinfo_url($rowid);
                        $project_houses_arr[]['houseinfo'] = $house_arr;
                    }
                }
            }
            
            //如果设置的房源全部都是非有效房源，还设置了干嘛。
            $project_houses_num = count($project_houses_arr);
            if(  $project_houses_num == 0)
            {
                $url = '/'.$set_tbl.'/manage/';
                $page_text = '设置失败，设置预约刷新的房源必须为有效';
                $this->jump( $url , $page_text , 2000);
                exit;
            }
        }
        
        //根据方案ID获取该方案参与房源
        $project_old_houses_arr = $this->reserve_model->get_projecthouses_by_pid($id, true);
        $project_old_houses_num = count($project_old_houses_arr);
        if($project_old_houses_num > 0)
        {	
			$house = $this->config->item('house');
            foreach($project_old_houses_arr as $key=>$val)
            {
                $house_esta = 0;
                if(in_array($val['tbl'], array('sell','rent')) && $val['rowid'] > 0)
                {
                    $cond_where = "id = '".$val['rowid']."' AND uid = '".$uid."'";
                    if($val['tbl'] == 'sell')
                    {	
						$select_filed = array('esta','blockshowname','room','hall','buildarea','price','expiretime');
                        $this->load->model('sell_model');
                        $this->sell_model->set_select_fields($select_filed);
                        $house_arr = $this->sell_model->find_one_by($cond_where);
                    }
                    else if($val['tbl'] == 'rent')
                    {	
						$select_filed = array('esta','blockshowname','room','hall','buildarea','price','priceunit','expiretime');
                        $this->load->model('rent_model');
                        $this->rent_model->set_select_fields($select_filed);
                        $house_arr = $this->rent_model->find_one_by($cond_where);
                    }
                    
                    $house_esta = isset($house_arr['esta']) ? isset($house_arr['esta']) : 2;
                }

                if($house_esta != 1)
                {
                    unset($project_old_houses_arr[$key]);
                }
                else
                {	
                    $house_arr['tbl'] = $val['tbl'];
                    $house_arr['rowid'] = $val['rowid'];
					$house_arr['price'] = strip_end_0($house_arr['price']);
					$house_arr['buildarea'] = strip_end_0($house_arr['buildarea']);
					$house_arr['price_unit'] = $val['tbl'] == 'sell' ? '万' : $house['shoppriceunit'][$house_arr['priceunit']];
                    $house_arr['url'] = $val['tbl'] == "sell" ? get_sellinfo_url($val['rowid']) : get_rentinfo_url($val['rowid']);
					//获取房源过期时间
					$days = intval(to_expire_day_new($house_arr['expiretime']));
					$house_arr['expiretime'] = $days;
                    $project_old_houses_arr[$key]['houseinfo'] = $house_arr;
                }
            }
        }
        
        //方案编号
        $data['id'] = $id;
        //方案名称
        $data['project_name'] = $project_name;
        //设置房源类型
        $data['set_tbl'] = $set_tbl;
        //方案数量
        $data['project_num'] = $project_num;
        //经纪人最大预约方案个数
        $project_max_num = $this->reserve_model->get_project_max_num();
        $data['project_max_num'] = $project_max_num;
        //最大设置天数
        $data['project_times_max_days'] = $this->reserve_model->get_project_times_max_days();
        //方案时间个数
        $data['project_times_num'] = $project_times_num;
        //方案时间数组
        $data['ptime_arr'] = $ptime_arr;
        //方案时间点字符串
        $data['project_times_str'] = $project_times_str;
        //方案数组
        $data['project_arr'] = $project_arr;
        //方案房源信息
        $data['project_houses_num'] = isset($project_houses_num) ? $project_houses_num : 0;
        $data['project_houses_arr'] = $project_houses_arr;
        //已参与预约方案的房源信息
        $data['project_old_houses_arr'] = $project_old_houses_arr;
        $data['project_old_houses_num'] = count($project_old_houses_arr);
        /** 页面初始化 */
        $data['page_title'] = '房源管理-预约刷新';
        //需要加载的css
        $data['css'] = load_css('zsb/css/v1.0/style1.css,zsb/css/v1.0/style2.css');
        //需要加载的JS
        $data['js'] = load_js('zsb/js/v1.0/js3.js');
		//帮助文档
		$data['documentation'] = $this->config->item('documentation');
        //最大预约刷新天数
        $data['max_reserve_days'] = $this->config->item('max_reserve_days');
        //加载模板
        $this->view( 'house_manage' , 'project_set' , $data);
    }
    
    
    //预约方案设置表单处理
    public function project_house_set_action()
    {   
        $result = array();
        
        $house_tbl = $this->input->post('house_tbl',TRUE);
        $pid = $this->input->post('pid',TRUE);
        $houses_arr = $this->input->post('housearr',TRUE);
        $secret_key = $this->input->post('secret_key',TRUE);
        $project_day = $this->input->post('project_day',TRUE);
        $oldhousearr = $this->input->post('oldhousearr',TRUE);
		$oldhouse_days =$this->input->post('oldhouse_days',TRUE);
		//print_r($_POST);die;
		//echo $oldhouse_days;die;
        //在添加房源的同时修改已关联的房源
        if(is_array($oldhousearr) && !empty($oldhousearr))
        {
            $old_house_arr = array();
            foreach($oldhousearr as $val)
            {
                $house = explode("-", $val);
                $harr['tbl'] = $house[0];
                $harr['rowid'] = $house[1];
                $harr['starttime'] = $house[2];
                $harr['endtime'] = $house[3];
                $old_house_arr[] = $harr;
            }
            
             $this->reserve_model->update_projecthouses( $pid, $old_house_arr);
        }
        else
        {
            //删除该方案的全部房源
            $this->reserve_model->delete_projecthouses($pid);
        }
        $result = $this->reserve_model->add_projecthouses($pid , $house_tbl , $houses_arr, $project_day);
        if($result === TRUE)
        {
            $page_text = '添加成功';
            $this->jump( '/reserve/project_manage/'.$pid.'/', $page_text , 1000);
            exit;
        }
        else
        {
            $page_text = '无添加信息';
            $this->jump( '/reserve/project_manage/', $page_text , 1000);
            exit;
        }
    }
    
    
    /*
     * 取消预约方案房源
     */
    public function project_house_cancel()
    {   
        $result = array();
        
        //获取表单提交信息
        $tbl = $this->input->post('tbl',TRUE);
        $actionid = $this->input->post('actionid',TRUE);
        $uid = intval($this->user_arr['uid']);
        
        if(isset($actionid) && !empty($actionid))
        {
           $arr_id = explode(',', $actionid) ;
           
            if (is_array($arr_id) && !empty($arr_id)) 
            {
                $result = $this->reserve_model->delete_projecthouse_batch($uid , $tbl, $arr_id);
            }
        }
        
        $url = $tbl == 'rent' ? '/rent/manage/active/' : '/sell/manage/active/';
        if($result === TRUE)
        {
            $page_text = '操作成功，已取消预约刷新';
        }
        else
        {
            $page_text = '预约刷新失败';
        }
        $this->jump( $url, $page_text , 2000);
        exit;
    }
    
    
    /*
     * 添加预约方案
     */
    public function add_project()
    {   
        //方案名称
        $project_name = $this->input->post('project_name',TRUE);
        $project_name = isset($project_name) ? trim(strip_tags($project_name)) : '';
        $project_name = $project_name != '' ? $project_name : '新的方案';

        //方案时间点
        $project_times = $this->input->post('project_times',TRUE); 
        $project_times = trim($project_times);
        $result = $this->_add_project( $project_name , $project_times );
        
        if(isset($result['is_ok']) && $result['is_ok'] == 1)
        {   
            $url = '/reserve/project_manage/'.$result['project_id'].'/';
            $page_text = $result['msg'];
        }
        else
        {
            $url = '/reserve/project_manage/';
            $page_text = $result['msg'];
        }
        
        $this->jump( $url , $page_text , 3000);
        exit;
    }
    
    
    /**
     * 添加新的预约方案
     * 
     * @param string $project_name 方案名称
     * @param string $project_times 方案时间
     * @return array 添加结果
     */
    private  function _add_project( $project_name , $project_times )
    {   
        $result = array();
        
        //获取我的全部预约刷新方案
        $project_arr = $this->reserve_model->get_myprojects(1);

        //已添加方案个数
        $project_num = count($project_arr);

        //最大方案个数
        $project_max_num = $this->reserve_model->get_project_max_num();
        
        if( $project_num < $project_max_num && trim(strip_tags($project_name)) != '')
        {
            //保存方案名
            $project_id = $this->reserve_model->add_projectname($project_name);
            
            //新增方案时间点
            $result_add  = FALSE;
            if( $project_id > 0 && $project_times != "")
            {
                $result_add = $this->reserve_model->add_projecttimes( $project_id ,  $project_times);
            }
            
            if($result_add === TRUE)
            {
                $result['is_ok'] = '1';
                $result['project_id'] = $project_id;
                $result['msg'] = "预约刷新方案'".$project_name."'添加成功";
                
                //清除预约方案缓存
                $this->reserve_model->get_myprojects(1);
            }
            else
            {
                $result['is_ok'] = '0';
                $result['msg'] = '预约方案已添加，预约刷新方案执行时间设置失败';
            }
        }
        else if($project_num < $project_max_num && $project_name == '')
        {
            $result['is_ok'] = '0';
            $result['msg'] = '请先设置预约方案的名称';
        }
        else
        {   
            $result['is_ok'] = '0';
            $result['msg'] = '预约刷新方案数量已超过最大数量限制';
        }
        
        return $result;
    }
    
    
    /*
     * 添加预约方案同时添加房源
     */
    public function add_project_and_houses()
    {
        //方案名称
        $project_name = $this->input->post('project_name',TRUE);
        $project_name = isset($project_name) ? trim($project_name) : '新的方案';
        $houses_arr = $this->input->post('housearr',TRUE);
        $project_times = $this->input->post('project_times',TRUE);
        $secret_key = $this->input->post('secret_key',TRUE);
        $tbl = $this->input->post('house_tbl',TRUE);
        $project_day = $this->input->post('project_day',TRUE); 
        
        //添加预约刷新方案和房源
        $result = array();
        $result = $this->_add_project_and_houses($project_name , $project_times , $tbl ,$houses_arr , $project_day);
        
        if($result['is_ok'] == 1)
        {
            $url = '/reserve/project_manage/'.$result['project_id'].'/';
        }
        else
        {
            $url = '/reserve/project_manage/';
        }
        
        $page_text = $result['msg'];
        $this->jump( $url , $page_text , 3000);
        exit;
    }
    
    /**
     * 添加预约方案同时添加房源
     * @param string $project_name 预约方案名称
     * @param string $project_times 预约方案时间点
     * @param string $tbl 预约方案表名称
     * @param array $houses_arr 预约方案房源数组
     * @param int $project_day  预约天数
     * @return array 操作结果
     */
    private function _add_project_and_houses( $project_name , $project_times , $tbl ,$houses_arr , $project_day)
    {   
        $result = array();
        
        //获取我的全部预约刷新方案
		$project_arr = $this->reserve_model->get_myprojects(1);
		$project_num = count($project_arr);

		if( $project_num < $this->reserve_model->get_project_max_num())
		{
            //保存方案名
            $project_id = $this->reserve_model->add_projectname($project_name);
            
            if( $project_id <= 0 )
            {
                $result['is_ok'] = '0';
                $result['msg'] = '预约刷新方案名称保存失败';
            }

            //新增方案时间点
            if( $project_id > 0 && $project_times != "")
            {
                $result_add = $this->reserve_model->add_projecttimes($project_id, $project_times);
                
                if( $result_add != TRUE )
                {
                    $result['is_ok'] = '0';
                    $result['msg'] = '预约刷新方案时间点保存失败';
                }
            }

            if($project_id > 0  && isset($tbl) && in_array($tbl , array('sell','rent'))  )//设置房源管理方案
            {
                $result_add = $this->reserve_model->add_projecthouses($project_id, $tbl, $houses_arr, $project_day);
                
                if( $result_add === TRUE )
                {
                    $result['is_ok'] = '1';
                    $result['project_id'] = $project_id;
                    $result['msg'] = "预约刷新方案'".$project_name."'添加成功";
                    
                    //清除预约方案缓存
                    $this->reserve_model->get_myprojects(1);
                }
                else
                {
                    $result['is_ok'] = '1';
                    $result['msg'] = '预约刷新方案房源添加失败';
                }
            }
		}
        else
        {
            $result['is_ok'] = '0';
            $result['msg'] = '预约刷新方案数量已超过最大数量限制';
        }

        return $result;
    }
    
    
    /**
     * 更新预约方案
     */
    public function update_project()
    {
        //方案编号
        $project_id = $this->input->post('pid',TRUE);
        $project_name = $this->input->post('project_name',TRUE);
        $secret_key = $this->input->post( 'secret_key' , TRUE );
        $project_times = $this->input->post( 'project_times' , TRUE );
        $project_houses = $this->input->post( 'housearr' , TRUE );
        
        $page_text = '';
        if( $project_id > 0 && md5('HOUSE365_PROJECT_UPDATE_'.$project_id) == $secret_key )
        {
            $result = $this->_update_project( $project_id , $project_name , $project_times , $project_houses);
        }
        else
        {
            $result = array('is_ok'=> '0' ,'msg'=>'参数错误');
        }

        $page_text = $result['msg'];
        $url = '/reserve/project_manage/'.$project_id.'/';
        $this->jump( $url , $page_text , 1000);
    }
    
    
    /**
     * 更新预约方案
     * @param int $project_id 方案编号
     * @param string $project_name 方案名称
     * @param string $project_times 方案时间点
     * @param array $project_houses 方案房源
     * return  array $result
     */
    public function _update_project( $project_id , $project_name , $project_times , $project_houses )
    {   
        $result = array();
        
        $name = $this->reserve_model->get_projectname_by_pid($project_id);
        
        //更新方案名称
        if($name != $project_name)
        {
           $this->reserve_model->update_projectname($project_id , $project_name);
        }
        
        //新增方案时间点
        if($project_times != '')
        {
            $this->reserve_model->add_projecttimes($project_id , $project_times);
        }
        else
        {
            $this->reserve_model->delete_projecttimes($project_id);
        }

        if(is_array($project_houses) && !empty($project_houses))
        {
            $house_arr = array();
            foreach($project_houses as $val)
            {
                $house = explode("-", $val);
                $harr['tbl'] = $house[0];
                $harr['rowid'] = $house[1];
                $harr['starttime'] = $house[2];
                $harr['endtime'] = $house[3];
                $house_arr[] = $harr;
            }
            
            $this->reserve_model->update_projecthouses($project_id, $house_arr);
        }
        else
        {
            //删除该方案的全部房源
            $this->reserve_model->delete_projecthouses($project_id);
        }
        
        //清除预约方案缓存
        $this->reserve_model->get_myprojects(1);
                    
        $result['is_ok'] = '1';
        $result['msg'] = '预约刷新方案信息已更新';
        
        return $result;
    }
    
    
    /**
     * 删除预约方案
     */
    public function delete_project()
    {
        //方案编号
        $project_id = $this->input->get('project_id',TRUE);
        $secret_key = $this->input->get( 'secret_key' , TRUE );
        
        if( $project_id > 0 && md5('HOUSE365_PROJECT_DELETE_'.$project_id) == $secret_key )
        {
            $result = $this->_delete_project($project_id);
        }
        else
        {
            $result = array('is_ok'=> '0' ,'msg'=>'参数错误');
        }

        $result['msg'] = iconv( 'gb2312' , 'utf-8',  $result['msg'] ); 
        print_r(json_encode($result));
        exit;
    }
    
    
    /**
     * 删除预约方案
     * 
     * @param int $project_id 方案编号
     * @return array 删除结果
     */
    private function _delete_project($project_id)
    {
        $result = array('is_ok'=> '0' ,'msg'=>'预约方案删除失败');
        
        if( $project_id > 0)
        {   
            //预约方案绑定房源个数
            $house_num = $this->reserve_model->get_projecthouses_num_by_pid($project_id);

            //1、删除预约方案绑定的房源
            if( $house_num > 0)
            {
                $result1 = $this->reserve_model->delete_projecthouses($project_id);
            }
            else
            {
                $result1 = TRUE;
            }
            
            if( $result1 === TRUE)
            {   
                //预约方案绑定时间方案个数
                $times_num = $this->reserve_model->get_projecttimes_num_by_pid($project_id);
                
                //2、删除方案设定的时间数据
                if( $times_num > 0)
                {
                    $result2 = $this->reserve_model->delete_projecttimes($project_id);
                }
                else
                {
                    $result2 = TRUE;
                }
                
                if($result2 === TRUE)
                {   
                    //3、最后删除方案名称信息
                    $result3 = $this->reserve_model->delete_project($project_id);
                    
                    if( $result3 === TRUE)
                    {
                        $result['is_ok'] = '1';
                        $result['msg'] = '预约刷新方案信息已删除';
                    }
                }
                
                //清除预约方案缓存
                $this->reserve_model->get_myprojects(1);
            }
        }
        return $result;
    }
}
/* End of file reserve.php */
/* Location: ./application/controllers/reserve.php */