<?php
/**
 * gitee: https://gitee.com/kyle-cao/
 * Created by: admin.dadmin.cn
 * User: imdong
 * Date: 2018/11/21
 * Time: 12:00
 */

namespace app\common\logic;

use app\common\model\Role as mRole;
use app\common\validate\Role as vRole;
use app\common\model\Manager as mManager;

class Role extends Base
{
    public function authIds($ids)
    {
        if (empty($ids)) {
            return [];
        }
        $mRole = new mRole();
        $where = [];
        if (is_string($ids)) {
            $ids = explode(',', $ids);
        }
        $where[] = ['id', 'in', $ids];
        $where[] = ['status', '=', 1];
        $mRoleData = $mRole -> field('auth_ids') -> where($where) -> select();
        if ($mRoleData -> isEmpty()) {
            return [];
        }
        $auth_ids = [];
        foreach ($mRoleData as $key => $value) {
            $auth_ids = array_merge($auth_ids, explode(',', $value -> auth_ids));
        }
        return array_filter($auth_ids);
    }


    public function create($param)
    {
        $result = ['code' => 200, 'msg' => '角色添加成功', 'data' => []];
        $vRole = new vRole();
        if (!$vRole -> scene('create') -> check($param)) {
            $result['code'] = 300001;
            $result['msg'] = $vRole -> getError();
            return $result;
        }
        try {
            $mRole = new mRole();
            $mRole -> name = $param['name'];
            $mRole -> remark = $param['remark'];
            $mRole -> status = $param['status'];
            $mRole -> create_time = time();
            $mRole -> save();
        } catch (\Exception $e) {
            $result['code'] = 300002;
            $result['msg'] = $this -> errorCode(300002);
        }
        return $result;
    }

    public function detail($param)
    {
        $result = ['code' => 200, 'msg' => '获取成功', 'data' => []];
        $detail = [];
        if (!empty($param['id'])) {
            $mRole = new mRole();
            $detail = $mRole -> where('id', '=', $param['id']) -> where('status', 'in', [0, 1]) -> find();
        }
        if ($detail) {
            $result['data'] = $detail;
        } else {
            $result['code'] = 300004;
            $result['msg'] = $this -> errorCode(300004);
        }
        return $result;
    }

    public function rule($param)
    {
        $result = ['code' => 200, 'msg' => '权限修改成功', 'data' => []];
        if (empty($param['id'])) {
            $result['code'] = 300004;
            $result['msg'] = $this -> errorCode(300004);
            return $result;
        }
        if (empty($param['auth_ids'])) {
            return $result;
        }
        $mRole = new mRole();
        $mRole = $this -> detail(['id' => $param['id']]);
        if (empty($mRole['data'])) {
            $result['code'] = 300004;
            $result['msg'] = $this -> errorCode(300004);
            return $result;
        }
        try {
            $mRole['data'] -> auth_ids = implode(',', $param['auth_ids']);
            $mRole['data'] -> save();
        } catch (\Exception $e) {
            $result['code'] = 0;
            $result['msg'] = $this -> errorCode(300003);
        }
        return $result;

    }

    public function update($param)
    {
        $result = ['code' => 200, 'msg' => '角色修改成功', 'data' => []];
        $vRole = new vRole();
        if (!$vRole -> scene('update') -> check($param)) {
            $result['code'] = 300001;
            $result['msg'] = $vRole -> getError();
            return $result;
        }
        $mRole = $this -> detail(['id' => $param['id']]);
        if (empty($mRole['data'])) {
            $result['code'] = 300004;
            $result['msg'] = $this -> errorCode(300004);
            return $result;
        }
        try {
            $mRole['data'] -> name = $param['name'];
            $mRole['data'] -> remark = $param['remark'];
            $mRole['data'] -> status = $param['status'];
            $mRole['data'] -> update_time = time();
            $mRole['data'] -> save();
        } catch (\Exception $e) {
            $result['code'] = 300003;
            $result['msg'] = $this -> errorCode(300003);
        }
        return $result;
    }

    public function lists($param)
    {
        $result = ['code' => 200, 'msg' => '', 'data' => []];
        $page = empty($param['page']) ? 1 : $param['page'];
        $limit = empty($param['limit']) ? 1 : $param['limit'];
        $where = [];
        $where [] = ['status', 'in', '0,1'];
        $field = 'id,name,remark,status,create_time';
        $mRole = new mRole();
        $result['count'] = $mRole -> field($field) -> where($where) -> count('id');
        $result['page'] = $page;
        $result['limit'] = $limit;
        $result['data'] = $mRole -> field($field) -> where($where) -> order('id') -> page($page, $limit) -> select();
        return $result;
    }

    public function enable($param)
    {
        $result = ['code' => 200, 'msg' => '角色启用成功', 'data' => []];
        $where = [];
        if (!empty($param['id'])) {
            $where[] = ['id', '=', $param['id']];
        }
        if (!$this -> reStatus($where, 1)) {
            $result['code'] = 300006;
            $result['msg'] = $this -> errorCode(300006);
        }
        return $result;
    }

    public function disable($param)
    {
        $result = ['code' => 200, 'msg' => '角色禁用成功', 'data' => []];
        $where = [];
        if (!empty($param['id'])) {
            $where[] = ['id', '=', $param['id']];
        }
        if (!$this -> reStatus($where, 0)) {
            $result['code'] = 300007;
            $result['msg'] = $this -> errorCode(300007);
        }
        return $result;
    }

    public function delete($param)
    {
        $result = ['code' => 200, 'msg' => '角色删除成功', 'data' => []];
        $where = [];
        if (!empty($param['id'])) {
            $where[] = ['id', '=', $param['id']];
        }
        if (!$this -> reStatus($where, - 1)) {
            $result['code'] = 300008;
            $result['msg'] = $this -> errorCode(300008);
        }
        return $result;
    }


    /**
     * @获取角色权限
     *
     * @param $param
     *
     * @return array
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @since: 2019/5/10 9:37
     * @author: zsl
     */
    public function auth($param)
    {
        $result = ['code' => 200, 'msg' => '请求成功', 'data' => []];
        $where = [];
        if (!empty($param['id'])) {
            $where[] = ['id', '=', $param['id']];
        }
        $mRole = new mRole();
        $auth_ids = $mRole -> field('auth_ids') -> where($where) -> find();
        if (!empty($auth_ids)) {
            $result['data'] = $auth_ids;
        } else {
            $result['code'] = 300004;
            $result['msg'] = $this -> errorCode(300004);
        }
        return $result;
    }

    private function reStatus($where, $status)
    {
        try {
            $mRole = new mRole();
            $mRole -> where($where) -> update(['status' => $status]);
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    private function errorCode($code)
    {
        $errorCode = [
                300001 => '',
                300002 => '角色添加失败',
                300003 => '角色修改失败',
                300004 => '角色不存在，或已被删除',
                300006 => '角色启用失败',
                300007 => '角色禁用失败',
                300008 => '角色删除成功',
        ];
        return empty($errorCode[$code]) ? '系统繁忙,请稍候再试' : $errorCode[$code];
    }

}
