<?php


namespace App\Http\Controllers\admin;

use App\Constants\HttpStatus;
use App\Http\Controllers\Controller;
use App\Services\BaseService;
use App\Services\MenuService;
use Exception;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

class Menu extends Controller
{


    /**
     * @api {get} /admin/menu 菜单列表
     * @apiGroup 菜单管理
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {int} [page=1]
     * @apiParam {int} [limit=10]
     * @apiParam {string} [title] 菜单名称
     * @apiParam {int} [parent_id] 上级菜单
     * @apiParam {int} [type] 类型 1-菜单 2-按钮
     * @apiSuccess (data) {Object} data
     * @apiSuccess (data) {int} data.total 数量
     * @apiSuccess (data) {Object[]} data.data 列表
     * @apiSuccess (data) {int} data.data.id
     * @apiSuccess (data) {int} data.data.parent_id 上级菜单
     * @apiSuccess (data) {string} data.data.title 菜单名称
     * @apiSuccess (data) {string} data.data.uri 路由地址
     * @apiSuccess (data) {int} data.data.sort 排序标识
     * @apiSuccess (data) {string} data.data.updated_at
     * @apiSuccess (data) {string} data.data.created_at
     */
    public function index()
    {
        try {
            request()->validate([
                'title' => ['nullable', 'string'],
                'permission_name' => ['nullable', 'string'],
            ]);
            $search = request()->all();
            $result = MenuService::paginate($search);
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::VALIDATION_FAILED, '', $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error(intval($e->getCode()));
        }
        return $this->success($result);
    }

    /**
     * @api {post} /admin/menu/submit 修改菜单
     * @apiGroup 菜单管理
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {int} id 菜单ID
     * @apiParam {string} title 菜单名称
     * @apiParam {string} [uri] 菜单链接地址/路由
     * @apiParam {string} [parent_id] 父级菜单ID
     * @apiParam {string} [sort] 排序值（越小越靠前）
     * @apiParam {string} [status] 状态 1-显示 2-隐藏
     * @apiParam {string} [type] 类型 1-菜单 2-按钮
     */
    public function store()
    {
        try {
            $id = request()->input('id');
            $validator = [
                'id' => ['nullable', 'integer', 'min:1'],
                'title' => 'required|string|max:100',
                'status' => 'required|nullable|integer',
                'icon' => 'nullable|string',
                'sort' => 'required|nullable|integer',
            ];
//            if (empty($id)) {
                $validator['parent_id'] = ['required', 'integer', 'min:0'];
                $validator['uri'] = ['required', 'string', 'max:200'];
                $validator['type'] = ['required', 'integer', 'in:1,2'];
//            }
            $params = request()->validate($validator);
            $ret = MenuService::submit($params);
            if ($ret['code'] == BaseService::NOT) {
                return $this->error($ret['code'], $ret['msg']);
            }
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error(intval($e->getCode()));
        }
        return $this->success([], $ret['msg']);
    }

    /**
     * @api {post} /admin/menu/delete 删除
     * @apiGroup 菜单管理
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {int} id 菜单ID
     */
    public function destroy()
    {
        return $this->error(HttpStatus::CUSTOM_ERROR, '禁止删除');
        $id = request()->post('id');
        // 示例：通过 ID 删除菜单
        $info = MenuService::findOne(['id' => $id]);
        if (!$info) {
            return $this->error(HttpStatus::CUSTOM_ERROR, '菜单不存在');
        }

        $info->delete();

        return $this->success([], '删除成功');
    }

    public function all(): JsonResponse
    {
        $result = \App\Models\Menu::query()->orderBy('status')
            ->orderBy('sort')->get()->toArray();
        $result = list_to_tree($result);
        return $this->success($result);
    }


    /**
     * @api {get} /admin/menu/mineMenu 我的菜单
     * @apiGroup 菜单管理
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiSuccess (data) {Object[]} data
     * @apiSuccess (data) {int} data.id 菜单ID
     * @apiSuccess (data) {int} data.parent_id 父级菜单ID
     * @apiSuccess (data) {string} data.title 菜单名称
     * @apiSuccess (data) {string} data.icon 菜单图标
     * @apiSuccess (data) {string} data.uri 菜单链接地址/路由
     * @apiSuccess (data) {string} data.type 类型 1-菜单 2-按钮
     * @apiSuccess (data) {string} data.status 状态 1-显示 2-隐藏
     * @apiSuccess (data) {int} data.sort 排序值（越小越靠前）
     * @apiSuccess (data) {array} data.children 下级菜单
     *
     */
    public function mineMenu()
    {
        $userId = request()->user->id;
        $type = request()->get('type', 1);
        $result = MenuService::getUserMenu($userId, $type);
        return $this->success($result);
    }

    /**
     * @api {get} /admin/menu/tree 菜单按钮树
     * @apiGroup 菜单管理
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiSuccess (data) {Object[]} data
     * @apiSuccess (data) {int} data.id 菜单ID
     * @apiSuccess (data) {int} data.parent_id 父级菜单ID
     * @apiSuccess (data) {string} data.title 菜单名称
     * @apiSuccess (data) {string} data.icon 菜单图标
     * @apiSuccess (data) {string} data.uri 菜单链接地址/路由
     * @apiSuccess (data) {string} data.type 类型 1-菜单 2-按钮
     * @apiSuccess (data) {string} data.status 状态 1-显示 2-隐藏
     * @apiSuccess (data) {int} data.sort 排序值（越小越靠前）
     * @apiSuccess (data) {array} data.children 下级菜单
     *
     */
    public function tree()
    {
        $result = MenuService::getTree();
        return $this->success($result);
    }

    /**
     * @api {post} /admin/menu/check 接口权限校验
     * @apiGroup 菜单管理
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {int} uri 接口地址 需要带admin 例子：admin/menu
     * @apiSuccess (data) {Object[]} data
     *
     */
    public function check()
    {
        $userId = request()->user->id;
        $uri = request()->post('uri', '');
        $result = MenuService::checkMenu($userId, $uri);
        if ($result) {
            return $this->success($result, '有权限访问');
        } else {
            return $this->error(99, '没有权限访问', $result);
        }
    }

}