<?php

namespace app\controller;

use app\model\Area;
use app\util\Util;
use support\Request;

class AreaController
{

    public function getAll (Request $request)
    {
        $parentId = Util::getParam($request,'parent_id');
        $level = Util::getParam($request,'level')?:1;
        $list = $this->getRegions($parentId, $level);
        return json($list);
    }



    function getRegions($parentId = null, $level = 1) {
        $regions = [];

        $where= array();
        if(!Util::isEmpty($parentId)){
            $where['parent_id'] = $parentId;
        }
        $where['level'] = $level;
        $results = Area::where($where)->get();

        foreach ($results as $row) {
//            $row['level'] = $level; // 添加层级信息
//            $regions = array_merge($regions, $this->getRegions($row['id'], $level + 1)); // 递归调用
            $row['children'] = $this->getRegions($row['id'], $row['level'] + 1);
            $regions[] = $row;
        }

        return $regions;
    }
    
}