<?php
/**
 * Created by PhpStorm.
 * User: ywl
 * Date: 2017/4/14
 * Time: 11:38
 */

namespace App\User\Services;


use App\Exceptions\ApiException;
use App\Services\CommonBaseService;
use App\User\Models\SysAdminUserModel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;

class SysMenuFuncAuthService extends CommonBaseService
{
    protected $cache = true;

    protected $cacheBucket = 'SysMenuFuncAuth:';

    protected $tokenBucket = 'Token:';

    protected $activeBucket = "Active:";

    /**
     * 后台角色授权
     * */
    public function saveMenuFuncAuth($menuFuncIds,$roleId){
        $time=nowTime();
        if(!empty($menuFuncIds)){
            //获取要保留下来的权限
            $remainedIds= $this->model
                ->where('role_id',$roleId)
                ->where('status',0)
                ->whereIn('menu_func_id',$menuFuncIds)
                ->pluck('menu_func_id')->toArray();
            $addMenuFuncIds=array_diff($menuFuncIds,$remainedIds);//获取要新增的权限
            $insertData=[];
            foreach ($addMenuFuncIds as $value){
                $insertData[]=['menu_func_id'=>$value,'role_id'=>$roleId,'create_time'=>$time,'update_time'=>$time];
            }
            //插入新增的权限
            if(!empty($insertData)){
                $this->model->insert($insertData);
            }
            //删除移除的权限
            $this->model->where('role_id',$roleId)->where('status',0)
                ->WhereNotIn('menu_func_id',$menuFuncIds)
                ->update(['status'=>2,'update_time'=>$time]);
        }else{
            $this->model->where('role_id',$roleId)->where('status',0)
                ->update(['status'=>2,'update_time'=>$time]);
        }
    }

    /**
     * 账号权限
     * */
    public function adminRoleAuth($roleId){
        $list = $this->model->alias('a')
            ->leftJoin('sys_menu_func as b','a.menu_func_id','=','b.id')
            ->where('a.role_id', '=', $roleId)
            ->where('a.status',0)
            ->selectRaw('a.menu_func_id,b.route_path')->get();
        if($list){
            $list = $list->toArray();
        }
        return $list;
    }
}
