<?php
namespace app\admin\service\auth;

use app\admin\validate\auth\AuthRuleValidate;
use app\admin\service\AdminBaseService;
use app\model\AuthRuleModel;
use app\model\AdminModel;
use app\model\AuthRoleModel;
use think\exception\ValidateException;

class AuthRuleService extends AdminBaseService
{
    public function add($param): array
    {
        try {
            // 参数校验
            validate(AuthRuleValidate::class)->scene('add')->check($param);
            $this->verifyRepeat($param);
            $authRule=new AuthRuleModel();
            $authRule->create($param);
            return $this->toData('0', '添加成功.', []);
        }catch (ValidateException $validateException){
            $message = $validateException->getError();
            return $this->toData('100400', $message);
        }catch (\Exception $exception){
            return $this->toData('100500', '系统繁忙.', [$exception->getMessage()]);
        }

    }

    /**
     * 查重验证
     * @param $param
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function verifyRepeat($param){
            $authRule=new AuthRuleModel();
            if(isset($param['id'])){ //编辑
                $authRule=$authRule->whereNotIn('id',[$param['id']]);
            }
            $rule = (clone $authRule)->where('name',$param['name'])->find();
            if(!empty($rule)){
                throw new ValidateException('权限标识已存在');
            }

            if($param['type']=='menu'){
                $rule = (clone $authRule)->where('path', $param['path'])->find();
                if(!empty($rule)){
                    throw new ValidateException('路由地址已存在');
                }
                $rule = (clone $authRule)->where('component',$param['component'])->find();
                if(!empty($rule)){
                    throw new ValidateException('组件已存在');
                }
            }
            if($param['type']=='catelog'){
                $rule = (clone $authRule)->where('path',$param['path'])->find();
                if(!empty($rule)){
                    throw new ValidateException('路由地址已存在');
                }
            }

    }

    public function list($user_id,$param){
        try {
            $authRule=new AuthRuleModel();
            //查询条件
            if(isset($param['name'])&&!empty($param['name'])){
                $authRule=$authRule->where('name',$param['name']);
            }
            if(isset($param['satus'])&&!empty($param['status'])){
                $authRule=$authRule->where('status',$param['status']);
            }

            //获取用户权限id
            $user=AdminModel::find($user_id);
            //查询拥有权限
            if($user->role_id=='7'){
                //超级管理员拥有全部权限
                $list=$authRule::order('sort', 'asc')->select()->toArray();
            }else{
                $role=AuthRoleModel::find($user->role_id);
                $list=$authRule::whereIn('id',$role->rules)->order('sort', 'asc')->select()->toArray();
            }

            // 总数
//            $total = $authRule->count();
//            $list=$authRule->order('sort', 'asc')->select()->toArray();
            $list=$this->getTreeMenu($list,0,true);


            return $this->toData('0', 'SUCCESS', $list);
        } catch (\Exception $exception) {
            return $this->toData('100500', 'The system is busy.', [$exception->getMessage(), $exception->getTrace()]);
        }
    }
    public function allList($user_id){
        try {
            //获取用户权限id
            $user=AdminModel::find($user_id);

            //查询拥有权限
            if($user->role_id=='7'){
                //超级管理员拥有全部权限
                $list=AuthRuleModel::order('sort', 'asc')->select()->toArray();
            }else{
                $role=AuthRoleModel::find($user->role_id);
                $list=AuthRuleModel::whereIn('id',$role->rules)->order('sort', 'asc')->select()->toArray();
            }
//            $list=$authRule->order('sort', 'asc')->select()->toArray();
            $list=$this->getTreeMenu($list,0,true);
            return $this->toData('0', 'SUCCESS',$list);
        } catch (\Exception $exception) {
            return $this->toData('100500', 'The system is busy.', [$exception->getMessage(), $exception->getTrace()]);
        }
    }
    public function edit($id, $param): array
    {
        try {
            // 主键
            if(empty($id) || $id <= 0){
                return $this->toData('200403', 'id字段丢失', []);
            }
            // 参数校验
            validate(AuthRuleValidate::class)->scene('edit')->check($param);
            // 查找用户信息
            $authRule = AuthRuleModel::find($id);
            if(empty($authRule)){
                return $this->toData('200403', 'Please log in first.', []);
            }
            $this->verifyRepeat($param);
            $authRule->save($param);
            // 返回
            return $this->toData('0', 'Modification successful.', []);
        }catch (ValidateException $validateException){
            $message = $validateException->getError();
            return $this->toData('200400', $message);
        }catch (\Exception $exception){
            return $this->toData('200500', 'The system is busy.', [$exception->getMessage()]);
        }

    }

    public function getSideMenu($user_id){
        try {
            //获取用户权限id
            $user=AdminModel::find($user_id);
            $role=AuthRoleModel::find($user->role_id);
            //查询拥有权限
            if($user->role_id=='7'){
                //超级管理员拥有全部权限
                $authRule=AuthRuleModel::order('sort', 'asc')->select()->toArray();
            }else{
                $role=AuthRoleModel::find($user->role_id);
                $authRule=AuthRuleModel::whereIn('id',$role->rules)->order('sort', 'asc')->select()->toArray();
            }
//            $authRule=AuthRuleModel::whereIn('id',$role->rules)->order('sort', 'asc')->select()->toArray();
//            $authRule=AuthRuleModel::order('sort', 'asc')->select()->toArray();//显示全部
            $menus=[];
            for($i=0;$i<count($authRule);$i++){
                $menuItem=[
                    'id'=>$authRule[$i]['id'],
                    'pid'=>$authRule[$i]['pid'],
                    'path'=>$authRule[$i]['path'],
                    'name'=>$authRule[$i]['name'],
                    'component'=>$authRule[$i]['component'],
                    'redirect'=>$authRule[$i]['redirect'],
                    'meta'=>[
                        'title'=>$authRule[$i]['title'],
                        'hideMenu'=>$authRule[$i]['show']===1?false:true,
                        'icon'=>$authRule[$i]['icon'],
                        'ignoreKeepAlive'=>true,
                        'isLink'=>false,
//                        'currentActiveMenu'=>"",
                    ]
                ];
                array_push($menus,$menuItem);
            }

            $list=$this->getTreeMenu($menus,0,true);

            return $this->toData('0', 'SUCCESS',$list);

        }catch (ValidateException $validateException){
            $message = $validateException->getError();
            return $this->toData('200400', $message);
        }catch (\Exception $exception){
            return $this->toData('200500', 'The system is busy.', [$exception->getMessage()]);
        }
    }

    /**
     * @param $id
     * @return array
     */
    public function del($id): array
    {
        try {
            $authRule = AuthRuleModel::find($id);
            $authRule->delete();
            // 返回
            return $this->toData('0', 'Modification successful.', []);
        }catch (ValidateException $validateException){
            $message = $validateException->getError();
            return $this->toData('200400', $message);
        }catch (\Exception $exception){
            return $this->toData('200500', 'The system is busy.', [$exception->getMessage()]);
        }

    }

}