<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class real_house_model  extends MY_Model
{
    public function __construct()
    {
        parent::__construct(1, 1, 1);
    }

    /**
     * 按照规定的格式显示，不足的补0
     * @param int $value 值
     * @param int $length 长度
     * @return string
     */
    private static function formatValue($value, $length)
    {
        return sprintf("%0{$length}d", $value);
    }

    /**
     * 随机产生的订单号后四位数
     * 1-9999
     */
    private static function randValue()
    {
        return rand(1, 9999);
    }

    public function getbrokermoney($uid){
        $this->dbback->select("real_house_money");
        $this->dbback->where('uid = '.intval($uid));
        $result = $this->dbback->get('broker')->row_array();
        return $result;
    }
    /**
     * 获取某个产品的交易号
     * @return int
     */
    public function getTransactionId()
    {
        //防止订单ID与租售宝重复，$type 定义为88
        $type = 88;
        $formatType = self::formatValue($type, 2);
        //随机数
        $randValue = self::formatValue(self::randValue(), 4);
        //订单号
        return time() . $formatType . $randValue;
    }

    /**
     * @param array $data
     * @return mixed
     */
    public function createOrder($data = array())
    {
        if ($this->db->insert('real_house_broker_orders', $data))
        {
            return $this->db->insert_id();
        }
    }

    /**
     * 获取保证金订单
     * @param $id
     * @return mixed
     */
    public function getOrderById($id)
    {
        $this->dbback->select("*");
        $this->dbback->where('id = '.intval($id));
        $result = $this->dbback->get('real_house_broker_orders')->row_array();
        return $result;
    }

    /**
     * 获取已支付的保证金订单
     * @param $brokerId
     * @return mixed
     */
    public function getOrderByBrokerId($brokerId)
    {
        $this->dbback->select("*");
        $this->dbback->where('pay_status = 1 and broker_id = '.intval($brokerId));
        $this->dbback->order_by('pay_time', 'DESC');
        $result = $this->dbback->get('real_house_broker_orders')->row_array();
        return $result;
    }
    /**
     * 获取经纪人保证金余额
     * @param $id
     * @return mixed
     */
    public function getBrokerRealHouseMoney($id)
    {
        $this->dbback->select("real_house_money");
        $this->dbback->where('uid = '.intval($id));
        $result = $this->dbback->get('broker')->row_array();
        return $result['real_house_money'];
    }


    /**
     * 获取经纪人首次充值时间
     */
    public function getBrokerPayTime($id)
    {

        $this->dbback->select("pay_time");
        $this->dbback->where('uid = '.intval($id));
        $result = $this->dbback->get('broker')->row_array();
        return $result['pay_time'];
    }

    /**
     * 获取指定时间六个月的时间
     */
    public function getSixMonthTime($first_pay_time,$type='-6')
    {
        $first_pay_time  = date("Y-m-d H:i:s",$first_pay_time);
        $result          = $this->db->query("select date_add('".$first_pay_time."', interval '".$type."' month) as month_six")->row_array();
        $result['month_six'] = strtotime($result['month_six']);
        return $result['month_six'];
    }


    /**
     * 获取指定时间前六个月之内的申请提现次数
     * $uid 经纪人id
     * $six_month_before 时间期限
     * $type 3是提现
     * $status 0待处理，1是已处理，2是处理成功，3，处理失败
     */
    public function getSixMonthApplyTimes($uid,$six_month_before,$type,$status)
    {
        $sql = 'SELECT count(id) as apply_count FROM real_house_broker_log WHERE broker_id='.$uid.' and type='.$type.' and status='.$status.' and create_time >= '.$six_month_before.'';
        $result= $this->db->query($sql)->row_array();
        return $result['apply_count'];
    }

    /**
     * 获取指定时间前六个月之内的申请
     */
    public function getSixMonthFristApply($uid,$six_month_before,$type,$status)
    {
        $sql = 'SELECT id,create_time FROM real_house_broker_log WHERE broker_id='.$uid.' and type='.$type.' and status='.$status.' and create_time >= '.$six_month_before.' order by create_time DESC limit 2';
        $result= $this->db->query($sql)->result_array();
        return $result;
    }


    /**
     * 获取经纪人信息
     * @param $id
     * @return mixed
     */
    public function getRealHouseInfo($id)
    {
        $this->dbback->select("uid,username,truename,telno,real_house_money,real_status");
        $this->dbback->where('uid = '.intval($id));
        $result = $this->dbback->get('broker')->row_array();
        return $result;
    }

    /**
     * 支付完成操作
     * @param $data
     * @return mixed
     */
    public function payFinish($data)
    {
        $id = $data['id'];
        $brokerId = $data['broker_id'];
        $money = $data['money'];
        $transaction_id = $data['transaction_id'];
        //获取经纪人保证金信息
        $moneyData = $this->getRealHouseInfo($brokerId);
        $realHouseMoney = $moneyData['real_house_money'];
        $newMoney = $realHouseMoney + $money;
        $time = time();
        //更改订单状态
        $result = $this->updateOrder($id, array('pay_status' => 1, 'payment_order_id' => $data['new_payment_order_id'], 'pay_time' => $time));
        if ($result) {
            $this->updateBroker($brokerId, array('real_house_money' => floatval($newMoney),'real_status'=>2));

            $payTypeList = array('wxpay' => '微信支付', 'alipay' => '支付宝');
            $payTypeName = $payTypeList[$data['pay_type']];
            $reason = '保证金充值，支付渠道：'.$payTypeName;
            $logData = array(
                'transaction_id' => $transaction_id,
                'payment_order_id' => $data['new_payment_order_id'],
                'type' => 1,
                'broker_id' => $brokerId,
                'broker_username' => $moneyData['username'],
                'broker_phone' => $moneyData['telno'],
                'broker_name' => $moneyData['truename'],
                'money' => $money,
                'remain_money' => $newMoney,
                'create_time' => $time,
                'source' => 1,
                'ip' => GetIP(),
                'status' => 2,
                'reason' => $reason
            );
            $this->insertLog($logData);
            //新增或者更新经纪人状态
            $accountData = array(
                'uid' => $brokerId,
                'username' => $moneyData['username'],
                'truename' => $moneyData['truename'],
                'telno' => $moneyData['telno'],
                'status' => 1,
                'time' => $time,
                'balance_time' => $time,
                'reason' => 0,
                'is_ka_status' => 0
            );
            $this->saveAccount($accountData);
        }
        return $result;
    }

    /**
     * 更新经纪人状态
     * @param $brokerId
     * @param $data
     * @return mixed
     */
    public function updateBroker($brokerId, $data)
    {
        $this->db->where('uid', $brokerId);
        $result = $this->db->update('broker', $data);
        return $result;
    }

    /**
     * 判断是否经纪人是否有支付成功的记录
     * @param $brokerId
     * @param $data
     * @return mixed
     */
    public function getBrokerPayRecord($brokerId)
    {
        $this->dbback->select("id");
        $this->dbback->where('pay_status = 1 and broker_id = '.intval($brokerId));
        $pay_result = $this->dbback->get('real_house_broker_orders')->row_array();
        return $pay_result;
    }

    /**
     * 更新举报的申述状态
     * @param $id
     * @param $data
     * @return mixed
     */
    public function updateReport($id, $data)
    {
        $this->db->where('id', $id);
        $result = $this->db->update('real_house_report', $data);
        return $result;
    }

    /**
     * 更新保证金订单
     * @param $id
     * @param $data
     * @return mixed
     */
    public function updateOrder($id, $data)
    {
        $this->db->where('id', $id);
        $result = $this->db->update('real_house_broker_orders', $data);
        return $result;
    }

    /**
     * 记录保证金明细日志
     * @param $data
     * @return mixed
     */
    public function insertLog($data)
    {
        if ($this->db->insert('real_house_broker_log', $data))
        {
            return $this->db->insert_id();
        }
    }

    /**
     * 记录打款记录
     * @param $data
     * @return mixed
     */
    public function insertRemit($data)
    {
        if ($this->db->insert('real_house_remit', $data))
        {
            return $this->db->insert_id();
        }
    }

    /**
     * 插入申述表
     * @param $data
     * @return mixed
     */
    public function insertAppeal($data)
    {
        if ($this->db->insert('real_house_appeal', $data))
        {
            return $this->db->insert_id();
        }
    }

    /**
     * 插入申述图片表
     * @param $data
     * @return mixed
     */
    public function insertAppealImage($data)
    {
        if ($this->db->insert('real_house_appeal_image', $data))
        {
            return $this->db->insert_id();
        }
    }

    /**
     * 记录房源日志
     * @param $data
     * @return mixed
     */
    public function insertHouseLog($data)
    {
        if ($this->db->insert('real_house_set_log', $data))
        {
            return $this->db->insert_id();
        }
    }

    /**
     * 保存经纪人账号信息
     * @param $data
     * @return mixed
     */
    public function saveAccount($data)
    {
        $result = $this->db->replace('real_house_account', $data);
        return $result;
    }

    /**
     * 获取经纪人保证金日志
     * @param $brokerId
     * @return mixed
     */
    public function getBrokerLog($brokerId)
    {

        $this->dbback->select("*");
        $this->dbback->where('broker_id = '.intval($brokerId));
        $this->dbback->order_by('id', 'DESC');
        $result = $this->dbback->get('real_house_broker_log')->result_array();
        return $result;
    }

    /**
     * 获取举报信息
     * @param array $data
     * @param int $offset
     * @param int $limit
     * @param string $select
     * @return mixed
     */
    public function getReport($data = array(), $offset = 0, $limit = 0, $select = "*")
    {
        $where = '';
        foreach ($data as $key => $value) {
            $where .= $where ? ' and '. $key .' = "'. $value .'"' : $key .' = "'. $value .'"';
        }
        $this->dbback->select($select);
        $this->dbback->where($where);
        $this->dbback->order_by('id', 'DESC');
        $this->dbback->limit($limit, $offset);
        $result = $this->dbback->get('real_house_report')->result_array();
        return $result;
    }

    /**
     * 获取举报总数
     * @param array $data
     * @return mixed
     */
    public function getReportCount($data = array())
    {
        $where = '';
        foreach ($data as $key => $value) {
            $where .= $where ? ' and '. $key .' = "'. $value .'"' : $key .' = "'. $value .'"';
        }
        $this->dbback->select("count(*) count");
        $this->dbback->where($where);
        $result = $this->dbback->get('real_house_report')->row_array();
        //echo $this->dbback->last_query();die;
        return $result['count'];
    }

    /**
     * 获取房源申述次数
     * @param array $data
     * @return mixed
     */
    public function getAppealCount($data = array())
    {
        $where = '';
        foreach ($data as $key => $value) {
            $where .= $where ? ' and '. $key .' = "'. $value .'"' : $key .' = "'. $value .'"';
        }
        $where .= ' and appeal != 0';
        $this->dbback->select("count(*) count");
        $this->dbback->where($where);
        $result = $this->dbback->get('real_house_report')->row_array();
        return $result['count'];
    }


    /**
     *
     * @param int $brokerId
     * @return mixed
     */
    public function get_real_house_account($brokerId)
    {
        $where = 'uid = '.$brokerId;
        $this->dbback->select("balance_time");
        $this->dbback->where($where);
        $result = $this->dbback->get('real_house_account')->result_array();
        return $result;
    }


    /**
     *
     * @param int $brokerId
     * @return mixed
     */
    public function get_real_house_sell_info($id)
    {
        $where = 'id = '.$id;
        $this->dbback->select("is_real_house");
        $this->dbback->where($where);
        $result = $this->dbback->get('sell')->result_array();
        return $result;
    }

    /**
     * 申请提现操作
     * @param $uid
     * @return mixed
     */
    public function applyRemit($uid,$type='')
    {
        //获取经纪人信息
        $brokerData = $this->getRealHouseInfo($uid);
        // 2018年7月21日 09:55:14  xzk  qq724087709
        //保证金提现条件判断变更
        /*if (!$brokerData['real_status']>0) {
             return false;
        }*/
        if ($brokerData['real_house_money'] < 299) {
            return false;
        }
        //更新经纪人房源金额
        $updateData = array();
        $updateData['real_house_money'] = $brokerData['real_house_money'] - 299;
        $updateData['real_status']      = 0;
        $flag = $this->updateBroker($uid, $updateData);

        if ($flag) {
            $time = time();
            //插入经纪人账号表
            //新增或者更新经纪人状态
            $real_house_account  =$this->get_real_house_account($uid);

            $accountData = array(
                'uid' => $uid,
                'username' => $brokerData['username'],
                'truename' => $brokerData['truename'],
                'telno' => $brokerData['telno'],
                'status' => 0,
                'time' => $time,
                'balance_time' => $real_house_account[0]['balance_time'],
                'reason' => 2
            );
            if($type){
                $accountData['status'] = 1;
                $accountData['reason'] = 0;
                $accountData['is_ka_status'] = 1;
            }
            $this->saveAccount($accountData);
            //插入真房源金额日志
            $payTypeList = array('wxpay' => '微信支付', 'alipay' => '支付宝');
            //获取最近的一条支付记录
            $data = $this->getOrderByBrokerId($uid);
            $payTypeName = $payTypeList[$data['pay_type']];
            if($type){
                $reason = '申请提现(系统)，提现渠道：'.$payTypeName;
            }else{
                $reason = '申请提现，提现渠道：'.$payTypeName;
            }
            $logData = array(
                'type' => 3,
                'broker_id' => $uid,
                'broker_username' => $brokerData['username'],
                'broker_phone' => $brokerData['telno'],
                'broker_name' => $brokerData['truename'],
                'money' => -299,
                'payment_order_id' => $data['payment_order_id'],
                'remain_money' => 0,
                'create_time' => $time,
                'source' => 1,
                'ip' => GetIP(),
                'status' => 0,
                'reason' => $reason
            );
            $logId = $this->insertLog($logData);
            //插入打款管理表
            if ($logId) {
                $remitData = array(
                    'infofrom' => 5,
                    'uid' => $uid,
                    'username' => $brokerData['truename'],
                    'telno' => $brokerData['telno'],
                    'paytype' => $data['pay_type'],
                    'orderid' => $data['payment_order_id'],
                    'price' => 299,
                    'reason' => '提现',
                    'isfrom' => $brokerData['username'],
                    'applytime' => $time,
                    'log_id' => $logId,
                    'status' => 0
                );
                $this->load->model('broker_model');
                $session_info = $this->broker_model->get_user_session();
                if(!empty($session_info['alipay_acount'])){
                    $remitData['account'] = $session_info['alipay_acount'];
                }
                /*if($type){
                    $remitData['reason'] = '';
                }*/
                $remitId = $this->insertRemit($remitData);
                //获取当前所有房源
                $houseInfo = $this->getBrokerRealHouse($uid);
                //下架所有房源
                if($type){
                    //当公司主动提现时，不下架房源
                    return false;
                }
                $houseIds = array();
                foreach ($houseInfo as $key => $value) {
                    $houseIds[] = $value['id'];
                }
                $this->updateRealHouse($houseIds);
                //记录日志
                $houseLog = array();
                $houseLog['uid'] = $uid;
                $houseLog['tbl'] = 'sell';
                $houseLog['type'] = 0;
                $houseLog['source'] = 0;
                $houseLog['ctime'] = $time;
                $houseLog['ip'] = GetIP();
                $houseLog['reason'] = 4; //项目退出
                $houseLog['operatetime'] = time();
                foreach ($houseInfo as $key => $value) {
                    $houseLog['rowid'] = $value['id'];

                    $this->insertHouseLog($houseLog);
                }
            }

            $this->canclevr($uid);
        }
    }


    public function canclevr($broker_id){
        $url = "http://newrent.house365.com/api/zsb/cancle-vr";
        $pa['broker_id'] = $broker_id;
        $pa['token'] = md5($broker_id.'365zsh');
        $this->request_post_($url,$pa);
    }

    public  function request_post_($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
    }


    /**
     * 更新房源
     * @param string $houseIds
     * @return mixed
     */
    public function updateRealHouse($houseIds)
    {
        $where = 'id in ('. implode(',',$houseIds) .')';
        $this->db->where($where);
        $data = array();
        //需求变更注释掉
        //$data['esta'] = 2;
        $data['is_real_house'] = 0;
        $data['lucupdatetime'] = time();
        $result = $this->db->update('sell', $data);
        return $result;
    }

    /**
     * 获取房源申述次数
     * @param int $brokerId
     * @return mixed
     */
    public function getBrokerRealHouse($brokerId)
    {
        $where = 'uid = '.$brokerId.' and esta = 1 and infofrom = 5 and is_real_house = 1 ';
        $this->dbback->select("id");
        $this->dbback->where($where);
        $result = $this->dbback->get('sell')->result_array();
        return $result;
    }

    public function getUidRealHouseNum($uid)
    {
        $sql = "SELECT id FROM sell where uid='$uid' and esta = 1 and is_real_house = 1";
        $result = $this->db->query($sql);
        return $result->num_rows;
    }

    public function getUidRealHouseNumExceptId($uid,$house_id)
    {
        $sql = "SELECT id FROM sell where uid='$uid' and is_real_house = 1 and id !={$house_id}";
        $result = $this->db->query($sql);
        return $result->num_rows;
    }

    public function insertReal_House_Set_log($uid,$rowid,$type,$operation_status=null)
    {
        $data           =array();
        $data['uid']    =$uid;
        $data['tbl']    ='sell';
        $data['rowid']  =$rowid;
        $data['type']    =$type;
        $data['source']  =0;
        $data['ctime']   =time();
        $data['ip']      =get_ip();
        $data['reason'] = $operation_status; //操作原因
        $data['operatetime'] = time();
        //print_r($data);die;
        $this->db->insert('real_house_set_log', $data);
        if($this->db->insert_id())
        {
            $rs =array();
            $rs['is_real_house']    =$type;
            $res = $this->real_vr_option($uid,$rowid,$type);
            $newre = array_merge($rs,$res);
            $this->db->where('id', $rowid);
            $this->db->update('sell', $newre);
        }
    }

    /**
     * @param $uid 经纪人id
     * @param $rowid 房源id
     * @param $type 0 取消真房源，1设置真房源
     */
    public function real_vr_option($uid,$rowid,$type,$source=0){


        $rs =array();
        //取消真房源时，要去掉

        $this->load->model('broker_model');
        $session_info = $this->broker_model->get_user_session();
        $uid = $session_info['uid'];

        $real = $this->dbback->from('broker')->where(array('uid'=>$uid,'real_status !='=>0))->get()->row_array();
        //只有房源不是放心看，且 经纪人 开通放心看时
        if(!$type && $real){

            $vrapps['shot_status'] = 5;
            $this->db->where(array('broker_id'=>$uid,'house_id'=>$rowid))->where_in('shot_status',array(1,2,7,8))->update('vr_applay',$vrapps);
            $rs['vr_model_id'] = 'vr_id_empty';
            $rs['isvr'] = 0;

            if($source){
                $this->db->where('id', $rowid)->update('sell', $rs);
            }
            return $rs;
        }else{
            //设置真房源时，检测当前的房源是否已被申请过拍摄VR
            $vrapp = $this->db->from('vr_applay')->where(array('broker_id'=>$uid,'house_id'=>$rowid,'vr_model_id !='=>''))->order_by('save_time','desc')->get()->row_array();
            if($vrapp){
                if($vrapp['vr_model_id'] != 'vr_id_empty'){
                    $rs['vr_model_id'] = $vrapp['vr_model_id'];
                    $rs['isvr'] = 1;
                    if($source){
                        $this->db->where('id', $rowid)->update('sell', $rs);
                    }
                }
            }
            return $rs;
        }
    }


    public function insertReal_House_Set_log2($uid,$rowid,$type,$operation_status = null)
    {


        $data           =array();
        $data['uid']    =$uid;
        $data['tbl']    ='sell';
        $data['rowid']  =$rowid;
        $data['type']    =$type;
        $data['source']  =0;
        $data['ctime']   =time();
        $data['ip']      =get_ip();
        $data['reason'] = $operation_status;
        $data['operatetime'] = time();
        //print_r($data);die;
        $this->db->insert('real_house_set_log', $data);

    }


    public function getUidRealHouseInfo($rowid)
    {
        $this->dbback->select("id,uid,blockid,subfloor,floor,totalfloor,room,hall,toilet,buildarea");
        $this->dbback->where('id = '.intval($rowid));
        $result = $this->dbback->get('sell')->row_array();


        $uid        =$result['uid'];
        $blockid    =$result['blockid'];
        $subfloor   =$result['subfloor'];
        $floor      =$result['floor'];
        $totalfloor =$result['totalfloor'];
        $room       =$result['room'];
        $hall       =$result['hall'];
        $toilet     =$result['toilet'];
        $buildarea_start  =$result['buildarea']-1;
        $buildarea_end  =$result['buildarea']+1;




        $this->dbback->select("id");
        $this->dbback->where('uid = '."'".$uid."'".' and is_real_house =1'.' and blockid ='.$blockid.' and subfloor ='.$subfloor.' and floor ='.$floor.' and totalfloor ='.$totalfloor.' and room ='.$room.' and hall ='.$hall.' and toilet ='.$toilet.' and buildarea >='.$buildarea_start.' and buildarea<='.$buildarea_end);
        $val = $this->dbback->get('sell')->row_array();
        if(!empty($val))
        {
            return 1;
        }else
        {
            return 0;
        }
    }



    public function insertCreditImage($tbl,$rowid,$arr)
    {
        $sql = "delete from credit_image where $tbl='$tbl' and houseid =$rowid ";
        $this->db->query($sql);

        if(!empty($arr))
        {
            foreach ($arr as $key=>$rs)
            {
                $filename  =$rs;
                $sql_insert = "insert into  credit_image (tbl,filename,houseid) values ($tbl,'$filename','$rowid') ";

                $this->db->query($sql_insert);
            }
        }


    }

    public function DeleteCreditImage($tbl,$rowid)
    {
        $sql = "delete from credit_image where $tbl='$tbl' and houseid =$rowid ";
        $this->db->query($sql);
    }


    public function getInfoByRowid($rowid)
    {
        $sql = "SELECT id FROM sell where id='$rowid' and is_real_house = 1 ";
        $result = $this->dbback->query($sql);

        return $result->num_rows;
    }


    public function getCreditImageByRowid($tbl,$rowid)
    {
        $sql = "SELECT filename FROM credit_image where tbl='$tbl' and houseid = $rowid ";
        $result = $this->dbback->query($sql);
        if($result->num_rows) {
            $arr = $result->result_array();
            return $arr;
        }else
        {
            return array();
        }

    }


    //发布页面激活真房源标签
    public function getUidRealHouseByOperate($result,$uid,$house_id)
    {
        $uid        =$uid;
        $blockid    =$result['blockid'];
        $subfloor   =$result['subfloor'];
        $floor      =$result['floor'];
        $totalfloor =$result['totalfloor'];
        $room       =$result['room'];
        $hall       =$result['hall'];
        $toilet     =$result['toilet'];
        $buildarea_start  =$result['buildarea']-1;
        $buildarea_end  =$result['buildarea']+1;


        $this->dbback->select("id");
        if($house_id!=0)
        {
            $this->dbback->where('uid = ' . "'" . $uid . "'" . ' and is_real_house =1' . ' and blockid =' . $blockid . ' and subfloor =' . $subfloor . ' and floor =' . $floor . ' and totalfloor =' . $totalfloor . ' and room =' . $room . ' and hall =' . $hall . ' and toilet =' . $toilet . ' and buildarea >=' . $buildarea_start . ' and buildarea<=' . $buildarea_end." and id !=".$house_id);
            $val = $this->dbback->get('sell')->row_array();

        }else {
            $this->dbback->where('uid = ' . "'" . $uid . "'" . ' and is_real_house =1' . ' and blockid =' . $blockid . ' and subfloor =' . $subfloor . ' and floor =' . $floor . ' and totalfloor =' . $totalfloor . ' and room =' . $room . ' and hall =' . $hall . ' and toilet =' . $toilet . ' and buildarea >=' . $buildarea_start . ' and buildarea<=' . $buildarea_end);
            $val = $this->dbback->get('sell')->row_array();
        }
        if(!empty($val))
        {
            return 1;
        }else
        {
            return 0;
        }
    }


    public function updateSocreNum($houseId,$num)
    {
        $where = 'id ='.$houseId;

        $this->db->where($where);
        $data = array();
        $data['scoresum'] = $num;
        $data['lucupdatetime'] = time();


        $this->db->update('sell', $data);
        //die("123");
        //return $result;
    }


    /**
     * 获取房源门牌号信息
     * @param int $brokerId
     * @return mixed
     */
    public function getHousebuildingnum($rowid)
    {
        $sql = "SELECT buildingnum,unitnum,roomnum FROM sell where id = $rowid ";
        $result = $this->dbback->query($sql);
        if($result->num_rows) {
            $arr = $result->result_array();
            return $arr;
        }else
        {
            return array();
        }
    }

    /**
     * 判断此人是否学规免罚已考过一次
     * @param $brokerId
     * @return mixed
     */
    public function getPaperScoreRecord($brokerId)
    {
        $this->dbback->select("id");
        $this->dbback->where('score = 100 and broker_id = '.intval($brokerId));
        $study_result = $this->dbback->get('paper_result_log')->row_array();
        return $study_result;
    }

    /**
     * 判定此人是否学规免罚今天已考过一次
     * @param $brokerId
     * @return mixed
     */
    public function getPaperTodayScoreRecord($brokerId,$date)
    {
        $this->dbback->select("id");
        $this->dbback->where('paper_time_today = '.$date.' and broker_id = '.intval($brokerId));
        $study_today_result = $this->dbback->get('paper_result_log')->row_array();
        return $study_today_result;
    }

    /**
     * 随机抽取二十道题
     * @param $brokerId
     * @return mixed
     */
    public function getRandPaperTitle(){
        $this->dbback->from('paper_title as t');
        $this->dbback->join('paper_title_answer as a','title_id=t.id','left');
        $this->dbback->select("t.id,t.title,a.answer,a.answer_type,a.true_answer_type,a.title_id");
        $this->dbback->where(array('t.type'=>1));
        $result = $this->dbback->get()->result_array();
        return $result;
    }

    /**
     * 抽取所有题目
     * @return mixed
     */
    public function getTotalPaperTitle(){
        $this->dbback->select("id,title");
        $this->dbback->where(array('type'=>1));
        $this->dbback->order_by('id');
        $paper_total_title = $this->dbback->get('paper_title')->result_array();
        return $paper_total_title;
    }

    /**
     * 获取相应题目下的答案
     * @return mixed
     */
    public function getPaperTitleAnswer($title_id){
        $this->dbback->select("answer,answer_type,true_answer_type");
        $this->dbback->where(array('title_id'=>$title_id));
        $this->dbback->order_by('id');
        $each_title_answer = $this->dbback->get('paper_title_answer')->result_array();
        foreach($each_title_answer as $key=>$value){
            $each_title_answer[$key]['answer_type_en']  = $this->num_contact($value['answer_type']);
        }
        return $each_title_answer;
    }

    //识别答案类型
    public function num_contact($num){
        $arr = array('A','B','C','D','E','F','G');
        return $arr[$num-1];
    }

    //获取正确答案
    public function get_right_answer($title_id){
        $this->dbback->select("answer_type");
        $this->dbback->where(array('title_id'=>$title_id,'true_answer_type'=>1));
        $right_answer = $this->dbback->get('paper_title_answer')->row_array();
        return $right_answer['answer_type'];
    }

    /**
     * 获取题目及其答案
     * @return mixed
     */
    public function getPaperInfo($title_id){
        $this->dbback->from('paper_title as t');
        $this->dbback->join('paper_title_answer as a','title_id=t.id','left');
        $this->dbback->select("t.id,t.title,a.answer,a.answer_type,a.true_answer_type");
        $this->dbback->where(array('t.type'=>1,'t.id'=>$title_id));
        $result = $this->dbback->get()->result_array();
        foreach($result as $key=>$value){
            $result[$key]['answer_type_en']  = $this->num_contact($value['answer_type']);
        }
        return $result;
    }

    /**
     * 插入考试记录表
     * @param $data
     * @return mixed
     */
    public function insertPaperResult($data)
    {
        if ($this->db->insert('paper_result_log', $data))
        {
            return $this->db->insert_id();
        }
    }

    /**
     * 通过学规免罚更新经纪人表
     * @param $id
     * @param $data
     * @return mixed
     */
    public function updateBrokerFree($brokerId, $data)
    {
        $this->db->where('uid', $brokerId);
        $result = $this->db->update('broker', $data);
        return $result;
    }

    /**
     * 通过学规免罚更新经纪人表
     * @param $id
     * @param $data
     */
    public function updateBrokerStatus($brokerId, $data)
    {
        $this->db->where('uid', $brokerId);
        $result = $this->db->update('real_house_account', $data);
        return $result;
    }

    /**
     * 获取经纪人考试错题信息
     * @param $id
     * @return mixed
     */
    public function getBrokerWrongTitle($broker_id)
    {
        $this->dbback->select("*");
        $this->dbback->where(array('broker_id'=>intval($broker_id),'paper_time_today'=>date('Ymd',time())));
        $result = $this->dbback->get('paper_result_log')->row_array();
        return $result;
    }

    /**
     * 获取经纪人学规免罚使用的记录
     * @param $id
     * @return mixed
     */
    public function getBrokerUselog($broker_id)
    {
        $this->dbback->select("*");
        $this->dbback->where(array('broker_id'=>$broker_id,'type'=>0));
        $result = $this->dbback->get('paper_times_use_log')->row_array();
        return $result;
    }


    public function getBrokerRealStatus($uid)
    {
        $sql = "SELECT real_status FROM broker WHERE uid=$uid and real_status>=1";
        $result= $this->db->query($sql)->row_array();

        return $result['real_status'];
    }

	public function getRealSell($broker_id){
		$count = $this->dbback->from('sell')->where(array('uid'=>$broker_id,'esta'=>1,'is_real_house'=>1,'infofrom'=>5))->count_all_results();
		return $count;
	}
}
