<?php
namespace app\api\controller;


use app\common\controller\Common;
use app\BaseController;
use think\facade\Db;
use think\facade\Request;

class Index  extends Base
{
    //app首页信息,如果用户只绑定了一个房间,则默认展示一个房间的
    public function index() {
        $page = Request::param('page',1);
        $uid = $this->uid;
        $village_id = Request::param('village_id');
        $field ="hvi.village_name,hvi.village_id,hvi.village_address,hvi.province_name,hvi.city_name,hvi.area_name";
        if(empty($village_id)) {
            $data = Db::name('house_user_bind')->alias('hub')
                ->leftJoin('house_vacancy hv','hv.vacancy_id = hub.vacancy_id')
                ->leftJoin('house_village hvi','hvi.village_id = hv.village_id')
                ->where(['hub.is_lately_login'=>1,'hub.uid'=>$uid])
                ->whereOr(['hub.uid'=>$uid])
                ->field($field)->find();
            echo Db::name('house_user_bind')->getLastSql();exit;
        } else {
            $data = Db::name('house_village')->alias('hvi')->where(['village_id'=>$village_id])->field($field)->find();
        }
        //首页推荐新闻
        $news= Db::name('news')->where(['village_id'=>$data['village_id'],'is_recommend'=>1])->order('recommend_sort_id','desc')
                ->field('news_id,title,pic,content')
                ->page($page,config('app.limit'))
                ->select()->toArray();
        foreach ($news as $k=>$v) {
            $news[$k]['content'] = mb_substr(strip_tags($v['content']),0,100);
        }
        $data['news'] = $news;

        //首页轮播图
        $banner = Db::name('village_banner')->where(['village_id'=>$village_id])->order(['sort_id'=>'desc','create_time'=>'desc'])->field('pic,url')->select()->toArray();
        if(!$banner) {
            $banner= [
                ['pic' => '/upload/banner/banner.jpg', 'url' => '#'],
                ['pic' => '/upload/banner/banner2.jpg', 'url' => '#'],
                ['pic' => '/upload/banner/banner3.jpg', 'url' => '#'],
                ['pic' => '/upload/banner/banner4.jpg', 'url' => '#'],
            ];
        }
        $data['banner'] = $banner;

        //公告
         $notice = Db::name('notice')->where(['village_id'=>$village_id])->order(['sort_id'=>'desc','create_time'=>'desc'])->field('notice_id,title')->limit(3)->select()->toArray();
         $data['notice'] = $notice;
         return $this->returnJson($data);
    }


    //获取布局
    public function getLayoutList(){
        $where['village_id'] = Request::param('village_id');
        $data = Db::name('layout_list')->where($where)->select()->toArray();
        foreach ($data as $k => $v) {
            $data[$k]['code_arr'] = explode('-',$v['code']);
        }
        return $this->returnJson($data);
    }

    //建筑列表
    public function buildList() {
        $where['lb.village_id'] = Request::param('village_id');
        $parent_id = Request::param('parent_id',0);
        $where['lb.parent_id'] = $parent_id;
        //检查当前的parent_id是否是最下的一个建筑了,如果是,则查询该下面的房屋
        if($parent_id != 0) {
            $layout_id = Request::param('layout_id');
            $listInfo = Db::name('layout_list')->where(['layout_id'=>$layout_id])->field('code,level')->find();
            $level = $listInfo['level']-1;
            $listArr = explode('-',$listInfo['code']);
            $name = array_pop($listArr);
            $is_last = Db::name('layout_build')->where(['layout_build_id'=>$parent_id,'level'=>$level])->find();
            if($is_last){ //查找房间
                $data = Db::name('house_vacancy')->where(['parent_id'=>$parent_id])->field('vacancy_id,vacancy_code')->select()->toArray();
                foreach ($data as $k => $v) {
                    $vacancyArr = explode('-',$v['vacancy_code']);
                    $code =  array_pop($vacancyArr);
                    $data[$k]['code_name'] = $code.$name;
                    $data[$k]['is_build'] = 0 ;
                }
            } else{
                $data = $this->getBuildInfo($where);
            }
        } else {
            $data = $this->getBuildInfo($where);
        }
        return $this->returnJson($data);
    }

    //获取建筑信息
    public function getBuildInfo($where) {
        if(Request::param('layout_id')) {
            $where['lb.layout_id'] = Request::param('layout_id');
        }
        $data = Db::name('layout_build')->alias('lb')->leftJoin('layout_list ll','ll.layout_id = lb.layout_id')->where($where)->order(['lb.layout_id'=>'asc','lb.sort_id'=>'desc'])
            ->field("lb.layout_build_id,lb.layout_id,lb.code,lb.level,lb.village_id,ll.code as list_code")
            ->select()
            ->toArray();
        foreach ($data as $k =>$v) {
            $data[$k]['code_name'] = $v['code'].explode('-',$v['list_code'])[$v['level']-1];
            $data[$k]['is_build'] = 1;
        }
        return $data;
    }

    //获取单个房间基本信息
    public function getVacancyInfo() {
        $vacancy_id = Request::param('vacancy_id');
        $data = Db::name('house_vacancy')->alias('hv')
                ->leftJoin('house_village hvi','hvi.village_id = hv.village_id')
                ->leftJoin('house_user_bind hub','hub.vacancy_id = hv.vacancy_id')
                ->where(['hv.vacancy_id'=>$vacancy_id])
                ->field('hv.vacancy_code,hv.village_id,hv.parent_id,layout_id,hvi.village_name,hvi.village_address,hvi.province_name,hvi.city_name,hvi.area_name')
                ->find();
        $data['vacancy_address'] = Common::getVacancyAddress($data['vacancy_code'],$data['layout_id']);
        $data['vacancyOwnerInfo'] = Common::getOwnerInfo($vacancy_id); //业主信息
        $data['isHasOwner'] = empty($data['vacancyOwnerInfo']) ? 0 : 1;
        $data['getUserBindType'] = Common::getUserBindType();
        $data['getFamilyBindType'] = Common::getFamilyBindType();
        return $this->returnJson($data);

    }

    //常用电话
    public function commonPhone() {
        $village_id = Request::param('village_id');
        $where['village_id'] = $village_id;
        $where['status'] = 1;
        $data = Db::name('village_phone')->where($where)->order(['is_on_call_phone'=>'desc','sort'=>'desc'])->select()->toArray();
        return $this->returnJson($data);
    }


    //当前用户的所有的房间列表
    public function allVacancy() {
        $uid = $this->uid;
        $userType = $this->userType;
        $where[] = ['hub.uid','=',$uid];
        $data = Db::name('house_user_bind')->alias('hub')->where($where)
                ->leftJoin('house_vacancy hv','hv.vacancy_id = hub.vacancy_id')
                ->leftJoin('house_village hvi','hvi.village_id = hub.village_id')
                ->field('hub.house_user_bind_id,hvi.village_name,hv.vacancy_code,hv.layout_id,hub.pass_time,hub.type,hub.status,hub.vacancy_id,hvi.village_logo,hvi.village_id')
                ->where(['hub.status'=>1])
                ->select()->toArray();
        foreach ($data as $k=>$v) {
            $rest = Common::getVacancyAddress($v['vacancy_code'],$v['layout_id']);
            $data[$k]['vacancy_address'] = $rest['vacancy_address'];
            //获取用户车辆信息
            $cars = Db::name('car')->where(['uid'=>$this->uid,'village_id'=>$v['village_id']])->field('car_id,license_plate,brand')->select()->toArray();
            $data[$k]['cars'] = $cars;
            $car_total = count($cars);
            $data[$k]['car_total'] = $car_total;
            $data[$k]['type_zh'] = $userType[$v['type']];
        }
        $data = Common::changeField($data,'pass_time');
        return $this->returnJson($data);
    }

    //查看车辆详情
    public function detailCar() {
        $car_id = Request::param('car_id');
        $data = Db::name('car')->where(['car_id'=>$car_id,'uid'=>$this->uid])->find();
        return $this->returnJson($data);
    }

//    //修改车辆
//    public function changeCar() {
//        $car_id = Request::param('car_id');
//        $data['license_plate'] = Request::param('license_plate');
//        $is_exit = Db::name('car')->where('uid','<>',$this->uid)->where($data)->find();
//        if($is_exit){
//            return $this->returnJson([],'该车牌号已存在!',400);
//        }
//        $data['name'] = Request::param('name');
//        $data['car_color'] = Request::param('car_color');
//        $data['village_id'] = Request::param('village_id');
//        $data['brand'] = Request::param('brand');
//        $data['car_type'] = Request::param('car_type');
//
//        $change = Db::name('car')->where(['car_id'=>$car_id])->save($data);
//
//        if($change) {
//            return $this->returnJson([],'操作成功!');
//        } else {
//            return $this->returnJson([],'操作失败!',400);
//        }
//
//    }

    //用户添加车辆
    public function changeCar() {
        $uid = $this->uid;
        $car_id = Request::param('car_id');
        $data['phone'] = Db::name('user')->where(['uid'=>$uid])->value('phone');
        $data['name'] = Request::param('name');
        $data['brand'] = Request::param('brand');
        $data['car_color'] = Request::param('car_color');
        $data['license_plate'] = Request::param('license_plate');
        $data['sort_id'] = Request::param('sort_id',1);
        $data['car_type'] = Request::param('car_type');
        $data['uid'] = $uid;
        $data['village_id'] = Request::param('village_id');
        if($car_id) {
            //判断车牌是否存在changeCar
            $is_exit = Db::name('car')->where(['license_plate'=>$data['license_plate']])->where('car_id','<>',$car_id)->find();
            if($is_exit) {
                return $this->returnJson([],'系统中已存在该车牌!',400);
            }
            $operation = Db::name('car')->where(['car_id'=>$car_id])->save($data);
        } else {
            $data['create_time'] = time();
            //判断车牌是否存在
            $is_exit = Db::name('car')->where(['license_plate'=>$data['license_plate'],'village_id'=>$data['village_id']])->find();
            if($is_exit) {
                return $this->returnJson([],'系统中已存在该车牌!',400);
            }
            $operation = Db::name('car')->save($data);
        }

        if($operation !== false) {
            return $this->returnJson([],'success');
        } else {
            return $this->returnJson([],'修改失败!',400);
        }
    }

    //删除车辆
    public function deleteCar() {
        $car_id = Request::param('car_id');
        $delete = Db::name('car')->where(['car_id'=>$car_id,'uid'=>$this->uid])->delete();
        if($delete !== false) {
            return $this->returnJson();
        } else {
            return $this->returnJson([],'删除失败!',400);
        }
    }

    //我的房间详情
    public function detailVacancy() {
        $bind_id = Request::param('bind_id');
        $uid = $this->uid;
        $where[] = ['hub.uid','=',$uid];
        $where[] = ['hub.house_user_bind_id','=',$bind_id];
        $where[] = ['hub.status','=',1];
        $data = Db::name('house_user_bind')->alias('hub')->where($where)
            ->leftJoin('house_vacancy hv','hv.vacancy_id = hub.vacancy_id')
            ->leftJoin('house_village hvi','hvi.village_id = hub.village_id')
            ->field('hvi.village_id,hvi.village_name,hv.vacancy_code,hv.layout_id,hub.pass_time,hub.type,hub.status,hub.vacancy_id,hvi.village_logo,hv.name,hv.phone,hub.house_user_bind_id')
            ->find();
        $res =  Common::getVacancyAddress($data['vacancy_code'],$data['layout_id']);
        $data['vacancy_address'] = $res['vacancy_address'];
        //获取用户车辆信息
        $cars = Db::name('car')->where(['uid'=>$this->uid,'village_id'=>$data['village_id']])->select()->toArray();
        $data['car'] = $cars;
        if($data['type'] ==0 ){
            //查询家属
            $family =  $this->getFamily($data['vacancy_id']);
            //查询租客
            $tenant = $this->getTenant($data['vacancy_id']);
            $data['user'] = array_merge($family,$tenant);
        } elseif($data['type'] ==2){
            $data['user'] = $this->getTenant($data['vacancy_id']);
        } else {
            $data['user'] = [];
        }
        return $this->returnJson($data);
    }


    //根据房间id,查询租客
    public function getTenant($vacancy_id) {
        //查询租客
        $where['hub.vacancy_id'] = $vacancy_id;
        $where['hub.type'] = 2;
        $tenant = $this->getUser($where);
        foreach ($tenant as $k =>$v) {
              $tenant[$k]['type_zh'] = "租客";
        }
        return $tenant;
    }
    //根据房间id,查询家属
    public function getFamily($vacancy_id) {
        //查询租客
        $where['hub.vacancy_id'] = $vacancy_id;
        $where['hub.type'] = 1;
        $family = $this->getUser($where);
        foreach ($family as $k =>$v) {
              $family[$k]['type_zh'] = "家属";
        }
        return $family;
    }

    //获取绑定用户信息
    public function getUser($where){
        $user = Db::name('house_user_bind')->alias('hub')->leftJoin('user','user.uid = hub.uid')
            ->where($where)
            ->whereNotIn('hub.status',[0,3])
            ->where('hub.uid','<>',null)
            ->field('hub.house_user_bind_id,hub.name,hub.phone,user.avatar,user.uid,hub.village_id,hub.status,hub.type')->select()->toArray();
        return $user;
    }


    //业主审核租客和家属,或家属租客申请解绑
    public function changeStatus() {
        $bind_id = Request::param('bind_id');
        $status = Request::param('status'); //1接受,0拒绝,4申请解绑,3已解绑
        $save['status'] = $status;
        $save['pass_time'] = time();
        $change = Db::name('house_user_bind')->where(['house_user_bind_id'=>$bind_id])->save($save);
        if($change !== false) {
            return $this->returnJson();
        } else {
            return $this->returnJson([],'操作失败!',400);
        }
    }




}