<?php

/**
 * model\growth\GrowthBlockImprove.php
 */

/**
 * 小区完善类
 *
 * @author bsw
 */
class GrowthBlockImprove {
    /**
     *
     * @var TINY_ADODB 主数据库 
     */    
    private $db;
    
    /**
     *
     * @var type 从数据库
     */
    private $dbback;
    
    /**
     *
     * @var type 缓存对象
     */
    private $mc;

    /**
     *
     * @var String 关联的表名 
     */
    private $table;

	/**
     *
     * @var array() 房屋配置
     */
    public $house_conf;


    /**
     * 构造函数，初始化db memcache 等。
     * @param string $table 表名，可以使用默认值。
     */
    public function __construct($table = null) {
        $container = Container::getInstance();
        $this->db = $container->get('db');
        $this->dbback = $container->get('dbback');
        $this->mc = $container->get('mc');
        $this->table = 'growth_block_improve_audit';
		$this->GrowthBlock = new GrowthBlock();
		global $house;
        $this->house_conf = $house;
		$this->broker_uid = $_SESSION['broker']['uid'];
    }
 
 
    
    /**
     * 获取小区完善字段信息
     * return array  
	 */
	 function getBlockImproveAttr(){
		$sql = SqlCombinHelper::select_sql('growth_block_attr',array('name_field','name'), " del_flag=0 ");

        //获取缓存
		$result = $this->mc->get($sql);
		if($result === false){
			$result = $this->dbback->getAll($sql);
			$this->mc->set($sql,$result,3600);
		}
		$attr_arr = array();
		if(is_array($result)){
			foreach($result as $val){
				$attr_arr[$val['name_field']] = $val['name'];
			}
		}
		return $attr_arr;
	 }

	/**
     * 获取我熟悉的小区(有房源的小区)
     * @param array $blockIds  小区id
     * return array
	 */
	 function getMyfamiliarBlock($blockIds,$start,$limit){
		if(!is_array($blockIds) || !$blockIds) return 0;
	 
		$FBlockIds = implode(',',$blockIds);
		if(!$FBlockIds) return array();

		$sql = "select b.id,b.blockname,b.district,b.lock_flag,b.lock_opennum,b.lock_outside,s.streetname from block as b left join street as s  on b.streetid = s.id where  b.id in ($FBlockIds) and b.esta = 2 order by b.lock_opennum desc,b.id desc limit {$start},{$limit }";  

		return  $this->dbback->getAll($sql);
	 }
     

	/**
     * 获取我熟悉的小区id(有房源的小区)
     * @param int $uid 经纪人id
     * return array
	 */
	 function getfamiliarBlockId($uid){
		if(!$uid) return array();
		$sql = SqlCombinHelper::select_sql('sell',array('blockid'), " uid='{$uid}' and agentcode='B000' and esta='1'  and blockid!=0 group by blockid ");

        //获取缓存
		$result = $this->mc->get($sql);
		if($result === false){
			$result = $this->dbback->getAll($sql);
			$this->mc->set($sql,$result,7200);
		}
		$blockid_arr = array();
		if(is_array($result)){
			foreach($result as $val){
				$blockid_arr[] = $val['blockid'];
			}
		}
		return $blockid_arr;
	 }


	/**
     * 查询小区开放完善的字段
     * @param int  $block_id  小区id  
     * return array
	 */
	 function getBlockOpneAttr($block_id){
		if(!$block_id) return array();
        //查询总锁定情况
		$block_info = $this->GrowthBlock->getBlockLockInfo($block_id);
		if($block_info['lock_flag'] == 1) return '';
		
        //查询单个属性锁定情况
		$sql = SqlCombinHelper::select_sql('growth_block_attr_lock',array('id,attr_name'), "block_id = '".$block_id."'");
		$block_lock = $this->dbback->getAll($sql);
		$lock_attr = array();
		if(is_array($block_lock)){
			foreach($block_lock as $val){
				$lock_attr[] = $val['attr_name'];
			}
		}
		
		//过滤已经锁定的属性
        $attr = array();
        $blockAttr = $this->getBlockImproveAttr();
		if(is_array($blockAttr)){
			foreach($blockAttr as $key=>$val){
				if(!in_array($key,$lock_attr)){
					if($key == 'b_map'){
					    $attr[] = 'b_map_x';
						$attr[] = 'b_map_y';
					}else{
						$attr[] = $key;
					}
				}
			}
		}

		return $attr;
	 }


	/**
     * 组装小区完善属性数据html
     * @param array  $block_info 小区属性数据 
	 * @param int $id 小区id
     * return array
	 */
	 function getBlobkAttrHtml($block_info,$id){
		if(!$block_info || !is_array($block_info) || !$id) return array();
		$blockAttr = $this->getBlockImproveAttr();
		
	    //组装数据
		$html = $html1 = $html2 = '';
		$flag = $flag1 = 0;
		$i = 0;
		$attr = array();
		//一般数据处理
        foreach($block_info as $key=>$val){
			if($i == 0) $html2 .= '<tr>';
			if($val['have_add']){
				$datacheck = '';
			    $html_add = " disabled ";
			}else{
				$datacheck = ' datacheck ';
			    $html_add = "";
			} 
 
			if($val['attr_field'] == 'district'){
				$i++;
				$flag = 1;
                $district = $this->house_conf['district'];
				$district = array_merge(array(''=>'请选择'),$district);
				$selectHtml = tonyForm('select','district',$district,$val['attr_info'],$td_num=1,"{$html_add} class='select_datacheck {$datacheck}' title='区属' data='".$val['attr_info']."'");
				$html2 .="<td class='w115 td_lable'>".$val['attr_name']."：</td><input   name='".$val['attr_field']."_check' type='hidden' value='0' />
				<td>{$selectHtml}</td>";
			}elseif($val['attr_field'] == 'streetid'){
				$i++;
				$flag = 1;
				$block_data = $this->GrowthBlock->getBlockInfoById($id);
				$streetInfo = $this->GrowthBlock->getStreetByDistrict($block_data['district'],1);
				$streetInfo = $streetInfo ? $streetInfo : array(''=>'请选择');
				$selectHtml = tonyForm('select','streetid',$streetInfo,$val['attr_info'],$td_num=1,"{$html_add} class='select_datacheck {$datacheck}' title='板块' data='".$val['attr_info']."'");
				$html2 .="<td class='w115 td_lable'>".$val['attr_name']."：</td><input   name='".$val['attr_field']."_check' type='hidden' value='0' />
				<td id='street_ajax'>{$selectHtml}</td>";
			}elseif($val['attr_field'] == 'b_introduction' || $val['attr_field'] == 'b_other'){
				$flag1 = 1;
				$data = trim(strip_tags($val['attr_info']));
				$html1 .= "<tr><td class='w115 td_lable' valign='top'>".$val['attr_name']."：</td><input   name='".$val['attr_field']."_check' type='hidden' value='0' /><td colspan='3'><textarea {$html_add} title='".$val['attr_name']."'  class='textarea p_w547 {$datacheck}' name='".$val['attr_field']."' >".$data."</textarea><textarea class='hide' name='".$val['attr_field']."_checktemp' >".$data."</textarea></td></tr>";
			}elseif($val['attr_field'] == 'b_map'){
				$flag1 = 1;
				$attr['b_map']['b_map_x'] = $val['attr_info']['b_map_x'];
				$attr['b_map']['b_map_y'] = $val['attr_info']['b_map_y'];
				$attr['b_map']['have_add'] = $val['have_add'];  
				$attr['b_map']['datacheck'] = $datacheck;
			}else{
				$i++;
				$flag = 1;
				$data = trim($val['attr_info']);
				$data_mark = $data ?  "data='{$data}'" : "data=''";
				$unit = '';
				if(in_array($val['attr_field'],array('area','b_area'))){
					$unit = " 平方米";
				}elseif($val['attr_field'] == 'total_room'){
					$unit = " 户";
				}elseif($val['attr_field'] == 'turn_time'){
					$unit = " 年";
				}
				if(in_array($val['attr_field'],array('area','b_area','total_room','turn_time'))){
					$html2 .="<td class='w115 td_lable'>".$val['attr_name']."：</td><input   name='".$val['attr_field']."_check' type='hidden' value='0' /><td><input {$data_mark} $html_add type='text' name='".$val['attr_field']."' class='input_text w160 {$datacheck}' title='".$val['attr_name']."' value='{$data}'>{$unit}</td>";
				}else{
					$html2 .="<td class='w115 td_lable'>".$val['attr_name']."：</td><input   name='".$val['attr_field']."_check' type='hidden' value='0' /><td><input {$data_mark} $html_add type='text' name='".$val['attr_field']."' class='input_text w205 {$datacheck}' title='".$val['attr_name']."' value='{$data}'>{$unit}</td>";
				}

			}
			if($i == 2) {
				$i = 0;
				$html2 .= '</tr>';
			}
		}
        
		if($flag == 1 ){
			$html = rtrim($html2,'</tr>').'</tr>'.$html1;
		}else{
			$html = $html1;
		}
        if($flag == 0 && $flag1 == 0) return array('status'=>0,'mes'=>'','other_data'=>array()); 
	    return  array('status'=>1,'mes'=>$html,'other_data'=>$attr);
	 }
      
	/**
     * 查询某个小区已经提交完善的字段
	 * @param int  $broker_id    经纪人uid
	 * @param int  $block_id 小区id
     * return array
	 */
	 function getBlockHaveImprove($broker_id,$block_id){
		if(!$broker_id || !$block_id) return array();
		$sql = SqlCombinHelper::select_sql('growth_block_improve_audit',array('attr_field'), " broker_id = {$broker_id} and block_id = {$block_id} and status = 0 ");
		$result = $this->dbback->getAll($sql);
		$attr = array();
		if(is_array($result)){
			foreach($result as $val){
				$attr[] = $val['attr_field'];
			}
		}
		return $attr;
	 }


	/**
     * 获取小区开放完善前台数据，组装数据
	 * @param array  $block_info 小区开放完善数组值
	 * @param int  $id 小区id
     * return array
	 */
	 function getBlockImproveDate($block_info,$id){

		if(!$block_info || !is_array($block_info) || !$id) return array();
		$broker_uid = $_SESSION['broker']['uid'];
        $blockHaveImprove = $this->getBlockHaveImprove($broker_uid,$id);

        //区域和板块绑定（二者要锁定需同时锁定）
		if(in_array('streetid',$blockHaveImprove) || in_array('district',$blockHaveImprove)){
			$blockHaveImprove[] = 'streetid';
			$blockHaveImprove[] = 'district';
			$blockHaveImprove = array_unique($blockHaveImprove);
		}
 
		$blockImproveAttr = $this->getBlockImproveAttr();

        $data = array();
		$i = 0;
		foreach($block_info as $key=>$val){
			if($key == 'b_map_y') continue;
			if($key == 'b_map_x'){
				$data[$i]['attr_field'] = 'b_map';
				$data[$i]['attr_name'] = $blockImproveAttr['b_map'];
				$data[$i]['attr_info'] = array('b_map_x'=>$block_info['b_map_x'],'b_map_y'=>$block_info['b_map_y']);
				$data[$i]['have_add'] =  in_array('b_map',$blockHaveImprove) ? 1 : 0;
			}else{
				$data[$i]['attr_field'] = $key;
				$data[$i]['attr_name'] = $blockImproveAttr[$key];
				$data[$i]['attr_info'] =  $val;
				$data[$i]['have_add'] =  in_array($key,$blockHaveImprove) ? 1 : 0;
			}
 
			$i++;
		}
		return $data;
	 }


	/**
     * 批量插入经纪人小区完善属性记录
	 * @param array  $data  属性完善字段和字段值
	 * @param int  $block_id 小区id
     * return array
	 */
	 function insertImproveBatch($data,$block_id){
		if(!$data || !is_array($data)|| !$block_id) return 0;
		$broker_uid = $_SESSION['broker']['uid'];
		$broker_groupid = $_SESSION['broker']['groupid'];
      
        //获取经纪人信息
		$arrBroker = array(
			'id' => $broker_uid,
			'groupid' => $broker_groupid,
		);
     
		//（积分和经验值）获取途径
		$wb = new WayBlock();
		$alias = $wb->getInfoLevelWayAlias($block_id, 1);
        //增加的成长值
		$gbe = new GrowthBrokerExp($arrBroker);
        $exp_score = $gbe->getScoreByWayAlias($alias);

		 
		//增加的积分
		$gbc = new GrowthBrokerCredit($arrBroker);
		$credit_score = $gbc->getScoreByWayAlias($alias);

		$flag = 0;
		$sql = "insert into growth_block_improve_audit  (block_id,broker_id,attr_field,attr_info,credit_score,exp_score) values ";
        foreach($data as $key=>$val){
			$sql .= "('{$block_id}','{$broker_uid}','{$key}','{$val}','{$credit_score}','{$exp_score}'),";
		}
		 
		$sql = rtrim($sql,',');
		$this->db->Execute($sql);

		$result = $this->db->Affected_Rows();
		$result = $result ? $result : 0;

		$credit_score_all = $credit_score*$result;
		$exp_score_all = $exp_score*$result;
 
		return array('status'=>$result,'credit_score'=>$credit_score_all,'exp_score'=>$exp_score_all);
	 }

	/**
     * 查询某个等级小区小区完善列表
	 * @param string  $lev  小区等级
	 * @param int  $start  开始下标  
	 * @param int  $limit  偏移量
     * return array
	 */
	 function getBlockImproveByLev($lev,$start,$limit){
		if(!$lev) return array();
		$sql = "select b.id,b.blockname,b.district,b.lock_opennum,b.lock_outside,b.lock_flag,s.streetname  from block as b inner join block_level_info_full as l on b.id  = l.block_id left join street as s  on b.streetid = s.id where b.esta=2 and  l.level='{$lev}' order by b.lock_opennum desc,b.id desc limit {$start},{$limit}"; 
		$result = $this->dbback->getAll($sql);
		return $result;
	 }

	/**
     * 查询某个等级小区小区完善总数
	 * @param string  $lev  小区等级
     * return array
	 */
	 function getBlockImproveCountByLev($lev){
		if(!$lev) return 0;
		$sql = "select count(b.id) from block as b inner join block_level_info_full as l on b.id  = l.block_id  where b.esta=2 and  l.level='{$lev}'";  
		$result = $this->dbback->getOne($sql);
        return $result;
	 }

	/**
     * 查询我的小区完善总数
	 * @param string  $uid  经纪人uid
     * return array
	 */
	 function getMyBlockImproveCount($uid){
		if(!$uid) return 0;
		$sql = "select count(*) from  growth_block_improve_audit where broker_id = '{$uid}' order by id desc  ";  
		$result = $this->dbback->getOne($sql);
        return $result;
	 }

	/**
     * 查询我的小区完善列表
	 * @param string  $uid  经纪人uid
	 * @param int  $start  开始下标  
	 * @param int  $limit  偏移量
     * return array
	 */
	 function getMyBlockImprove($uid,$start,$limit){
		if(!$uid) return array();
		$sql = "select b.id,b.blockname,b.district,b.lock_opennum,s.streetname,a.attr_field,a.attr_info,a.ctime,a.credit_score,a.exp_score,a.status from block as b inner join growth_block_improve_audit as a on b.id  = a.block_id left join street as s  on b.streetid = s.id where  a.broker_id='{$uid}' order by a.id desc limit {$start},{$limit} ";  
		$result = $this->dbback->getAll($sql);
 
        return $result;
	 }

	/**
     * 查询小区完善总数(通过名称)
	 * @param string  $blockname  小区名称
     * return array
	 */
	 function getBlockImproveCountByName($blockname){
		if(!$blockname) return 0;
		$sql = "select count(id) from block where blockname like  '%{$blockname}%' and esta=2";  
		$result = $this->dbback->getOne($sql);
        return $result;
	 }

	/**
     * 查询我的小区完善列表(通过名称)
	 * @param string  $blockname   小区名称
	 * @param int  $start  开始下标  
	 * @param int  $limit  偏移量
     * return array
	 */
	 function getBlockImproveByName($blockname,$start,$limit){
		if(!$blockname) return array();
		$sql = "select b.id,b.blockname,b.district,b.lock_opennum,b.lock_outside,b.lock_flag,s.streetname from block as b  left join street as s  on b.streetid = s.id where  b.blockname like '%{$blockname}%' and b.esta=2 order by b.lock_opennum desc limit {$start},{$limit} ";  
		$result = $this->dbback->getAll($sql);
        return $result;
	 }

	/**
     * 查询我的小区完善(通过小区id)
	 * @param string  $blockid   小区id
     * return array
	 */
	 function getBlockImproveById($blockid){
		if(!$blockid) return array();
		$sql = "select b.id,b.blockname,b.district,b.lock_opennum,s.streetname from block as b  left join street as s  on b.streetid = s.id where  b.id ='{$blockid}' and b.esta=2";  
		$result = $this->dbback->getRow($sql);
        return $result;
	 }


	/**
     * 批量插入到小区图片审核库
	 * @param int  $block_info   小区信息
	 * @param array  $pic_arr  小区图片数组 
     * return int
	 */
	 function addBlockImprovePic($block_info,$pic_arr){
		if(!$block_info || !$pic_arr || !is_array($pic_arr)) return 0;
		$uid = $_SESSION['broker']['uid'];
        $broker_groupid = $_SESSION['broker']['groupid'];
	    
        $time = time();

		////////////////////////////////图片入库////////////////////////////
		$data = array();
		foreach($pic_arr as $key=>$val){
            $data[$key]['block_id'] = $block_info['id'];
			$data[$key]['blockname'] = $block_info['blockname'];
			$data[$key]['uid'] = $uid;
			$data[$key]['pic'] = $val;

            $sql = "insert into admin_pic_entry (`blockid`,`blockname`,`sort`,`pic_url`,`dateline`,`uid`) values ";
			$sql .= "('".$block_info['id']."','".$block_info['blockname']."','1','".$val."','{$time}','{$uid}');";
			$this->db->Execute($sql); 
		    $data[$key]['sid'] = $this->db->Insert_ID();
		}
 
 
		///////////////////插入到图片完善审核表//////////////////////
		//获取经纪人信息
		$arrBroker = array(
			'id' => $uid,
			'groupid' => $broker_groupid,
		);
		//（积分和经验值）获取途径
		$wb = new WayBlock();
		$alias = $wb->getInfoLevelWayAlias($block_info['id'], 2);
        //增加的成长值
		$gbe = new GrowthBrokerExp($arrBroker);
        $exp_score = $gbe->getScoreByWayAlias($alias);

		//增加的积分
		$gbc = new GrowthBrokerCredit($arrBroker);
		$credit_score = $gbc->getScoreByWayAlias($alias);
        
		$flag = 0;
		$n = 0;
		$sql = "insert into growth_pic_check_log (`sid`,`uid`,`blockid`,`blockname`,`pic_type`,`pic_url`,`add_time`,`exp_score`,`credit_score`) values ";
		foreach($data as $val){
			$flag = 1;
			$n++;
			$sql .= "('".$val['sid']."','".$val['uid']."','".$val['block_id']."','".$val['blockname']."','1','".$val['pic']."','{$time}','{$exp_score}','{$credit_score}'),";
		}
        if($flag == 1){
			$sql = rtrim($sql,',');
            $this->db->Execute($sql); 
		    $res = $this->db->Affected_Rows();
		}

		$credit_score_all  = $credit_score*$n;
		$exp_score_all = $exp_score*$n;

		$result = array('status'=>$res,'credit_score'=>$credit_score_all,'exp_score'=>$exp_score_all);
        return $result;
	 }
	 

	/**
     * 查询我的小区图片完善总数
	 * @param string  $uid  经纪人uid
     * return array
	 */
	 function getMyBlockImprovePicCount($uid){
		if(!$uid) return 0;
		$sql = SqlCombinHelper::select_sql('growth_pic_check_log',array('count(*) as num'), "uid = '{$uid}'");
		$result = $this->dbback->getOne($sql);
        return $result;
	 }


	/**
     * 查询我的小区完善图片审核列表 
	 * @param string  $uid   经纪人uid
	 * @param int  $start  开始下标  
	 * @param int  $limit  偏移量
     * return array
	 */
	 function getMyBlockImprovePicInfo($uid,$start,$limit){
		if(!$uid) return array();
		$sql = "select b.id,b.blockname,b.district,s.streetname,l.pic_url,l.pic_status,l.exp_score,l.credit_score ,l.add_time from growth_pic_check_log as l  inner join  block as b  on l.blockid = b.id  left join street as s  on b.streetid = s.id   where l.uid='{$uid}'   order by l.id desc limit {$start},{$limit} ";  
		$result = $this->dbback->getAll($sql);
        return $result;
	 }

	/**
     * 删除小区完善审核数据（默认保留90天）
	 * @param int  $days    保留天数
     * return array
	 */
	 function delBlockImproveByday($days=90){
		if(!$days || $days < 1) return 0;
		$date = date('Y-m-d H:i:s',strtotime("-".$days." day"));
		$sql = SqlCombinHelper::delete_sql('growth_block_improve_audit'," ctime < '{$date}'");  
		$this->db->Execute($sql);
        return $this->db->Affected_Rows();
	 }

	/**
     * 清空表
     */
    public function emptyTable() {
        $sql = "TRUNCATE TABLE  growth_block_attr";
        $this->db->Execute($sql);
    }

	/**
     * 初始化表字段信息
     * @param string $sql  初始化sql语句
     * @return type
     */
    public function initData($sql) {
        return $this->db->Execute($sql);
    }
}

?>
