luck-draw/app/controller/manager/Account.php

158 lines
4.1 KiB
PHP

<?php
namespace app\controller\manager;
use app\exception\RepositoryException;
use app\model\Account as AccountModel;
use app\repository\AccountRepository;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\response\Json;
use think\response\View;
/**
* 用户管理
*
* Class Footmarks
* @package app\controller\manager
*/
class Account extends Base
{
protected $noNeedLogin = [];
/**
* 详情
*
* @return View
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
* @throws RepositoryException
*/
public function detail(): View
{
$id = input('id/d', 0);
$item = AccountRepository::getInstance()->findById($id);
$this->data['item'] = $item;
return $this->view();
}
/**
* 编辑
*
* @return Json|View
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
* @throws Exception
*/
public function edit()
{
$id = input('id/d', 0);
if (!$info = AccountRepository::getInstance()->findById($id)) {
if ($this->request->isPost()) {
return $this->json(4000, '用户不存在');
} else {
return $this->error('用户不存在');
}
}
if ($this->request->isPost()) {
$item = input('post.');
$validate = $this->validateByApi($item, [
'nickname' => 'require',
]);
if ($validate !== true) {
return $validate;
}
try {
$info->save($item);
return $this->json();
} catch (ValidateException $e) {
return $this->json(4001, $e->getError());
}
}
$this->data['item'] = $info;
return $this->view();
}
/**
* 单个字段编辑
*
* @return Json
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
* @throws Exception
*/
public function modify(): Json
{
if ($this->request->isPost()) {
$item = input('post.');
$validate = $this->validateByApi($item, [
'field' => 'require',
'value' => 'require',
]);
if ($validate !== true) {
return $validate;
}
if (!$info = AccountModel::findById($item['id'])) {
return $this->json(4001, '记录不存在');
}
$update = [$item['field'] => $item['value']];
try {
$info->save($update);
return $this->json();
} catch (ValidateException $e) {
return $this->json(4001, $e->getError());
}
}
return $this->json(4000, '非法请求');
}
/**
* 列表
*
* @return View|Json
* @throws Exception
*/
public function index()
{
if ($this->request->isPost()) {
$page = input('page/d', 1);
$size = input('size/d', 20);
$searchParams = input('searchParams');
$search = [];
if ($searchParams) {
foreach ($searchParams as $key => $param) {
if ($param || $param == '0') {
$search[] = [$key, 'like', '%'.$param.'%'];
}
}
}
try {
$items = AccountRepository::getInstance()->getAndHandleAccountList($search, [], $page, $size);
return $this->json(0, '操作成功', $items);
} catch (RepositoryException $e) {
return $this->json(4001, $e->getMessage());
} catch (Exception $e) {
return $this->json(5001, '获取用户列表失败'.$e->getMessage());
}
}
return $this->view();
}
}