<?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 SysRoleService extends CommonBaseService
{
    protected $cache = true;

    protected $cacheBucket = 'SysRole:';

    protected $tokenBucket = 'Token:';

    protected $activeBucket = "Active:";

    /**
     * 保存角色
     * */
    public function saveRole($params)
    {
        $ret = ['code' => 0, 'data' => 0];
        $data = array();
        $data['role_name'] = $params['role_name'];
        $data['update_time'] = nowTime();
        $checkRet = $this->checkRole($params);
        if ($checkRet['code'] === 0) {
            if (!empty($params['id'])) {
                $id = $params['id'];
                $data['id'] = $id;
                $this->model->where('id', $id)->update($data);
            } else {
                $data['create_time'] = nowTime();
                $id = $this->model->insertGetId($data);
            }
            $ret['data'] = $id;
        } else {
            $ret['code'] = $checkRet['code'];
        }
        return $ret;
    }

    /**
     * 修改角色状态
     * */
    public function setStatus($id, $status)
    {
        $data = [];
        $data['update_time'] = nowTime();
        $data['status'] = $status;
        $ret = $this->model->where('id', $id)->update($data);
        return $ret;
    }

    /**
     * 获取后台角色列表
     * */
    public function getRoleList($params)
    {
        $pageSize = empty($params['page_size']) ? 10 : $params['page_size'];
        $page = empty($params['page']) ? 1 : $params['page'];
        $skip = ($page - 1) * $pageSize; //页面记录的开始位置，即偏移量
        $where = [];
        $where[] = ['a.status', '<', '2'];
        $query = $this->model->alias('a')->where($where);
        if (!empty($params['keyword'])) {
            $keyword = $params['keyword'];
            $query->where('role_name', 'like', "%" . $keyword . "%");
        }
        $totalCount = $query->count();
        $list = $query->skip($skip)
            ->limit($pageSize)
            ->get()->toArray();
        $list=mapByKey($list,'id');
        $ids=array_keys($list);
        $roleData=[];
        if(!empty($ids)){
           $roleAuth= $this->model->alias('a')
                ->leftJoin('sys_menu_func_auth as b', 'a.id', '=', 'b.role_id')
                ->leftJoin('sys_menu_func as c', 'b.menu_func_id', '=', 'c.id')
                ->whereIn('a.id',$ids)
                ->where('b.status',0)
                ->where('c.status',0)
                ->selectRaw('b.role_id,b.menu_func_id,c.menu_func_name,path_name,c.type')
                ->get();
           if(!empty($roleAuth)){
               $roleAuth=$roleAuth->toArray();
               foreach ($roleAuth as $roleValue){
                   $roleData[$roleValue['role_id']][]=$roleValue;
               }
           }
        }
        foreach ($list as &$value){
            if(!empty($roleData[$value['id']])){
                $value['auth_item']=$roleData[$value['id']];
            }else{
                $value['auth_item']=[];
            }
        }
        $list=array_values($list);
        $results = buildPage($list, $skip, $page, $pageSize, $totalCount);
        return $results;
    }

    /**
     * 角色保存验证 验证通过返回 true 失败返回 false
     * return array
     * */
    private function checkRole($params)
    {
        $ret = ['code' => 0];
        $role_name = $params['role_name'];
        if (!empty($params['id'])) {
            $id = $params['id'];
            $exist = $this->model
                ->where('id', '<>', $id)
                ->where('role_name', '=', $role_name)
                ->count();
        } else {
            $exist = $this->model
                ->where('role_name', '=', $role_name)
                ->count();
        }
        if ($exist) {
            $ret['code'] = 11001;
        }
        return $ret;
    }
}
