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

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

class Role extends ApiController
{
    public function getRoles()
    {
        $result=Db::name('role')
        ->select();

        if(!$result){
            $result=[];
        }
        // foreach($result as $key=>$val){
        //     // $rtn=Db::name('goods')->where('gc_id',$val['id'])->select()->toArray();
        //     // if($rtn){
        //     //     $result[$key]['goods']=[];
        //     // }
        //     $result[$key]['goods']=Db::name('goods')->where('gc_id',$val['id'])->select()->toArray();
        // }
        return $this->Success($result);
    }

    public function getRoleById(){
        $id=input('id');

        $result=Db::name('role')
        ->where('id',$id)
        ->find();

        $rtn=[
            'id' => $result['id'],
            'name' => $result['name'],
            'desc' => $result['desc'],
            'permission'=>json_decode($result['limits'])
        ];

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

    public function addRole(){
        $req=input();

        $data = [
            'name'=>$req['name'],
            'desc'=>$req['desc'],
            'limits'=>json_encode($req['permission'])
        ];

        $result=Db::name('role')
        ->insert($data);

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

    public function updateRole(){
        $req=input();

        $data = [
            'name'      =>$req['name'],
            'desc'      =>$req['desc'],
            'limits'    =>json_encode($req['permission'])
        ];

        $result=Db::name('role')
        ->where('id',$req['id'])
        ->update($data);

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

    public function deleteRole(){
        $id=input('id');


        $result=Db::name('role')
        ->where('id',$id)
        ->delete();

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

}
