<?php
declare (strict_types = 1);

namespace app\admin\controller\v1;

use app\admin\model\v1\SysMenuModel;
use app\admin\model\v1\SysRoleAuthorityModel;
use app\admin\model\v1\SysUserLoginLogModel;
use app\admin\model\v1\SysUserModel;
use app\admin\validate\v1\SysUserValidate;

/**
 * 用户管理控制器
 */
class User
{
    // 获取用户菜单权限
    public function menu()
    {
        $id   = request()->param('id');
        $user = SysUserModel::bypk($id)->find();
        if (empty($user)) {
            return error('用户不存在');
        }

        $menus = SysMenuModel::alias('menu')->field([
                'menu.id',
                'menu.pid',
                'menu.title',
                'menu.name',
                'menu.path',
                'menu.icon',
                'menu.redirect',
                'menu.component',
                'menu.hidden',
                'menu.actived',
                'menu.keep_alive'
            ])
            ->where('menu.status', '=', 1)
            ->whereExists(function($query) use($user) {
                $query->table((new SysRoleAuthorityModel)->getTable())->alias('authority')
                    ->where('authority.role_id', '=', $user->role_id)
                    ->where('authority.menu_id = menu.id')
                    ->group('authority.menu_id');
            })
            ->order(['menu.sort' => 'asc', 'menu.id' => 'desc'])
            ->select();
        if (!$menus->isEmpty()) {
            $authoritys = SysRoleAuthorityModel::field([
                    'menu_id', 
                    'permission'
                ])
                ->roleId($user->role_id)
                ->whereNotNull('permission')
                ->select();
            $authoritys_map = [];
            foreach ($authoritys as $val) {
                $authoritys_map[$val['menu_id']][] = $val['permission'];
            }
            $menus->each(function($item) use($authoritys_map) {
                $meta = [
                    'title'       => $item['title'],
                    'icon'        => $item['icon'],
                    'isKeepAlive' => !!$item['keep_alive'],
                    'actived'     => !!$item['actived'],
                    'permissions' => []
                ];
                unset($item['title'], $item['icon'], $item['keep_alive'], $item['actived']);
                if (isset($authoritys_map[$item['id']])) {
                    $meta['permissions'] = $authoritys_map[$item['id']];
                }
                $item['hidden'] = !!$item['hidden'];
                $item['meta']   = $meta;
                return $item;
            });
        }
        
        return success('获取成功', array_to_tree($menus->toArray(), 0, 'pid', false));
    }

    // 用户分页数据
    public function index()
    {
        $params = request()->get([
            'username',
            'status',
            'page/d' => 1,
            'size/d' => 10
        ]);

        $users = SysUserModel::withoutField([
                'password',
                'salt',
                'created_at',
                'updated_at',
                'deleted_at'
            ])
            ->with(['role' => function($query) {
                $query->field(['id', 'name' => 'role_name']);
            }])
            ->withSearch(['username'], [
                'username' => $params['username']??null,
            ])
            ->status($params['status']??null)
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $params['size'],
                'page'      => $params['page'],
            ])
            ->bindAttr('role', ['role_name'])
            ->hidden(['role_id', 'role']);
        if ($users->isEmpty()) {
            return success('获取成功');
        }

        // 查询用户最后登录记录
        $logs = SysUserLoginLogModel::where('id', 'IN', function($query) use($users) {
                $query->table((new SysUserLoginLogModel)->getTable())
                    ->field(['MAX(id)'])
                    ->whereIn('user_id', array_column($users->items(), 'id'))
                    ->group('user_id');
            })
            ->column([
                'ip',
                'created_at'
            ], 'user_id');
        if (!empty($logs)) {
            $users->each(function($item) use($logs) {
                $item['last_login_ip'] = '';
                $item['last_login_at'] = '';
                if (!empty($logs[$item['id']])) {
                    $item['last_login_ip'] = long2ip($logs[$item['id']]['ip']);
                    $item['last_login_at'] = $logs[$item['id']]['created_at'];
                }
                return $item;
            });
        }

        return success('获取成功', $users);
    }

    // 用户详情
    public function read($id)
    {
        $id = request()->param('id');

        $user = SysUserModel::withoutField([
                'password',
                'salt',
                'delete_disable',
                'created_at',
                'updated_at',
                'deleted_at',
            ])
            ->bypk($id)
            ->find();
        if (empty($user)) {
            return error('用户不存在');
        }

        return success('获取成功', $user);
    }

    // 用户新增
    public function save()
    {
        $post = request()->post([
            'username',
            'password',
            'repassword',
            'nickname',
            'avatar',
            'mobile',
            'email',
            'role_id',
            'status' => 1,
        ]);
        $post = array_merge($post, ['salt' => random_str(16)]);

        $validate = new SysUserValidate;
        if (!$validate->scene('create')->check($post)) {
            return error($validate->getError());
        }

        $post['password'] = password_with_salt($post['password'], $post['salt']);
        unset($post['repassword']);
        $user = SysUserModel::create($post);
        if ($user->isEmpty()) {
            return error('新增失败');
        }

        return success('新增成功');
    }

    // 用户更新
    public function update()
    {
        $id  = request()->param('id');
        $put = request()->put([
            'username',
            'password',
            'repassword',
            'nickname',
            'avatar',
            'mobile',
            'email',
            'role_id',
            'status' => 1,
        ]);
        $data = array_merge($put, ['id' => $id]);

        $validate = new SysUserValidate;
        if (!$validate->scene('update')->check($data)) {
            return error($validate->getError());
        }

        $user = SysUserModel::bypk($id)->find();
        if (empty($user)) {
            return error('请确认要操作的对象是否存在');
        }

        if (!empty($data['password'])) {
            $data['salt']     = random_str(16);
            $data['password'] = password_with_salt($data['password'], $data['salt']);
        } else {
            unset($data['password']);
        }
        unset($data['repassword']);
        if (!$user->save($data)) {
            return error('操作失败');
        }

        return success('操作成功');
    }

    // 用户删除
    public function delete()
    {
        $id = request()->param('id');

        $user = SysUserModel::bypk($id)->find();
        if (empty($user)) {
            return error('请确认要操作的对象是否存在');
        }
        if ($user->delete_disable == 1) {
            return error('该用户禁止删除');
        }

        if (!$user->delete()) {
            return error('操作失败');
        }

        return success('操作成功');
    }
}
