<?php
declare (strict_types = 1);

namespace app\warehouse\controller\v1;


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

class Admin extends AuthController
{
    /**
     * 登录和菜单信息 [当前登录者]
     */
    public function init(Request $request){
        return app('json')->success([
            'user_info' => [
                'id'         => $this->adminInfo['id'],
                'username'   => $this->adminInfo['username'],
                'name'       => $this->adminInfo['name'],
                'lx_name'    => $this->adminInfo['lx_name'],
                'lx_tel'     => $this->adminInfo['lx_tel'],
                'money'      => $this->adminInfo['money']
            ],
        ]);
    }

    /**
     * 退出登陆
     * @return mixed
     */
    public function logout()
    {
        $key = trim(ltrim($this->request->header(Config::get('cookie.admin_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);
        $adminRole = new AdminRole();
        $adminRole->setSassId($request->site['sassid']);

        if($id == $this->adminInfo['id']) {
            return app('json')->success([
                'id' => $id,
                'sassid' => $this->adminInfo['sassid'],
                'username'  => $this->adminInfo['username'],
                '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'  => $adminRole->getRoleId($this->adminInfo['role_id'],'name')
            ]);
        }
    }

    /**
     * 修改信息 [当前登录者]
     * @param Request $request
     */
    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
     */
    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
     */
    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'],'sassid'=>[$request->site['sassid'],'!empty']]
                ,$pageSize,'id desc');
        $adminRole = new AdminRole();
        $adminRole->setSassId($request->site['sassid']);
        $result = UtilService::getParam([
            'id',
            'sassid',
            'username',
            'name',
            'avatar',
            '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) use($adminRole) {
                    return  $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,
            'sassid'    => $adminInfo['sassid'],
            'username'  => $adminInfo['username'],
            'name'      => $adminInfo['name'],
            'avatar'    => $adminInfo['avatar'],
            'role_id'   => $adminInfo['role_id'],
            'status'    => $adminInfo['status']
        ]);
    }


    /**
     * 保存数据
     * @param Request $request
     */
    public function  save(Request $request) {
        $post = UtilService::getMore(
            [
                ['id','0'],
                ['name','','empty','请输入姓名'],
                ['username','','empty','请输入账户'],
                ['status','0'],
                ['role_id','','empty','请选择管理角色'],
                ['password',''],
                ['avatar','']
            ],
            $request
        );

        $post['sassid']=$request->site['sassid'];
        $bool = AdminModel::saveAdmin($post);
        if($bool)
            return app('json')->success("操作成功", []);
        else
            return app('json')->fail(AdminModel::getErrorInfo());
    }

    /**
     * 删除数据
     * @param Request $request
     */
    public function del(Request $request) {
        [$id] = UtilService::getMore(
            [
                ['id','0'],
            ],
            $request,true
        );
        AdminModel::del($id);
        return app('json')->success("删除成功", []);
    }


}
