<?php


namespace app\api\controller;



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

class User extends Base
{
    //获取用户所入住的小区|搜索小区
    public function getUserVillage() {
        $keyword = Request::param('keyword','');
        $page = Request::param('page',1);
//        $province_id = Request::param('province_id');
//        $city_id = Request::param('city_id');
//        $area_id = Request::param('area_id');
        $where =[];
//        if($province_id) {
//            $where['province_id'] = $province_id;
//        }
//        if($city_id) {
//            $where['city_id'] = $city_id;
//        }
//        if($area_id) {
//            $where['area_id'] = $area_id;
//        }
        if($keyword) { //如果有关键字就搜索关键字的小区
            $villages = Db::name('house_village')->where($where)->where('village_name','like','%'.$keyword.'%')->field('village_name,village_id,province_name,city_name,area_name,village_logo,village_address')->page($page,config('app.limit'))->select()->toArray();
            $res['total'] =  Db::name('house_village')->where($where)->where('village_name','like','%'.$keyword.'%')->count();
            $rest=[];
            foreach ($villages as $k =>$v) {
                $rest['village_name'] = $v['village_name'];
                $rest['village_id'] = $v['village_id'];
                $rest['village_address'] = $v['province_name'].$v['city_name'].$v['area_name'].$v['village_address'];
                $rest['village_logo'] = $v['village_logo'];
                $rest['vacancy'] = Common::getVacancy($v['village_id'],$this->uid);
                $res['data'][] = $rest;
            }
        } else { //没有就展示已入住的小区
            $where['hub.uid'] = $this->uid;
            $where['hub.status'] = 1;
            $village_ids = DB::name('house_user_bind')->alias('hub')->where($where)->group('village_id')->column('village_id');
            $village_info = Db::name('house_village')->whereIn('village_id',$village_ids)->field('village_name,village_id,province_name,city_name,area_name,village_logo,village_address')->select()->toArray();
            $res['total'] = count($village_ids);
            $rest=[];
            foreach ($village_ids as $k =>$v) {
                foreach ($village_info as $key =>$val) {
                    if($val['village_id'] == $v) {
                        $rest['village_name'] = $val['village_name'];
                        $rest['village_id'] = $val['village_id'];
                        $rest['village_address'] = $val['province_name'].$val['city_name'].$val['area_name'].$val['village_address'];
                        $rest['village_logo'] = $val['village_logo'];
                        break;
                    }
                }
                $rest['vacancy'] = Common::getVacancy($v,$this->uid);
                $res['data'][] = $rest;
            }
        }
       if($res['total']==1){
           $res['data'] = array_values($res['data']);
       }
       $res['keyword'] = $keyword;
        return $this->returnJson($res);
    }

    //用户设置密码
    public function setPassword() {
        $password = Request::param('password');
        if(strlen($password) <7) {
            return $this->returnJson([],'密码长度最起码7位',400);
        }
        $data['password'] = md5($password);
        $save = Db::name('user')->where(['uid'=>$this->uid])->save($data);
        if($save) {
            return $this->returnJson();
        } else {
            return $this->returnJson([],'设置失败',400);
        }
    }

    //用户绑定房间
    public function userBindVacancy(){
        //判断参数是否为空
        $data['type'] = Request::param('type');
        $village_id = Request::param('village_id');
        $vacancy_id =  Request::param('vacancy_id');
        $data['vacancy_id'] = $vacancy_id;
        $data['name'] = $car['name'] = Request::param("name");
        $data['phone'] =  $car['phone'] = Request::param("phone");
        $data['village_id'] =  $car['village_id']= $village_id;
        $is_exit = Common::getOwnerInfo($vacancy_id);
        $data['id_card'] = Request::param("id_card");
        $data['uid'] =$car['uid'] = $this->uid;
        $data['status'] = 2;
        $data['create_time'] =$car['create_time']= time();
        $data['memo'] = Request::param('memo');
        $car['brand'] = Request::param('brand');
        $car['car_type'] = Request::param('car_type');
        $car['license_plate'] = Request::param('license_plate');
        $car['car_color'] = Request::param('car_color');

        //查看当前手机号是否重复绑定当前房间,一个房间对应的一个手机号只能有一种身份
        $is_only = Db::name('house_user_bind')->where(['village_id'=>$village_id,'vacancy_id'=>$vacancy_id,'phone'=>$data['phone']])->where('status',"<>",3)->find();
        if($is_only){
            return $this->returnJson([],'用户已绑定房间!',400);
        }
        if($data['type'] == 0) { //申请业主不需要填写业主后四位手机号
            //检查该房间是否有房主绑定
            if(!empty($is_exit)){
                return $this->returnJson([],'该房间下已有业主!',400);
            }
            $save['id_card'] = $data['id_card'];
            $save['name'] = $data['name'];
            $save['phone'] = $data['phone'];
            $save['uid'] = $data['uid'];
            //修改房间的信息
            Db::name('house_vacancy')->where(['vacancy_id'=>$vacancy_id])->save($save);
        }else{
            if(empty($is_exit)){
                return $this->returnJson([],'该房间未绑定业主,不能绑定租客!',400);
            }
            $ownerPhone = $is_exit['phone'];
            $phone_num = Request::param('phone_num');
            if($phone_num != substr($ownerPhone,7)){
                return $this->returnJson([],'业主后四位手机号不正确!',400);
            }
        }

        Db::startTrans();
        try{
             Db::name('house_user_bind')->save($data);
             if($car['brand'] && $car['car_type'] && $car['license_plate']) {
                 //查看系统中是否存在了,存在则修改,不存在则添加
                 $is_exit = Db::name('car')->where(['village_id'=>$village_id,'license_plate'=>$data['license_plate']])->find();
                 if($is_exit){
                     Db::name('car')->where(['village_id'=>$village_id,'license_plate'=>$data['license_plate']])->save($car);
                 }else{
                     Db::name('car')->save($car);
                 }
             }
             Db::commit();

            return $this->returnJson();
        }catch(\Exception $e){
            Db::rollback();
            return $this->returnJson([],'绑定失败,请重试!',400);
        }
    }

    //用户申请解绑
    public function userUnBind(){
        $where['house_user_bind_id'] = Request::param('house_user_bind_id');
        $where['uid'] = $this->uid;
        $save['status'] = 4;
        $change =Db::name('house_user_bind')->where($where)->save($save);
        if($change) {
            return $this->returnJson([],'申请成功!');
        } else {
            return $this->returnJson([],'申请失败!',400);
        }
    }


    //查看所有的房间,如果是业主,展示房间下的所有租客或家属
//    public function getUserVacancy() {
//        $uid = $this->uid;
//        $where['hub.uid'] = $uid;
//        $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 = hub.village_id')
//                ->where($where)->whereIn('hub.status',[1,2,4])
//                ->field('hub.type,hub.house_user_bind_id,hub.vacancy_id,parent_id,hv.vacancy_code,hv.layout_id,hv.name,hv.phone,hvi.village_name')
//                ->select()->toArray();
//        foreach ($data as $k =>$v) {
//            $data[$k]['vacancy_address'] = Common::getVacancyAddress($v['vacancy_code'],$v['layout_id']);
//            if($v['type'] ==0) {
//                //如果是业主身份,查找下面的租客或家属等
//                $data[$k]['myTenant'] = Db::name('house_user_bind')->where(['vacancy_id'=>$v['vacancy_id']])->whereIn('type',[1,2,3])->field('name,phone,status')->select()->toArray();
//            }else{
//                //如果是租客身份,查找所属业主
//                $data[$k]['myOwner'] = Db::name('house_user_bind')->where(['vacancy_id'=>$v['vacancy_id'],'type'=>0,'status'=>1])->field('name,phone,status')->find();
//            }
//        }
//
//        return $this->returnJson($data);
//    }


    //个人中心,如果没与传递bind_id,则返回最新的已绑定的房间信息
    public function person(){
        $bind_id = Request::param('bind_id');
        $village_id = Request::param('village_id');
        if($bind_id){
            $where['hub.house_user_bind_id'] = $bind_id;
            $where['hub.status'] = 1;

        }
        $where['hub.uid'] = $this->uid;
        $where['hub.village_id'] = $village_id;
        $data = Db::name('house_user_bind')->alias('hub')
             ->leftJoin('house_vacancy hv','hv.vacancy_id = hub.vacancy_id')
             ->leftJoin('user','user.uid = hub.uid')
             ->order('hub.create_time','desc')
             ->where($where)
             ->field('hub.house_user_bind_id as bind_id,hub.name,hv.vacancy_code,hv.layout_id,hv.village_id,user.sex,user.nickname,user.avatar,user.face_img')
             ->find();
        if(!$data) {
            //如果,新用户,只能返回基础信息
            $whereOne['uid'] = $this->uid;
            $data = Db::name('user')->alias('user')
                ->where($whereOne)->field('user.sex,user.nickname,user.avatar,user.face_img')->find();
        }

        //获取当日值班电话
        $phone = Db::name('village_phone')->where(['village_id' => $village_id, 'is_on_call_phone' => 1, 'status' => 1])->value('phone');
        $data['today_phone'] = $phone;
        if(isset($data['vacancy_code'])) {
            $res = Common::getVacancyAddress($data['vacancy_code'],$data['layout_id']);
            $data['vacancy_address'] = $res['vacancy_address'];
        }


        return $this->returnJson($data);
    }

    //更改人脸图片信息
    public function changeUserFaceImg() {
        $where['uid'] = $this->uid;
        $data['face_img'] = Request::param('face_img');
        if(empty($data)) {
            return $this->returnJson([],'图片必传!',400);
        }
        $change = Db::name('user')->where($where)->save($data);
        if($change) {
            return  $this->returnJson();
        } else {
            return  $this->returnJson([],'更改失败!');
        }
    }



    //人脸图片文件上传
    public function uploadFaceImg() {
        $path = Request::param('path','face');
        $file = request()->file('img');
        if(!$file || !in_array($path,['header','face'])){
            return $this->returnJson([],'参数错误!',400);
        }
        $path = '/'.$path;
        $data = Common::uploadImg($file,$path);
        if($data) {
            return $this->returnJson($data,'success');
        } else {
            return $this->returnJson([],'请上传图片文件',400);
        }
    }


    //设置本次登入的房间未最近一次登入的,下次登入自动切换
    public function setUserBind(){
        $bind_id = Request::param('house_user_bind_id');
        $uid = $this->uid;
        Db::name('house_user_bind')->where(['uid'=>$uid])->save(['is_lately_login'=>0]);
        Db::name('house_user_bind')->where(['uid'=>$uid,'house_user_bind_id'=>$bind_id])->save(['is_lately_login'=>1]);
        return $this->returnJson([],'success');

    }


    //修改头像和昵称
    public function changeUserInfo() {
        $data['nickname'] = Request::param('nickname');
        $data['sex'] = Request::param('sex');
        $data['avatar'] = Request::param('avatar');
        $where['uid'] = $this->uid;
        $change = Db::name('user')->where($where)->save($data);
        if($change) {
            return $this->returnJson();
        } else {
            return $this->returnJson([],'修改失败!',400);
        }
    }






}