<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\model\ActionLog;
use think\App;
use think\facade\Db;
//菜单
class Menu extends Base
{

    /**
     * 显示资源列表
     * @return \think\Response
     */
    public  function __construct(App $app)
    {
        parent::__construct($app);
//        $this->post  =$this->request->post();
    }

//    public function list()
//    {
//        $uid = $this->uid;
//        if($uid==''){
//            return error_show(101,'未找到用户信息');
//        }
//        $role =$this->checkRole();
////        var_dump($role);
//        if(empty($role)){
//            return app_show(0,"获取成功",[]);
//        }
//        $data= Db::name("view_menu")->where('aid',"in",explode(",",$role['action_conllect']))->where(['status'=>1,"cstatus"=>1,"is_display"=>1])
//            ->order("weight desc,id asc,cweight desc,cid asc")->select();
//        $list=[];
//        $act=[];
//        foreach ($data as $value){
//            $list[$value["id"]]['menu_name']=$value['menu_name'];
//            $list[$value["id"]]['menu_img']=$value['menu_img'];
//            $list[$value["id"]]['menu_route']=$value['menu_route'];
//            $list[$value["id"]]['is_display']=$value['is_display'];
//            $list[$value["id"]]['status']=$value['status'];
//            $temp=[];
//            $temp['menu_name']=$value['cname'];
//            $temp['menu_img']=$value['cmenu_img'];
//            $temp['menu_route']=$value['cmenu_route'];
//            $temp['menu_url']=$value['cmenu_url'];
//            $temp['status']=$value['cstatus'];
//            $temp['is_private']=$value['cprivate'];
//            $temp['is_display']=$value['cis_display'];
//            $list[$value["id"]]['child'][$value['cid']]=$temp;
//            $act[$value['id']][$value['cid']][]=$value['acode'];
//            $list[$value["id"]]['child'][$value['cid']]['action']= $act[$value['id']][$value['cid']];
//        }
//        array_walk($list,function (&$value){
//            $value['child']= array_values($value['child']);
//        });
//        return app_show(0,"获取成功",array_values($list));
//    }
    public function list()
    {
        $post = $this->request->filter('trim')->post();

//        $uid = $this->uid;
//        if ($uid == '') {
//            return error_show(101, '未找到用户信息');
//        }

        //相关权限等以后重新梳理
//        $role = $this->checkRole();

        $where = [['status', '=', 1], ['cstatus', '=', 1], ['is_display', '=', 1]];

        //先把当前账号能看到的菜单筛选出来
        switch ($this->level) {

            case 1:
                //超管,能看到等级为012的菜单
                $role['action_conllect'] = Db::name('action')
                    ->where(['is_del' => 0, 'status' => 1])
                    ->column('id');
//                $where[] = ['blevel', 'in', [0, 1, 2]];
                break;
            case 2:
                $role['action_conllect'] = Db::name('user_role')
                    ->alias('a')
                    ->leftJoin('role_action b', 'b.role_id=a.roleid')
                    ->where(['a.uid' => $this->uid, 'a.is_del' => 0, 'a.companyNo' => $post['relaComNo']])
                    ->value('b.action_conllect');

//                $where[] = ['blevel', 'in', [0, $level]];
                break;

            case 3:

                $role['action_conllect'] = Db::name('user_role')
                    ->alias('a')
                    ->leftJoin('role_action b', 'b.role_id=a.roleid')
                    ->where(['a.uid' => $this->uid, 'a.is_del' => 0])
                    ->value('b.action_conllect');

//                $where[] = ['blevel', 'in', [0, $level]];
                break;

        }

//        if (isset($post['level']) && $post['level'] !== '' && $post['level'] != 1) $where[] = ['blevel', 'in', [0, $post['level']]];
        if (isset($post['level']) && $post['level'] !== '') $where[] = ['blevel', 'in', [0, $post['level']]];
        else {
            if ($this->level == 1) $where[] = ['blevel', 'in', [0, 1, 2]];
            else $where[] = ['blevel', 'in', [0, $this->level]];
        }

//        if (empty($role['action_conllect'])) {
//            return app_show(0, "获取成功", []);
//        }

//        if (!empty($role['action_conllect'])) $where[] = ['aid', 'in', $role['action_conllect']];

        $data = Db::name("view_menu")
            ->where($where)
            ->whereIn('aid', $role['action_conllect'])
            ->order("weight desc,id asc,cweight desc,cid asc")
            ->select()
            ->toArray();

        $list = [];
        $act = [];
        foreach ($data as $value) {
            $list[$value["id"]]['menu_name'] = $value['menu_name'];
            $list[$value["id"]]['menu_img'] = $value['menu_img'];
            $list[$value["id"]]['menu_route'] = $value['menu_route'];
            $list[$value["id"]]['is_display'] = $value['is_display'];
            $list[$value["id"]]['status'] = $value['status'];
            $temp = [];
            $temp['menu_name'] = $value['cname'];
            $temp['menu_img'] = $value['cmenu_img'];
            $temp['menu_route'] = $value['cmenu_route'];
            $temp['menu_url'] = $value['cmenu_url'];
            $temp['status'] = $value['cstatus'];
            $temp['is_private'] = $value['cprivate'];
            $temp['is_display'] = $value['cis_display'];
            $list[$value["id"]]['child'][$value['cid']] = $temp;
            $act[$value['id']][$value['cid']][] = $value['acode'];
            $list[$value["id"]]['child'][$value['cid']]['action'] = $act[$value['id']][$value['cid']];
        }
        array_walk($list, function (&$value) {
            $value['child'] = array_values($value['child']);
        });
        return app_show(0, "获取成功", array_values($list));
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function MenuEdit(){
        $post  =$this->request->post();
//        $token = isset($post['token']) ? trim($post['token']) : "";
//        if($token==""){
//            return error_show(101,'token不能为空');
//        }
//        $effetc = VerifyTokens($token);
//        if(!empty($effetc) && $effetc['code']!=0){
//            return error_show($effetc['code'],$effetc['message']);
//        }
        $id = isset($post['id']) ?intval($post['id']) :"";
        if($id!=""){
            $menu = Db::name("admin_menu")->where("id","=",$id)->find();
            if($menu==false){
                return error_show(1003,"菜单不信息不存在");
            }
        }
        $name = isset($post['name']) ?trim($post['name']) :"";
        if($name==""){
            return error_show(1002,"菜单名称不能为空");
        }
        $url = isset($post['url']) ?trim($post['url']) :"";
        $route = isset($post['route']) ?trim($post['route']) :"";
        $code = isset($post['menu_code']) ?trim($post['menu_code']) :"";
        $img = isset($post['img']) ?trim($post['img']) :"";
        $pid = isset($post['pid']) ?intval($post['pid']) :0;
        $weight = isset($post['weight']) ?floatval($post['weight']) :1;
        $status = isset($post['is_show']) ? intval($post['is_show']) : 0;
        $is_display = isset($post['is_display']) ? intval($post['is_display']) : 0;
        $private = isset($post['private']) ?intval($post['private']) :(isset($menu['is_private']) ?$menu['is_private'] : 0);
        if($pid!=0 && $route==""){
            return error_show(1002,"子级菜单路由不能为空");
        }
        $level = isset($post['level'])?intval($post['level']):'';
        if($level==='') return json_show(0,'菜单等级不能为空');//这里要用全等,有可能level传值0
        $data=[
            "menu_name"=>$name,
            "menu_url"=>$url,
            "menu_route"=>$route,
            "menu_code"=>$code,
            "menu_img"=>$img,
            "pid"=>$pid,
            'is_show'=>$status,
            'is_display'=>$is_display,
            "is_private"=>$private,
            'status'=>1,
            'level'=>$level,
            "weight"=>$weight,
            "updatetime"=>date("Y-m-d H:i:s"),
        ];
        $message="新建";
        if($id!=""){
            $message="编辑";
            $data['id']=$id;
        }
        $result = Db::name("admin_menu")->save($data);
        $orde = ["order_code"=>$code,"status"=>0,"action_remark"=>'',"action_type"=>"edit"];
        ActionLog::logAdd(['id'=>$this->uid,'nickname'=>$this->uname],$orde,"admin_menu",0,$orde);
        return $result ? app_show(0,"{$message}成功"): error_show(1003,"{$message}失败");
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function MenuStatus(){
        $post  =$this->request->post();
//        $token = isset($post['token']) ? trim($post['token']) : "";
//        if($token==""){
//            return error_show(101,'token不能为空');
//        }
//        $effetc = VerifyTokens($token);
//        if(!empty($effetc) && $effetc['code']!=0){
//            return error_show($effetc['code'],$effetc['message']);
//        }
        $id = isset($post['id']) ?intval($post['id']) :"";
        $menu = Db::name("admin_menu")->where("id","=",$id)->find();
        if($menu==false){
            return error_show(1003,"菜单信息不存在");
        }
        $statu = isset($post['status'])&&$post['status']!="" ? intval($post['status']) :"";
        if($statu===""){
            return error_show(1003,"菜单状态不能为空");
        }
        $var= $menu['status'];
        $menu['status']=$statu;
        $menu['updatetime']=date("Y-m-d H:i:s");
        $result = Db::name("admin_menu")->save($menu);
        $orde = ["order_code"=>$menu['menu_name'],"status"=>$var,"action_remark"=>'',"action_type"=>"edit"];
        ActionLog::logAdd(['id'=>$this->uid,'nickname'=>$this->uname],$orde,"admin_menu", $menu['status'],$orde);
        return $result ? app_show(0,"状态更新成功"): error_show(1003,"状态更新失败");
    }

    /**
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function   MenuAllList(){
//        $post  =$this->request->post();

        $data = Db::name("admin_menu")
            ->where(['pid'=>0,'is_del'=>0])
            ->order("weight desc,id asc")
            ->select()
            ->toArray();
        $l=[];
        foreach ($data as $key=>$value){
            $temp=[];
            $temp =  Db::name("admin_menu")
                ->where(['pid'=>$value['id'],'is_del'=>0])
                ->order("weight desc,id asc")
                ->select()
                ->toArray();
            $value['child']=$temp;
            $l[]=$value;
        }
        return app_show(0,"获取成功",$l);
    }

    /**
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */

    public function MenuDel(){
        $post  =$this->request->post();
//        $token = isset($post['token']) ? trim($post['token']) : "";
//        if($token==""){
//            return error_show(101,'token不能为空');
//        }
//        $effetc = VerifyTokens($token);
//        if(!empty($effetc) && $effetc['code']!=0){
//            return error_show($effetc['code'],$effetc['message']);
//        }
        $id = isset($post['id']) ?intval($post['id']) :"";
        $menu =  Db::name("admin_menu")->where("id","=",$id)->find();
        if($menu==false){
            return error_show(1003,"菜单不信息不存在");
        }
        $var=$menu['status'];
        $menu['is_show']=0;
        $menu['status']=0;
        $menu['is_del']=1;
        $menu['updatetime']=date("Y-m-d H:i:s");
        $result =  Db::name("admin_menu")->save($menu);
        $orde = ["order_code"=>$menu['menu_name'],"status"=>$var,"action_remark"=>'',"action_type"=>"delete"];
        ActionLog::logAdd(['id'=>$this->uid,'nickname'=>$this->uname],$orde,"admin_menu", $menu['status'],$orde);
        return $result ? app_show(0,"删除成功"): error_show(1003,"删除失败");
    }

    /**
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function MenuActionDel(){
        $post  =$this->request->post();
//        $token = isset($post['token']) ? trim($post['token']) : "";
//        if($token==""){
//            return error_show(101,'token不能为空');
//        }
//        $effetc = VerifyTokens($token);
//        if(!empty($effetc) && $effetc['code']!=0){
//            return error_show($effetc['code'],$effetc['message']);
//        }
        $id = isset($post['id']) ?intval($post['id']) :"";
        $menu =  Db::name("action")->where("id","=",$id)->find();
        if($menu==false){
            return error_show(1003,"菜单功能信息不存在");
        }

        $result =  Db::name("action")->delete($menu);
        $orde = ["order_code"=>$menu['id'],"status"=>0,"action_remark"=>'',"action_type"=>"delete"];
        ActionLog::logAdd(['id'=>$this->uid,'nickname'=>$this->uname],$orde,"action",0,$orde);
        return $result ? app_show(0,"删除成功"): error_show(1003,"删除失败");
    }
}