sifangpay/app/Http/Controllers/Admin/BaseController.php

523 lines
12 KiB
PHP

<?php
namespace App\Http\Controllers\Admin;
use App\Models\AdminLog;
use App\Services\SearchServices;
use Illuminate\Support\Facades\Auth;
use Route;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Schema;
use Validator;
use AnyUpload;
use DB;
class BaseController extends Controller
{
//
const ADMIN_BLADE_DIR='admin.';
public $title='';
public $route=[];
public $pages=[];
public $model;
public $share_view=[];
public $guard_name='admin';
public $dblast_id='';
public $adminModel='App\Models\Admin';
public function __construct()
{
$route_arr=explode('@', Route::currentRouteAction());
$this->route['controller_name']='\\'.$route_arr[0];
$this->route['action_name']=$route_arr[1];
$this->route['controller_base']=str_replace('Controller','',str_replace('App\\Http\\Controllers\\Admin\\','',$route_arr[0]));
$this->route['blade']=self::ADMIN_BLADE_DIR.strtolower($this->route['controller_base']).'.'.$this->route['action_name'];
$this->share_view['controller']="\\".$this->route['controller_name'];
$this->title=ucwords($this->route['action_name']);
$this->share_view['title']=$this->title;
$this->setPagesInfo();
//$this->handleUrl();
$this->getTable();
$this->share_view['action_name']=$this->route['action_name'];
$this->share_view['page']=$this->pages;
$this->shareView();
// $this->checkPermission();
}
public function alertError($error_str,$status=1){
return response()->json( ['error'=>$status,'msg'=>$error_str,'type'=>'validator']);
}
/**
* 验证规则
* @param array $data
* @return array
*/
protected function checkRule($id='')
{
}
/**
* 设置表单验证错误信息
* @return array
*/
public function setErrorMsg(){
$messages = [
];
return $messages;
}
/**
* 全局返回表单错误消息
* @param $error
* @return array
*/
protected function formError($error){
$error=$error->all();
if(count($error)<=0) return [];
$error_str='';
foreach($error as $k=>$v)
{
$error_str.=$v."*<br/>";
}
return ['error'=>1,'msg'=>$error_str,'type'=>'validator'];
}
public function errorJosn($msg){
return ['error'=>1,'msg'=>$msg];
}
protected function beforeStore($request){
}
protected function beforeSave($request,$id){
}
/**
* 全局检测表单是否错误,如果又返回错误数组,否则空数组
* @param $request
* @param string $id
* @return array
*/
protected function validatorForm($request,$id=''){
$validator = Validator::make($request->all(), $this->checkRule($id),$this->setErrorMsg());
if($validator->fails()) {
if($request->ajax() || $request->wantsJson())
{
return $validator->errors();
}
}
return [];
}
//附加验证
protected function extendValidate($request,$model,$id){
return true;
}
/**
* 设置创建数据键值对
* @param $obj
* @param $data
* @return mixed
*/
protected function setDbKeyValue($obj,$data){
$fileds=$this->getField();
foreach ($data as $field=>$v)
{
if(in_array($field,$fileds)){
$v=is_null($v)?'':$v;
$obj->$field = trim($v);
}
}
return $obj;
}
/**
* 全局创建和更新操作返回消息
* @param $result
* @param $request
* @param string $id
* @return \Illuminate\Http\JsonResponse
*/
protected function saveMessage($result,$request,$id=''){
$type=$id?'更新':'创建';
if($request->method()=='DELETE')
{
$type='删除';
}
$msg_type=$result?'成功':'失败';
$msg_str=$this->pages['name'].$type.$msg_type;
if($result)
{
$this->insertLog($msg_str);
}
if ($request->ajax() || $request->wantsJson()) {
return response()->json([
'error'=>$result?0:1,
'msg'=>$msg_str
]);
}
}
protected function insertLog($msg){
AdminLog::addLog($msg);
}
protected function backMessage( $data=[],$success,$request_type,$type)
{
$return_arr=[];
$type_str=$request_type=='edit'?'更新':'创建';
if($type=='ajax')
{
if($success)
{
$return_arr['error']=0;
$return_arr['msg']=$type_str.'成功';
}else
{
$return_arr['error']=1;
$return_arr['msg']=$type_str.'失败,请重新操作';
}
}
return $return_arr;
}
/**
* 共享视图资源
* @return mixed
*/
public function shareView(){
return view()->share($this->share_view);
}
public function setPageName($name){
$data=$this->pages;
$data['name']=$name;
view()->share('page',$data);
}
/**
* 设置页面标题
* @param string $title
*/
protected function setTitle($title=''){
$title=$title?$title:$this->pages['name'];
view()->share('title',$title?$title:$this->title);
}
/**
* 页面page设置
*/
protected function setPagesInfo(){
$this->pages=[
'name'=>''
];
}
/**
* 改变自动获取blade
* @param $path
* @param int $cover 是否完全覆盖
* @param int $is_seft 是否在当前的控制下目录
* @return string
*/
protected function setViewPath($path='',$filename='',$cover=0,$is_seft=1)
{
if($cover){
return $this->route['blade']=$path;
}
if($is_seft==0)
{
return $this->route['blade']=self::ADMIN_BLADE_DIR.$path;
}
if($filename!='')
{
$this->route['action_name']=$filename;
}
if($path)
{
$this->route['action_name']=$path.".".$this->route['action_name'];
}
return $this->route['blade']=self::ADMIN_BLADE_DIR.strtolower($this->route['controller_base']).'.'.$this->route['action_name'];
}
/**
* 取得当前的模型的字段列表
* @param $model
* @return mixed
*/
protected function getField(){
$table=$this->getTable();
$data=Schema::getColumnListing($table);
if(array_key_exists('id', $data))
{
unset($data['id']);
}
return $data;
}
/**
* 取得table
* @return string
*/
protected function getTable(){
if(gettype($this->setModel())!='object')
{
$table='';
}else
{
$table=$this->setModel()->getTable();
}
$this->share_view['table_name']=$table;
$this->shareView();
return $table;
}
/**
* 本页面操作的模型
*/
protected function setModel(){
}
protected function afterStore($request){
}
protected function afterUpdate(){
}
protected function getShow($id){
$show=$this->setModel()->find($id);
if(!$show)
{
return abort(404);
}
view()->share('show',$show);
return $this->display($this->shareData($show));
}
/**
* 输出视图
* @param array $data
* @return mixed
*/
public function display($data=[]){
return view($this->route['blade'],$data);
}
public function jsonDebug($json){
print_r($json);
return '';
}
public function setDbLastId($result,$obj){
if($result) {
$this->dblast_id=$obj->id;
return true;
}
return false;
}
protected function saveAfter($request,$model,$id=''){
}
protected function postDataDb($request,$id=''){
return $request->all();
}
protected function searchKey($model,$arr,$where=1){
if(empty($arr))
{
return $model;
}
return $model->search($arr,$where);
}
public function indexData(){
$this->setTitle();
return [];
}
//共享创建和编辑数据
protected function shareData($id=''){
return [];
}
public function checkValueData(){
$filed_arr=[];
$value=0;
if(count($filed_arr)<=0){
return false;
}
return ['fields'=>$filed_arr,'value'=>$value];
}
public function checkOnValue($data, $handel_arr, $value = 0)
{
$handel_data=$this->checkValueData();
if($handel_data)
{
$handel_arr=$handel_data['fields']+$handel_arr;
$value=$handel_data['value'];
}
if (count($handel_arr) <= 0) {
return $data;
}
foreach ($handel_arr as $k => $v) {
if (array_key_exists($v, $data)) {
continue;
}
$data[$v] = $value;
}
return $data;
}
/**
* 创建和更新操作
* @param $request
* @param $model
* @param string $id
* @return array|\Illuminate\Http\JsonResponse
*/
protected function saveData($request,$model,$id=''){
$error=$this->validatorForm($request,$id);
if(count($error)>0){
return $this->formError($error);
};
$extend_checked=$this->extendValidate($request,$model,$id);
if(is_array($extend_checked))
{
return response()->json($extend_checked);
}
//设置请求参数
$data=$this->postDataDb($request,$id);
//设置is_checkd不选择的时候为0
if($id)
{
if(in_array('is_checked',$this->getField()))
{
//$data=$this->checkOnValue($data,['is_checked'],0);
}
}
$model=$this->setDbKeyValue($model,$data);
$begin=isset($data['begindb'])?$data['begindb']:0;
if($begin!=0)
{
DB::beginTransaction();
$result=$model->save();
$this->setDbLastId($result,$model);
$after_result=$this->saveAfter($request,$model,$id);
if($result && $after_result)
{
DB::commit();
}else
{
DB::rollback();
}
}else
{
$result=$model->save();
$this->setDbLastId($result,$model);
$this->saveAfter($request,$model,$id);
}
return $this->saveMessage($result,$request,$id);
}
public function jsonMsg($error,$str){
return response()->json(['error'=>$error,'msg'=>$str]);
}
/*********基本控制器资源设置*********/
/**
* 设置相关操作,比如链表
* @param $model
* @return mixed
*/
public function apiSetModelRel($model){
return $model;
}
/**
* 设置关联数据等操作
* @param $model
* @return mixed
*/
public function apiSetResult($model){
return $model;
}
public function setApiSearchParam($data){
return $data;
}
public function searchType(){
return '';
}
public function getSearchModel($data,$type=''){
$model=new SearchServices($this->setModel(),$data,$this->searchType());
// dd(SearchServices::$where);
return $model->getModel();
}
public function returnJson($total,$narr,$debug){
$json = [
"status" => 1,
'code' => $total > 0 ? 0 : 1,
'msg' => $total > 0 ? '请求数据成功' : '暂无数据',
'count' => $total,
'data' => $narr
];
if ($debug) {
return $this->jsonDebug($json);
}
return response()->json($json);
}
}