<?php
/**
 * 出售房源业务逻辑
 *
 * @author user
 */
load_m("sell_base_model");
class Sell_model extends Sell_base_model {
    /**
     * 类初始化
     */
    public function __construct()
    {
        parent::__construct(1,0,0);
    }

    /**
     * 获取全景房源提醒
     * @author Candison <www.kandisheng.com>
     */
    public function get360Notice(){
        // 没有开通全景房功能，不判断
        if($this->config->item('is_publish_360') != 1){
            return '';
        }
        $this->load->model('broker_model');
        $user = $this->broker_model->get_user_session();
        // 用户没有登录，不判断
        if(!isset($user['uid'])){
            return '';
        }
        $userID = $user['uid'];
        // 3星以下不展示
        $result = $this->dbback
            ->select('starlevel')
            ->where(sprintf('uid = %s', $userID))
            ->limit(1)
            ->get('broker');
        if($result === false){
            return '';
        }
        $result = $result->result_array();
        $star = isset($result[0]['starlevel']) ? intval($result[0]['starlevel']) : 0;
        if($star < 3){
            return '';
        }
        $result = $this->dbback
            ->select('num,type')
            ->where(sprintf('uid = %s', $userID))
            ->limit(1)
            ->get('panorama_pic_violation_total');
        // 数据库没有数据，不判断
        if($result === false){
            return '';
        }
        $result = $result->result_array();
        $type = $result[0]['type'];
        if($type == '2'){
            return '您由于全景图违规十分严重，全景通道已被永久关闭！';
        }
        if($type == '0'){
            return '您由于全景图违规严重，全景通道已被暂时关闭！';
        }
        if($type == '1'){
            $number = $result[0]['num'];
            if(5 - $number > 0){
                return sprintf('全景图再被删除%s次，将关闭全景通道2个月！', 5 - $number);
            }
            if(10 - $number > 0){
                return sprintf('全景图再被删除%s次，将永久关闭全景通道！', 10 - $number);
            }
        }
        return '';
    }

    /**
     * 房源模板对外接口的url地址
     * @param string $func_name 功能名称
     * @return string 相应功能url地址
     */
    public function find_func_url($func_name = '')
    {
        $url = '/' . $this->get_tbl() . '/';
        switch ($func_name)
        {
            case 'add': //发布房源页
                $url .= 'add/';
                break;
            case 'insert': //插入房源
                $url .= 'insert/';
                break;
            case 'modify': //修改房源页
                $url .= 'modify/';
                break;
            case 'update': //修改房源页
                $url .= 'update/';
                break;
            default :  //房源模板列表页
                $url .= 'manage/';
        }
        return $url;
    }

    /**
     * 获取修改房源地址
     * @param int $id 房源编号
     * @param string $tab tab页
     */
    public function get_modify_house_url($id, $tab = '')
    {
        return $this->find_func_url('modify') . $id . '/' . $tab;
    }

    /**
     * 插入房源图片
     * @param type $pics
     * @param type $tbl
     * @param type $house_id
     * @param type $pic1
     * @param type $blockid
     */
    public function insert_house_pic($pics, $tbl, $house_id, $pic1,
                                     $blockid, $deleteupload = '')
    {
        //调用pic_model
        $this->load->model('pic_model');
        $return = array();
        $temp = 0;
        //先删除原上传的图片，再重新添加上传图片数据，这个不知道是谁设计的
        if ($deleteupload == 1)
        {
            $this->pic_model->del_house_pic_by($tbl, $house_id);
        }
        if (!$pics)
        {
            return $return;
        }
        $i=1;
        $indexpic = $firstpic = '';
        $temppic1 = false;	//判断设置的封面图片是否被上传
        foreach($pics['p_filename'] as $k => $v)
        {
            if (!in_array($pics['p_sort'][$k], array(1,2,0,9,10)) ) {
                echo '<script type="text/javascript">alert("上传图片的类型有误！");history.go(-1);</script>';
                exit();
            }
            $token = explode("=",$v);
            $pid = intval($token[1]);

            $filename = $v;

             // 图片不以http开头 跳过
            if (strpos($v,'http') !== 0) {
                continue;
            }
            //$filename = substr($v, 0, strpos($v, '?'));
//            $idkind   = substr( $token[0],-3);
            $title = $pics['p_title'][$k]=='图片描述..限30字' ? '': strip_tags($pics['p_title'][$k]);
            $sort = $pics['p_sort'][$k];
            $flg = $sort == 9 || $sort == 10 ? 1 : 0;//图库选择的图片不需要再次审核。

            //是否图库图片
            $fromblockimg = false;
            //图库图片使用记录
            if($sort == 9 || $sort == 10)
            {
                //图库选择的户型图为9，外景图为10
                $sort = $sort == 9 ? 0 : ($sort == 10 ? 1 : $sort);
                $insert_data = array(
                    'blockid' => $blockid, 'tbl' => $tbl,
                    'rowid' => $house_id, 'pic' => $filename,
                    'type' => $sort, 'dateline' => date("Ymd")
                );
                $this->load->model('block_model');
                $this->block_model->insert_block_img_used($insert_data);
                $fromblockimg = true;
            }
            $sort = $sort == 9 ? 0 : ($sort == 10 ? 1 : $sort);//图库选择的户型图为9，外景图为10
            if (isset($pics['p_block'][$k]))
            {
                $isblock = intval($pics['p_block'][$k]);
            }
            else
            {
                $isblock = 0;
            }
            $createtime = time();
            //房源图片的参数
            $insert_data_house = array(
                'tbl' => $tbl, 'rowid' => $house_id, 'position' => "pic$i",
                'filename' => $filename, 'title' => $title, 'blockid' => $blockid,
                'sort' => $sort, 'isblock' => $isblock, 'createtime' => $createtime,
                'flg' => $flg, 'isfrom' => 2, 'isinfotype' => $pics['infotype']
            );
            $picid = $this->pic_model->insert_house_pic($insert_data_house, $tbl, $house_id);
//            if($idkind=='pid' && $pid > 0 && !$fromblockimg && !$flg)
            if(!$fromblockimg && !$flg)
            {
                //审图用，获取缓存图片库中的图片信息
//                $parr = $this->pic_model->find_temp_by_id($pid);
                //审图用，组合图片信息
                $return[$temp]['pictbl'] = $this->pic_model->get_upload_table_name($tbl, $house_id);
                $return[$temp]['picid'] = $picid;
                $return[$temp]['picurl'] = $filename;
                $return[$temp]['sort'] = $sort;
                $return[$temp]['surface'] = 0;
//                if(isset($parr['from_device']) && $parr['from_device'] != '')
//                {
//                    $return[$temp]['from_device'] = $parr['from_device'];
//                }
//                if (isset($parr['file_md5']) && $parr['file_md5'] != '')
//                {
//                    $return[$temp]['file_md5'] = $parr['file_md5'];
//                }
                $temp++;
            }

            $temppic1 = $temppic1 ? true : $pic1 == $filename;	//判断设置的封面图片是否被上传
            if($firstpic == '') $firstpic = $filename;
            $i++;
        }
        $indexpic = $temppic1 ? $pic1 : $firstpic;	//当封面被删除，默认设定第一张图片为封面
        //审图用，设置封面图并过滤掉来自设备的非封面图
        if(is_array($return) && !empty($return))
        {
            foreach($return as $key=>$val)
            {
                if($val['picurl'] == $indexpic)
                {
                    $return[$key]['surface'] = 1;
                }
            }
        }
        //更新房源封面图
        //$this->update(array('pic1' => $indexpic), $house_id);
        return array('pic_check' => $return, 'indexpic' => $indexpic);
    }

    /**
     * 修改经纪人的房源电话信息
     * update_sell_mobile
     * @param int $mobile
     * @param string $uid 条件
     * @return void
     */
    public function update_sell_mobile($uid,$mobile){
        $cond_where['uid'] = $uid;
        $cond_where['infofrom'] = 5;
        $this->db->where($cond_where);
        //$esta_arr = array(0,1,2,5);
        // $this->db->where_in('esta',$esta_arr);
        $this->db->update($this->get_tbl(),array('telno'=>$mobile));
    }

    /**
     * 获取发布出售房源的权限
     * @param int $groupid 权限编号
     * @return boolean
     */
    public function get_public_permission($groupid)
    {
        $this->load->model('package_model');

        $package = $this->package_model->find_by_id($groupid);
        if (isset($package['package_sell_purview'])
            && $package['package_sell_purview'] == 1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 获取发布出售房源类型的权限
     * @param int $groupid 权限编号
     * @return array 可发布类型数组
     */
    public function get_public_infotype_permission($groupid)
    {
        $this->load->model('package_model');
        $package = $this->package_model->find_by_id($groupid);
        $my_allow_infotype = explode(';', $package['allow_infotype']);
        return $my_allow_infotype;
    }

    /**
     * 张宽广 2018-06-29
     * @param $id
     * @param $type 0经纪人，1是个人房源
     */
    public function getHouseInfo($id,$applay_type=0){

        $tab = 'sell';
        $houseInfo = $this->dbback->from($tab)->where('id', $id)->get()->row_array();
        if($houseInfo){
            $streetid = $houseInfo['streetid'];
            $street = $this->dbback->from('street')->where('id', $streetid)->get()->row_array();
            $houseInfo['street'] = '';
            if($street){
                $houseInfo['street'] = $street['streetname'];
            }
            //获取经纪人电话
            $brocker_id = $houseInfo['uid'];

            if($applay_type !=3){
                $broker = $this->dbback->from('broker')->where('uid', $brocker_id)->get()->row_array();
                $houseInfo['agent_telno'] = '';
                if($broker){
                    $houseInfo['agent_telno'] = $broker['telno'];
                }
            }else{//获取个人信息
                $houseInfo['agent_telno'] = $houseInfo['telno'];
            }

            if($tab == 'sell'){
                $houseInfo['house_type'] = 1;
            }

        }

        return $houseInfo;
    }


    //检测当前用户是否是放心看经纪人
    public function checkisreal($broker_id){
        $broker = $this->dbback->from('broker')->where(array('uid'=>$broker_id))->get()->row_array();
        if(!$broker){
            return false;
        }

        //非放心看经纪人，永久只能申请一套
        if(!$broker['real_status']){
            return false;
        }

        return true;
    }


    //检测经纪人能否再申请
    public function checkBrokerApplay($broker_id,$type=0,$applay_type=0){

        if($applay_type !=3){
            $broker = $this->dbback->from('broker')->where(array('uid'=>$broker_id))->get()->row_array();
            if(!$broker){
                return false;
            }

            //非放心看经纪人，永久只能申请一套
            if(!$broker['real_status']){
                $applay_count = $this->dbback->from('vr_applay')->where(array('broker_id'=>$broker_id))->where_not_in('shot_status',array(5,6,9))->count_all_results();
                if($applay_count){
                    return false;
                }
                return true;
            }
            //当type不为0时，则不检查放心看经纪人
            if($type){
                return true;
            }
        }

        //放心看经纪人，拍摄中的只能存在3个
        $applay_count_total = $this->dbback->from('vr_applay')->where(array('broker_id'=>$broker_id))->where_in('shot_status',array(1,2))->count_all_results();


        if($applay_count_total>=3){
            return false;
        }

        return true;
    }

    //房源能否申请VR
    public function isvrapplay($house_id){
        $config = $this->config->item('house');
        $vr_show_district = $config['vr_show_district'];

        $houseInfo = $this->getHouseInfo($house_id);
        if(!$houseInfo){
            return array('code'=>0,'msg'=>'参数错误');
        }
        $district = $houseInfo['district'];

        if(!in_array($district,$vr_show_district)){
            return array('code'=>0,'msg'=>'该区域不支持申请VR拍摄');
        }

        return array('code'=>1,'msg'=>'ok');

    }

    /**
     * Notes:经纪人信息
     * User: zhangkg
     */
    public function brokerInfo($broker_id,$applay_type=1){

        if($applay_type != 3){

            $broker = $this->dbback->from('broker')->where(array('uid'=>$broker_id))->get()->row_array();
            if(!$broker){
                return false;
            }
            $agency_code = $broker['agentcode'];
            $agency = $this->dbback->from('agency')->where(array('agentcode'=>$agency_code))->get()->row_array();
            $broker['agentshortname'] = '';
            if($agency){
                $broker['agentshortname'] = $agency['agentshortname'];
            }

        }else{
            //个人用户
            /*$broker = $this->userdb->from('personal_user')->where(array('id'=>$broker_id))->get()->row_array();
            if(!$broker){
                return false;
            }*/
            $broker['truename'] = '';
            $broker['agentshortname'] = '';
        }


        return $broker;

    }


    /**
     * 申请VR 拍摄
     * @param $program
     * @return array
     */
    public function vrApplay($program){
        $id = $program['rowid'];

        $applay_type = 1;
        if(array_key_exists('applay_type',$program)){
            if($program['applay_type']){
                $applay_type = $program['applay_type'];
            }
        }

        $houseInfo = $this->getHouseInfo($id,$applay_type);
        if(!$houseInfo){
            return array('code'=>0,'msg'=>'参数错误');
        }
        $isvr = $this->isvrapplay($id);
        if(!$isvr['code']){
            return $isvr;
        }

        //同一套房源不能申请多次
        $applay_count = $this->dbback->from('vr_applay')->where(array('house_id'=>$id))->where_in('shot_status',array(1,2))->count_all_results();

        if($applay_count > 0){
            return array('code'=>0,'msg'=>'该房源正在拍摄中,不可再次申请');
        }

        //同一套房源不能申请多次
        $applay_count = $this->dbback->from('vr_applay')->where(array('house_id'=>$id))->where_not_in('shot_status',array(5,6,9))->count_all_results();
        if($applay_count > 0){
            return array('code'=>0,'msg'=>'该房源拍摄已完成,不可再次申请');
        }

        $broker_id = $houseInfo['uid'];

        $isok = $this->checkBrokerApplay($broker_id,0,$applay_type);
        if(!$isok){
            return array('code'=>0,'msg'=>'您的申请已达到上限，不可申请了');
        }

        if($applay_type !=3){
            $isrealbroker = $this->checkisreal($broker_id);

            $applay_type = 2;//普通经纪人
            if($isrealbroker){
                $applay_type = 1; // 放心看中介
            }
        }



        //限定该经纪人 最多只能保留 3个 "已审核，已预约"状态
        /* $applay_count_total = $this->dbback->from('vr_applay')->where(array('broker_id'=>$broker_id,'shot_status '=>1))->or_where(array('broker_id'=>$broker_id,'shot_status '=>2))->count_all_results();
         if($applay_count >= 3){
             return array('code'=>0,'msg'=>'您当前正有多套房源拍摄中，完成后可再申请');
         }*/

        $order_date = $program['order_date'];

        $count_manage = $this->dbback->from('vr_count_manage')->where(array('order_date'=>$order_date))->get()->row_array();
        if($count_manage){
            $total_count = $count_manage['count'];
        }else{
            $total_count = 40;
        }
        //检测是否超过40套
        $applay_count = $this->db->from('vr_applay')->where(array('order_date'=>$order_date))->where_not_in('shot_status',array(5,6,9))->count_all_results();
        if($applay_count >=$total_count){
            return array('code'=>0,'msg'=>'申请已超过40套');
        }

        $remark = $program['blockshownameall'];
        if($remark){
            $remark = iconv('utf8','gbk//IGNORE',$remark);
        }

        $broker = $this->brokerInfo($broker_id);

        if($applay_type == 3){
            $applayname = isset($program['applayname'])?$program['applayname']:'';
            if($applayname){
                $applayname = iconv('utf-8','gbk',$applayname);
            }
            $data['truename'] = $houseInfo['contactor'];
            $data['agentshortname'] = empty($applayname)?'365':$applayname;
        }else{
            $data['truename'] = $broker['truename'];
            $data['username'] = $broker['username'];
            $data['agentshortname'] = $broker['agentshortname'];

        }
        $data['broker_id'] = $houseInfo['uid'];
        $data['applay_type'] = $applay_type;
        $data['broker_telno'] = $program['agent_telno'];
        $data['house_id'] = $id;
        $data['house_type'] = $houseInfo['house_type'];
        $data['village_name'] = $houseInfo['blockshowname'];
        $data['area'] = $houseInfo['district'];
        $data['plate'] = $houseInfo['street'];
        $data['building'] = $program['buildingnum'];
        $data['unit'] = $program['unitnum'];
        $data['room_num'] = $program['roomnum'];
        $data['order_time'] = $program['order_time'];
        if($program['order_date'] != '2018'){
            $data['order_date'] = $program['order_date'];
        }else{
            $data['order_date'] = '';
            $data['order_time'] = 6;
        }
        $data['remark'] = $remark;
        $data['save_time'] = date('Y-m-d H:i:s',time());


        $ok = $this->db->insert('vr_applay', $data);

        if($ok){
            return array('code'=>1,'msg'=>'申请已收到');

        }
        return array('code'=>0,'msg'=>'出现意外了');

    }

    /**
     * 检测房源 vr 申请状态
     */
    public function vrapplay_status($house_id,$house_type=1){

        // $applay = $this->dbback->from('vr_applay')->where(array('house_id'=>$house_id,'house_type'=>$house_type))->order_by('save_time desc')->limit(1)->get()->row_array();


        $applay = $this->dbback->from('vr_applay as a')->join('vr_shot_person as b','a.shot_person_id=b.id','left')->select('a.*,b.shot_name,b.telno')->where(array('a.house_id'=>$house_id,'a.house_type'=>$house_type))->order_by('a.save_time','desc')->get()->row_array();

        if(!$applay){
            $applay['shot_status'] = 0;
            $applay['shot_name'] = '';
            $applay['telno'] = '';
        }

        return $applay;
    }

    /**
     * 取消vr
     * @param $row_id
     */
    public function cancle_vr($row_id,$house_type=1){
        $applay = $this->dbback->from('vr_applay')->where(array('house_id'=>$row_id,'house_type'=>$house_type))->order_by('save_time desc')->limit(1)->get()->row_array();

        if($applay){
            $vrstatus = $applay['shot_status'];
            $id = $applay['id'];
            if($vrstatus == 1){

                $data['shot_status'] = 5;
                $ok = $this->db->where(array('id'=>$id))->update('vr_applay',$data);
                if($ok){
                    return array('code'=>1,'msg'=>'操作成功');
                }
                return array('code'=>0,'msg'=>'操作失败');

            }elseif($vrstatus == 2){
                return array('code'=>0,'msg'=>'拍摄已预约，取消预约请拨打客服电话 ');
            }else{
                return array('code'=>0,'msg'=>'该申请无法取消');
            }
        }
        return array('code'=>0,'msg'=>'无效数据');

    }

    /**
     * 检测是否有相似房源绑定vr
     * @param $data
     */
    public function check_vr($data,$house_type=1){
        $rowid = $data['rowid'];


        if(array_key_exists('applay_type',$data)){
            $applay_type = $data['applay_type'];
            //个人房源不检测相似房源
        }

        $houseInfo = $this->getHouseInfo($rowid,$house_type);

        if(!$houseInfo){
            return array('code'=>0,'msg'=>'房源不存在');
        }
        $village_name = $houseInfo['blockshowname'];
        $building = $data['buildingnum'];
        $unit = $data['unitnum'];
        $room_num = $data['roomnum'];
        if($applay_type == 3){
            $applay = $this->dbback->from('vr_applay')->where(array('village_name'=>$village_name,'building'=>$building,'unit'=>$unit,'room_num'=>$room_num,'vr_model_id !='=>'','shot_status'=>4))->order_by('save_time desc ')->get()->row_array();
            if($applay){
                return array('code'=>1,'msg'=>'有相似房源','data'=>$applay);
            }
            return array('code'=>0,'msg'=>'无相似房源');
        }

        if($houseInfo){
            $broker_id = $houseInfo['uid'];//经纪人id
            //查询当前经纪人门店编号

            $agentcode_array = $this->similarHouse($rowid,$broker_id);
            if(!$agentcode_array['code']){
                return $agentcode_array;
            }
            $agentcodes = $agentcode_array['data'];


            $applay = $this->dbback->from('vr_applay as a')->join('broker as b','a.broker_id = b.uid','left')->select('a.*,b.agentcode')->where(array('village_name'=>$village_name,'building'=>$building,'unit'=>$unit,'room_num'=>$room_num,'vr_model_id !='=>'','a.shot_status'=>4))->where_in('agentcode',$agentcodes)->order_by('a.save_time desc ')->get()->row_array();

            if($applay){
                return array('code'=>1,'msg'=>'有相似房源'.$applay['id'],'data'=>$applay);
            }
            return array('code'=>0,'msg'=>'无相似房源');
        }
        return array('code'=>0,'msg'=>'可能申请已被删除');
    }

    /**
     * Notes:个人相似房源
     * User: zhangkg
     */
    public function likehouse($data1){

        $re = $this->check_vr($data1,3);

        $rowid = $data1['rowid'];

        $applay = $this->dbback->from('vr_applay')->where(array('house_id'=>$rowid,'vr_model_id !='=>''))->where_not_in('shot_status',array(5,6,9))->order_by('save_time desc ')->get()->row_array();
        if($applay){
            return array('code'=>0,'msg'=>'该房源已申请');
        }

        if($re['code']){
            $houseInfo = $this->getHouseInfo($rowid,3);

            $like = $re['data'];
            $tbl = 1;
            $likeid = $like['house_id'];
            $rowid = $data1['rowid'];
            $vr_model_id = $like['vr_model_id'];
            //查找房源的vr图片
            $vr_imgs = $this->dbback->from('vr_image')->where(array('tbl'=>$tbl,'houseid'=>$likeid))->get()->row_array();

            $data['truename'] = $houseInfo['contactor'];
            //$data['username'] = $houseInfo['agent_telno'];
            $data['agentshortname'] = '365';

            $data['broker_id'] = $houseInfo['uid'];
            $data['broker_telno'] = $houseInfo['agent_telno'];

            $data['house_id'] = $rowid;
            $data['house_type'] = $houseInfo['house_type'];
            $data['village_name'] = $houseInfo['blockshowname'];
            $data['area'] = $houseInfo['district'];
            $data['plate'] = $houseInfo['street'];
            $data['building'] = $data1['buildingnum'];
            $data['unit'] = $data1['unitnum'];
            $data['room_num'] = $data1['roomnum'];
            $data['order_date'] = '';
            $data['vr_model_id'] = $vr_model_id;
            $data['order_time'] = 5;
            $data['shot_status'] = 4;
            $data['applay_type'] = 3;
            $data['save_time'] = date('Y-m-d H:i:s',time());

            $ok = $this->db->insert('vr_applay', $data);

            //return array('code'=>1,'msg'=>$this->db->last_query());

            //自动绑定房源
            $ups['vr_model_id'] = $vr_model_id;
            $ups['isvr'] = 1;
            $this->db->where(array('id'=>$rowid))->update('sell',$ups);
            if($vr_imgs){

                $vri = $this->dbback->from('vr_image')->where(array('tbl'=>$tbl,'houseid'=>$rowid))->get()->row_array();

                if($vri){
                    $vr_imgs_data['filename'] = $vr_imgs['filename'];
                    $vr_imgs_data['house_type_images'] = $vr_imgs['house_type_images'];
                    $vr_imgs_data['rom_images'] = $vr_imgs['rom_images'];
                    $this->db->where(array('tbl'=>$tbl,'houseid'=>$rowid))->update('vr_image', $vr_imgs_data);
                }else{
                    $vr_imgs_data['tbl'] = $tbl;
                    $vr_imgs_data['filename'] = $vr_imgs['filename'];
                    $vr_imgs_data['house_type_images'] = $vr_imgs['house_type_images'];
                    $vr_imgs_data['rom_images'] = $vr_imgs['rom_images'];
                    $vr_imgs_data['houseid'] = $rowid;
                    $this->db->insert('vr_image', $vr_imgs_data);
                }



                //如果有户型图，户型图同步

                if($vr_imgs['house_type_images']){
                    $house_typeims[0] = $vr_imgs['house_type_images'];
                    $this->romupdate($rowid,$house_typeims,0);
                }

                $rom_images_c = $vr_imgs['rom_images'];
                if(!empty($rom_images_c)){
                    $rom_images = json_decode($rom_images_c);
                }
                //室内图
                if($rom_images){
                    $this->romupdate($rowid,$rom_images,2);
                }
            }

            if($ok){
                return array('code'=>1,'msg'=>'绑定成功');
            }
        }
        return $re;
    }


    /**
     * Notes: type 0 户型图，1 外景图，2室内图
     * User: zhangkg
     */
    public function romupdate($house_id,$images,$type){

        $uploadtbl = $this->get_upload_tblname('sell',$house_id);

        $imageData = $this->dbback->from($uploadtbl)->where(array('rowid'=>$house_id,'tbl'=>'sell','sort'=>$type))->get()->result_array();
        $deleids = array();
        foreach($imageData as $key=>$value){
            if(!in_array($value['filename'],$images)){
                array_push($deleids,$value['id']);
            }else{
                $ks = array_search($value['filename'],$images);
                unset($images[$ks]);
            }
        }

        if($deleids){
            $ids = implode(',',$deleids);

            $this->db->where_in('id',$deleids)->delete($uploadtbl);

           /* $sql = "delete from ".$uploadtbl." where id in(".$ids.")";
            $this->db->Execute($sql);*/
        }

        $lasts = $this->dbback->from($uploadtbl)->select('position')->where(array('rowid'=>$house_id,'tbl'=>'sell'))->order_by('position desc')->get()->row_array();
        /*$sql = "select position from ".$uploadtbl." where rowid='".$house_id."' && tbl='sell' order by position desc";
        $last = $this->dbback->GetOne($sql);*/

        if($lasts){
            $last = $lasts['position'];
        }
        $postion = 0;
        if($last){
            preg_match('/^pic([\d]).*/',$last,$postions);
            if($postions){
                if(!empty($postions[1])){
                    $postion = intval($postions[1]);
                }
            }
        }
        $title = '图片描述30字';
        $time = time();
        foreach ($images as $k=>$v){
            $newpos = 'pic'.($postion+1);

            $upload['tbl'] = 'sell';
            $upload['rowid'] = $house_id;
            $upload['position'] = $newpos;
            $upload['filename'] = $v;
            $upload['title'] = $title;
            $upload['sort'] = $type;
            $upload['createtime'] = $time;
            $this->db->insert($uploadtbl, $upload);
            ++$postion;
        }
    }



    public function check_bind($data1,$house_type=1){
        $rowid = $data1['rowid'];

        /*ini_set('error_reporting',E_ALL);
        ini_set('display_errors',true);*/
        $applay_type = 0;
        if(array_key_exists('applay_type',$data1)){
            $applay_type = $data1['applay_type'];
            //个人房源不检测相似房源
        }
        if($applay_type=='3'){

            return $this->likehouse($data1);
        }

        $houseInfo = $this->getHouseInfo($rowid);

        if($houseInfo){

            $isok = $this->checkBrokerApplay($houseInfo['uid'],1);
            if(!$isok){
                return array('code'=>0,'msg'=>'您的申请已达到上限，不可申请了');
            }

            $village_name = $houseInfo['blockshowname'];
            $building = $data1['buildingnum'];
            $unit = $data1['unitnum'];
            $room_num = $data1['roomnum'];
            $tbl = $houseInfo['house_type'];
            //$applay = $this->dbback->from('vr_applay')->where(array('village_name'=>$village_name,'building'=>$building,'unit'=>$unit,'room_num'=>$room_num,'vr_model_id !='=>'','shot_status'=>4))->get()->row_array();

            $broker_id = $houseInfo['uid'];//经纪人id
            //查询当前经纪人门店编号

            $agentcode_array = $this->similarHouse($rowid,$broker_id);
            if(!$agentcode_array['code']){
                return $agentcode_array;
            }
            $agentcodes = $agentcode_array['data'];

            $applay = $this->dbback->from('vr_applay as a')->join('broker as b','a.broker_id = b.uid','left')->select('a.*,b.agentcode')->where(array('village_name'=>$village_name,'building'=>$building,'unit'=>$unit,'room_num'=>$room_num,'vr_model_id !='=>'','shot_status'=>4))->where_in('agentcode',$agentcodes)->order_by('a.save_time desc ')->get()->row_array();

            if($applay){
                $vr_model_id = $applay['vr_model_id'];
                $likeid = $applay['house_id'];


                $broker = $this->brokerInfo($broker_id);

                $data['truename'] = $broker['truename'];
                $data['username'] = $broker['username'];
                $data['agentshortname'] = $broker['agentshortname'];

                //查找房源的vr图片
                $vr_imgs = $this->dbback->from('vr_image')->where(array('tbl'=>$tbl,'houseid'=>$likeid))->get()->row_array();

                $data['broker_id'] = $houseInfo['uid'];
                $data['broker_telno'] = $houseInfo['agent_telno'];

                $data['house_id'] = $rowid;
                $data['house_type'] = $houseInfo['house_type'];
                $data['village_name'] = $houseInfo['blockshowname'];
                $data['area'] = $houseInfo['district'];
                $data['plate'] = $houseInfo['street'];
                $data['building'] = $data1['buildingnum'];
                $data['unit'] = $data1['unitnum'];
                $data['room_num'] = $data1['roomnum'];
                $data['order_date'] = '';
                $data['vr_model_id'] = $vr_model_id;
                $data['order_time'] = 5;
                $data['shot_status'] = 4;
                $data['save_time'] = date('Y-m-d H:i:s',time());
                $this->db->trans_begin();
                $ok = $this->db->insert('vr_applay', $data);


                //自动绑定房源
                $ups['vr_model_id'] = $vr_model_id;
                $ups['isvr'] = 1;
                $this->db->where(array('id'=>$rowid))->update('sell',$ups);

                if($vr_imgs){

                    $vri = $this->dbback->from('vr_image')->where(array('tbl'=>$tbl,'houseid'=>$rowid))->get()->row_array();
                    if($vri){
                        $vr_imgs_data['filename'] = $vr_imgs['filename'];
                        $vr_imgs_data['house_type_images'] = $vr_imgs['house_type_images'];
                        $vr_imgs_data['rom_images'] = $vr_imgs['rom_images'];
                        $this->db->where(array('tbl'=>$tbl,'houseid'=>$rowid))->update('vr_image', $vr_imgs_data);
                    }else{
                        $vr_imgs_data['tbl'] = $tbl;
                        $vr_imgs_data['filename'] = $vr_imgs['filename'];
                        $vr_imgs_data['houseid'] = $rowid;
                        $vr_imgs_data['house_type_images'] = $vr_imgs['house_type_images'];
                        $vr_imgs_data['rom_images'] = $vr_imgs['rom_images'];
                        $this->db->insert('vr_image', $vr_imgs_data);
                    }


                    //如果有户型图，户型图同步

                    if($vr_imgs['house_type_images']){
                        $house_typeims[0] = $vr_imgs['house_type_images'];
                        $this->romupdate($rowid,$house_typeims,0);
                    }

                    $rom_images_c = $vr_imgs['rom_images'];
                    if(!empty($rom_images_c)){
                        $rom_images = json_decode($rom_images_c);
                    }
                    //室内图
                    if($rom_images){
                        $this->romupdate($rowid,$rom_images,2);
                    }

                }
                //事务
                if ($this->db->trans_status() === FALSE)
                {
                    $this->db->trans_rollback();
                    return array('code'=>0,'msg'=>'绑定失败了，请重新尝试');

                }
                else
                {
                    $this->db->trans_commit();
                    return array('code'=>1,'msg'=>'绑定成功');

                }

            }else{
                return array('code'=>0,'msg'=>'无相似房源');
            }
        }
        return array('code'=>0,'msg'=>'无效的房屋信息');

    }

    function get_upload_tblname($tbl,$id){

        if(defined('picTableType') && picTableType == '0')
        {
            return 'upload';
        }

        if($tbl == 'sell' && $id < 23972101) return 'upload0';

        if($tbl == 'rent' && $id < 11907211) return 'upload0';

        if($tbl == 'sell' && ($id >= 23972101 && $id < 27029364)) return 'upload1';

        if($tbl == 'rent' && ($id >= 11907211 && $id < 13224200)) return 'upload1';

        if($tbl == 'sell' && ($id >= 27029364 && $id < 31695721)) return 'upload2';

        if($tbl == 'rent' && ($id >= 13224200 && $id < 14495163)) return 'upload2';

        if($tbl == 'sell' && ($id >= 31695721 && $id < 34963370)) return 'upload3';

        if($tbl == 'rent' && ($id >= 14495163 && $id < 15172611)) return 'upload3';

        if($tbl == 'sell' && ($id >= 34963370 && $id < 38640564)) return 'upload4';

        if($tbl == 'rent' && ($id >= 15172611 && $id < 15871631)) return 'upload4';

        if($tbl == 'sell' && ($id >= 38640564 && $id < 42138930)) return 'upload5';

        if($tbl == 'rent' && ($id >= 15871631 && $id < 16675751)) return 'upload5';

        if($tbl == 'sell' && ($id >= 42138930 && $id < 45947999)) return 'upload';

        if($tbl == 'rent' && ($id >= 16675751 && $id < 43871899)) return 'upload';

        if($tbl == 'sell' && ($id >= 45947999 && $id < 49830000)) return 'upload6';
        //49825505
        if($tbl == 'rent' && ($id >= 43871899 && $id < 45040000)) return 'upload6';
        //45038726
        if($tbl == 'sell' && ($id >= 49830000 && $id < 54705651)) return 'upload7';
        //54703651
        if($tbl == 'rent' && ($id >= 45040000 && $id < 45788862)) return 'upload7';
        //45787862
        if($tbl == 'sell' && ($id >= 54705651 && $id < 58020733)) return 'upload8';
        //58018737
        if($tbl == 'rent' && ($id >= 45788862 && $id < 46230598)) return 'upload8';
        //46229598
        if($tbl == 'sell' && ($id >= 58020733 && $id < 61223139)) return 'upload9';
        //61221139
        if($tbl == 'rent' && ($id >= 46230598 && $id < 46633747)) return 'upload9';
        //46633347
        if($tbl == 'sell' && ($id >= 61223139 && $id < 63983200)) return 'upload10';
        //63981991
        if($tbl == 'rent' && ($id >= 46633747 && $id < 46923000)) return 'upload10';
        //46922654
        if($tbl == 'sell' && ($id >= 63983200 && $id < 66893902)) return 'upload11';
        //66892902
        if($tbl == 'rent' && ($id >= 46923000 && $id < 47264784)) return 'upload11';
        //47264284
        if($tbl == 'sell' && ($id >= 66893902 && $id < 71182067)) return 'upload12';
        //71181067
        if($tbl == 'rent' && ($id >= 47264784 && $id < 47951200)) return 'upload12';
        //47950659
        if($tbl == 'sell' && ($id >= 71182067 && $id < 76015831)) return 'upload13';
        //76014531
        if($tbl == 'rent' && ($id >= 47951200 && $id < 48556731)) return 'upload13';                                                                             //48556231

        if($tbl == 'sell' && ($id >= 76015831 && $id < 81507192)) return 'upload14';
        //81506192
        if($tbl == 'rent' && ($id >= 48556731 && $id < 49140972)) return 'upload14';                                                                        //49140466

        if($tbl == 'sell' && ($id >= 81507192 && $id < 88723014)) return 'upload15';
        //88722131
        if($tbl == 'rent' && ($id >= 49140972 && $id < 49884209)) return 'upload15';
        //49883609

        if($tbl == 'sell' && ($id >= 88723014 && $id < 95316101)) return 'upload16';
        //95314101
        if($tbl == 'rent' && ($id >= 49884209 && $id < 50532293)) return 'upload16';
        //50531293

        if($tbl == 'sell' && ($id >= 95316101 && $id < 103859999)) return 'upload17';
        //103819999
        if($tbl == 'rent' && ($id >= 50532293 && $id < 51527468)) return 'upload17';
        //51527468
        if($tbl == 'sell' && ($id >= 103859999 && $id < 108815839)) return 'upload18';
        //108806111
        if($tbl == 'rent' && ($id >= 51527468 && $id < 52249156)) return 'upload18';
        //52239180
        if($tbl == 'sell' && ($id >= 108815839 && $id < 114379999)) return 'upload19';

        if($tbl == 'rent' && ($id >= 52249156 && $id < 53130499)) return 'upload19';


        if($tbl == 'sell' && ($id >= 114379999 && $id < 119229999)) return 'upload20';

        if($tbl == 'rent' && ($id >= 53130499 && $id < 53780499)) return 'upload20';



        if($tbl == 'sell' && ($id >= 119229999 && $id < 123619999)) return 'upload21';

        if($tbl == 'rent' && ($id >= 53780499 && $id < 54659999)) return 'upload21';


        if($tbl == 'sell' && ($id >= 123619999 && $id < 128434999)) return 'upload22';

        if($tbl == 'rent' && ($id >= 54659999 && $id < 55793999)) return 'upload22';


        if($tbl == 'sell' && ($id >= 128434999 && $id < 132662039)) return 'upload23';

        if($tbl == 'rent' && ($id >= 55793999 && $id < 56609929)) return 'upload23';


        if($tbl == 'sell' && ($id >= 132662039 && $id < 136312505)) return 'upload24';

        if($tbl == 'rent' && ($id >= 56609929 && $id < 57307409)) return 'upload24';


        if($tbl == 'sell' && ($id >= 136312505 && $id < 140145507)) return 'upload25';

        if($tbl == 'rent' && ($id >= 57307409 && $id < 58017786)) return 'upload25';


        if($tbl == 'sell' && ($id >= 140145507 && $id < 147125418)) return 'upload26';

        if($tbl == 'rent' && ($id >= 58017786 && $id < 59209979)) return 'upload26';

        if($tbl == 'sell' && ($id >= 147125418 && $id < 154138704)) return 'upload27';

        if($tbl == 'rent' && ($id >= 59209979 && $id < 60562010)) return 'upload27';

        if($tbl == 'sell' && ($id >= 154138704 && $id < 166754880)) return 'upload28';

        if($tbl == 'rent' && ($id >= 60562010 && $id < 63483875)) return 'upload28';

        return 'upload29';

    }


    //查询经纪人同公司下的所有门店
    public function similarHouse($house_id,$broker_id){

        $broker = $this->dbback->from('broker as a')->join('agency as b','a.agentcode=b.agentcode','left')->select('a.uid,b.*')->where(array('a.uid'=>$broker_id))->get()->row_array();
        if(!$broker){
            return array('code'=>0,'msg'=>'房源无经纪人');
        }
        $agentcode = $broker['agentcode'];
        $agenttype = $broker['agenttype'];
        $parentcode = $broker['parentcode'];
        if($agenttype == 2){
            $parentcode = $agentcode;
        }
        if($agenttype == 3){
            return array('code'=>1,'msg'=>'','data'=> array($agentcode));
        }
        //查询所有的子公司

        $all = $this->dbback->from('agency')->where(array('parentcode'=>$parentcode))->get()->result_array();
        if(!$all){
            return array('code'=>0,'msg'=>'公司信息错误');
        }
        $rearray = array();
        foreach ($all as $k=>$v){
            array_push($rearray,$v['agentcode']);
        }
        return array('code'=>1,'msg'=>'','data'=> $rearray);


    }

    /**
     * Notes:经纪人保障金冻结
     * User: zhangkg
     */
    public function broker_real_frozen($type=0){
        $this->load->model('broker_model');
        $session_info = $this->broker_model->get_user_session();
        $uid = $session_info['uid'];

        $time = time();
        $result = $this->dbback->from('paper_times_use_log')->where(array('broker_id'=>$uid,'type'=>1))->order_by('create_time desc')->get()->row_array();
        if($result){
            if($result['end_time'] > $time){
                $date = date('Y-m-d',$result['end_time']);
                if($type){
                    return array('code'=>0,'msg'=>'由于您放心看房源已被举报删除，在'.$date.'前您无法申请提现！');
                }
                return array('code'=>0,'msg'=>'当前保证金账户冻结状态，无法设置放心看');
            }
        }
        return array('code'=>1,'msg'=>'');

    }

}
