<?php

namespace App\Http\Controllers\User;

use Illuminate\Http\Request;
//use App\Http\Controllers\Controller;
use App\Models\Functions;
use App\Services\BmmcService;
use App\Services\CommonService;
use BlueCity\Core\Inc\ErrorInc;
use App\Http\Controllers\BaseController;
use DB;

/**
 * @name 权限管理
 * Class FunctionsController
 * @package App\Http\Controllers\Admin
 */
class FunctionsController extends BaseController
{
	protected $rules = array(
		'function_name' => '方法名',
		'function_model' => '控制器名',
		'function_action' => '动作名称',
		'function_parent_id' => '父类栏目',
		'function_position' => '按钮位置',
		'function_private' => '是否为私有',
		'function_parent_name' => '父类栏目名称',
		'function_id' => '数据编号'
	);
    /**|---------------------------------------------------------------------------------
     * @name 列表页
     * @param Request function_name
     * @param Request function_model
     * @param Request function_action
     * @param Request page
     * @param Request page_zize
     * @return \Illuminate\Http\JsonResponse
     * |---------------------------------------------------------------------------------
     */
    public function index (Request $request)
    {
        $functions = New Functions();
        if ($request->filled('function_name')){
            $functions = $functions->where('function_name','like','%'.$request->input('function_name').'%');
        }
        if ($request->filled('function_model')){
            $functions = $functions->where('function_model','like','%'.$request->input('function_model').'%');
        }
        if ($request->filled('function_action')){
            $functions = $functions->where('function_action','like','%'.$request->input('function_action').'%');
        }
        $page_size=(int)$request->input('page_size',15);
        $paginate = $functions->orderBy('function_id','ASC')->paginate($page_size);
        $list = self::dataToArray($paginate->items());
    	$all_button = BmmcService::whereButton($request->input('token'),$request->input('Pri_id'));
        $export = BmmcService::getTopButton('addLM,addEntry,addAction','export', $all_button);
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮
        if ($list){
            foreach ($list as $k=>$v){
	            if($v['function_type'] < 3){
                	$button = BmmcService::getListButton(['editFuncName,delEntry'],$all_button);
            	}else{
	            	$button = BmmcService::getListButton(['editAction,delEntry'],$all_button);
            	}
                $list[$k]['button_one'] = $button['button_one']??[];
                $list[$k]['button_two'] = $button['button_two']??[];
                $list[$k]['button_three'] = $button['button_three']??[];
            }
             //返回数据
            $data['list'] = $list;
            $data['page'] = [
                'count' => $paginate->total(),
                'page'=>$paginate->currentPage(),
                'page_size'=>$page_size,
                'allPage'=>$paginate->lastPage()
            ];
            return $this->success('成功', $data);
        }else{
            $data['list'] = [];
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY, []);
        }
    }
    /**----------------------------------------------------------------------------------
     * @name 添加栏目
     * @param Request function_name
     * @param Request function_model
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021/07/19>
     * ----------------------------------------------------------------------------------
     */
    public function addLM (Request $request)
    {
	    $parameter = $request->only('function_name','function_model');
		$checkKey = CommonService::checkKey(['function_name','function_model'],$parameter,$this->rules);
	    if($checkKey['code']!=1){
			return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);
		}
		$res = Functions::whereRaw("(function_name='".$parameter['function_name']."' or function_model='".$parameter['function_model']."')")->where("function_type",1)->value("function_id");
		if( $res ){
			return $this->error('栏目名称或栏目方法已存在', ErrorInc::REPEAT_SUBMIT, []);
		}else{
	        $input['function_name'] = $parameter['function_name'];
	        $input['function_model'] = $parameter['function_model'];
	        $input['function_type'] = 1;
	        $input['function_parent_id'] = 0;
	        $function_id = Functions::insertGetId($input);
	        if ($function_id){
		        $content = "添加栏目：".$input['function_name'];
		        $this->insertingLog("添加栏目，",'',$content,"权限管理",$request->ip(),$request->get('session_token')['admin_acc']);//日志
	            $function_id = ['function_id'=>$function_id];
	            return $this->success('添加成功', $function_id);
	        }else{
		        return $this->error('添加失败', ErrorInc::MYSQL_FAILED, []);
	        }
        }
    }
    /**----------------------------------------------------------------------------------
     * @name 添加管理
     * @param function_parent_id   父类栏目id
     * @param function_parent_name 父类名称
     * @param function_name        方法名
     * @param function_model       控制器
     * @param function_action      默认动作(array)
     * @param    --array--
     * @param function_name        方法名
     * @param function_model       与顶级参数function_model相同
     * @param function_action       动作
     * @param function_img_src      按钮图片
     * @param function_position      按钮位置 1.横排；2.记录后；3.不显示；4.搜索栏
     * @param    --array--
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021-07-19>
     * ----------------------------------------------------------------------------------
     */
    public function addEntry (Request $request)
    {
        $parameter = $request->only('function_name','function_model','function_parent_id','function_action','function_parent_name');
		$checkKey = CommonService::checkKey(['function_name','function_model','function_parent_id','function_action','function_parent_name'],$parameter,$this->rules);
	    if($checkKey['code']!=1){
			return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);
		}
		$res = Functions::where("function_id",$parameter['function_parent_id'])->value('function_id');
		if(!$res){
			return $this->error('无对应栏目信息', ErrorInc::REQUEST_FORBIDDEN, []);
		}else{
			$res = Functions::whereRaw("(function_name='".$parameter['function_name']."' or function_model='".$parameter['function_model']."')")->where("function_type",2)->value("function_id");
			if($res){
				return $this->error('管理名称或控制器方法已存在', ErrorInc::REPEAT_SUBMIT, []);
			}else{
		        $arr['function_parent_id'] = $parameter['function_parent_id'];
		        $arr['function_parent_name'] = $parameter['function_parent_name'];
		        $arr['function_name'] = $parameter['function_name'];
		        $arr['function_model'] = $parameter['function_model'];
		        $arr['function_type'] = 2;
		        $arr['sort_order'] = 1;
		        DB::beginTransaction();
		        $flag = 1;
		        $insArr = Functions::insertGetId($arr);
		        DB::table('column')->where('id','>=','0')->delete();
		        if ($insArr){
		            $function_action = $parameter['function_action'];
		            foreach ($function_action as $k =>$v){
		                $fns['function_parent_id'] = $insArr;
		                $fns['function_parent_name'] = $parameter['function_name'];
		                $fns['function_name'] = $v['function_name'];
		                $fns['function_model'] = $arr['function_model'];
		                $fns['function_action'] = $v['function_action'];
		                $fns['function_img_src'] = $v['function_img_src']?? '';
		                $fns['function_position'] = $v['function_position'];
		                $fns['function_type'] = 3;
		                $fnRes = Functions::insert($fns);
		                if (!$fnRes){
		                    DB::rollback();
		                    $flag = 2;
		                    return $this->error('默认动作添加失败', ErrorInc::MYSQL_FAILED, []);
		                }
		            }
		        }else{
		            DB::rollback();
		            $flag = 2;
		            return $this->error('管理添加失败', ErrorInc::MYSQL_FAILED, []);
		        }
		        if ($flag == 1){
			        $content = "添加管理：".$arr['function_parent_name'].'-'.$arr['function_name']."(".$arr['function_model'].")";
		        	$this->insertingLog("添加管理，",'',$content,"权限管理",$request->ip(),$request->get('session_token')['admin_acc']);//日志
		            DB::commit();
		            return $this->success('添加成功', []);
		        }
	        }
        }
    }
    /**
     * ----------------------------------------------------------------------------------
     * @name 添加动作
     * @param Request function_parent_id   父类id
     * @param Request function_parent_name 父类名称
     * @param Request function_model       控制器
     * @param Request function_name        方法名
     * @param Request function_action      动作
     * @param Request function_position    按钮位置 1.横排；2.记录后；3.不显示；4.搜索栏--
     * @param Request function_private     是否私有 1：是；2否
     * @param Request function_img_src     图片位置
     * @param Request sort_order           排序
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021-07-19>------
     * ----------------------------------------------------------------------------------
     */
    public function addAction (Request $request)
    {
	    $parameter = $request->only('function_name','function_model','function_parent_id','function_action','function_position','function_parent_name','function_private','function_img_src','sort_order');
		$checkKey = CommonService::checkKey(['function_name','function_model','function_parent_id','function_action','function_position','function_parent_name','function_private'],$parameter,$this->rules);
	    if($checkKey['code']!=1){
			return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);
		}
		$res = Functions::whereRaw("((function_name='".$parameter['function_name']."' and function_action='".$parameter['function_action']."') or function_action='".$parameter['function_action']."')")->where("function_type",3)->where('function_parent_id',$parameter['function_parent_id'])->value("function_id");
		if($res){
			return $this->error('该控制器下已存在该方法名称或动作', ErrorInc::REPEAT_SUBMIT, []);
		}else{
	        $parameter['function_type'] = 3;
	        $insArr = Functions::insertGetId($parameter);
	        if ($insArr){
		        $content = "添加动作：".$parameter['function_parent_name'].'-'.$parameter['function_name']."(".$parameter['function_action'].")";
	        	$this->insertingLog("添加动作，",'',$content,"权限管理",$request->ip(),$request->get('session_token')['admin_acc']);//日志
		        return $this->success('添加成功', $insArr);
	        }else{
		        return $this->error('添加失败', ErrorInc::MYSQL_FAILED, []);
	        }
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取父类栏目名称
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021-07-19>
     * |---------------------------------------------------------------------------------
     */
    public function getParent (Request $request)
    {
        $list = Functions::where('function_type',1)->select('function_id','function_name')->orderBy('function_id','ASC')->get();
        if (!$list->isEmpty()){
	        return $this->success('操作成功', $list);
        }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY, []);
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取父类管理名称
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021-07-19>
     * |---------------------------------------------------------------------------------
     */
    public function getmanagement (Request $request)
    {
        $list = Functions::where('function_type',2)->orderBy('function_parent_name','ASC')->orderBy('function_id','ASC')->get();
        if (!$list->isEmpty()){
            return $this->success('操作成功', $list);
        }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY, []);
        }

    }
    /**|---------------------------------------------------------------------------------
     * @name 编辑动作
     * @param function_id                  编号
     * @param Request function_name        方法名
     * @param Request function_position    按钮位置 1.横排；2.记录后；3.不显示；4.搜索栏--
     * @param Request function_private     是否私有 1：是；2否
     * @param Request sort_order     排序
     * @param Request function_parent_id     父类id
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021-07-19>
     * |---------------------------------------------------------------------------------
     */
    public function editAction (Request $request)
    {
	    $parameter = $request->only('function_id','function_name','function_position','function_private','sort_order','function_parent_id','function_action');
	    $checkKey = CommonService::checkKey(['function_id','function_name','function_position','function_private','sort_order','function_action'],$parameter,$this->rules);
	    if($checkKey['code']!=1){
			return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);
		}
		$function_id  = $parameter['function_id'];
		$function_parent_id  = $parameter['function_parent_id'];
		unset($parameter['function_id']);
		$res = Functions::where("function_name",$parameter['function_name'])->where("function_action",$parameter['function_action'])->where("function_type",3)->where('function_parent_id',$function_parent_id)->where("function_id","!=",$function_id)->value("function_id");
		if($res){
			return $this->error('该控制器下已存在该方法名称或动作', ErrorInc::REPEAT_SUBMIT, []);
		}else{
	        $upRes = Functions::where('function_id',$function_id)->update($parameter);
	        if ($upRes){
		        return $this->success('操作成功', []);
	        }else{
	            return $this->error('操作失败', ErrorInc::MYSQL_FAILED, []);
	        }
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 编辑栏目/管理模块名称
     * @param function_id                  编号
     * @param Request function_name        方法名
     * @param Request function_type  		数据级别
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021-07-20>
     * |---------------------------------------------------------------------------------
     */
    public function editFuncName (Request $request)
    {
	    $parameter = $request->only('function_id','function_name','function_type');
	    $checkKey = CommonService::checkKey(['function_id','function_name','function_type'],$parameter,$this->rules);
	    if($checkKey['code']!=1){
			return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);
		}
		$function_id  = $parameter['function_id'];
		unset($parameter['function_id']);
		$res = Functions::where("function_name",$parameter['function_name'])->where("function_type",$parameter['function_type'])->where("function_id","!=",$function_id)->value("function_id");
		unset($parameter['function_type']);
		if($res){
			return $this->error('该名称已存在', ErrorInc::REPEAT_SUBMIT, []);
		}else{
			DB::beginTransaction();
	        $upRes = Functions::where('function_id',$function_id)->whereIn("function_type",[1,2])->update($parameter);
	        Functions::where('function_parent_id',$function_id)->update(array('function_parent_name'=>$parameter['function_name']));
	        if ($upRes){
		        DB::commit();
		        return $this->success('操作成功', []);
	        }else{
		        DB::rollback();
	            return $this->error('操作失败', ErrorInc::MYSQL_FAILED, []);
	        }
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 删除权限
     * @param Request function_id  数据id
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021-07-19>
     * |---------------------------------------------------------------------------------
     */
    public function delEntry (Request $request)
    {
        if (in_array($request->input('function_id'),[75,76,77])){
	        return $this->error('无删除权限', ErrorInc::REQUEST_FORBIDDEN, []);
        }
        if ($request->filled('function_id')){
	        $function_parent_id = Functions::where("function_parent_id",$request->input('function_id'))->value('function_parent_id');
	        if($function_parent_id){
		        return $this->error('存在下级', ErrorInc::REQUEST_FORBIDDEN, []);
	        }else{
	            $info = Functions::where('function_id',$request->input('function_id'))->first();
	            $res = Functions::where('function_id',$request->input('function_id'))->delete();
	            if ($res){
		            $content = "删除：".$info['function_parent_name']."(".$info['function_model'].")-".$info['function_name']."(".$info['function_action'].")";
	        		$this->insertingLog("删除权限，",'',$content,"权限管理",$request->ip(),$request->get('session_token')['admin_acc']);//日志
	                return $this->success('操作成功', []);
	            }else{
	                return $this->error('参数错误', ErrorInc::MYSQL_FAILED, []);
	            }
            }
        }else{
	        return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);
        }
    }

}
