<?php


namespace app\shequ\controller;


//关于房屋的操作
use app\common\controller\Common;
use think\facade\Db;
use think\facade\Request;

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

    //房间列表
    public  function vacancyList() {
        $page = Request::param('page',1);
        $where[] = ['hv.village_id','=',$this->village_id];
        if(Request::param('phone')) {
            $where[] = ['hv.phone','=',Request::param('phone')];
        }
        if(Request::param('name')) {
            $where[] = ['hv.name','=',Request::param('name')];
        }
        if(Request::param('vacancy_code')) {
            $vacancy_code = Request::param('vacancy_code');
            $where[] = ['hv.vacancy_code','like',$vacancy_code."%"];
        }
        $total = Db::name('house_vacancy')->alias('hv')
                 ->where($where)
                 ->count();
        $data = Db::name('house_vacancy')->alias('hv')->field('hv.layout_id,hv.vacancy_code,hv.vacancy_id,hv.vacancy_code,hv.name,hv.phone,hv.create_time,hv.village_name,hv.village_id,hv.area,hv.id_card')
                ->where($where)
                ->order('create_time','desc')
                ->page($page,config('app.limit'))
                ->select()->toArray();
        foreach ($data as $k =>$v) {
            $res =  $this->getVacancyAddress($v['vacancy_code'],$v['layout_id']);
            $data[$k]['vacancy_address'] = $res['vacancy_address'];
            $data[$k]['room_num'] =  $res['room_num'];
        }
        $res['total'] = $total;
        $res['data'] = Common::changeField($data);
        return $this->returnJson($res,'success');
    }

    //房间详情
    public function detailVacancy() {
        $vacancy_id = Request::param('vacancy_id');
        $where['hv.vacancy_id'] = $vacancy_id;
        $where['hv.village_id'] = $this->village_id;
        $data = Db::name('house_vacancy')->alias('hv')->where($where)->find();
        $res = $this->getVacancyAddress($data['vacancy_code'],$data['layout_id']);
        $data['vacancy_address'] = $res['vacancy_address'];;
        unset($data['village_name']);//用连表查询的社区名称
        if($data['is_inherit'] ==1 ) {
            $p_info = Db::name('layout_build')->where(['layout_build_id'=>$data['parent_id']])
            ->field('property_price,water_price,electric_price,gas_price,parking_price')->find();
            $data['property_fee'] = $p_info['property_price'];
            $data['water_fee'] = $p_info['water_price'];
            $data['electric_fee'] = $p_info['electric_price'];
            $data['gas_fee'] = $p_info['gas_price'];
            $data['parking_fee'] = $p_info['parking_price'];
        }
        return $this->returnJson(Common::changeField($data),'success');
    }

    //添加| 修改 房间
    public function createVacancy() {
        $vacancy_id = Request::param('vacancy_id');
        $data['layout_id'] =  Request::param('layout_id');
        $data['village_id'] = $add['village_id']= $this->village_id;
        $vacancy_code =  Request::param('vacancy_code');
        if($vacancy_id) {
            $res = $this->checkVacancyCode($vacancy_code,$vacancy_id,$data['layout_id'] );
        } else {
            $res = $this->checkVacancyCode($vacancy_code,0,$data['layout_id'] );
        }
        if($res['code'] !=200) {
            return $this->returnJson([],$res['msg'],400);
        }
        $data['vacancy_code'] =  $vacancy_code ;
        $data['name'] = $add['name'] =  Request::param('name'); //业主姓名
        $data['id_card'] = $add['id_card'] = Request::param('id_card'); //身份证id /
        $phone =  Request::param('phone'); //业主手机号
        if(!isPhoneNo($phone)) {
            return $this->returnJson([],'手机号不合法!',400);
        }
        $data['phone'] = $add['phone']= $phone;
        if(Request::param('property_start_time') && Request::param('property_end_time')) {
            $data['property_start_time'] =  date('Y-m',strtotime(Request::param('property_start_time')));
            $data['property_end_time'] =   date('Y-m',strtotime(Request::param('property_end_time')));
            if($data['property_start_time'] && $data['property_end_time']) {
                //判断物业服务开始时间和结束时间是否合理
                $res = $this->checkVacancyPropertyTime($data['property_start_time'],$data['property_end_time']);
                if($res['code'] !=200) {
                    return $this->returnJson([],$res['msg'],400);
                }
            }
        }
        $data['village_name'] = Db::name('house_village')->where(['village_id'=>$data['village_id']])->value('village_name');
        $data['area'] =  Request::param('area');
        $data['status'] =  Request::param('status',1);
        $data['memo'] =  Request::param('memo');
        $data['park_flag'] =  Request::param('park_flag',1); //是否有车位
        $data['house_type'] =  Request::param('house_type',1); //类型 1住宅 2商铺 3办公
        $data['is_inherit'] =  Request::param('is_inherit',1);
        $data['property_fee'] =  Request::param('property_fee');
        $data['water_fee'] =  Request::param('water_fee');
        $data['electric_fee'] =  Request::param('electric_fee');
        $data['gas_fee'] =  Request::param('gas_fee');
        $data['parking_fee'] =  Request::param('parking_fee');
        $data['parent_id'] =  Request::param('parent_id');

        $add['type'] = $add['status'] = 0;

        $park_code = Request::param('park_code');

        if($park_code) {
            //判断是否有该编号的车位
            $is_exit = Db::name('park_car')->where(['village_id'=>$this->village_id,'park_code'=>$park_code])->field('park_car_id,status')->find();
            if(!$is_exit) {
                return $this->returnJson([],'暂未查询到该编号的车位!',400);
            }
            if($is_exit['status'] == 1) {
                return $this->returnJson([],'该车位已占用,请先解绑对应的车位!',400);
            }
            $data['park_car_id'] = $is_exit['park_car_id'];
        }
        if($vacancy_id) { //修改
            $operation = Db::name('house_vacancy')->where(['vacancy_id'=>$vacancy_id])->update($data);
            $change = Db::name('house_user_bind')->where(['vacancy_id'=>$vacancy_id])->save($add);
            if($operation || $change) {
                return $this->returnJson([],'success');
            } else {
                return $this->returnJson([],'error',400);
            }
        } else {
            $data['create_time'] = $add['pass_time']=$add['create_time'] = time();
            Db::startTrans();
            try{
                $operation = Db::name('house_vacancy')->insertGetId($data);
                $add['vacancy_id'] = $operation;
                $change = Db::name('house_user_bind')->save($add);
                Db::commit();
                return $this->returnJson([],'success');
            }catch(\Exception $e){
                Db::rollback();
                return $this->returnJson([],'error',400);
            }

        }
    }

    //查看房间的绑定的人员
    public function vacancyBindUser() {
        $vacancy_id = Request::param('vacancy_id');
        $data = Db::name('house_user_bind')->where(['vacancy_id'=>$vacancy_id])->field('house_user_bind_id,name,phone,type,pass_time,unbind_time,status')
            ->order('pass_time','desc')
            ->select()->toArray();
        return $this->returnJson(Common::changeField($data,['pass_time','unbind_time']),'success');
    }

    //删除房间
    public function deleteVacancy() {
        $vacancy_id = Request::param('vacancy_id');
        $where[] = $where_one[] = ['status','in',[0,1,2]];
        $where[] = $where_two[] = ['vacancy_id','=',$vacancy_id];
        //查询房间是否绑定了用户,如果存在,则不删除
        $is_exit = DB::name('house_user_bind')->where($where)->find();
        if($is_exit) {
            return $this->returnJson([],'该房间下有用户记录,请先解绑!',400);
        }
        $del1 = Db::name('house_user_bind')->where($where_one)->delete();

        $del = Db::name('house_vacancy')->where($where_two)->delete();
        if($del || $del1) {
            return $this->returnJson([],'success');
        } else {
            return $this->returnJson([],'error',400);
        }
    }

    //检查房间编号是否合法
    public function checkVacancyCode($vacancy_code,$vacancy_id=0,$layout_id) {
        if($vacancy_id == 0){
            $vacancyInfo = Db::name('house_vacancy')->where(['village_id'=>$this->village_id,'vacancy_code'=>$vacancy_code,'layout_id'=>$layout_id])->field('vacancy_id')->find();
        } else{
            $vacancyInfo = Db::name('house_vacancy')->where(['village_id'=>$this->village_id,'vacancy_code'=>$vacancy_code,'layout_id'=>$layout_id])->where('vacancy_id','<>',$vacancy_id)->field('vacancy_id,vacancy_code')->find();
        }
        if($vacancyInfo) {
            return ['code'=>400,'msg'=>'物业编号已存在!'];
        }
        $array = explode ('-',$vacancy_code);

        //查看布局是否黑
        $layoutCode = Db::name('layout_list')->where(['layout_id'=>$layout_id])->value('code');
        if(count($array) != count(explode('-',$layoutCode))){
            return ['code'=>400,'msg'=>'房间位置不合法!'];
        }
        //去掉最后一个房间编号的
        array_pop($array);
        $count = Db::name('layout_build')->where('layout_build_id','in',$array)->count();
        if($count != count($array)) {
            return ['code'=>400,'msg'=>'房间位置不合法!'];
        } else {
            return ['code'=>200,'msg'=>'success!'];
        }

    }

    //判断输入的物业开始时间和结束时间是否合理
    public function checkVacancyPropertyTime($stat_time,$end_time){
        if($stat_time ==$end_time) {
            return ['code'=>400,'msg'=>"开始时间和结束时间不能相同!"];
        }
        $new_time = date('Y-m',time());
        if($stat_time == $new_time) {
            return ['code'=>400,'msg'=>"开始时间不能早于当前月份!"];
        }

        if($stat_time > $end_time || $stat_time =$end_time) {
            return ['code'=>400,'msg'=>"开始时间不能大于结束时间!"];
        }

        $new_year = explode('-',$new_time)[0];
        $end_year = explode('-',$end_time)[0];
        $time_diff = $new_year - $end_year;
        if($time_diff > 3) {
            return ['code'=>400,'msg'=>"结束时间不能设置不能超过2年!"];
        }


    }

    //通过房间编号获取房间地址
    public function getVacancyAddress($vacancyCode,$layout_id=0) {
        if($layout_id == 0) {
           $layout_id = Db::name('house_vacancy')->where(['village_id'=>$this->village_id,'vacancy_code'=>$vacancyCode])->value('layout_id');
        }
        $layoutCode = Db::name('layout_list')->where(['layout_id'=>$layout_id,'village_id'=>$this->village_id])->value('code');
        $codeArr = explode('-',$layoutCode);
        $rom = array_pop($codeArr); //获取最后一个房间的单位
        $arr = explode('-',$vacancyCode);
        $room_code = array_pop($arr);
        $string = '';
        $room_num = '';
        foreach ($arr as $v) {
             $code_name = Db::name('layout_build')->where(['layout_build_id'=>$v])->field('code,level')->find();
             $key =  $code_name['level'] -1;
             $string.=$code_name['code'].$codeArr[$key];
             $room_num.=$code_name['code']."-";
        }
        $room_num = $room_num.$room_code;
        return ['vacancy_address'=>$string.$room_code.$rom,'room_num'=>$room_num];
    }

    //通过物业编号拼接房间编号
    public function getVacancyRoomNum($vacancy_code){
        $vacancy_codeArr = explode('-',$vacancy_code);
        array_pop($vacancy_codeArr);
        $room_num = '';
        foreach ($vacancy_codeArr as $v){
            $num = Db::name('layout_build')->where(['layout_build_id'=>$v])->value('code');
            $room_num.=$num."-";
        }
        return trim($room_num,'-');

    }

    //房间批量导入
    public function importVacancy() {

        $filePath = Request::param('filePath');
        if(!file_exists($filePath)){
            return $this->returnJson([],'文件不存在!',400);
        }
        $village_id = $this->village_id ?? 1;
        $res = Common::importVacancy($filePath,$village_id);
        if($res['code']==200) {
           return  $this->returnJson([],'success');
        } elseif($res['code'] ==400) {
            return  $this->returnJson([],$res['msg'],400);
        }
    }

    //excel文件上传
    public function uploadFile() {
        $file = request()->file('xls');
        $ext = $file->getOriginalExtension();
        if($ext != 'xls') {
            return $this->returnJson([],'请上传xls文件',400);
        }
        $savename = \think\facade\Filesystem::putFile('', $file,'datea');
        $data['filePath'] = "./upload/".$savename;
        return $this->returnJson($data,'success');

    }

    //房间批量下载模板下载
    public function downloadImportVacancy() {
        $file = "./formwork/importVacancy.xls";
        $phpExcel = \PHPExcel_IOFactory::load($file);
        $village_id = $this->village_id ?? 1;
        $optionsArr = Db::name('layout_list')->where(['village_id'=>$village_id])->column('code');
        $optionsString = implode(',',$optionsArr);//这个是选择布局
        $car_blockArr = Db::name('park_block')->where(['village_id'=>$village_id])->column('name');
        $optionsCarBlockString = implode(',',$car_blockArr);//这个是车库布局
        for($i=2;$i<3;$i++) {
            $phpExcel->getActiveSheet()->getCell('H'.$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.'"');; //这一句为要设置数据有效性的单元格
            if($optionsCarBlockString) {
                $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('"'.$optionsCarBlockString.'"');; //这一句为要设置数据有效性的单元格
            }
            $phpExcel->getActiveSheet()->getCell('I'.$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 vacancyCost(){
        $convertArr = $this->convertArr;
        $cost_month = Request::param('month');
        $page = Request::param('page',1);
        $vacancy_id = Request::param('vacancy_id');
        $isPay = Request::param('is_pay');
        $type = Request::param('type');
        $where['village_id'] = $this->village_id;
        $where['vacancy_id'] = $vacancy_id;
        if($cost_month){
            $where['cost_month'] =$cost_month;
        }
        if($isPay) {
            $where['is_pay'] = $isPay;
        }
        if($type && $type == "other") {
            $where['is_default'] = 0; //自定义收费的

        } elseif($type == "other") {
            $where['is_default'] = 1;
        }
        $data = Db::name('cost')->where($where)->order('cost_id','desc')->field('cost_id,price,type,total_money,cost_month,is_pay,area,pay_time,prefer_money,pay_money,explain,is_default')->page($page,config('app.limit'))->select()->toArray();

        foreach ($data as $k => $v){
            $data[$k]['type'] = $convertArr[$v['type']];
        }
        $total = Db::name('cost')->where($where)->count();
        $res['total'] = $total;
        $res['data'] = Common::changeField($data,'pay_time');
        return $this->returnJson($res);
    }

    //每月账单详情
    public function detailCost() {
        $where['cost_id'] = Request::param('cost_id');
        $where['village_id'] = $this->village_id;
        $data = Db::name('cost')->where($where)->find();
        switch ($data['type']){
            case "property":
                $data['type'] ="物业费";
                break;
            case "water":
                $data['type'] ="水费";
                break;
            case "gas":
                $data['type'] ="燃气费";
                break;
            case "electric":
                $data['type'] ="电费";
                break;
            case "park":
                $data['type'] ="停车费";
                break;
        }

        return $this->returnJson(Common::changeField($data,['create_time','pay_time']));


    }


    //修改某个房间的费用明细
    public function changeCost() {
        $where['cost_id'] = Request::param('cost_id');
        $where['village_id'] = $this->village_id;
        $where['is_default'] = 1;
        $data['price'] =Request::param('price');
        $data['area'] =Request::param('area');
        $data['total_money'] = $data['price'] * $data['area'];
        $data['prefer_money'] = Request::param('prefer_money',0);
        $data['explain'] = Request::param('explain');
        if($data['prefer_money'] !=0 && !isset($data['explain'])) {
            return $this->returnJson([],'优惠说明必填!',400);
        }
        $data['pay_money'] = $data['total_money']-$data['prefer_money'];
        $data['is_pay'] =Request::param('is_pay',0);
        $change = Db::name('cost')->where($where)->save($data);
        if($change) {
            Db::name('cost_log')->insert(['cost_id'=>$where['cost_id'],'community_admin_id'=>$this->uid,'data'=>json_encode($data)]);
            return $this->returnJson();
        } else {
            return $this->returnJson([],'修改失败',400);
        }
    }

    //添加|修改自定义收费
    public function createCustomizeCost(){
        $cost_id =Request::param('cost_id');
        $type = Request::param("type");
        if(empty($type)){
           return $this->returnJson([],'收费类目必填!');
        }
        $data['type'] = $type;
        $data['pay_money'] = $data['total_money'] = Request::param('pay_money');
        $data['explain'] = Request::param('explain');
        $data['is_pay'] = Request::param('is_pay',0);
        if($cost_id) {
            $where['cost_id'] = $cost_id;
            $operation = Db::name('cost')->where($where)->save($data);
        } else{
            $data['village_id'] = $this->village_id;
            $data['vacancy_id'] = Request::param('vacancy_id');
            $data['create_time'] = time();
            $data['is_default'] = 0;
            $operation = Db::name('cost')->insert($data);
        }
        if($operation) {
            return $this->returnJson();
        } else {
            return $this->returnJson([],'操作成功!',400);
        }
    }








}