<?php


namespace app\shequ\controller;

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



//这是关于创建建筑之类的接口
class Build extends Base
{

    protected $middleware = ['app\middleware\CommunityLoginCheck::class','app\middleware\CommunityAfter::class'];


    //添加建筑时候选择布局
    public function layoutInfo() {
        $where['village_id'] = $this->village_id;
        $data = Db::name('layout_list')->where($where)->select()->toArray();
        $res = [];
        foreach ($data as $k =>$v) {
            $arr = explode('-',$v['code']);
            array_pop($arr); //最后一个是房间的,去掉
            $res[] = $this->zuhe($arr,$v['layout_id']);

        }

        return $this->returnJson($res,'success');
    }

    public function zuhe($arr,$layout_id) {

        $res['code'] = $arr[0];
        $res['layout_id'] = $layout_id;
        $nam = ['code'];
        $res['son']['code'] = isset($arr[1]) ? $arr[1] : [];
        if(!$res['son']['code']){
            unset($res['son']['code']);
            return $res;
        }
        $res['son']['son']['code'] = isset($arr[2]) ? $arr[2] :[];
        if(!$res['son']['son']['code']){
            unset($res['son']['son']['code']);
            return $res;
        }
        $res['son']['son']['son']['code'] = isset($arr[3]) ? $arr[3] : [];
        if(!$res['son']['son']['son']['code']){
            unset($res['son']['son']['son']['code']);
            return $res;
        }
        $res['son']['son']['son']['son']['code'] = isset($arr[4]) ? $arr[4] : [];
        if(!$res['son']['son']['son']['son']['code']){
            unset($res['son']['son']['son']['son']['code']);
            return $res;
        }
        $res['son']['son']['son']['son']['son']['code'] = isset($arr[5]) ? $arr[5] : [];
        if(!$res['son']['son']['son']['son']['son']['code']){
            unset($res['son']['son']['son']['son']['son']['code']);
            return $res;
        }
        $res['son']['son']['son']['son']['son']['son'] = isset($arr[6]) ? $arr[6] : [];
        if(!$res['son']['son']['son']['son']['son']['son']){
            unset($res['son']['son']['son']['son']['son']['son']['code']);
            return $res;
        }
    }



    //创建建筑
    public function createBuild() {
        $village_id = $this->village_id;
        $data['layout_id'] = Request::param('layout_id');
        $data['code'] = Request::param('code');

        $layoutInfo = DB::name('layout_list')->where(['layout_id'=>$data['layout_id']])->value('code');
        if($layoutInfo) {
            $codeArr = explode('-',$layoutInfo);
        } else {
            return $this->returnJson([],'未找到对应的模板',400);
        }
        $data['parent_id'] = Request::param('parent_id',0);

        //查询是否有相同的编号
        $is_exit = DB::name('layout_build')->where($data)->find();
        if($is_exit) {
            return $this->returnJson([],'相同编号建筑已存在!',400);
        }

        //位置 拼接
        if($data['parent_id'] ==0) {
            $village_name = DB::name('house_village')->where(['village_id'=>$village_id])->value('village_name');
            $data['level'] = 1;

        } else {
            $village_name = DB::name('layout_build')->where(['layout_build_id'=>$data['parent_id']])->value('address');
            $p_level = Db::name('layout_build')->where(['layout_build_id'=>$data['parent_id']])->value('level');
            $data['level'] = ++$p_level;
        }
        $addre = $data['code'].$codeArr[$data['level']-1]; //小区编号转码
        $data['property_price'] = $save['property_price']= Request::param('property_price');
        $data['water_price'] = $save['water_price']= Request::param('water_price');
        $data['electric_price'] = $save['electric_price']= Request::param('electric_price');
        $data['gas_price'] = $save['gas_price']= Request::param('gas_price');
        $data['parking_price'] = $save['parking_price']= Request::param('parking_price');
        $data['explain'] = Request::param('explain');
        $data['village_id'] = $village_id;
        $data['name'] =  $codeArr[$data['level']-1];
        $data['create_time'] = time();
        $data['sort_id'] = Request::param('sort_id');
        $data['is_inherit'] = Request::param('is_inherit',1);//默认集成上一级的费用明细
        $data['measure_area'] = Request::param('measure_area');//面积


        $data['address']  = $village_name.$addre;
        //判断是否设置了小区的参数,设置了就不用设置,
        $is_exit  = DB::name('house_village')->where(['village_id'=>$village_id])->field('village_id,property_price,water_price,electric_price,gas_price,parking_price as park_price')->find();
        if(!$is_exit['property_price'] && !$is_exit['water_price'] &&!$is_exit['electric_price'] &&!$is_exit['gas_price']&&!$is_exit['parking_price'] ) {
            DB::name('house_village')->where(['village_id'=>$village_id])->save($save);
        }
        $insert = Db::name('layout_build')->insert($data);
        if($insert) {
            return $this->returnJson([],'success');
        } else{
            return $this->returnJson([],'error',400);
        }
    }

    //修改建筑信息
    public function changeBuild() {

        $layout_build_id = Request::param('layout_build_id');
        $where['layout_build_id'] = $layout_build_id;
        //先查询原先的数据
        $buildInfo = Db::name('layout_build')->where($where)->find();

        $code = Request::param('code');
        //查询修改的code是否存在
        $is_exit = Db::name('layout_build')->where(['village_id'=>$buildInfo['village_id'],'layout_id'=>$buildInfo['layout_id'],'parent_id'=>$buildInfo['parent_id'],'code'=>$code])->where('layout_build_id','<>',$buildInfo['layout_build_id'])->find();
        if($is_exit) {
            return $this->returnJson([],'该建筑编号已存在!',400);
        }
        $data['code']= $code;
        $data['explain']= Request::param('explain');
        $data['measure_area']= Request::param('measure_area');

        $data['property_price'] = $where['property_price'] = Request::param('property_price');
        $data['water_price'] = $where['water_price'] = Request::param('water_price');
        $data['electric_price'] = $where['electric_price'] = Request::param('electric_price');
        $data['gas_price'] = $where['gas_price'] = Request::param('gas_price');
        $data['parking_price'] = $where['parking_price'] = Request::param('parking_price');
        $data['parent_id'] = $buildInfo['parent_id'];

        $is_inherit = Request::param('is_inherit',1); //物业费等是否继承上一级,1继承,0不继承
        unset($where['layout_build_id']);
        if($is_inherit == 1 ) {
            if($data['parent_id'] == 0) {
                $is_find = Db::name('house_village')->where(['village_id'=>$this->village_id])->where($where)->find();
            } else {
                $is_find = Db::name('layout_build')->where(['village_id'=>$this->village_id,'layout_build_id'=>$data['parent_id']])->where($where)->find();
            }
            if(!$is_find){
                return $this->returnJson([],'费用有误,请重新输入!',400);
            }
        }

        //判断是否修改了费用字段
        if($data['property_price'] != $buildInfo['property_price'] || $data['water_price'] != $buildInfo['water_price'] ||  $data['electric_price'] != $buildInfo['electric_price'] ||  $data['gas_price'] != $buildInfo['gas_price'] ||  $data['parking_price'] != $buildInfo['parking_price'] ) {
            //先修改下面的建筑,然后在修改其他
            $ids = $this->findBuildId($layout_build_id);

            Db::name('layout_build')->where('layout_build_id','in',$ids)->save($where);
        }

        $data['is_inherit'] = $is_inherit;
        $change = Db::name('layout_build')->where(['layout_build_id'=>$layout_build_id])->save($data);
        if($change) {
            return $this->returnJson([],'success');
        } else{
            return $this->returnJson([],'error',400);
        }

    }


    //删除建筑
    public function deleteBuild() {
        //如果该建筑下有子建筑,则无法删除
        $layout_build_id = Request::param('layout_build_id');
        $is_exit = Db::name('layout_build')->where(['village_id'=>$this->village_id,'parent_id'=>$layout_build_id])->find();
        if($is_exit) {
            return $this->returnJson([],'该建筑有子建筑,无法删除!',400);
        }
        $del =  Db::name('layout_build')->where(['layout_build_id'=>$layout_build_id])->delete();

        if($del) {
            return $this->returnJson([],'success');
        } else {
            return $this->returnJson([],'删除失败',400);
        }

    }


    //建筑列表
    public function buildList() {
        $village_id = $this->village_id;
        $where['lb.village_id'] = $village_id;
        $where['lb.parent_id'] = Request::param('parent_id',0);

        if(Request::param('layout_id')) {
            $where['lb.layout_id'] = Request::param('layout_id');
        }
        $page = Request::param('page',1);

        $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'])->page($page,config('app.limit'))
                    ->field("lb.*,ll.name as layout_name,ll.level as layout_level")
                    ->select()
                    ->toArray();

        foreach ($data as $k => $v) {
            $is_exit = Db::name('layout_build')->where(['parent_id'=>$v['layout_build_id']])->value('layout_build_id');
            if($is_exit){
                $data[$k]['hasChildren'] = true;
            } else{
                $data[$k]['hasChildren'] = false;
            }
            //查看当前是否是最后一级建筑(不是房间)
            if($v['level'] == ($v['layout_level']-1)){
                $data[$k]['isEnd'] = true;
                //获取建筑的物业编号
                $code = [];
                $data[$k]['buildNum'] = $this->createNum($v['layout_build_id'],$code);
            } else {
                $data[$k]['isEnd'] = false;
                $data[$k]['buildNum'] = '-';
            }

        }
        $count = Db::name('layout_build')->alias('lb')->where($where)->count();
        $res['count'] = $count;
        $res['data'] = Common::changeField($data);
        return $this->returnJson($res,'success');
    }

    //根据建筑id拼接物业编号
    public function createNum($build_id,$code) {
        $data = Db::name('layout_build')->where(['layout_build_id'=>$build_id])->field('layout_build_id,parent_id,code')->find();
        array_unshift($code,$data['code']);
        if($data['parent_id'] == 0) {
            return implode('-',$code);
        } else {
            return $this->createNum($data['parent_id'],$code);
        }
    }

    //根据建筑id获取同一级的建筑
    public function getCurrent() {
        $build_id = Request::param('build_id');
        $layoutInfo = Db::name('layout_build')->alias('lb')
                ->leftJoin('layout_list ll','ll.layout_id = lb.layout_id')
                ->where(['layout_build_id'=>$build_id])
                ->field('lb.level,lb.code,lb.layout_build_id,lb.layout_id,lb.village_id,ll.code as ll_code')->find();
        $where['layout_id'] = $layoutInfo['layout_id'];
        $where['village_id'] = $layoutInfo['village_id'];
        $where['level'] = $layoutInfo['level'];
        $data = Db::name('layout_build')->where($where)->field('layout_build_id,layout_id,code,level')->select()->toArray();
        if($layoutInfo){
            $res['code_name'] = explode('-',$layoutInfo['ll_code'])[$layoutInfo['level']-1];
        } else {
            $res['code_name'] ='';
        }
        $res['data'] = $data;
        return $this->returnJson($res);

    }



    //查看社区的水电物业费等
    public function costPrice() {
        $where['village_id'] = Request::param('village_id');
        $data =DB::name('house_village')->where($where)->field('village_id,property_price,water_price,electric_price,gas_price,park_price')->find();
        return $this->returnJson($data,'success');

    }

    //根据id查看建筑详情
    public function queryCostPrice(){
        $where['lb.layout_build_id'] = Request::param('layout_build_id');//建筑id
        $where['lb.village_id'] = $this->village_id;
        $res = Db::name('layout_build')->alias('lb')->leftJoin('layout_list ll','ll.layout_id = lb.layout_id')->where($where)
            ->field('lb.is_inherit,lb.layout_build_id,lb.layout_build_id,lb.property_price,lb.water_price,lb.electric_price,lb.gas_price,lb.parking_price,lb.code,lb.explain,lb.parent_id,lb.create_time,lb.measure_area,lb.address,lb.sort_id,ll.code as code_name, ll.name')
            ->find();
        $data = Common::changeField($res);
        return $this->returnJson($data,'success');

    }

    //获取水电费等集成当前建筑的id
    public function findBuildId($pid){
        static $id = [];
        $ids = DB::name('layout_build')->where(['parent_id'=>$pid,'is_inherit'=>1])->column('layout_build_id');
        if(!empty($ids)){
            foreach ($ids as $v) {
                $this->findBuildId($v);
                $id[] = $v;
            }
        }
        sort($id);
        return $id;
    }


    //获取子元素的所有建筑ID
    public function allBuildId($pid) {
        static $id = [];
        $ids = DB::name('layout_build')->where(['parent_id'=>$pid])->column('layout_build_id');
        if(!empty($ids)){
            foreach ($ids as $v) {
                $this->findBuildId($v);
                $id[] = $v;
            }
        }
        sort($id);
        return $id;
    }

}