You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

300 lines
13 KiB

12 months ago
<?php
namespace App\Http\Controllers\Admin;
use App\Exports\BaseFormExport;
use App\Http\Requests\BaseFormRequest;
use App\Models\Admin;
use App\Models\BaseForm;
use App\Models\CustomForm;
use App\Models\CustomFormField;
use App\Models\SearchResult;
use App\Repositories\BaseFormExtendRepository;
use App\Repositories\BaseFormRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Helpers\ResponseCode;
use Maatwebsite\Excel\Facades\Excel;
use Rap2hpoutre\FastExcel\FastExcel;
/**
* 自定义表单增删改查操作
*/
class BaseFormController extends CommonController
{
/**
* @OA\Get(
* path="/api/admin/base-form/index",
* tags={"自定义表单增删改查操作"},
* summary="列表",
* description="",
* @OA\Parameter(name="table_name", in="query", @OA\Schema(type="string"), required=false, description="表名"),
* @OA\Parameter(name="is_export", in="query", @OA\Schema(type="string"), required=false, description="是否导出0否1是"),
* @OA\Parameter(name="export_fields", in="query", @OA\Schema(type="string"), required=false, description="需要导出的字段数组,键值对数组,例如:['name'=>'名字','user.sex'=>'性别']"),
* @OA\Parameter(name="export_name", in="query", @OA\Schema(type="string"), required=false, description="导出的文件名"),
* @OA\Parameter(name="page_size", in="query", @OA\Schema(type="string"), required=false, description="每页显示的条数"),
* @OA\Parameter(name="page", in="query", @OA\Schema(type="string"), required=false, description="页码"),
* @OA\Parameter(name="filter", in="query", @OA\Schema(type="string"), required=false, description="查询条件。数组"),
* @OA\Parameter(name="sort_name", in="query", @OA\Schema(type="string"), required=false, description="排序字段名字"),
* @OA\Parameter(name="sort_type", in="query", @OA\Schema(type="string"), required=false, description="排序类型"),
* @OA\Parameter(name="is_auth", in="query", @OA\Schema(type="string"), required=false, description="是否鉴权 0否1是"),
* @OA\Parameter(name="show_relation", in="query", @OA\Schema(type="string"), required=false, description="需要输出的关联关系数组,不填输出全部,填写输出指定数据"),
* @OA\Parameter(name="token", in="query", @OA\Schema(type="string"), required=true, description="token"),
* @OA\Response(
* response="200",
* description="暂无"
* )
* )
*/
public function index(BaseFormRepository $repository)
{
$all = \request()->all();
$list = $repository->buildWith($all['show_relation'] ?? [])->buildSeacher($all['filter'] ?? [])
->where(function ($query) use ($all) {
// 权限
if (isset($all['is_auth']) && !empty($all['is_auth'])) {
$user = $this->getUser();
$departmentIds = Admin::roleAllowAdminIds($user);
$query->where(function ($qry) use ($departmentIds, $user) {
$qry->whereIn('department_id', $departmentIds)->orWhere('admin_id', $user->id);
});
}
})->orderBy($all['sort_name'] ?? 'id', $all['sort_type'] ?? 'desc');
if (isset($all['is_export']) && !empty($all['is_export'])) {
$list = $list->limit(5000)->get()->toArray();
return Excel::download(new BaseFormExport($list, $all['export_fields'] ?? ''), $all['file_name'] ?? '' . date('YmdHis') . '.xlsx');
} else {
// 输出
$list = $list->paginate($all['page_size'] ?? 20);
// json数组转换
foreach ($list as $item) {
$repository->getJsonData($item);
}
}
return $this->success($list);
}
/**
* @OA\Get(
* path="/api/admin/base-form/show",
* tags={"自定义表单增删改查操作"},
* summary="详情",
* description="",
* @OA\Parameter(name="table_name", in="query", @OA\Schema(type="string"), required=false, description="表名"),
* @OA\Parameter(name="id", in="query", @OA\Schema(type="string"), required=true, description="id"),
* @OA\Parameter(name="json_data_fields", in="query", @OA\Schema(type="string"), required=false, description="是否获取复选框/多文件字段详细数据,传字段的一维数组"),
* @OA\Parameter(name="token", in="query", @OA\Schema(type="string"), required=true, description="token"),
* @OA\Response(
* response="200",
* description="暂无"
* )
* )
*/
public function show(BaseFormRepository $repository)
{
$all = \request()->all();
$messages = [
'id.required' => 'Id必填',
];
$validator = Validator::make($all, [
'id' => 'required'
], $messages);
if ($validator->fails()) {
return $this->fail([ResponseCode::ERROR_PARAMETER, implode(',', $validator->errors()->all())]);
}
$detail = $repository->buildWith()->find($all['id']);
// 获取所有一对多json附加数据
$detail = $repository->getJsonData($detail);
return $this->success($detail);
}
/**
* @OA\Post(
* path="/api/admin/base-form/save",
* tags={"自定义表单增删改查操作"},
* summary="更新",
* description="",
* @OA\Parameter(name="table_name", in="query", @OA\Schema(type="string"), required=false, description="表名"),
* @OA\Parameter(name="id", in="query", @OA\Schema(type="int"), required=true, description="Id(存在更新,不存在新增)"),
* @OA\Parameter(name="字段名_relation", in="query", @OA\Schema(type="string"), required=true, description="关联表数据二维数组。如果存在id则更新否则新增 "),
* @OA\Parameter(name="token", in="query", @OA\Schema(type="string"), required=true, description="token"),
* @OA\Response(
* response="200",
* description="暂无"
* )
* )
*/
public function save(BaseFormRequest $request, BaseFormRepository $repository)
{
$all = $request->all();
DB::beginTransaction();
try {
if (isset($all['id'])) {
$model = BaseForm::find($all['id']);
} else {
$model = new BaseForm();
$all['admin_id'] = $this->getUserId();
$all['department_id'] = $this->getUser()->department_id;
}
// 保存前额外前置操作
$allAfter = BaseFormExtendRepository::saveBefore($all);
$model->fill($allAfter);
$model->save();
DB::commit();
$model = $model->find($model->id);
// 更新模型关系
$repository->updateRelation($all, $model);
// 保存后额外后置操作
BaseFormExtendRepository::saveAfter($all, $model);
// 添加搜索
SearchResult::addResources($model);
return $this->success($model);
} catch (\Exception $exception) {
DB::rollBack();
return $this->fail([$exception->getCode(), $exception->getMessage()]);
}
}
/**
* @OA\Get(
* path="/api/admin/base-form/destroy",
* tags={"自定义表单增删改查操作"},
* summary="删除",
* description="",
* @OA\Parameter(name="table_name", in="query", @OA\Schema(type="string"), required=false, description="表名"),
* @OA\Parameter(name="id", in="query", @OA\Schema(type="string"), required=true, description="id"),
* @OA\Parameter(name="destroy_relation", in="query", @OA\Schema(type="string"), required=true, description="需要删除的关联关系字段数组"),
* @OA\Parameter(name="token", in="query", @OA\Schema(type="string"), required=true, description="token"),
* @OA\Response(
* response="200",
* description="暂无"
* )
* )
*/
public function destroy(BaseFormRepository $repository)
{
$all = \request()->all();
$messages = [
'id.required' => 'Id必填',
];
$validator = Validator::make($all, [
'id' => 'required'
], $messages);
if ($validator->fails()) {
return $this->fail([ResponseCode::ERROR_PARAMETER, implode(',', $validator->errors()->all())]);
}
$form = $repository->find($all['id']);
if (isset($all['destroy_relation']) && !empty($all['destroy_relation'])) {
// 删除关联关系
foreach ($all['destroy_relation'] as $item) {
$form->$item()->delete();
}
}
$form->delete();
return $this->success('删除成功');
}
/**
* @OA\Post(
* path="/api/admin/base-form/excel-show",
* tags={"自定义表单增删改查操作"},
* summary="导入预览",
* description="",
* @OA\Parameter(name="table_name", in="query", @OA\Schema(type="string"), required=false, description="表名"),
* @OA\Parameter(name="file", in="query", @OA\Schema(type="string"), required=true, description="文件"),
* @OA\Parameter(name="token", in="query", @OA\Schema(type="string"), required=true, description="token"),
* @OA\Response(
* response="200",
* description="暂无"
* )
* )
*/
public function excelShow(Request $request)
{
$all = \request()->all();
$messages = [
'table_name' => '表名必填',
'file.required' => 'file必填',
'file.file' => 'file必须是文件',
'file.max' => '文件大小不能超过50MB',
'file.mimes' => '仅允许上传以下格式的文件: zip, rar, ppt, pptx, xls, xlsx, doc, docx, png, gif, jpg, jpeg, pdf, mp4, mp3'
];
$validator = Validator::make($all, [
'table_name' => 'required',
'file' => 'required|file|mimes:zip,rar,ppt,pptx,xls,xlsx,doc,docx,png,gif,jpg,jpeg,pdf,mp4,mp3|max:51200000',
], $messages);
if ($validator->fails()) {
return $this->fail([ResponseCode::ERROR_PARAMETER, implode(',', $validator->errors()->all())]);
}
$file = $request->file('file');
$tempFile = $file->getRealPath();
$dataArray = (new FastExcel)->import($tempFile)->toArray();
// 数据过滤,只能导入数据表有的字段
$customFormField = new CustomFormField();
$rowTableFieldByComment = $customFormField->getRowTableFieldsByComment($all['table_name']);
$list = [];
foreach ($dataArray as $key => $value) {
foreach ($rowTableFieldByComment as $k => $v) {
if (isset($value[$v])) {
$list[$key][$k] = $value[$v];
}
}
}
return $this->success($list);
}
/**
* @OA\Post(
* path="/api/admin/base-form/import",
* tags={"自定义表单增删改查操作"},
* summary="导入",
* description="",
* @OA\Parameter(name="table_name", in="query", @OA\Schema(type="string"), required=false, description="表名"),
* @OA\Parameter(name="data", in="query", @OA\Schema(type="string"), required=true, description="导入分析获取到的二维数组"),
* @OA\Parameter(name="token", in="query", @OA\Schema(type="string"), required=true, description="token"),
* @OA\Response(
* response="200",
* description="暂无"
* )
* )
*/
public function import(BaseFormRepository $repository)
{
$all = \request()->all();
$messages = [
'data.required' => '数据必填',
];
$validator = Validator::make($all, [
'data' => 'required',
], $messages);
if ($validator->fails()) {
return $this->fail([ResponseCode::ERROR_PARAMETER, implode(',', $validator->errors()->all())]);
}
$baseForm = new BaseForm();
DB::beginTransaction();
try {
$list = [];
foreach ($all['data'] as $item) {
$list[] = array_merge($item, [
'admin_id' => $this->getUserId(),
'department_id' => $this->getUser()->department_id,
'created_at' => date('Y-m-d H:i:s')
]);
}
// 分段导入
foreach (array_chunk($list, 500) as $chunk) {
$baseForm->insert($chunk);
}
DB::commit();
return $this->success(['total' => count($all['data'])]);
} catch (\Exception $exception) {
DB::rollBack();
return $this->fail([$exception->getCode(), $exception->getMessage()]);
}
}
}