<?php

//小区专家类
class Block_expert extends MY_Model {

    const STATUS_YES = 1;//表示目前是小区专家
    const STATUS_NO = 2;//表示不是小区专家
    const STATUS_APPLY = 3;//申请中
    const STATUS_REJECT = 4;//被驳回
    const STATUS_FIRE = 5;//解职
    const STATUS_EXPIRED = 6;//过期

    protected $uid;
    protected $companycode;
    protected $username;
    protected $truename;
    protected $agentname;
    protected $telno;
    protected $headimg;
    protected $package_id;
    protected $groupname;
    protected $wfen = 500; //最低房豆
    protected $room = 5; //优质房源数
    protected $block_num = 4;   //专家数量
    protected $freeze_num = 3;  //可以被冻结的次数	
    protected $fen = 500;//每次申请要扣的房豆
    /**
     * 成长体系中的经纪人房豆对象
     * @var  GrowthBrokerCredit
     */
    private $gbc;
    /**
     * 小区专家获取房豆方式对应的标识字符串，growth_credit_way表中可查
     * @var string 
     */
    private $expertCreditWay = 'bidAExperts';
    
    /**
     * 经纪人的小区专家的状态
     * @var type 
     */
    private $status;
    
    /**
     *
     * @var type 
     */
    private $record;
    
    private $myBlockId;

    public function __construct() {
        parent::__construct(1,1,0);
        //读取配置文件的变量
        $sys = $this->config->item('block_expert');
        if (!$sys) {
            throw new Exception;
        }
        $this->wfen = $sys['wfen'];
        $this->room = $sys['room'];
        $this->block_num = $sys['block_num'];
        $this->freeze_num = $sys['freeze_num'];
        $this->load->model('broker_model');
        $this->init();
        $this->initRecord();
        $this->init_status();
    }

    private function init() {
        $info = $this->broker_model->get_user_session();
        $this->uid = $info['uid'];
        $this->username = $info['username'];
        $this->truename = $info['truename'];
        $this->package_id = $info['package_id'];
        //$this->groupname = $info['groupname'];
        $this->companycode = $info['agentcode'];
        $this->telno = $info['telno'];
        $this->headimg = $info['smallphoto'];

        $this->agency = $this->broker_model->get_broker_company();
        $this->agentname = $this->agency?$this->agency['agentshortname']:'';
                
        //成长体系房豆对象
        $this->gbc = new GrowthBrokerCredit(array('id' => $this->uid, 'groupid' => $this->package_id));
    }
    
    private function init_status() {
        if($this->record) {
            if($this->record['esta']==='1'||$this->record['esta']==='11') {//申请的或强制指定的
                if($this->record['endtime']<time()) {
                    $this->status = self::STATUS_EXPIRED;
                } else {
                    $this->status = self::STATUS_YES;
                }
                
            } else 
            if($this->record['esta']==='0') {
                $this->status = self::STATUS_APPLY;
            } else 
            if($this->record['esta']==='-1') {
                $this->status = self::STATUS_REJECT;
            } else
            if($this->record['esta'] ==='2') {
                $this->status = self::STATUS_FIRE;
            } else {
                $this->status = self::STATUS_NO;
                $this->record = null;
            }
            
        } else {
            $this->status = self::STATUS_NO;
        }
    }

    /**
     * 返回经纪人当前状态
     * @return type
     */
    public function getStatus() {
        return $this->status;
    }

    /**
     * 当前小区专家申请的记录
     * @return type
     */
    public function getRecord() {
        return $this->record;
    }
    /**
     * 当前任职的小区专家的小区id
     * @return type
     */
    public function getMyBlockId() {
        return $this->myBlockId;
    }


    /**
     * 判断是否小区专家
     * @return boolean
     */
    public function isExpert() {
        return $this->status === self::STATUS_YES;
    }

    /**
     * 判断是否申请中
     * @return boolean
     */
    public function isApply() {
        return $this->status === self::STATUS_APPLY;
    }

    /**
     * 判断既不是小区专家也未申请小区专家
     */
    public function isNothing() {
        return $this->status === self::STATUS_NO;
    }

    /**
     * 是否被驳回
     * @return type
     */
    public function isReject() {
        return $this->status === self::STATUS_REJECT;
    }

    /**
     * 是否过期
     * @return type
     */
    public function isExpired() {
        return $this->status === self::STATUS_EXPIRED;
    }
    /**
     * 是否被解职
     * @return type
     */
    public function isFire() {
        return $this->status === self::STATUS_FIRE;
    }
    /**
     * 
     * @return type
     */
    public function get_block_num() {
        return $this->block_num;
    }

    /**
     * 
     * @return type
     */
    public function get_wfen() {
        return $this->wfen;
    }

    /**
     * 经纪人房豆
     */
    public function get_fen() {
//        $this->dbback->select("agentshortname");
//        $this->dbback->where("agentcode = '".$user_arr['agentcode']."'");
//        $arr_data = $this->dbback->get('agency')->row_array();
        $credit = $this->gbc->getValidCredit();
        return $credit;
    }

    /**
     * 验证是否申请中,是isApply的别名方法
     */
    public function is_apping() {
        return $this->isApply();
    }
    
    /**
     * 获得申请中的记录，没有申请返回空数组
     * @return type
     */
    public function get_apping() {
        $this->dbback->select("block_apply.id,block_apply.apptime,blockname,block_apply_data.reason,b_introduction,b_bus,b_metro,b_other,bi_seri");
        $this->dbback->where("block_apply.uid ='$this->uid' and agentcode ='" . $this->companycode . "' and esta=0");
        $this->dbback->from('block_apply left join block_apply_data on block_apply.uid=block_apply_data.uid and block_apply.apptime=block_apply_data.apptime');
        $query = $this->dbback->get();
        $arr_data = $query->row_array();
        //print_r($arr_data);exit;
        return $arr_data;
        //$sql = "select  from  where ";
        //return $dbback->GetRow($sql);
    }
    
    /**
     * 验证是否专家并返回信息
     */
    public function get_expert() {
        $this->dbback->select("block_apply.blockid,block_apply.apptime,block_apply.endtime,block_apply_data.reason");
        $this->dbback->from("block_apply left join block_apply_data on block_apply.uid=block_apply_data.uid");
        $this->dbback->where("block_apply.uid =" . $this->uid . " and block_apply.agentcode ='" . $this->companycode . "' and esta = 1 and endtime >'" . time() . "'");
        $this->dbback->limit(1, 0);
        $query = $this->dbback->get();
        return $query->row_array();
//        $sql = "select block_apply.blockid,block_apply.apptime,block_apply.endtime,block_apply_data.reason from block_apply left join block_apply_data on block_apply.uid=block_apply_data.uid where block_apply.uid=" . $this->uid . " and block_apply.agentcode='" . $this->companycode . "' and esta = 1 and endtime>'" . time() . "'";
//        $rs = $dbback->GetRow($sql);
//        return $rs;
    }

    private function initRecord() {
        $this->dbback->select("block_apply.blockid,block_apply.apptime,block_apply.endtime,reason,esta");
        $this->dbback->from("block_apply ");
        $this->dbback->where("block_apply.uid =" . $this->uid . " and block_apply.agentcode ='" . $this->companycode . "'");
        $this->dbback->order_by('block_apply.id','desc');
        $this->dbback->limit(1, 0);
        $query = $this->dbback->get();
        $this->record = $query->row_array();
        $this->myBlockId = $this->record?$this->record['blockid']:'';
    }
    
    /**
     * 获得线上小区详细
     */
    public function get_blockinfo($blockid) {
        $this->dbback->select("id,blockname,b_introduction,b_bus,b_metro,b_other,app");
        $this->dbback->from("block");
        $this->dbback->where("id = '$blockid'");
        $this->dbback->limit(1, 0);
        $query = $this->dbback->get();
        return $query->row_array();
//        $sql = "select blockname,b_introduction,b_bus,b_metro,b_other,app from block where id=" . $blockid;
//        return $dbback->GetRow($sql);
    }

    /**
     * 是否有处罚
     */
    public function get_festa() {
        $this->dbback->select("festa");
        $this->dbback->from("broker");
        $this->dbback->where("package_id = 3 and uid =" . $this->uid . " and agentcode =" . $this->companycode);
        $this->dbback->limit(1,0);
        $query = $this->dbback->get();
        $res = $query->row_array();
        if($res) {
            return $res['festa'];
        } else {
            return null;
        }
//        $sql = "select festa from broker where package_id=3 and uid=" . $this->uid . " and agentcode=" . $this->companycode;
//        return $dbback->GetOne($sql);
    }
    
    /**
     * 检查小区是否可申请，返回小区已有小区专家数
     */
    public function get_people($blockid) {
        $this->dbback->select("count(id) as num");
        $this->dbback->from("block_apply");
        $this->dbback->where("blockid = ".$blockid." and esta = 1 and endtime > ".time());
        $query = $this->dbback->get();
        $res = $query->row_array();
        if(!empty($res)) {
            return $res['num'];
        } else {
            return null;
        }
//        $sql = "select count(id) as num from block_apply where blockid=" . $blockid . " and esta=1 and endtime>" . time();
//        return $dbback->GetOne($sql);
    }
    
    /**
     * 强制指定默认的小区专家
     */
    public function get_init_expert($blockid) {return 0;
        $this->dbback->select("COUNT(*) as num");
        $this->dbback->from("block_apply");
        $this->dbback->where("blockid = $blockid  AND esta = 11");
        $query = $this->dbback->get();
        $res = $query->row_array();
        $intInitExpertNum = intval($res['num']);
//        $strSql = 'SELECT COUNT(*) FROM `block_apply` WHERE blockid = ' . $blockid . ' AND esta = ' . "'11'";
//        $intInitExpertNum = $db->GetOne($strSql);
//        //我爱我家在指定的小区上显示小区专家
        return $intInitExpertNum ;
    }

    /**
     * 检查小区是否可编辑
     */
    public function get_app($blockid) {
        if (empty($blockid))
            return;
        $this->dbback->select("app");
        $this->dbback->from("block");
        $this->dbback->where("id=$blockid");
        $this->dbback->limit(1,0);
        $query = $this->dbback->get();
        $res = $query->row_array();
        if($res) {
            return $res['app'];
        } else {
            return null;
        }
//        $sql = "select app from block where id=$blockid";
//        return $dbback->GetOne($sql);
    }

    /**
     * 小区还剩的小区专家空缺位
     * @param type $blockid
     */
    public function block_avalid_expert_num($blockid) {
        return $this->block_num-$this->block_expert_num($blockid);
    }
    
    /**
     * 小区目前有多少专家
     * @param type $blockid
     * @return type
     */
    public function block_expert_num($blockid) {
        //预设的小区专家数
        $a = $this->get_init_expert($blockid);
        //通过申请当上的小区专家数
        $b = intval($this->get_people($blockid));
        return $a+$b;
    }


    //符合条件的小区
    public function get_block() {
        //房豆不足，满足条件的小区为空数组
        if ($this->get_fen() < $this->get_wfen()) {
            return array();
        }
        
        $this->dbback->select("COUNT(id) AS num,blockid")
                ->from("sell")
                ->where("uid = ".$this->uid." AND agentcode='B000' AND esta='1' ")
                ->group_by("blockid")->having("num >= $this->room")//房源数大于要求的数目
                ->order_by("num","DESC");
        $query = $this->dbback->get();
        $rs = $query->result_array();//AND blockid IN (SELECT id FROM block WHERE  esta = 2 )
        //取得满足条件的小区id数组
        //$ids = array();
        foreach ($rs as &$val) {
            $blockid = $val['blockid'];
            $houseNum = $val['num'];
            //房源数满足
            //var_dump($houseNum >= $this->room);
            if ($houseNum >= $this->room) {
                //$sql = "SELECT blockname FROM block WHERE id=" . $value;
                //专家数
                $val['expert_num'] = $this->block_expert_num($blockid);
                //可用空缺数
                $val['avalid_expert_num'] = $this->block_num-$val['expert_num'];
                $this->dbback->select("id,blockname")
                ->from("block")
                ->where("id = $blockid");
                $query1 = $this->dbback->get();
                $res = $query1->row_array();
                //小区名称
                $val['blockname'] = $res['blockname'];
                //$ids[] = $blockid;
                //小区专家最早到期时间
                if($val['avalid_expert_num']<=0) {
                    $this->dbback->select("endtime")->from("block_apply")
                            ->where("blockid = '".$blockid."' and endtime > ".time())
                            ->order_by("endtime","asc");
                    $query2 = $this->dbback->get();
                    $res2 = $query2->row_array();
                    $val['endtime'] = $res2['endtime'];
                } else {
                    $val['endtime'] = null;
                }
                //状态，未申请，申请中（待审核），被驳回，在职中
                if($this->isNothing()) {
                    $val['status'] = '未申请';
                    $val['action'] = array('key'=>'apply','name'=>'申请');
                } 
                if($this->isExpert()) {
                    if($this->myBlockId==$val['blockid']) {
                        $val['status'] = '在职中';
                    } else {
                        $val['status'] = '未申请';
                    }
                    $val['action'] = array();
                }
                if($this->isApply()) {
                    if($this->myBlockId==$val['blockid']) {
                        $val['status'] = '待审核';
                        $val['action'] = array('key'=>'cancel','name'=>'取消');
                    } else {
                        $val['status'] = '未申请';
                        $val['action'] = array();
                    }
                } 
                
                if($this->isReject()) {
                    if($this->myBlockId==$val['blockid']) {
                       $val['status'] = '被驳回';
                    } else {
                        $val['status'] = '未申请';
                    } 
                    $val['action'] = array('key'=>'apply','name'=>'申请');
                }
                if($this->isExpired()) {
                    if($this->myBlockId==$val['blockid']) {
                       $val['status'] = '已到期';
                    } else {
                        $val['status'] = '未申请';
                    } 
                    $val['action'] = array('key'=>'apply','name'=>'申请');
                }
                
                if($this->isFire()) {
                    if($this->myBlockId==$val['blockid']) {
                       $val['status'] = '被解职';
                    } else {
                        $val['status'] = '未申请';
                    } 
                    $val['action'] = array('key'=>'apply','name'=>'申请');
                }
            }
        }
        //print_r($rs);exit;
        return $rs;
        //查满足条件的小区名称
//        $arr_block = array();
//        if(!$ids) {//没有小区直接返回空数组
//            return $arr_block;
//        }
        //继续处理
//        $this->dbback->select("id,blockname")
//                ->from("block")
//                ->where("id = (".implode(",", $ids).")");
//        $query1 = $this->dbback->get();
//        $res = $query1->result_array();
//        foreach ($res as $key => $value) {
//            $arr_block[$value['id']] = $value['blockname'];
//        }
        return $arr_block;
    }


    //满足条件但是小区专家人数满的小区
    function get_block_full() {
        //房豆不足，满足条件的小区为空数组
        if ($this->get_fen() < $this->get_wfen()) {
            return array();
        }
        $this->dbback->select("blockid,count(id) as num")
                ->from("sell")
                ->where("uid = ".$this->uid." and agentcode = 'B000' and esta = '1' and isstar = '3' and blockid in ( select id from block where app in (1,2))")
                ->group_by("blockid")
                ->order_by("num","DESC");
        $query = $this->dbback->get();
        $rs = $query->result_array();
        
        //$sql = "select blockid,count(id) as num from sell where uid=" . $this->uid . " and agentcode='B000' and esta='1' and isstar='3' and blockid in (select id from block where app in (1,2)) group by blockid order by num desc";
        //$rs = $dbback->GetAssoc($sql);
        $arr_block = array();
        foreach ($rs as $k => $val) {
            $key = $val['blockid'];
            $value = $val['num'];
            if ($value >= $this->room && $this->block_avalid_expert_num($key)<=0) {
                //$sql = "select blockname from block where id=" . $key;
                //$arr_block[$key]['blockname'] = $dbback->GetOne($sql);
                $this->dbback->select("id,blockname")
                    ->from("block")
                    ->where("id = ".$key);
                $query1 = $this->dbback->get();
                $arr_block[$key]['blockname'] = $query1->row_array();
                
                $this->dbback->select("endtime")->from("block_apply")
                        ->where("blockid = '".$key."' and endtime > ".time())
                        ->order_by("endtime","asc");
                $query2 = $this->dbback->get();
                $res2 = $query2->row_array();
                if($res2) {
                    $arr_block[$key]['endtime'] = $res2['endtime'];
                } else {
                    $arr_block[$key]['endtime'] = null;
                }
                //$sql = "select endtime from block_apply where blockid='" . $key . "' and endtime>'" . time() . "' order by endtime asc ";
                //$arr_block[$key]['endtime'] = $db->GetOne($sql);
            }
            //echo $value.','.$this->get_people($key)."<br />";
        }
        return $arr_block;
    }

    //补充资料(replace)
    function insert_block_apply_data($blockid, $reason, $b_introduction, $b_bus, $b_metro, $b_other, $apptime, $uptime = '') {
        global $db;
        $bi_seri = '';
        $img_arr = array();
        if (isset($_REQUEST['p_filename'])) {
            foreach ($_REQUEST['p_filename'] as $k => $v) {
                $token = explode("=", $_REQUEST['p_filename'][$k]);
                $filename = substr($_REQUEST['p_filename'][$k], 0, strpos($_REQUEST['p_filename'][$k], '?'));
                $img_arr[filename][] = $filename;
                $img_arr[title][] = $_REQUEST['p_title'][$k];
                $img_arr[type][] = $_REQUEST['p_sort'][$k];
                $idkind = substr($token[0], -3);
                if ($idkind == 'pid')
                    $db->Execute("delete from house_upload_provisional where id=$token[1]");
            }
            $bi_seri = serialize($img_arr);
        }
        $sql = "replace into block_apply_data (uid,reason,b_introduction,b_bus,b_metro,b_other,bi_seri,blockid,apptime,uptime,flg) values (" . $this->uid . "," . $db->qstr($reason) . "," . $db->qstr($b_introduction) . "," . $db->qstr($b_bus) . "," . $db->qstr($b_metro) . "," . $db->qstr($b_other) . ",'" . $bi_seri . "'," . $blockid . ",'" . $apptime . "','" . $uptime . "',0)";
        $db->Execute($sql);
    }

    /**
     * 申请小区专家
     * @param type $blockid
     * @param type $blockname
     * @param type $reason
     * @return int
     */
    function insert_block_apply($blockid, $blockname, $reason) {
        if($this->isExpert()) {//已经是小区专家
            return 3;
        } 
        if($this->isApply()) {//已经在申请了
            return 5;
        }
        //还不是小区专家可以申请
        //判断是否有足够的房豆
        if ($this->get_fen() < $this->get_wfen()) {//分数不够
            return 2;
        }
        //是否有空缺
        $number = $this->block_avalid_expert_num($blockid);
        if ($number <= 0) {
            return 4;
        }
        
        //分数够
        $apptime = time();
        $data = array(
                'agentcode' => $this->companycode ,
                'agentname' => $this->agentname ,
                'uid' => $this->uid,
                'username' => $this->username,
                'truename' => $this->truename,
                'telno' => $this->telno,
                'headimg' => $this->headimg,
                'blockid' => $blockid,
                'blockname' => $blockname,
                'reason' => $reason,
                'apptime' =>$apptime,
                'esta' =>0,);
        $this->db->insert('block_apply', $data); 
//        $sql = "insert into block_apply (agentcode,agentname,uid,username,truename,telno,headimg,blockid,blockname,reason,apptime,esta) values (
//            '" . $this->companycode . "','" . $this->agentname . "'," . $this->uid . ",'" . $this->username . "','" . $this->truename . "','" . $this->telno . "','" . $this->headimg . "'," . $blockid . ",'" . $blockname . "','" . $reason . "','" . $apptime . "',0)";
//        $db->Execute($sql);
        //先行扣分
        $res = $this->gbc->reduce($this->expertCreditWay, '申请小区专家预扣房豆', $this->fen);
        //apply::waster_fen($this->uid);
        return 1;

    }

    /**
     * 清除用户申请记录
     */
    public function del_apply($blockid) {
//        $sql = "delete from block_apply where uid=" . $this->uid . " and esta=0";
//        $db->Execute($sql);
        $this->db->where("uid = '$this->uid' and blockid = '$blockid' and esta = 0")->delete("block_apply");
        //返还房豆
//        include_once($base_dir . "housecp/block/apply.class.php");
//        apply::return_fen($this->uid);
        $this->gbc->increase($this->expertCreditWay, '申请小区专家失败，返还房豆', $this->fen);
    }

    /**
     * 冻结条数
     * @return type
     */
    public function expert_freeze() {
        $month = mktime(0, 0, 0, date("m"), 1, date("Y"));
        $nextmonth = mktime(0, 0, 0, date("m") + 1, 1, date("Y"));
        //$total = $dbback->GetOne("select count(*) from house_freeze where uid=" . $this->uid . " and freezetime>$month and freezetime<$nextmonth and esta != 3");
        $this->dbback->select("id")->from("house_freeze")->where("uid = ".$this->uid." and freezetime > $month and freezetime < $nextmonth and esta != 3");
        $query = $this->dbback->get();
        return $query->num_rows();
        //return $total;
    }

    /**
     * 公共接口
     * @param type $uid
     * @return boolean
     */
    public static function get_info($uid) {
        //$sql = "select * from block_apply where uid=" . $uid . " and esta=1 and endtime>" . time();
        //$info = $dbback->GetRow($sql);
        $this->dbback->from("block_apply")->where(" uid = ".$uid." and esta = 1 and endtime > ".time())->limit(1,0);
        $query = $this->dbback->get();
        $info = $query->row_array();
        return $info;
    }

}
?>

