AdminUser.php 2.74 KB
<?php
declare(strict_types=1);

namespace app\controller\admin;

use app\BaseController;
use think\facade\Db;

class AdminUser extends BaseController
{
    public function list()
    {
        $rows = Db::name('sys_admin')->order('id', 'asc')->select()->toArray();
        $list = [];
        foreach ($rows as $r) {
            $list[] = [
                'id'        => (int) $r['id'],
                'username'  => $r['username'],
                'nickname'  => $r['nickname'],
                'role_id'   => (int) $r['role_id'],
                'status'    => (int) $r['status'],
                'create_time' => $r['create_time'],
            ];
        }

        return json(['code' => 0, 'msg' => 'ok', 'data' => ['list' => $list]]);
    }

    public function save()
    {
        $id       = (int) $this->request->post('id', 0);
        $username = trim((string) $this->request->post('username', ''));
        $nickname = trim((string) $this->request->post('nickname', ''));
        $password = (string) $this->request->post('password', '');
        $roleId   = (int) $this->request->post('role_id', 0);
        $status   = (int) $this->request->post('status', 1);

        $now = date('Y-m-d H:i:s');
        if ($id <= 0) {
            if ($username === '' || $password === '') {
                return json(['code' => 400, 'msg' => '账号密码必填', 'data' => []]);
            }
            if (Db::name('sys_admin')->where('username', $username)->count() > 0) {
                return json(['code' => 400, 'msg' => '账号已存在', 'data' => []]);
            }
            Db::name('sys_admin')->insert([
                'username'    => $username,
                'password'    => password_hash($password, PASSWORD_DEFAULT),
                'nickname'    => $nickname ?: $username,
                'role_id'     => $roleId,
                'status'      => $status,
                'create_time' => $now,
                'update_time' => $now,
            ]);
        } else {
            $data = [
                'nickname'    => $nickname,
                'role_id'     => $roleId,
                'status'      => $status,
                'update_time' => $now,
            ];
            if ($password !== '') {
                $data['password'] = password_hash($password, PASSWORD_DEFAULT);
            }
            Db::name('sys_admin')->where('id', $id)->update($data);
        }

        return json(['code' => 0, 'msg' => '已保存', 'data' => []]);
    }

    public function delete(int $id)
    {
        if ($id === 1) {
            return json(['code' => 400, 'msg' => '不能删除超级管理员', 'data' => []]);
        }
        Db::name('sys_admin')->where('id', $id)->delete();
        return json(['code' => 0, 'msg' => '已删除', 'data' => []]);
    }
}