<?php
namespace app\admin\controller;

use app\common\controller\AdminBaseController;
use app\admin\model\AuthRuleModel;

/**
 * 后台菜单
 * Class Menu
 * @package app\admin\controller
 */
class MenuController extends AdminBaseController {

	protected function menulist(){
        $admin_menu_list = AuthRuleModel::order('path asc')->all();

        foreach ($admin_menu_list as $key=>$vo) {
            $str = '';
            $level = str_word_count($vo['path'], 0, '-');

            $str = str_repeat('--', $level-1);

            $admin_menu_list[$key]['str'] = $str;
        }

        return $admin_menu_list;
	}
    /**
     * 后台菜单
     * @return mixed
     */
    public function index() {
        return $this->fetch();
    }

    public function getMenus() {
        $res['code'] = 0;
        $res['msg'] = 'success';
        $res['data'] = $this->menulist();
        return $res;
    }

    public function changeShow()
    {
        return parent::switchOperate(new AuthRuleModel());
    }

    public function updateField() {
        return parent::fieldUpdate(new AuthRuleModel());
    }

    /**
     * 添加菜单
     * @param string $pid
     * @return mixed
     */
    public function add($pid = '') {
        if ($this->request->isPost()) {
            $data = $this->request->param();

            $rule = AuthRuleModel::create($data);

            $id = $rule->id;

            if ($id) {
                $path = '0-'.$id;

                if ($data['pid']) {
                    $ppath = AuthRuleModel::where('id',$data['pid'])->value('path');
                    $path = $ppath.'-'.$id;
                }

                db('auth_rule')->where('id',$id)->setField('path',$path);

                $res['code'] = 1;
                $res['msg'] = '添加成功！';
                $res['url'] = url('menu/index');
            } else {
                $res['code'] = 0;
                $res['msg'] = '添加失败！';
            }

            return $res;
        } else {
            $this->assign('admin_menu_level_list', $this->menulist());
            return $this->fetch('add', ['pid' => $pid]);
        }
    }

    /**
     * 删除菜单
     * @param $id
     */
    public function delete($id) {
        if (AuthRuleModel::destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}
