<?php

namespace app\admin\controller;

use app\admin\common\Base;
use think\Request;
use think\Db;
use think\Log;
header("Content-type: text/html; charset=utf-8"); 
class Menu extends Base
{
	/**
	*初始化
	*/
	protected function _initialize(){
	/*	parent::_initialize();
		if(session('admin_user_type') != 1){
	    		$result['erro']=-1;
	    		$result['msg']='权限不足';
	    		Response::create($result,'json')->send();
	    		exit;
	    	}*/
	}
	public function index()
    {
        // $this->alreadyLogin();
        return $this->view->fetch('index');
    }
    public function nav()
    {
        // $this->alreadyLogin();
        return $this->view->fetch('nav');
    }
    public function getUserInfor(){
    	$data=Db::name("user")
    			->field('user_name,user_head')
    			->where('id',session('admin_user_id'))
    			->find();
    	$result=['status'=>1,'msg'=>'查询成功','infro'=>$data];
    	return json($result);
    }
     /**
     * 获取菜单列表
     * @author hjc
     * @date 2024-05-14
     */
    public function getMenuList(Request $request){
        $data=$request->param();
      //  $this->checkToken($data['Token']);
        //升序获取菜单列表
        $result = Db::name('menu')
        		->field('id,pid,menu_name,url,seq_on,menu_icon')
        		->order('seq_on')
        		->select();
        //找二级菜单
        $second=[];
        foreach ($result as $key => $value) {
            if($value['pid'] != '' && $value['pid'] != 0){
                //二级
                $value['grade']="二级菜单";
                $second[]=$value;
                unset($result[$key]);
            }else{
            	$result[$key]['grade']="一级菜单";
            }
        }
        //二级组装到一级
        $result=array_values($result);
        foreach ($result as $key => $value) {
            $result[$key]['type']=1;
            $result[$key]['No']=$key+1;
            foreach ($second as $k => $v) {
                if($value['id']==$v['pid']){
                    $v['type']=2;
                    $result[$key]['children'][]=$v;
                }
            }
        }
        if($result){
            $status=1;
            $msg="获取数据成功！！";
        }
        else{
            $status=0;
            $msg="获取数据失败！！";
        }
        return json(['status'=>$status,'msg'=>$msg,'data'=>$result]);
    }
    /**
     * 权限菜单列表
     * @author hjc
     * @date 2024-05-14
     */
    public function getPermissionMenu(Request $request){
        $data=$request->param();
        //$this->checkToken($data['Token']);
        //升序获取菜单列表
        $result=Db::name('menu')->field('id,pid,menu_name,url,seq_on,menu_icon')->order('seq_on')->select();
        //找二级三级菜单
        $second=[];
        foreach ($result as $key => $value) {
            if($value['pid'] != ''){
                $second[]=$value;
                unset($result[$key]);
            }
        }
        //二级组装到一级
        foreach ($result as $key => $value) {
            $result[$key]['type']=1;
            foreach ($second as $k => $v) {
                if($value['menu_id']==$v['pid']){
                    $v['type']=2;
                    $result[$key]['second'][]=$v;
                }
            }
        }
        if($result){
            $status=1;
            $msg="获取数据成功！！";
        }
        else{
            $status=0;
            $msg="获取数据失败！！";
        }
        return json(['status'=>$status,'msg'=>$msg,'data'=>$result]);
    }
    
    public function getMenuOption(Request $request){
        $data=$request->param();
       // $this->checkToken($data['Token']);
        //升序获取菜单列表
        $result = Db::name('menu')
        		->field('id,pid,menu_name')
        		//->where('status',0)
        		->order('seq_on')
        		->select();
        //找二级三级菜单
        $second=[];
        // $third=[];
        foreach ($result as $key => $value) {
            if($value['pid'] != ''){
                //二级
                $second[$key]['value']=$value['id'];
                $second[$key]['label']=$value['menu_name'];
                $second[$key]['pid']=$value['pid'];
                unset($result[$key]);
            }
        }
        //二级组装到一级
        $first=[];
        foreach ($result as $key => $value) {
            $first[$key]['value']=$value['id'];
            $first[$key]['label']=$value['menu_name'];
            foreach ($second as $k => $v) {
                if($value['menu_id']==$v['pid']){
                    unset($v['pid']);
                    $first[$key]['children'][]=$v;
                }
            }
        }
        if($first){
            $status=1;
            $msg="获取数据成功！！";
        }
        else{
            $status=0;
            $msg="获取数据失败！！";
        }
        return json(['status'=>$status,'msg'=>$msg,'data'=>$first]);
    }
    //获取当前菜单最大序号
    public function getMaxSeq($map){
        $result=Db::name('menu')->field('seq_on')->where($map)->order('seq_on','desc')->find();
        if($result){
            return $result['seq_on']+1;
        }else{
            return 1;
        }
    }
    //添加菜单
    public function doaddMenu(Request $request){
        //获取一下表单提交的数据，并保存在变量中
        $data=$request->param();
       // $this->checkToken($data['Token']);
        unset($data['Token']);
        $menu_id=md5(uniqid(''));//一级菜单id
        $create_time=date('Y-m-d H:i:s');//插入时间
        $data1=[];
        //添加一级菜单
        if(empty($data['father'])){
            $map['pid']='';
        }else{
            $map['pid']=$data['father'];
        }
        //获取一级菜单最大序号
        $seq_on=$this->getMaxSeq($map);
        $data1=$map;
        if(!empty($data['urs'])){
            $data1['url']=$data['url'];
        }
        if(!empty($data['menu_icon'])){
            $data1['menu_icon']=$data['menu_icon'];
        }
        $data1['id']=$menu_id;
        $data1['menu_name']=$data['title'];
        $data1['seq_on']=$seq_on;
        $data1['create_time']=$create_time;
        $res=Db::name('menu')->insert($data1);
        if($res){
            $status=1;
            $msg='添加菜单成功！！';
        }else{
            $status=0;
            $msg='添加菜单失败！！';
        }
        return json(['status'=>$status,'msg'=>$msg]);
    }
    /**
     * 修改菜单详情
     * @param $data 菜单id（一级菜单、二级菜单）
     * @param $data 菜单详情
     * @author hjc
     * @date 2024-05-14
     */
    public function updMenu(Request $request){
        $data=$request->param();
        $result=Db::name('menu')->field('id,pid,menu_name,url,menu_icon')->where('menu_id',$data['menu_id'])->find();
        $result['type']=1;
        if(!empty($result['pid'])){
            $result['type']=2;
            $result['father']=$result['pid'];
        }
        unset($result['pid']);
        if($result){
            $status=1;
            $msg="获取数据成功！！";
        }else{
            $status=0;
            $msg="获取数据失败！！";
        }
        return json_encode(['status'=>$status,'msg'=>$msg,'data'=>$result]);
    }
    public function doupdMenu(Request $request){
        $data=$request->param();
        $data1=[];
        //添加一级菜单
        if(empty($data['father'])){
            $data1['pid']='';
            if(!empty($data['menu_icon'])){
                $data1['menu_icon']=$data['menu_icon'];
            }
        }else{
            $data1['pid']=$data['father'];
            //获取一级菜单最大序号
            if(!empty($data['url'])){
                $data1['url']=$data['url'];
            }
        }
        $data1['menu_name']=$data['menu_name'];
        $res=Db::name('menu')->where('id',$data['id'])->update($data1);
        if($res){
            $status=1;
            $msg='修改菜单成功！！';
        }else{
            $status=0;
            $msg='修改菜单失败！！';
        }
        return json_encode(['status'=>$status,'msg'=>$msg]);
    }
    /**
     * 设置菜单状态
     * @param $data 一级菜单id、二级菜单id
     * @author hjc
     * @date 2024-05-14
     */
    public function setMenuStatus(Request $request){
        $data=$request->param();
        $this->checkToken($data['Token']);
        $res=Db::name('menu')->where('id',$data['id'])->update(['status'=>$data['status']]);
        if($res){
            $status=1;
            $msg='设置成功！！';
        }else{
            $status=0;
            $msg='设置失败！！';
        }
        return json_encode(['status'=>$status,'msg'=>$msg]);
    }
    /**
     * 删除菜单
     * @param $data 一级菜单id、二级菜单id
     *@author hjc
     * @date 2024-05-14
     */
    public function delMenu(Request $request){
        $data=$request->param();
        $res=Db::name('menu')->where('id',$data['id'])->find();
        //一级菜单
        if($res['pid']==''){
            $map1['id|pid']=$data['id'];
            $map2['id']=['in',[$data['id'],$res['pid']]];
        }else{
            $map1['id']=$data['id'];
            $map2['id']=$data['id'];
        }
        // 启动事务
        Db::startTrans();
        try{
            //删除二级菜单
            Db::name('menu')->where($map1)->delete();
         //   Db::table('t_nv_role_menu')->where($map2)->delete();
            // 提交事务
            Db::commit();
            $status=1;
            $msg='删除菜单成功！！';
        } catch (\Exception $e) {
            Log::record($e->getMessage(),'error');
            // 回滚事务
            Db::rollback();
            $status=0;
            $msg='删除菜单失败！！';
        }
        return json_encode(['status'=>$status,'msg'=>$msg]);
    }
}
