<?php


namespace app\shequ\controller;


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

class Userbind extends Base
{
    protected $middleware = ['app\middleware\CommunityLoginCheck::class','app\middleware\CommunityAfter::class'];

    //用户绑定|解绑房间
    public function unbind() {
        $where['house_user_bind_id'] = Request::param('bind_id');
        //现获取这一条房间的绑定的状态
        $bindInfo = Db::name('house_user_bind')->where($where)->field('phone,id_card,vacancy_id,type')->find();
        $status=  Request::param('status',3);
        $save['status'] = $status;
        if($status == 1) {
            $save['pass_time'] = time();
            if($bindInfo['type'] == 3) { //这是更换业主或审核房主
                //1.更换房间表的信息
                $data['name'] = $bindInfo['name'];
                $data['id_card'] = $bindInfo['id_card'];
                $save['type'] = 0;
                Db::startTrans();
                try{
                    Db::name('house_vacancy')->where(['vacancy_id'=>$bindInfo['vacancy_id']])->save($data);
                    //更改原先的业主的绑定字段
                    Db::name('house_user_bind')->where(['vacancy_id'=>$bindInfo['vacancy_id'],'type'=>0,'status'=>1])->save(['status'=>3]);
                    //更改现在的用户为房主
                    $change = Db::name('house_user_bind')->where($where)->update($save);
                    Db::commit();

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

        }
        if($status == 3) {
            $save['unbind_time'] = time();
            //如果是解绑的话,需要考虑,当前如果是业主,需要查看是否又其他的用户绑定了
            if($bindInfo['type']==0) {
                $is_exit = Db::name('house_user_bind')->where(['vacancy_id'=>$bindInfo['vacancy_id']])->where('status','<>',3)->where('type','<>',0)->find();
                if($is_exit) {
                    return $this->returnJson([], '业主解绑失败,该房间下还有用户未解绑!');
                }
            }
        }
        $change = Db::name('house_user_bind')->where($where)->update($save);
        if($change) {
            return $this->returnJson([],'success',200);
        } else {
            return $this->returnJson([],'error',200);
        }
    }


    //业主列表| 租客列表 | 家属列表
    public function houseOwnerList(){
        $vacancy = new Vacancy($this->app);
        $page = Request::param('page',1);
        $where[] = ['hub.type','=',Request::param('type',0)];
        $where[] = ['hub.village_id','=',$this->village_id];
        if(Request::param('phone')) {
            $where[] = ['hub.phone','=',Request::param('phone')];
        }
        if(Request::param('status')) {
            $where[] = ['hub.status','=',Request::param('status')];
        }

        $total = DB::name('house_user_bind')->alias('hub')->where($where)->count();
        $data = DB::name('house_user_bind')->alias('hub')
                ->leftJoin('house_vacancy hv','hv.vacancy_id = hub.vacancy_id')
                ->where($where)
                ->order(['hub.pass_time'=>'desc','hub.status'=>'desc'])
                ->page($page,config('app.limit'))
                ->field('hub.house_user_bind_id,hub.name,hub.phone,hub.id_card,hub.pass_time,hub.unbind_time,hub.status,hub.type,hv.vacancy_code,hv.layout_id')
                ->select()->toArray();


        foreach ($data as $k => $v) {
            $res = $vacancy->getVacancyAddress($v['vacancy_code'],$v['layout_id']);
            $data[$k]['vacancy_address'] = $res['vacancy_address'];
        }
        $res['total'] = $total;
        $res['data'] = Common::changeField($data,['pass_time','unbind_time']);
        return $this->returnJson($res,'success');

    }


    //修改入住人员信息
    public  function changeHouseOwner() {
        $where['house_user_bind_id'] = Request::param('bind_id');
        $save['name'] = Request::param('name');
        $save['phone'] = Request::param('phone');
        $is_card = Request::param('id_card');
        if(!isCreditNo($is_card)) {
            return $this->returnJson([],'身份证号码不正确!',400);
        }
        $save['id_card'] = $is_card;
        $save['type'] = Request::param('type');
        $save['relatives_type'] = Request::param('relatives_type');
        $save['memo'] = Request::param('memo');
        $change = Db::name('house_user_bind')->where($where)->update($save);
        if($change) {
            return $this->returnJson([],'success');
        } else {
            return $this->returnJson([],'error',400);
        }
    }

    //删除绑定人员,需要用户先解绑
    public function deleteHouseOwner() {
        $where['house_user_bind_id'] = Request::param('bind_id');
        $where['village_id'] = $this->village_id;
        $bindInfo = Db::name('house_user_bind')->where($where)->field('house_user_bind_id,status')->find();
        if($bindInfo['status'] != 3) {
            return $this->returnJson([],'请先解绑用户!',400);
        }
        $del =  Db::name('house_user_bind')->where($where)->delete();
        if($del) {
            return $this->returnJson([],'success');
        } else {
            return $this->returnJson([],'error',400);
        }

    }

    //绑定人员详情
    public function detailHouseOwner() {
        $vacancy = new Vacancy($this->app);
        $where['house_user_bind_id'] = Request::param('bind_id');
        $data = Db::name('house_user_bind')->alias('ub')->leftJoin('house_vacancy hv','hv.vacancy_id = ub.vacancy_id')->where($where)
                ->field('ub.*,hv.vacancy_code,hv.layout_id')
                ->find();
        $data = Common::changeField($data);
        if($data) {
            $res =  $vacancy->getVacancyAddress($data['vacancy_code'],$data['layout_id']);
            $data['vacancy_address'] = $res['vacancy_address'];
        } else {
            $data = [];
        }
        return $this->returnJson($data,'success');

    }
    //添加绑定的人员
    public function createBindUser() {
        $data['village_id'] = $this->village_id;
        $data['name'] = Request::param('name');
        $data['phone'] = Request::param('phone');
        $data['create_time'] = $data['pass_time']= time();
        $data['memo'] = Request::param('memo');
        $data['type'] = Request::param('type');
        $data['relatives_type'] = Request::param('relatives_type');
        $data['status'] = Request::param('status',1);
        $data['id_card'] = Request::param('id_card');
        //根据房间编号获取房间id,
        $vacancy_code = Request::param('vacancy_code');
        $vacancy_id = DB::name('house_vacancy')->where(['village_id'=>$this->village_id,'vacancy_code'=>$vacancy_code])->value('vacancy_id');
        if(!$vacancy_id) {
            return $this->returnJson([],'房间编号不存在!',400);
        }
        $data['vacancy_id'] = $vacancy_id;
        //查看该用户是否绑定了同一个房间的多个身份
        $is_exit = Db::name('house_user_bind')->where(['vacancy_id'=>$vacancy_id,'id_card'=>$data['id_card']])->find();
        if($is_exit) {
            return $this->returnJson([],'该身份证用户在该房间下以绑定,请勿重复绑定!',400);
        }
        //业主只能有一个
        if($data['type'] ==0){
            $is_owner = Db::name('house_user_bind')->where(['village_id'=>$this->village_id,'vacancy_id'=>$vacancy_id,'type'=>0,'status'=>1])->find();
            if($is_owner) {
                return $this->returnJson([],'该房间编号下以绑定业主,请先解绑!',400);
            }
        }
        $add = Db::name('house_user_bind')->save($data);
        if($add) {
            return $this->returnJson([],'success');
        } else {
            return $this->returnJson([],'添加失败',400);
        }

    }

    //用户导入模板下载
    public function downloadTenant() {
        $file_dir = "./formwork/importTenant.xls";
        $phpExcel = \PHPExcel_IOFactory::load($file_dir);
        $village_id = $this->village_id??1;
        $optionsArr = Db::name('layout_list')->where(['village_id'=>$village_id])->column('code');
        $optionsString = implode(',',$optionsArr);//这个是选择布局
        for($i=2;$i<20;$i++) {
            $phpExcel->getActiveSheet()->getCell('F'.$i)->getDataValidation()-> setType(\PHPExcel_Cell_DataValidation::TYPE_LIST)
                -> setErrorStyle(\PHPExcel_Cell_DataValidation::STYLE_INFORMATION)
                -> setAllowBlank(false)
                -> setShowInputMessage(true)
                -> setShowErrorMessage(true)
                -> setShowDropDown(true)
                -> setErrorTitle('输入的值有误')
                -> setError('您输入的值不在下拉框列表内.')
                -> setPromptTitle('社区布局')
                -> setFormula1('"'.$optionsString.'"');; //这一句为要设置数据有效性的单元格

            $phpExcel->getActiveSheet()->getCell('E'.$i)->getDataValidation()-> setType(\PHPExcel_Cell_DataValidation::TYPE_LIST)
                -> setErrorStyle(\PHPExcel_Cell_DataValidation::STYLE_INFORMATION)
                -> setAllowBlank(false)
                -> setShowInputMessage(true)
                -> setShowErrorMessage(true)
                -> setShowDropDown(true)
                -> setErrorTitle('输入的值有误')
                -> setError('您输入的值不在下拉框列表内.')
                -> setPromptTitle('社区布局')
                -> setFormula1('"租客,业主,家属"');; //这一句为要设置数据有效性的单元格

        }
        $objWriter = new \PHPExcel_Writer_Excel5($phpExcel);
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="用户导入.xls"');
        header('Cache-Control: max-age=0');
        $objWriter->save("php://output");
    }


    //用户批量导入数据
    public function importTenant() {
        $filePath = Request::param('filePath');
        if(!file_exists($filePath)){
            return $this->returnJson([],'文件不存在!',400);
        }
        $village_id = $this->village_id ?? 1;
        $res = Common::importTenant($filePath,$village_id);
        if($res['code']!=200) {
            return  $this->returnJson([],'success');
        }

    }


    //查看用户关联到车辆
    public function userCar() {
        $phone = Request::param("phone");
        $data = Db::name('car')->where(['phone'=>$phone])->field("car_id,phone,license_plate,create_time,name,car_color,brand")->order('create_time','desc')->select()->toArray();
        return $this->returnJson(Common::changeField($data),'success');

    }











}