<?php
declare (strict_types = 1);

namespace app\system\controller;
use app\model\system\AdminMenu;
use app\model\system\AdminRole;
use app\model\system\Admin as AdminModel;
use app\Request;
use app\system\controller\AuthController;
use library\services\UtilService;
use library\utils\IpLocation;
use think\facade\Config;
use think\facade\Cache;

class Admin extends AuthController
{
    /**
     * 退出登陆
     * @return mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function logout()
    {
        $key = trim(ltrim($this->request->header(Config::get('cookie.system_token_name')), ''));
        $res = Cache::store('redis')->delete($key);
        return app('json')->success("ok", []);
    }

    /**
     * 获取登录信息 [自己]
     * @param Request $request
     * @return mixed
     */
    public function info(Request $request) {
        [$id] = UtilService::getMore([
            ['id','','empty','参数错误']
        ],$request,true);
        if($id == $this->adminInfo['id']) {
            return app('json')->success([
               'id' => $id,
               'username'  => $this->adminInfo['username'],
               'nickname'  => $this->adminInfo['nickname'],
               'name'      => $this->adminInfo['name'],
               'avatar'    => $this->adminInfo['avatar'],
               'regTime'   => empty($this->adminInfo['time']) ? '' : date('Y-m-d',$this->adminInfo['time']),
               'lastTime'  => empty($this->adminInfo['last_time']) ? '' : date('Y-m-d',$this->adminInfo['last_time']),
               'ip'        => $this->adminInfo['ip'],
               'ipArea'    => (new IpLocation())->getlocation($this->adminInfo['ip'])['country'],
               'roleName'  => (new  AdminRole())->getRoleId($this->adminInfo['role_id'],'name')
            ]);
        }
    }

    /**
     * 修改信息 [自己]
     * @param Request $request
     * @return mixed
     */
    public function edit(Request $request) {
        [$name,$avatar] = UtilService::getMore([
            ['name','','empty','请输入管理姓名'],
            ['avatar','']
        ],$request,true);

       $bool = AdminModel::update(['name'=>$name,'avatar'=>$avatar],['id'=>$this->adminInfo['id']]);
        if($bool) {
            return app('json')->success("修改成功", []);
        }
        return app('json')->fail("数据更新失败");
    }

    /**
     * 修改密码 [自己]
     * @param Request $request
     * @return mixed
     */
    public function password(Request $request) {
        [$oldPass,$newPass] = UtilService::getMore([
            ['oldPass','','empty','请输入旧密码'],
            ['newPass','','empty','请输入新密码']
        ],$request,true);

        if(!AdminModel::checkPassowrd($this->adminInfo['id'],$oldPass)){
            return app('json')->fail("旧密码错误，请重新输入");
        }
        AdminModel::where('id',$this->adminInfo['id'])->save(['password'=>password_hash($newPass,PASSWORD_BCRYPT)]);
        return app('json')->success("密码修改成功", []);
    }

    /**
     * 获取管理列表 [筛选]
     * @param Request $request
     * @return mixed
     */
    public function list(Request $request)
    {
        $pageSize = 50;
        [$page, $roleId, $keyword] = UtilService::getMore(
            [
                ['page', 1],
                ['roleId', 0],
                ['keyword', ''],
            ], $request, true
        );
        list($pageCount, $data) = (new AdminModel)
            ->getList($page,
                ['role_id' => [$roleId, '!empty'], 'username' => [$keyword, '!empty']]
                , $pageSize, ['*',""],'id desc');
        $result = UtilService::getParam([
            'id',
            'username',
            'name',
            'avatar',
            'nickname',
            'status',
            ['regTime', 'time', 'date("Y-m-d",$1)'],
            ['lastTime', 'last_time', 'date("Y-m-d",$1)'],
            'ip',
            ['ipArea', 'ip',
                function ($item) {
                    return (new IpLocation())->getlocation($item)['country'];
                },
            ],
            ['roleName', 'role_id',
                function ($item) {
                    return (new  AdminRole())->getRoleId($item, 'name');
                },
            ],
        ], $data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $page,
        ]);
    }

    /**
     * 获取管理数据 [某一管理]
     * @param Request $request
     * @return mixed
     */
    public function getInfo(Request $request) {
        [$id] = UtilService::getMore([
            ['id','','empty','参数错误']
        ],$request,true);
        $adminInfo = AdminModel::get(compact('id'));
        return app('json')->success([
            'id' => $id,
            'username'  => $adminInfo['username'],
            'nickname'  => $adminInfo['nickname'],
            'name'      => $adminInfo['name'],
            'avatar'    => $adminInfo['avatar'],
            'role_id'   => $adminInfo['role_id'],
            'status'    => $adminInfo['status']
        ]);
    }

    /**
     * 保存数据 [某一个管理]
     * @param Request $request
     * @return mixed
     */
    public function  save(Request $request) {
        $post = UtilService::getMore(
            [
                ['id','0'],
                ['name','','empty','请输入姓名'],
                ['username','','empty','请输入账户'],
                ['nickname',''],
                ['status','0'],
                ['role_id','','empty','请选择管理角色'],
                ['password',''],
                ['avatar',''],
            ],
            $request
        );
        $bool = AdminModel::saveAdmin($post);
        if($bool)
            return app('json')->success("操作成功", []);
        else
            return app('json')->fail(AdminModel::getErrorInfo());
    }
    /**
     * 删除数据 [删除管理员]
     * @param Request $request
     * @return mixed
     */
    public function del(Request $request) {
       [$id] = UtilService::getMore(
            [
                ['id','0'],
            ],
            $request,true
        );
        AdminModel::del($id);
        return app('json')->success("删除成功", []);
    }


}
