<?php
namespace app\admin\controller\v1;

use app\api\ApiController;
use think\facade\Db;

class Right extends ApiController
{
    public function getTree()
    {

        $data=[
            'title'=>'所有權限',
            'key'=>'all',
            'level'=>0,
            'index'=>0
        ];

        $data=$this->buildTree($data);


        if(!$data){
            $result=[];
        }

        // $result['children']=$children;


        $rtn=[
            // 'total' => $total,
            $data
        ];

       return $this->Success($rtn);
    }

    private static function buildTree($data,$level=0){
        $level=$level+1;
        $menu = Db::name('menu')
        ->where('pid',$data['index'])
        ->select();

        if(!$menu){
            return $data;
        }

        $children=[];

        foreach($menu as $key => $val){
            $children[$key]['title']=$val['title'];
            $children[$key]['index']=$val['id'];
            $children[$key]['level']=$level;
            $children[$key]['key']=$val['node'];
            if($level < 2){
                $children[$key]=self::buildTree($children[$key],$level);
            }else{
                $children[$key]=self::appendPermission($children[$key]);
            }
        }
        if($children){
            $data['children'] = $children;
        }
        return $data; 
    }

    private static function appendPermission($data){
        $perm = Db::name('permission')
        ->where('menu_id',$data['index'])
        ->select();

        if(!$perm){
            return $data;
        }

        $children=[];

        foreach($perm as $key => $val){
            $children[$key]['title']=lang($val['code']);
            $children[$key]['index']=$val['id'];
            $children[$key]['key']=$val['code'];
        }
        if($children){
            $data['children'] = $children;
        }
        return $data; 
    }
}
