<?php

namespace app\admin\controller;

use app\admin\controller\base\Permissions;
use app\admin\model\AdminMenu as menuModel;
use think\Db;

class Menu extends Permissions
{
    public function index()
    {
        $model = new menuModel();
        if ($this->request->isAjax()) {
            $data = $model->order('orders asc')->select();
            foreach ($data as $k => $v) {
                $v['type_text'] = $v->type == 1 ? "权限节点" : "普通节点";
                $v['is_display_text'] = $v->is_display == 1 ? "显示在左侧菜单" : "操作节点";
                $data[$k] = $v;
            }
            return $data;
        } else {
            $menus = $model->order('orders asc')->select();
            $menus_all = $model->menulist($menus);
            $this->assign('menus', $menus_all);
            $this->assign('noInsertRoutes', $this->noInsertRoutes());
            return $this->fetch();
        }
    }

    public function publish()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model = new menuModel();
        $post = $this->request->post();
        if ($this->request->isPost()) {
            $validate = new \think\Validate([
                ['name', 'require', '菜单名称不能为空'],
                ['pid', 'require', '请选择上级菜单'],
                // ['module', 'require', '请填写模块名称'],
                // ['controller', 'require', '请填写控制器名称'],
                // ['function', 'require', '请填写方法名称'],
                ['type', 'require', '请选择菜单类型'],
            ]);
            if (!$validate->check($post)) {
                $this->error('提交失败:' . $validate->getError());
            }
        }

        if ($id > 0) {
            if ($this->request->isPost()) {
                if ($id == $post['pid']) {
                    $this->error('不能选自己当上级分类');
                }
                $menu = $model->where('id', $id)->find();
                if (empty($menu)) {
                    $this->error('id不正确');
                }
                //如果关闭默认展开,给默认值0
                if (empty($post['is_open'])) {
                    $post['is_open'] = 0;
                }
                if (false == $model->allowField(true)->save($post, ['id' => $id])) {
                    $this->error('修改失败');
                } else {
                    $this->success('修改菜单信息成功', 'admin/menu/index');
                }
            } else {
                $menu = $model->where('id', $id)->find();
                $menus = $model->order('orders asc')->select();
                $menus_all = $model->menulist($menus);
                $this->assign('menus', $menus_all);
                if (!empty($menu)) {
                    $this->assign('menu', $menu);
                    return $this->fetch();
                } else {
                    $this->error('id不正确');
                }
            }
        } else {
            if ($this->request->isPost()) {
                if (false == $model->allowField(true)->save($post)) {
                    $this->error('添加菜单失败');
                } else {
                    $this->success('添加菜单成功', 'admin/menu/index');
                }
            } else {
                $pid = $this->request->has('pid') ? $this->request->param('pid', null, 'intval') : null;
                if (!empty($pid)) {
                    $this->assign('pid', $pid);
                }
                $menu = $model->order('orders asc')->select();
                $menus = $model->menulist($menu);
                $this->assign('menus', $menus);
                return $this->fetch();
            }
        }
    }

    public function delete()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            if (Db::name('admin_menu')->where('pid', $id)->select() == null) {
                if (false == Db::name('admin_menu')->where('id', $id)->delete()) {
                    $this->error('删除失败');
                } else {
                    $this->success('删除成功', 'admin/menu/index');
                }
            } else {
                $this->error('该菜单下还有子菜单,不能删除');
            }
        }
    }

    public function orders()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $i = 0;
            foreach ($post['id'] as $k => $val) {
                $order = Db::name('admin_menu')->where('id', $val)->value('orders');
                if ($order != $post['orders'][$k]) {
                    if (false == Db::name('admin_menu')->where('id', $val)->update(['orders' => $post['orders'][$k]])) {
                        $this->error('更新失败');
                    } else {
                        $i++;
                    }
                }
            }
            $this->success('成功更新' . $i . '个数据', 'admin/menu/index');
        }
    }

    /**
     * 未添加的路由
     * @return array
     */
    private function noInsertRoutes()
    {
        $allRoutes = [];
        $controllers = getFilenameList(APP_PATH . 'admin' . DS . 'controller' . DS, '*.php');
        foreach ($controllers as $controller) {
            if ($controller != "Permissions") {
                $actions = getActions("\app\admin\controller\\" . $controller, $base = '\app\admin\controller\base\Permissions');
                foreach ($actions as $action) {
                    $allRoutes[] = "admin-$controller-$action";
                }
            }
        }

        $allMenus = (new menuModel())->field("concat(module,'-',controller,'-',function) as route")->where('module', '<>', '')->select();
        $allMenusLowCase = [];
        foreach ($allMenus as $menu) {
            $allMenusLowCase[] = strtolower($menu['route']);
        }

        $noInsertRoutes = [];
        foreach ($allRoutes as $route) {
            if (!in_array(strtolower($route), $allMenusLowCase)) {
                $noInsertRoutes[] = explode('-', $route);
            }
        }
        return $noInsertRoutes;
    }

    /**
     * 批量添加
     */
    public function batchAdd()
    {
        $post = $this->request->param();
        if (isset($post['name']) && is_array($post['name'])) {
            $data = [];
            foreach ($post['name'] as $key => $name) {
                if (!isset($post['pid'][$key])) {
                    continue;//没有选择上级节点
                }
                $data[] = [
                    'name' => $name,
                    'module' => $post['module'][$key],
                    'controller' => $post['controller'][$key],
                    'function' => $post['function'][$key],
                    'is_display' => $post['is_display'][$key],
                    'type' => $post['type'][$key],
                    'pid' => $post['pid'][$key],
                    'icon' => 'fa-tag',
                ];
            }
            $model = new menuModel();
            if (false == $model->allowField(true)->saveAll($data)) {
                $this->error('添加菜单失败');
            } else {
                $this->success('添加菜单成功', 'admin/menu/index');
            }
        }
        $this->error('当前没有路由可添加');
    }
}