<?php
/**
 * 角色管理Model
 * Created by PhpStorm.
 * User: 小威
 * Date: 2019/11/08
 * Time: 16:00
 */

namespace JinDouYun\Model\Department;

use JinDouYun\Dao\System\DAdminSetting;
use JinDouYun\Model\System\MModule;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;
use Mall\Framework\Core\ResultWrapper;

use JinDouYun\Cache\RoleAclCache;


use JinDouYun\Dao\Department\DRole;
use JinDouYun\Model\Department\MRoleAcl;

class MRole
{

    private $objDRole;
    private $objMRoleAcl;
    private $enterpriseId;
    private $objDAdminSetting;

    public function __construct($enterpriseId)
    {
        $this->objDRole = new DRole('default');
        $this->objMRoleAcl = new MRoleAcl($enterpriseId);
        $this->enterpriseId = $enterpriseId;
        $this->objDRole->setTable($this->objDRole->get_Table().'_'.$enterpriseId);
        $this->objDAdminSetting = new DAdminSetting();
        self::initRole();

    }

    /**
     * Doc: (des="初始化角色")
     * User: XMing
     * Date: 2020/9/4
     * Time: 11:43 上午
     */
    public function initRole()
    {
        $adminLists = $this->objDAdminSetting->select(['type'=>StatusCode::$adminSettingType['role']]);
        if ($adminLists === false){
            return ResultWrapper::fail($this->objDAdminSetting->error(),ErrorCode::$dberror);
        }
        if (empty($adminLists)){
            return ResultWrapper::success();
        }
        $allSignIds = [];
        foreach ($adminLists as $value){
            $allSignIds[] = $value['signId'];
        }
        $roleList = $this->objDRole->select(['signId' => $allSignIds]);
        if ($roleList === false){
            return ResultWrapper::fail($this->objDRole->error(),ErrorCode::$dberror);
        }
        $insert = [];
        if (empty($roleList)){
            foreach ($adminLists as $item){
                $insert[] = [
                    'roleName' => $item['title'],
                    'pid'      => 0,
                    'createTime' => time(),
                    'signId'    => $item['signId']
                ];
            }
        }else{
            $allRoleSignIds = [];
            foreach ($roleList as $role) {
                $allRoleSignIds[] = $role['signId'];
            }
            foreach ($adminLists as $item){
                if (!in_array($item['signId'],$allRoleSignIds)){
                    $insert[] = [
                        'roleName' => $item['title'],
                        'pid'      => 0,
                        'createTime' => time(),
                        'signId'    => $item['signId']
                    ];
                }
            }
        }

        if (!empty($insert)){
            $insertResult = $this->objDRole->insert($insert,true);
            if ($insertResult === false){
                return ResultWrapper::fail($this->objDRole->error(),ErrorCode::$dberror);
            }
        }
        return ResultWrapper::success(true);
    }

    /**
     * 角色添加
     * @param $params
     * @return ResultWrapper
     */
    public function addRole($params)
    {
        $params['createTime'] = $params['updateTime'];
        $params['deleteStatus'] = StatusCode::$standard;

        $isAdministrator = $params['isAdministrator'];
        unset($params['isAdministrator']);
        $acl = $params['acl'];
        unset($params['acl']);
        if(empty( $params['shopId'])){
            $params['shopId'] = '';
        }
        //校验名称
        $dbResult = $this->objDRole->select(['roleName' => $params['roleName'], 'shopId' => $params['shopId'], 'deleteStatus' => StatusCode::$standard]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDRole->error, ErrorCode::$dberror);
        }
        if($dbResult){
            return ResultWrapper::fail('名称已存在', ErrorCode::$paramError);
        }
        unset($dbResult);

        $dbResult = $this->objDRole->insert($params);

        if($dbResult === false){
            return ResultWrapper::fail($this->objDRole->error(), ErrorCode::$dberror);
        }else{
            $roleAclData = [
                'isAdministrator' => $isAdministrator,
                'acl' => $acl,
                'roleId' => $dbResult,
                'updateTime' => time(),
                'createTime' => time()
            ];
            $result = $this->objMRoleAcl->addRoleAcl($roleAclData);
            if($result->isSuccess() == false) {
                return ResultWrapper::fail($result->getData(), $result->getErrorCode());
            }

            //缓存角色和权限的关系
            $aclData = [
                'isAdministrator' => $isAdministrator,
                'acl' => json_decode($acl),
            ];
            $objRoleAclCache = new RoleAclCache();
            $objRoleAclCache->cacheRoleIdAndAcl($this->enterpriseId, $dbResult, $aclData);
            $objMModule = new MModule();
            if($isAdministrator == StatusCode::$delete){
                //缓存角色绑定权限
                $acl = json_decode($acl, true);
                if(!empty($acl)){
                    foreach($acl as $value){
                        if(!empty($value['extend'])){
                            $objRoleAclCache->addAuthorityBindRole($this->enterpriseId, $dbResult, $value['extend']);
                        }
                        $value['associate'] = json_decode($value['associate'], true);
                        if(!empty($value['associate'])){
                            $modelResult = $objMModule->getDataModule(['id' => $value['associate']]);
                            if(!$modelResult->isSuccess()){
                                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
                            }
                            $array = $modelResult->getData();
                            foreach($array as $vv){
                                if(!empty($vv['extend'])){
                                    $objRoleAclCache->addAuthorityBindRole($this->enterpriseId, $dbResult, $vv['extend']);
                                }
                            }
                        }
                    }
                }
            }else{
                //缓存超级管理员
                $objRoleAclCache->addAdministrator($this->enterpriseId, $dbResult);
            }

            return ResultWrapper::success($dbResult);
        }
    }

    /**
     * 角色删除
     * @param $id
     * @return ResultWrapper
     */
    public function deleteRole($id)
    {
        $params = [
                'deleteStatus' => StatusCode::$delete,
                'updateTime' => time(),
            ];
        $roleInfo = $this->objDRole->get(['id'=>$id]);
        if ($roleInfo === false){
            return ResultWrapper::fail($this->objDRole->error(),ErrorCode::$dberror);
        }
        if (empty($roleInfo)){
            return ResultWrapper::fail('未获取到指定角色',ErrorCode::$paramError);
        }
        if (in_array($roleInfo['signId'],[StatusCode::$roleId['cashier'],StatusCode::$roleId['guide']])){
            return ResultWrapper::fail('内置角色不能删除',ErrorCode::$dberror);
        }
        $dbResult = $this->objDRole->update($params, $id);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDRole->error(), ErrorCode::$dberror);
        }else{
            //删除权限
            $result = $this->objMRoleAcl->deleteRoleAcl(['roleId'=>$id]);
            if($result->isSuccess() == false) {
                return ResultWrapper::fail($result->getData(), $result->getErrorCode());
            }
            $objRoleAclCache = new RoleAclCache();
            $objRoleAclCache->delAdministrator($this->enterpriseId, $id);
            $objRoleAclCache->delAuthorityBindRole($this->enterpriseId, $id);
            return ResultWrapper::success($dbResult);
        }
    }

    /**
     * 角色修改
     * @param $params
     * @param $id
     * @return ResultWrapper
     */
    public function updateRole($params, $id)
    {
        $isAdministrator = $params['isAdministrator'];
        unset($params['isAdministrator']);
        $acl = $params['acl'];
        unset($params['acl']);
        $roleInfo = $this->objDRole->get(['id'=>$id]);
        if ($roleInfo === false){
            return ResultWrapper::fail($this->objDRole->error(),ErrorCode::$dberror);
        }
        if (empty($roleInfo)){
            return ResultWrapper::fail('未获取到指定角色',ErrorCode::$paramError);
        }
        if (in_array($roleInfo['signId'],[StatusCode::$roleId['cashier'],StatusCode::$roleId['guide']])){
            //收银员，或导购不能修改名称
            unset($params['roleName']);
        }
        $dbResult = $this->objDRole->update($params,$id);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDRole->error(), ErrorCode::$dberror);
        }else{
            //修改权限
            $roleAclData = [
                'isAdministrator' => $isAdministrator,
                'acl' => $acl,
                'roleId' => $id,
                'updateTime' => time()
            ];
            $result = $this->objMRoleAcl->addRoleAcl($roleAclData);

            if($result->isSuccess() == false) {
                return ResultWrapper::fail($result->getData(), $result->getErrorCode());
            }
            //修改缓存
            $objRoleAclCache = new RoleAclCache();
            if($isAdministrator == StatusCode::$delete){
                $objRoleAclCache->delAdministrator($this->enterpriseId, $id);
                $objRoleAclCache->delAuthorityBindRole($this->enterpriseId, $id);
                //缓存角色绑定权限
                $objMModule = new MModule();
                $acl = json_decode($acl, true);
                foreach($acl as $value){
                    if(!empty($value['extend'])){
                        $objRoleAclCache->addAuthorityBindRole($this->enterpriseId, $id, $value['extend']);
                    }
                    $value['associate'] = json_decode($value['associate'], true);
                    if(!empty($value['associate'])){
                        $modelResult = $objMModule->getDataModule(['id' => $value['associate']]);
                        if(!$modelResult->isSuccess()){
                            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
                        }
                        $array = $modelResult->getData();
                        foreach($array as $vv){
                            if(!empty($vv['extend'])){
                                $objRoleAclCache->addAuthorityBindRole($this->enterpriseId, $id, $vv['extend']);
                            }
                        }
                    }

                }
            }else{
                $objRoleAclCache->addAdministrator($this->enterpriseId, $id);
                $objRoleAclCache->delAuthorityBindRole($this->enterpriseId, $id);
            }
            return ResultWrapper::success($dbResult);
        }
    }

    /**
     * 角色列表
     * @param $selectParams
     * @return ResultWrapper
     */
    public function getAllRole($selectParams)
    {
        /*$limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);*/

        $where = 'deleteStatus=' . StatusCode::$standard;
        if(isset($selectParams['roleName'])) {
            $where .= ' AND roleName LIKE "%' . $selectParams['roleName'] . '%"';
        }

        $dbResult = $this->objDRole->select($where, '*', 'createTime desc');
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDRole->error(), ErrorCode::$dberror);
        }

        $total = $this->objDRole->count($where);

        $return = [
            'data' => self::formatList($dbResult),
            'total' => ($total) ? intval($total) : 0,
        ];

        if($return === false){
            return ResultWrapper::fail($this->objDRole->error(), ErrorCode::$dberror);
        }else{
            return ResultWrapper::success($return);
        }
    }

    /**
     * 角色详情
     * @param $params
     * @return ResultWrapper
     */
    public function getRoleInfo($params)
    {
        $dbResult = $this->objDRole->get($params);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDRole->error(), ErrorCode::$dberror);
        }else{
            //获取角色的权限
            $roleAclResult = $this->objMRoleAcl->getRoleAclInfo(['roleId'=>$params['id']]);
            $roleAclInfo = $roleAclResult->getData();
            $dbResult['isAdministrator'] = isset($roleAclInfo['isAdministrator']) ? $roleAclInfo['isAdministrator'] : StatusCode::$delete;
            $dbResult['acl'] = isset($roleAclInfo['acl']) ? $roleAclInfo['acl'] : [];
            return ResultWrapper::success(self::formatInfo($dbResult));
        }
    }

    /**
     * 格式化角色详情
     * @param $data
     * @return mixed
     */
    public function formatInfo($data)
    {
        //取出上级id
        $roleId = $data['pid'];
        //查询上级 id 名称
        $roleData = $this->objDRole->get(['id' => $roleId], 'roleName');
        $data['pidName'] = isset($roleData['roleName']) ? $roleData['roleName'] : '';
        return $data;
    }

    /**
     * 格式化角色列表
     */
    public function formatList($data)
    {
        //格式化层级关系
        return arr2tree($data);
    }

    /**
     * 根据角色id获取角色id和角色名称
     * @param $id
     * @return array|ResultWrapper
     */
    public function roleDataByRoleId($id)
    {
        //查询 id 部门名称
        $where = [
            'deleteStatus' => StatusCode::$standard,
            'id' => $id,
        ];
        $fields = 'id, roleName';
        $departmentData = $this->objDRole->get($where, $fields);
        if($departmentData === false){
            return ResultWrapper::fail($this->objDRole->error(), ErrorCode::$dberror);
        }
        return $departmentData;
    }

    /**
     * 根据角色ids获取角色id和角色名称
     * @param array $ids
     * @return bool|ResultWrapper
     */
    public function roleDataByRoleIds(array $ids)
    {
        //查询所有 id 角色名称
        $where = [
            'id' => $ids,
            'deleteStatus' => StatusCode::$standard,
        ];
        $fields = 'id,roleName';
        $RoleData = $this->objDRole->select($where, $fields);
        if($RoleData === false){
            return ResultWrapper::fail($this->objDRole->error(), ErrorCode::$dberror);
        }
        return $RoleData;
    }

}