<?php
// +----------------------------------------------------------------------
// | 菜单新增
// +----------------------------------------------------------------------
// | Copyright (c) 2018 https://blog.junphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小黄牛 <1731223728@qq.com>
// +----------------------------------------------------------------------

namespace app\controller\admin\auth;
use app\controller\SuperClass\Admin;

class Menu_insert extends Admin
{

    /**
     * @AopBefore(class="app\aop\AdminLogin", function="before")
     * @RequestMapping(route="/admin/auth/menu_insert", method="GET|POST", title="菜单新增")
     * @Ioc(class="\x\Db", name="Db")
    */
    public function run() {
        if (\x\Request::is_ajax()) {
            return $this->_insert();
        }
        $param = \x\Request::get();
        $controller = '';
        if (!empty($param['pid'])) {
            $controller = $this->Db->name('auth_menu')->where('id', $param['pid'])->value('controller');
        }
        $this->assign('controller', $controller);
        $this->assign('pid', $param['pid']);

        $this->Db->return();
        return $this->display();
    }

    // Ajax处理
    private function _insert() {
        $param = \x\Request::post();
        $param['create_time'] = time();
        $id = $this->Db->name('auth_menu')->insertGetId($param);
        if ($id != false) {
            $param = $this->param_group($param, $id);
            $ress  = $this->Db->name('auth_menu')->where('id', $param['id'])->update($param);
            $this->Db->return();
            if ($ress != false) {
                return $this->returnJson('00', '创建成功！');
            }

            return $this->returnJson('01', '写入成功，但注意：更新权限路径失败！');
        }

        $this->Db->return();
        return $this->returnJson('01', '创建失败！');
    }

    // 参数组合处理
    private function param_group($param=[], $id) {
        // 需要获取到的参数如下：
        // path 为全路径
        // level 为等级

        $return = [
            'id' => $id,
        ];
        // 顶级权限等级为1，全路径为自身
        if ($param['pid'] == 0) {
            $return['level'] = 1;
            $return['path'] = $id;
        } else {
            $info =$this->Db->name('auth_menu')->where('id', $param['pid'])->field('path, level')->find();
            $return['level'] = $info['level']+1;
            $return['path'] = $info['path'].'/'.$id;
        }

        return $return;
    }
}

