<?php


namespace app\admin\controller;

use app\BaseController;
use app\admin\model\Menu as MenuModel;
use app\admin\model\RoleMenu;
use app\admin\model\Admin;
use app\admin\validate\MenuValidate;
use think\facade\Db;

class Menu extends BaseController
{

    /**
     * @api {get} /menu/list 查询菜单列表
     */
    public function list()
    {
        try {
            $count = MenuModel::count();
            $list = MenuModel::order('sort', 'asc')
                ->order('id', 'asc')
                ->select();
            
            $list = linear_to_tree($list, 'children');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success(['count' => $count, 'list' => $list]);
    }

    /**
     * @api {get} /menu/route 获取菜单路由
     */
    public function route()
    {
        try {
            $adminId = $this->admin_id;
            // 缓存优化
            $list = cache('MenuLogic:getMenuByAdminId:'.$adminId);
            if(empty($list)){
                $admin = Admin::where('id',$adminId)->find();
                $where = [];
                $where[] = ['type', 'in', [1,2]];
                $where[] = ['is_disable', '=', 0];
                if ($adminId != 1) {
                    $roleMenu = RoleMenu::whereIn('role_id', $admin['role_id'])->column('menu_id');
                    $where[] = ['id', 'in', $roleMenu];
                }
                $menu = MenuModel::where($where)
                    ->order(['sort' => 'desc', 'id' => 'asc'])
                    ->select();
                $list = linear_to_tree($menu, 'children');
                cache('MenuLogic:getMenuByAdminId:'.$adminId,$list);
            }
            
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success($list);
    }

    /**
     * @api {get} /menu/info 菜单详情
     */
    public function info()
    {
        try {
            $params = (new MenuValidate())->goCheck('id');
            $detail = MenuModel::where('id', $params['id'])->find();
            if(empty($detail)){
                return $this->error('菜单不存在');
            }
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success($detail);
    }

    /**
     * @api {post} /menu/update 添加/修改
     * @apiGroup 菜单
     * @apiVersion 1.0.0
     * @apiUse header
     * @apiUse lang
     *
     * @apiParam {Integer} parent_id 父级ID
     * @apiParam {String} type 类型 M:菜单 C:按钮
     * @apiParam {String} name 名称
     * @apiParam {String} icon 图标
     * @apiParam {Integer} sort 排序
     * @apiParam {String} perms 权限
     * @apiParam {String} paths 路径
     * @apiParam {String} component 组件
     * @apiParam {String} params 参数
     * @apiParam {Integer} is_cache 是否缓存:1是 0否,默认0
     * @apiParam {Integer} status 状态: 1正常 0停用，默认1
     */
    public function update()
    {
        Db::startTrans();
        try {
            $params = (new MenuValidate)->post()->goCheck('edit');
            $id = $this->request->param('id',0);
            $params['parent_id'] = $params['parent_id'] ?? 0;
            $params['is_cache'] = $params['is_cache'] ?? 0;
            $params['status'] = $params['status'] ?? 1;
            $params['sort'] = $params['sort'] ?? 0;

            if (!$id) {
                MenuModel::create($params);
            } else {
                MenuModel::where('id', $id)->update($params);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success([],'保存成功');

    }

    //删除
    public function delete()
    {
        try {
            $params = (new MenuValidate())->goCheck('id');
            MenuModel::where('id', $params['id'])->delete();
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success([],'删除成功');
    }

}