<?php

namespace App\Http\Controllers\User;

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

/**
 * @name 部门管理
 * Class BmmcController
 * @package App\Http\Controllers\Admin
 */
class BmmcController extends BaseController
{
	protected $rules = array(
		'bmmc_name' => '部门名称',
		'id' => '数据编号',
	);

    /**|---------------------------------------------------------------------------------
     * @name 列表页
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author dou
     * |---------------------------------------------------------------------------------
     */
    public function index (Request $request)
    {
        $page_size = (int)$request->input('page_size',10);
        $page = (int)$request->input('page',1);
        if($page<1){
            $page = 1;
        }
        $offset = ($page-1)*$page_size;
        if($request->get('session_token')['admin_groupnew']!='7'){
//            CommonService::startmysql();
            $list = Bmmc::whereRaw("FIND_IN_SET ('".$request->get('session_token')['admin_groupnew']."',bmmc_pids) ");
            if($request->get('session_token')['admin_groupnew']!='8'){
                $list = $list->whereIn('company_id',[$request->get('session_token')['company_id'],1]);
            }else{
                $all_companys = $request->get('session_token')['all_companys'];
                $all_companys[] = 1;
                $list = $list->whereIn('company_id',$all_companys);
            }
            $list = $list->select('id','bmmc_name','bmmc_pid','bmmc_pids')->orderBy('id','ASC')->get();
//            dump(CommonService::showmysql());
            $parent_id = $request->get('session_token')['admin_groupnew'];
        }else{
            $list = Bmmc::select('id','bmmc_name','bmmc_pid','bmmc_pids')->orderBy('id','ASC')->get();
            $parent_id = 0;
        }
        $all_button = BmmcService::whereButton($request->input('token'),$request->input('Pri_id'));
        $export = BmmcService::getTopButton('addEntry','', $all_button);
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮
        if (!$list->isEmpty()){
            foreach ($list as $k=>$v){
                $button = BmmcService::getListButton(['editEntry,savePower'],$all_button);
                $list[$k]['button_one'] = $button['button_one']??[];
                $list[$k]['button_two'] = $button['button_two']??[];
                $list[$k]['button_three'] = $button['button_three']??[];
            }
            $list = $list->toArray();
        }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$data);
        }
        $list = BmmcService::getTree($list,$parent_id);
        $count = count($list);
        $list = array_slice($list,$offset,$page_size);//截取数组

        $data['page'] = [
            'page'=>$page,
            'allPage'=>ceil($count/$page_size),
            'page_size'=>$page_size,
            'count'=>$count
        ];
        if ($list){
            $data['list'] = $list;
        }else{
            $data['list'] = [];
//            return $this->error('暂无数据', ErrorInc::DATA_EMPTY, []);
        }
        return $this->success('成功', $data);
    }



    /**|---------------------------------------------------------------------------------
     * @name 添加
     * @param bmmc       部门名称
     * @param bmmc_pid   上级部门id
     * @param bmmc_level 上级部门级别
     * @param bmmc_pids  上级id串
     * @return \Illuminate\Http\JsonResponse
     * @author dou
     * |---------------------------------------------------------------------------------
     */
    public function addEntry (Request $request)
    {
        $parameter = $request->only('bmmc_name','bmmc_pid','bmmc_level','bmmc_pids','company_id');
	    $checkKey = CommonService::checkKey(['bmmc_name','bmmc_pid','bmmc_level'],$parameter,$this->rules);
	    if($checkKey['code']!=1){
			return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);
		}
        $Res = Bmmc::whereRaw("bmmc_name='".$request->input('bmmc_name')."'")->get();
       	if (!$Res->isEmpty()){
	       	return $this->error('部门名称已存在', ErrorInc::FAILED_PARAM, []);
        }
        $bmmc_level = $parameter['bmmc_level']+1;
        if($bmmc_level>8){
        	return $this->error('部门级别已经超过最高限制', ErrorInc::REQUEST_FORBIDDEN, []);
        }
        $session = $request->get('session_token');
        if ($session['admin_groupnew'] != 7){
            $parameter['company_id'] = $session['company_id'];
        }else{
            $parameter['company_id'] = $parameter['company_id']??'';
        }
        $parameter['bmmc_level'] = $bmmc_level;
        if($parameter['bmmc_pid']!=''){
        	$parameter['bmmc_pids'] = trim($parameter['bmmc_pids'],',').",".$parameter['bmmc_pid'];
    	}
    	$parameter['bmmc_pids'] = trim($parameter['bmmc_pids'],',');
    	$parameter['function_id'] = '571,572,573';
        $insRes = Bmmc::insert($parameter);
        if ($insRes){
            $this->insertingLog('添加，','','部门名称：'.$parameter['bmmc_name'],'部门管理',$request->ip(),$request->get('session_token')['admin_acc']);
            return $this->success('添加成功', []);
        }else{
            return $this->error('添加失败', ErrorInc::MYSQL_FAILED, []);
        }
    }



    /**|---------------------------------------------------------------------------------
     * @name  编辑部门名称
     * @param id 数据id
     * @param bmmc_name 部门名称
     * @return \Illuminate\Http\JsonResponse
     * |---------------------------------------------------------------------------------
     */
	public function editEntry (Request $request)
	{
        $parameter = $request->only('id','bmmc_name');
	    $checkKey = CommonService::checkKey(['id','bmmc_name'],$parameter,$this->rules);
	    if($checkKey['code']!=1){
			return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);
		}
        $bmmc_name = Bmmc::where('id',$parameter['id'])->value('bmmc_name');
        $insRes = Bmmc::whereRaw("bmmc_name='".$parameter['bmmc_name']."' and id !='".$parameter['id']."'")->first();
       	if ($insRes){
	       	return response()->json(['Data'=>'','ErrorMessage'=>'部门名称已存在','ErrorCode'=>5]);exit;
        }
        $poss['bmmc_name'] = $parameter['bmmc_name'];
		$res = Bmmc::where('id',$parameter['id'])->update($poss);
		if($res){
		   $content = $bmmc_name.'->'.$parameter['bmmc_name'];
		   $this->insertingLog('编辑，','',$content,'部门管理',$request->ip(),$request->get('session_token')['admin_acc']);
		   return $this->success('操作成功', []);
		}else{
		   return $this->error('操作失败', ErrorInc::MYSQL_FAILED, []);
		}
	}
    /**|---------------------------------------------------------------------------------
     * @name 获取权限
     * @param id 数据id
     * @return \Illuminate\Http\JsonResponse
     * @author dou
     * |---------------------------------------------------------------------------------
     */
    public function getSysFunctions (Request $request)
    {
        if (!$request->filled('id')){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);
        }
        $function_id = Bmmc::where('id',$request->input('id'))->value('function_id');
        if($request->get('session_token')['admin_groupnew']=='7'){
            $bmmc_pid = Bmmc::where('id',$request->input('id'))->value('bmmc_pid');
            if($bmmc_pid=='7' || $bmmc_pid=='') {
                $list = Functions::select('function_id', 'function_parent_id', 'function_name', 'function_type')->where('is_show','<',3)->get();
            }else{
                $function_ids = Bmmc::where('id',$bmmc_pid)->value('function_id');
                $function_ids = $function_ids??0;
                if($function_ids){
                    $list = Functions::whereRaw("function_id in (".trim($function_ids,',').")")->where('is_show','<',3)->select('function_id','function_parent_id','function_name','function_type')->orderBy('function_id','ASC')->get();
                }else{
                    $list = [];
                }
                // DB::connection()->enableQueryLog();

                // print_r(DB::getQueryLog());
            }
        }else{
            $bmmc_pid = Bmmc::where('id',$request->input('id'))->value('bmmc_pid');
            $function_ids = Bmmc::where('id',$bmmc_pid)->value('function_id');
            $list = Functions::whereRaw("function_id in (".trim($function_ids,',').")")->where('is_show','<',3)->select('function_id','function_parent_id','function_name','function_type')->orderBy('function_id','ASC')->get();
        }
        if($list){
            $list = $list->toArray();
        }else{
            return $this->error('无可操作权限', ErrorInc::DATA_EMPTY, []);
        }
        $function_id = explode(',',trim($function_id,','));
        $lists = BmmcService::getsTree($list,0);
        $all = array( );
        $part = array( );
        foreach( $lists as $k => $v )
        {
            $xz1 = '0';
            $wx1 = '0';
            if($v['function_children']!='') {
                foreach ($v['function_children'] as $ka => $va) {
                    $xz2 = '0';
                    $wx2 = '0';
                    if($va['function_children']){
                        foreach ($va['function_children'] as $ke => $ve) {
                            if (in_array($ve['function_id'], $function_id)) {
                                $xz2 = '1';
                                $lists[$k]['function_children'][$ka]['function_children'][$ke]['type'] = '1';
                                $all[] = $ve['function_id'];
                                $part[] = $ve['function_id'];
                            } else {
                                $wx2 = '1';
                                $lists[$k]['function_children'][$ka]['function_children'][$ke]['type'] = '3';
                            }
                        }
                    }

                    if ($xz2 == '1' && $wx2 == '1') {
                        $lists[$k]['function_children'][$ka]['type'] = '2';
                        $xz1 = '1';
                        $wx1 = '1';
                        $all[] = $va['function_id'];
                    } elseif ($xz2 == '1' && $wx2 == '0') {
                        $lists[$k]['function_children'][$ka]['type'] = '1';
                        $xz1 = '1';
                        $all[] = $va['function_id'];
                        $part[] = $va['function_id'];
                    } elseif ($xz2 == '0' && $wx2 == '1') {
                        $lists[$k]['function_children'][$ka]['type'] = '3';
                        $wx1 = '1';
                    }
                }
            }
            if($xz1=='1' && $wx1=='1'){
                $lists[$k]['type'] = '2';
                $all[] = $v['function_id'];
            }elseif ( $xz1=='1' &&  $wx1=='0')
            {
                $lists[$k]['type'] = '1';
                $all[] = $v['function_id'];
                $part[] = $v['function_id'];
            }elseif ( $xz1=='0' &&  $wx1=='1')
            {
                $lists[$k]['type']='3';
            }
        }
        $data['list'] = $lists;
        $data['all'] = $all;
        $data['part'] = $part;

        if (!empty($lists)){
            return $this->success('成功', $data);
        }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY, []);
        }

    }

    /**|---------------------------------------------------------------------------------
     * @name 保存权限
     * @param bmmc_id
     * @param function_id
     * @return \Illuminate\Http\JsonResponse
     * @author dou
     * |---------------------------------------------------------------------------------
     */
    public function savePower ( Request $request )
    {
	    $parameter = $request->only('bmmc_id','function_id');
	    $checkKey = CommonService::checkKey(['bmmc_id','function_id'],$parameter);
	    if($checkKey['code']!=1){
			return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);
		}
        $poss['function_id'] = $parameter['function_id'];
        $function_id = Bmmc::where('id',$parameter['bmmc_id'])->value('function_id');
        $res = Bmmc::where('id',$parameter['bmmc_id'])->update($poss);
        $info = Bmmc::whereRaw("FIND_IN_SET ('".$parameter['bmmc_id']."',bmmc_pids) ")->get();
        if (!$info->isEmpty()){
            foreach ($info as $k=>$v){
                foreach ($info as $ks=>$vs){
                    if ($vs['bmmc_pid'] == $v['id']){
                        if (isset($v['function_id']) && isset($vs['function_id'])){
                            $akli = array_intersect(explode(',',$vs['function_id']),explode(',',$v['function_id']));
                            $akli = trim(implode(',',$akli),',');
                            Bmmc::where('id',$vs['id'])->update(['function_id'=>$akli]);
                        }
                    }
                }
            }
        }
        if($res){
            if (isset($function_id)){
                $content = '编辑权限：('.$function_id.')->('.$request->input('function_id').')';
            }else{
                $content = '编辑权限：(null)->('.$request->input('function_id').')';
            }

			$this->insertingLog('编辑权限，','',$content,'部门管理',$request->getClientIp(),$request->get('session_token')['admin_acc']);
			return $this->success('操作成功', $res);
        }else{
	        return $this->error('操作失败', ErrorInc::MYSQL_FAILED, []);
        }
    }
}
