<?php

namespace app\controller\common;

use app\extra\basic\Base;
use app\extra\service\system\MenuService;
use app\extra\tools\DataExtend;
use app\middleware\AuthMiddleware;
use app\model\system\SystemMenu;
use DI\Attribute\Inject;
use LinFly\Annotation\Route\Controller;
use LinFly\Annotation\Route\Route;
use support\Request;
use support\Response;
use LinFly\Annotation\Route\Middleware;


#[Controller(prefix: "/api/menu"),Middleware(AuthMiddleware::class)]
class Menu extends Base
{

    #[Inject]
    protected MenuService $service;

    /**
     * 获取菜单
     */
    #[Route(path: "list",methods: "get")]
    public function getMenuList(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "form.default"  => $request->user['type'],
                "type.default"  => 1
            ]);
            $hide = 0;
            $menu = $this->service->getMenuList($request->user['is_super'],$hide,$param['form']);
            $permissionsData = [];
            foreach ($menu as $val) {
                if ($val['type'] == 'button') {
                    $permissionsData[] = $val['name'];
                }
            }
            $menu = $this->filterMenu(DataExtend::arr2tree($menu),$param['type']);
            if($param['type'] == 1) {
                $permissions = $permissionsData;
                $dashboardGrid = [];
                return successTrans("success.data",compact('menu','permissions','dashboardGrid'));
            }
            return successTrans("success.data",$menu);
        } catch (\Throwable $throwable) {
            echo $throwable->getFile()."\n";
            echo $throwable->getLine()."\n";
            return error($throwable->getMessage());
        }
    }


    /**
     * 更新
     * @param Request $request
     * @return Response
     */
    #[Route(path: "save",methods: "post")]
    public function saveMenuData(Request $request): Response
    {
        try {
            $state = (new SystemMenu)->setAutoData($request->post());
            if(!$state) return errorTrans("error.data");
            return successTrans("success.data");
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }
}