<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * zsb
 *
 * 租售宝系统基本类库
 *
 * @package         zsb
 * @author          EllisLab Dev Team
 * @copyright       Copyright (c) 2006 - 2014, HOUSE365, Inc.
 * @link            http://nj.sell.house.com
 * @since           Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * 租售宝系统模型层预约刷新类文件
 *
 * 预约刷新类文件功能描述
 *
 * @package         zsb
 * @subpackage      Models
 * @category        Models
 * @author          fisher
 */
class Reserve_xiao_model extends MY_Model 
{   
    private $_uid;
    //设置该经纪人的最大预约方案数
    private $_project_max_num = 10;
    //设置经纪人一条方案的最大时间点数
    private $_project_times_max_num = 10;
    //设置经纪人一条房源最大预约天数
    private $_project_times_max_days = 31; //默认31天
    private $_project_table = 'reserve_refresh_project';
    private $_project_house_table = 'reserve_refresh_project_house';
    private $_project_time_table = 'reserve_refresh_project_time';
	private $_reserve_refresh_log = 'reserve_refresh_log';

    /**
    * 缓存KEY
    * @var private 
    */
    private $_mem_key;

    public function __construct()
    {
        parent::__construct(1,1,2);
		$this->_mem_key = GB_CITY.'_reserve_model';
        $max_reserve_days = $this->config->item('max_reserve_days');
        $this->_project_times_max_days = !empty($max_reserve_days) ? intval($max_reserve_days) : $_project_times_max_days;
    }
    
    
    //设置经纪人UID
    public function set_uid($uid)
    {
        $this->_uid = $uid;
    }
    
    
    //获取经纪人预约方案最大个数
    public function get_project_max_num()
    {
        return $this->_project_times_max_num;
    }
    
    //获得最大设置天数
    public function get_project_times_max_days()
    {
        return $this->_project_times_max_days;
    }
    

    /*获取我的预约刷新方案
     * @param int $update_cache 0不清除缓存，1清除缓存
     */
    public function get_myprojects( $update_cache = 0)
    {	
        $project_arr = array();

        if( $this->_uid > 0)
        {	
            $mem_key = $this->_mem_key.'_get_myprojects'.$this->_uid;
            if( $update_cache == 1 )
            {
                $this->mc->delete($mem_key);
            }
            $cache = $this->mc->get($mem_key);
            
            if(isset($cache['is_ok']) && $cache['is_ok'] == 1 )
            {   
                $project_arr = $cache['data'];
            }
            else
            {
                $this->dbback->select('id, name');
                $cond_where = "uid = '".$this->_uid."' ";
                $this->dbback->where( $cond_where );
                $project_arr = $this->dbback->get($this->_project_table)->result_array();
                $this->mc->add($mem_key, array('is_ok'=>1 , 'data'=>$project_arr) , 3600);
            }
        }
        return $project_arr;
    }
    
    
    //根据方案ID获取该方案名称
    public function get_projectname_by_pid($pid)
    {
        $project_name = "";
        
        $pid = intval($pid);

        if($pid > 0)
        {
            $this->dbback->select('name');
            $cond_where = "id = '".$pid."' AND uid = '".$this->_uid."' ";
            $this->dbback->where( $cond_where );
            $project_arr = $this->dbback->get($this->_project_table)->row_array();

            $project_name = isset($project_arr['name']) ? $project_arr['name'] : '';
        }

        return $project_name;
    }
    
    
    //根据方案ID获取该方案时间点
    public function get_projecttimes_by_pid($pid)
    {
        $pid = intval($pid);
        $name = $this->get_projectname_by_pid($pid);

        if($name != "")
        {
            $this->dbback->select('time');
            $cond_where ="pid = '".$pid."' ORDER BY time ASC";
            $this->dbback->where( $cond_where );
            $project_arr = $this->dbback->get($this->_project_time_table)->result_array();
        }

        return $project_arr;
    }


	//根据条件获取该方案时间点
    public function get_projecttimes_by_cond($cond_where)
    {
        if($cond_where != "")
        {
            $this->dbback->select('pid, count(*) as num');
            $this->dbback->where( $cond_where );
            $project_arr = $this->dbback->get($this->_project_time_table)->result_array();
        }

        return $project_arr;
    }
    
    
    /**
     * 根据方案ID获取该方案时间点
     * @param int  $pid 方案编号
     * @return int $project_num 方案时间点个数
     */
    public function get_projecttimes_num_by_pid($pid)
    {   
        $projecttimes_num = 0;
        $pid = intval($pid);
        
        if( $pid > 0)
        {
            $name = $this->get_projectname_by_pid($pid);

            if($name != "")
            {
                $cond_where ="pid = '".$pid."'";
                $this->dbback->where( $cond_where );
                $projecttimes_num = $this->dbback->count_all_results($this->_project_time_table);
            } 
        }
        
        return $projecttimes_num;
    }
    
    
    //根据时间点字符串拆分为数组渲染页面
    public function deal_strtime_2_arr($project_times_arr)
    {
        $ptime_arr = array();
        if(is_array($project_times_arr) && !empty($project_times_arr))
        {
            foreach($project_times_arr as $val)
            {
                $time_str = $val['time'];
                $time_arr = explode(":", $time_str);
                if($time_arr[0] != "00")
                {
                    $ptime_arr[$time_arr[0]][$time_arr[1]] = $time_arr[1];
                }
            }
        }
        return $ptime_arr;
    }
    
    
    //根据方案ID获取该方案参与房源
    public function get_projecthouses_by_pid($pid)
    {
        $pid = intval($pid);
        $project_name = array();
        $name = $this->get_projectname_by_pid($pid);

        if($name != "")
        {
            $this->dbback->select('id, tbl, rowid, starttime, endtime');
            $cond_where = "pid = '".$pid."' ORDER BY tbl ASC, endtime ASC";
            $this->dbback->where($cond_where);
            $project_arr = $this->dbback->get($this->_project_house_table)->result_array();
        }

        return $project_arr;
    }


    //根据方案ID获取该方案参与房源
    public function get_projecthouses_by_cond($cond_weher)
    {
        $project_name = array();

        if($cond_weher != "")
        {
            $this->dbback->select('count(id) as num, pid');
            $this->dbback->where($cond_weher);
            $project_arr = $this->dbback->get($this->_project_house_table)->result_array();
        }

        return $project_arr;
    }
    
    
    //根据方案ID获取该方案参与房源
    public function get_projecthouses_num_by_pid($pid)
    {
        $pid = intval($pid);
        $projecthouses_num = 0;
        
        if( $pid > 0 )
        {
            $project_name = array();
            $name = $this->get_projectname_by_pid($pid);

            if($name != "")
            {
                $cond_where = "pid = '".$pid."'";
                $this->dbback->where($cond_where);
                $projecthouses_num = $this->dbback->count_all_results($this->_project_house_table);
            }
        }

        return $projecthouses_num;
    }
    
    
    //根据方案ID获取该方案详细信息
    public function get_project_by_pid($pid)
    {
        $project = array();

        $pid = intval($pid);
        $name = $this->get_projectname_by_pid($pid);

        if($name != "")
        {
            $project['id'] = $pid;
            $project['name'] = $name;
            $project['time'] = $this->get_projecttimes_by_pid($pid);
            $project['house'] = $this->get_projecthouses_by_pid($pid);
        }

        return $project;
    }
    
    
    //根据房源信息获取该方案详细信息
    public function get_project_by_tblrowid($tbl, $rowid)
    {
        $project = array();

        $tbl = $tbl == "sell" ? "sell" : "rent";
        $rowid = intval($rowid);

        //获取我的预约刷新方案
        $project_arr = $this->get_myprojects();
        if(is_array($project_arr) && !empty($project_arr))
        {
            $this->dbback->select('pid, endtime');
            $cond_where = "tbl = '".$tbl."' AND rowid = '".$rowid."' ";
            $this->dbback->where( $cond_where );
            $parr = $this->dbback->get($this->_project_house_table)->row_array();
        }

        if( isset($parr['pid']) && $parr['pid'] > 0)
        {   
            $count_project = count($project_arr);
            for( $i = 0 ; $i < $count_project ; $i ++ )
            {
                if($parr['pid'] == $project_arr[$i]['id'] )
                {
                    $project['name'] = $project_arr[$i]['name'];
                }
            }
            $project['id'] = $parr['pid'];
            $project['endtime'] = $parr['endtime'];
        }

        return $project;
    }
    
    
    //根据房源信息获取该方案详细信息
    public function get_project_by_rowids($tbl, $rowid_arr)
    {
        $project = array();

        $tbl = $tbl == "sell" ? "sell" : "rent";

        //获取我的预约刷新方案
        $project_arr = $this->get_myprojects(1);
        if(is_array($project_arr) && !empty($project_arr))
        {   
            $parr = array();
            if(isset($rowid_arr) && is_array($rowid_arr))
            {
                $rowid_str = implode(',',$rowid_arr);
                $this->dbback->select('pid,tbl,uid,rowid,endtime');
                $cond_where = "tbl = '".$tbl."' AND rowid IN ( ".$rowid_str.") ";
                $this->dbback->where( $cond_where );
                $parr = $this->dbback->get($this->_project_house_table)->result_array();
            }
        }
        
        $project = array();
        if( isset($parr) && is_array($parr))
        {   
            $count_project = count($project_arr);
            for( $i = 0 ; $i < $count_project ; $i ++ )
            {   
                foreach( $parr as $key => $value)
                {
                    if($value['pid'] == $project_arr[$i]['id'] )
                    {   
                        $project[$value['rowid']]['id'] = $value['pid'];
                        $project[$value['rowid']]['name'] = $project_arr[$i]['name'];
                        $project[$value['rowid']]['endtime'] = $value['endtime'];
                    }
                }
            }
        }
        
        return $project;
    }
    
    
    /**
     * 删除房源与预约方案的关联
     * @param int $uid 经纪人编号
     * @param string $tbl 房源类型
     * @param int $rowid 房源编号
     * @return boolean 是否删除成功
     */
    public function delete_projecthouse($uid , $tbl , $rowid)
    {   
        $result = FALSE; 
         
        $tbl = $tbl == "sell" ? "sell" : "rent";
        $rowid = intval($rowid);
        $uid = intval($uid);

        if($rowid > 0)
        {
            $sswhere = "tbl = '".$tbl."' AND rowid = '".$rowid."' ";
            $this->db->delete($this->_project_house_table, $sswhere);
            $reslut = $this->db->affected_rows() > 0 ? TRUE : FALSE;
        }
        
        return $reslut;
    }
    
    
    /**
     * 批量删除房源与预约方案的关联
     * @param int $uid 经纪人编号
     * @param string $tbl 房源类型
     * @param array $rowid_arr 房源编号
     * @return boolean 是否删除成功
     */
    public function delete_projecthouse_batch($uid , $tbl , $rowid_arr)
    {   
        $result = FALSE; 
         
        $tbl = $tbl == "sell" ? "sell" : "rent";
        $uid = intval($uid);
		foreach($rowid_arr as $key=>$value){
			$info = $this->get_project_by_tblrowid($tbl, $value);
			if(!isset($info['id']) && $info['id'] == 0)
			{
				unset($rowid_arr[$key]);
			}
		}
		
        if(is_array($rowid_arr) && !empty($rowid_arr))
        {   
            $rowid_str = implode(',', $rowid_arr);
            $cond_where = "tbl = '".$tbl."' AND rowid IN(".$rowid_str.") ";
            $this->db->delete($this->_project_house_table, $cond_where);
            $reslut = $this->db->affected_rows() > 0 ? TRUE : FALSE;
			if($reslut)
			{
				$time = time();
				//记录删除的日志
				foreach($rowid_arr as $val){
					if($val)
					{
						$data = array();
						$data['uid'] = $uid;
						$data['pid'] = 0;
						$data['tbl'] = $tbl == 'sell' ? 1 : 2;
						$data['rowid'] = $val;
						$data['operateType'] = 3;
						$data['createtime'] = $time;
						$this->insert_reserve_refresh_log($data);
					}
				}
			}
        }
        
        return $reslut;
    }
    
    
    //删除时间点与预约方案$pid的关联
    public function delete_projecttimes($pid)
    {   
        $result = FALSE;
        
        $pid = intval($pid);
        if( $pid > 0)
        {
            $cond_where = "pid = '".$pid."'";
            $this->db->delete($this->_project_time_table, $cond_where);
            $reslut = $this->db->affected_rows() > 0 ? TRUE : FALSE;
        }
        
        return $reslut;
    }
    
    
    //删除房源与预约方案$pid的关联
    public function delete_projecthouses($pid,$is_delete = true)
    {
        $result = FALSE;
        
        $pid = intval($pid);
        if( $pid > 0)
        {
			$old_house_arr = $this->get_projecthouses_by_pid($pid);
            $cond_where = "pid = '".$pid."'";
            $this->db->delete($this->_project_house_table, $cond_where);
			//result 不是 reslut 
            $reslut = $this->db->affected_rows() > 0 ? TRUE : FALSE;
			if($reslut)
			{
				//记录删除的日志
				if($is_delete)
				{
					$uid = $this->_uid;
					foreach($old_house_arr as $val){
						if($val['rowid'])
						{
							$data = array();
							$data['uid'] = $uid;
							$data['pid'] = $pid;
							$data['tbl'] = $val['tbl'] == 'sell' ? 1 : 2;
							$data['rowid'] = $val['rowid'];
							$data['operateType'] = 3;
							$data['createtime'] = time();
							$this->insert_reserve_refresh_log($data);
						}
					}
				}
			}
        }
        
        return $reslut;
    }
    
    
    //删除预约方案$pid
    public function delete_project($pid)
    {
        $result = FALSE;
        
        $pid = intval($pid);
        
        if( $pid > 0)
        {
            $cond_where = "id = '".$pid."'";
            $this->db->delete($this->_project_table, $cond_where);
            $reslut = $this->db->affected_rows() > 0 ? TRUE : FALSE;
        }
        
        return $reslut;
    }
    
    
    //新增方案名称
    public function add_projectname($p_name)
    {
        $project = $this->get_myprojects();
        $now_nums = count($project);

        $pid = 0;
        //判断当前预约刷新方案数是否已满
        if($now_nums < $this->_project_max_num)
        {
            $p_name = strip_tags(trim($p_name));

			if($p_name != '')
			{
				$dateline = time();
				$field = array('uid'=>$this->_uid, 'name'=>$p_name, 'dateline'=>$dateline);
				$this->db->insert($this->_project_table, $field);
				$pid = $this->db->insert_id();
			}
        }

        return  intval($pid);
    }
    
    
    //更新方案名称
    public function update_projectname($pid, $pname)
    {
        $pid = intval($pid);
        $name = $this->get_projectname_by_pid($pid);

        if($name != "")
        {
            $pname = strip_tags(trim($pname));

            $field = array('name'=>$pname);
            $sswhere = "id = '".$pid."' ";
            $this->db->update($this->_project_table, $field, $sswhere);
        }
    }
    
    
    //新增方案时间点
    public function add_projecttimes($pid, $times)
    {
        $pid = intval($pid);
        $times = strip_tags(trim($times));
        $add_result = FALSE;
        
        if($pid > 0 && $times != "")
        {
            $time_arr = explode(",", $times);
            //提交的数据如果带，的话，就会多一个
            unset($time_arr[$this->_project_times_max_num]);
            
            $project_times_num = count($time_arr);
            if(is_array($time_arr) && !empty($time_arr) && ($project_times_num <= $this->_project_times_max_num) )
            {   
                //需要先删除历史数据
                $this->delete_projecttimes($pid);
                //再重新插入数据
                $i = 0;
                foreach($time_arr as $val)
                {
                    $time = strtotime($val);
                    if($time > 0)
                    {
                        $val = date('H:i:s', $time);
                        $field[$i] = array('pid'=>$pid, 'time'=>$val);
                        $i ++;
                    }
                }
                
                if(is_array($field) && !empty($field))
                {
                    $this->db->insert_batch($this->_project_time_table, $field);
                    $add_result = $this->db->affected_rows() > 0 ? TRUE : FALSE;
                }
            }
        }
        
        return $add_result;
    }
    
    
    //新增方案参与房源
    public function add_projecthouses($pid, $tbl, $house_arr, $days)
    {   
        $result = FALSE;
        $pid = intval($pid);
        $name = $this->get_projectname_by_pid($pid);

        $tbl = isset($tbl) && in_array($tbl,array( 'sell', 'rent')) ? $tbl : '';
        if( $tbl == '')
        {
            return $result;
        }
        
        $days = intval($days);
        $days = $days > $this->_project_times_max_days ? $this->_project_times_max_days : ($days < 1 ? 1 : $days);

        $starttime = time();
        $endtime = strtotime(date("Y-m-d")) + $days * 86400 - 1;

        if($name != "" && $pid > 0 && is_array($house_arr) && !empty($house_arr))
        {
			//判断是更新 还是删除

			//对比原有方案来得到更新的数组
			$old_house_arr = $this->get_projecthouses_by_pid($pid);
			//处理$old_house_arr数组使其格式与$house_arr保持一致
			foreach($old_house_arr as $key=>$value)
			{
				unset($value['id']);
				unset($value['starttime']);
				unset($value['endtime']);
				$old_arr[] = implode(',',$value);
			}
			$uid = $this->_uid;
            foreach($house_arr as $val)
            {
                $rowid = intval($val);
				$str = $tbl.','.$rowid;
				$time = time();
				$data_delete = array();
				if(!in_array($str,$old_arr))
				{
					$operateType = 1;
					$info = $this->get_project_by_tblrowid($tbl, $rowid);
					if(isset($info['id']) && $info['id']>0)
					{
						$data_delete['uid'] = $uid;
						$data_delete['pid'] = $info['id'];
						$data_delete['tbl'] = $tbl == 'sell' ? 1 : 2;
						$data_delete['rowid'] = $rowid;
						$data_delete['operateType'] = 3;
						$data_delete['createtime'] = $time;
					}
				}
				else
				{
					$operateType = 2;
				}
               
                $field = array('pid'=>$pid, 'tbl'=>$tbl, 'rowid'=>$rowid,'uid'=>$this->_uid, 'starttime'=>$starttime, 'endtime'=>$endtime);
                $this->db->replace($this->_project_house_table, $field);
                $result = $this->db->affected_rows() > 0 ? TRUE : FALSE;
				//记录日志
				if($result)
				{
					$data = array();
					$data['uid'] = $uid;
					$data['pid'] = $pid;
					$data['tbl'] = $tbl == 'sell' ? 1 : 2;
					$data['rowid'] = $rowid;
					$data['operateType'] = $operateType;
					if($operateType ==1 && !empty($data_delete))
					{
						$this->insert_reserve_refresh_log($data_delete);
					}
					$data['reserveDays'] = $days;
					$data['createtime'] = $time;
					$this->insert_reserve_refresh_log($data);
				}
            }
        }
        
        return $result;
    }
    
    
    //更新方案参与房源
    public function update_projecthouses($pid, $house_arr)
    {
        $pid = intval($pid);
        $name = $this->get_projectname_by_pid($pid);

        if($name != "" && $pid > 0 && is_array($house_arr) && !empty($house_arr))
        {
			//对比原有方案来得到删除的数组
			$old_house_arr = $this->get_projecthouses_by_pid($pid);
			//处理$old_house_arr数组使其格式与$house_arr保持一致
			foreach($old_house_arr as $key=>$value)
			{
				unset($value['id']);
				$old_arr[] = implode(',',$value);
			}
			//处理$house_arr数组
			foreach($house_arr as $k=>$v)
			{
				$new_arr[] = implode(',',$v);
			}
			$result = array_diff($old_arr,$new_arr);
			$uid = $this->_uid;
			//记录删除的日志
			foreach($result as $item)
			{
				$info = explode(',',$item);
				$data = array();
				$data['uid'] = $uid;
				$data['pid'] = $pid;
				$data['tbl'] = $info[0] == 'sell' ? 1 : 2;
				$data['rowid'] = $info[1];
				$data['operateType'] = 3;
				$data['createtime'] = time();
				$this->insert_reserve_refresh_log($data);
			}
            $this->delete_projecthouses($pid,false);

            foreach($house_arr as $val)
            {
                $rowid = intval($val['rowid']);
                $tbl = $val['tbl'] == 'sell' ? 'sell' : 'rent';
                $starttime = $val['starttime'];
                $endtime = $val['endtime'];
                $field = array('pid'=>$pid, 'tbl'=>$tbl, 'rowid'=>$rowid, 'uid'=>$this->_uid,'starttime'=>$starttime, 'endtime'=>$endtime);
                $this->db->replace($this->_project_house_table, $field);
            }
        }
    }


    //预约未执行的刷新次数
    public function get_reserve_remain_num() 
    {
        $remainNum = 0;

        //获取预约方案
        $getProjectId = $this->get_myprojects();

        if ($getProjectId) 
        {
            $getProjectNewId = array();

            foreach($getProjectId as $v) 
            {
                $getProjectNewId[] = $v['id'];
            }

            $pids = implode(',', $getProjectNewId);

            if ($pids) 
            {
                $nowShortDate = date('H:i:s');
                $cond_where = "pid IN ($pids) AND time >= '$nowShortDate' GROUP BY pid";
                $hasPid = $this->get_projecttimes_by_cond($cond_where);

                if ($hasPid) 
                {
                    //求两个数值的交集
                    $hasPidNum = array();
                    foreach($hasPid as $v) 
                    {
                        $hasNewPid[] = $v['pid'];
                        $hasPidNum[$v['pid']] = $v['num'];
                    }

                    if ($hasNewPid) 
                    {
                        $hasNewPids = implode(',', $hasNewPid);
                        $time = time();
                        //$housePid = $dbback->getAll("select count(id) as num, pid from
                        $cond_where = "pid IN($hasNewPids) and endtime >= $time GROUP BY pid";
                        //$cond_where = "pid IN($hasNewPids) GROUP BY pid";
                        $housePid = $this->get_projecthouses_by_cond($cond_where);

                        if ($housePid) 
                        {
                            foreach($housePid as $v) 
                            {
                                $remainNum = $remainNum +  $hasPidNum[$v['pid']] * $v['num'];
                            }
                        }
                    }
                }
            }
        }
        return $remainNum;
   }

   public function insert_reserve_refresh_log($field){
		$this->db->insert($this->_reserve_refresh_log, $field);
   }

	public function get_reserve_refresh_log($uid,$tbl,$rowid,$startTime,$endTime,$start,$number) {
		$startTime = strtotime($startTime);
        $endTime = strtotime($endTime) + 86400;
		//拼装查询条件
		$cond_where ="uid = $uid AND tbl = $tbl AND createtime >= '$startTime' AND createtime <= '$endTime'";
		if($rowid)
		{
			$cond_where .=" AND  rowid = $rowid";
		}

        $this->dbback->select("*")
                ->from($this->_reserve_refresh_log)
                ->where($cond_where)
                ->order_by("id desc")->limit($number,$start);
        $query = $this->dbback->get();					
        $result = $query->result_array();
		return $result;
    }

	public function count_reserve_refresh_log($uid,$tbl,$rowid,$startTime,$endTime) {
        $startTime = strtotime($startTime);
        $endTime = strtotime($endTime) + 86400;
		$cond_where ="uid = $uid AND tbl = $tbl AND createtime >= '$startTime' AND createtime <= '$endTime'";
		if($rowid)
		{
			$cond_where .=" AND  rowid = $rowid";
		}
		//echo $this->_reserve_refresh_log;die;
        $this->dbback->select("*")
                ->from($this->_reserve_refresh_log)
                ->where($cond_where);
        $result = $this->dbback->count_all_results();
		//echo $this->dbback->last_query();  exit();
		return $result;
    }
}
/* End of file Reserve_model.php */
/* Location: ./zsb/model/Reserve_model.php */