package com.njcn.rdms.module.system.controller.admin.permission;

import cn.hutool.core.util.StrUtil;
import com.njcn.rdms.framework.common.enums.CommonStatusEnum;
import com.njcn.rdms.framework.common.pojo.CommonResult;
import com.njcn.rdms.framework.common.util.validation.ValidationUtils;
import com.njcn.rdms.framework.common.util.object.BeanUtils;
import com.njcn.rdms.module.system.controller.admin.permission.vo.menu.MenuListReqVO;
import com.njcn.rdms.module.system.controller.admin.permission.vo.menu.MenuRespVO;
import com.njcn.rdms.module.system.controller.admin.permission.vo.menu.MenuSaveVO;
import com.njcn.rdms.module.system.controller.admin.permission.vo.menu.MenuSimpleRespVO;
import com.njcn.rdms.module.system.dal.dataobject.permission.MenuDO;
import com.njcn.rdms.module.system.enums.permission.PermissionScopeTypeEnum;
import com.njcn.rdms.module.system.service.permission.MenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.List;

import static com.njcn.rdms.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 菜单")
@RestController
@RequestMapping("/system/menu")
@Validated
public class MenuController {

    private static final String GLOBAL_SCOPE_TYPE = PermissionScopeTypeEnum.GLOBAL.getScopeType();
    private static final String OBJECT_SCOPE_TYPE = PermissionScopeTypeEnum.OBJECT.getScopeType();
    private static final String GLOBAL_OBJECT_TYPE = PermissionScopeTypeEnum.GLOBAL_OBJECT_TYPE;

    @Resource
    private MenuService menuService;

    @PostMapping("/create")
    @Operation(summary = "创建菜单")
    @PreAuthorize("@ss.hasPermission('system:menu:create')")
    public CommonResult<Long> createMenu(@Valid @RequestBody MenuSaveVO createReqVO) {
        Long menuId = menuService.createMenu(normalizeScopeReqVO(createReqVO));
        return success(menuId);
    }

    @PutMapping("/update")
    @Operation(summary = "修改菜单")
    @PreAuthorize("@ss.hasPermission('system:menu:update')")
    public CommonResult<Boolean> updateMenu(@Valid @RequestBody MenuSaveVO updateReqVO) {
        menuService.updateMenu(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除菜单")
    @Parameter(name = "id", description = "菜单编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:menu:delete')")
    public CommonResult<Boolean> deleteMenu(@RequestParam("id") Long id) {
        menuService.deleteMenu(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Operation(summary = "批量删除菜单")
    @Parameter(name = "ids", description = "编号列表", required = true)
    @PreAuthorize("@ss.hasPermission('system:menu:delete')")
    public CommonResult<Boolean> deleteMenuList(@RequestParam("ids") List<Long> ids) {
        menuService.deleteMenuList(ids);
        return success(true);
    }

    @GetMapping("/list")
    @Operation(summary = "获取菜单列表", description = "用于【菜单管理】界面")
    @PreAuthorize("@ss.hasPermission('system:menu:query')")
    public CommonResult<List<MenuRespVO>> getMenuList(MenuListReqVO reqVO) {
        MenuListReqVO effectiveReqVO = normalizeScopeReqVO(reqVO);
        List<MenuDO> list = menuService.getMenuList(effectiveReqVO,
                effectiveReqVO.getScopeType(), effectiveReqVO.getObjectType());
        list.sort(Comparator.comparing(MenuDO::getSort));
        return success(BeanUtils.toBean(list, MenuRespVO.class));
    }

    @GetMapping("/simple-list")
    @Operation(summary = "获取菜单精简信息列表", description = "只包含已启用的菜单，用于【角色分配菜单】功能的选项")
    public CommonResult<List<MenuSimpleRespVO>> getSimpleMenuList(MenuListReqVO reqVO) {
        MenuListReqVO effectiveReqVO = normalizeScopeReqVO(reqVO);
        effectiveReqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
        List<MenuDO> list = menuService.getMenuList(effectiveReqVO,
                effectiveReqVO.getScopeType(), effectiveReqVO.getObjectType());
        list = menuService.filterDisableMenus(list);
        list.sort(Comparator.comparing(MenuDO::getSort));
        return success(BeanUtils.toBean(list, MenuSimpleRespVO.class));
    }

    @GetMapping("/get")
    @Operation(summary = "获取菜单信息")
    @PreAuthorize("@ss.hasPermission('system:menu:query')")
    public CommonResult<MenuRespVO> getMenu(Long id) {
        MenuDO menu = menuService.getMenu(id);
        return success(BeanUtils.toBean(menu, MenuRespVO.class));
    }

    private MenuListReqVO normalizeScopeReqVO(MenuListReqVO reqVO) {
        MenuListReqVO effectiveReqVO = reqVO == null ? new MenuListReqVO() : reqVO;
        String scopeType = normalizeScopeType(effectiveReqVO.getScopeType());
        effectiveReqVO.setScopeType(scopeType);
        effectiveReqVO.setObjectType(normalizeObjectType(scopeType, effectiveReqVO.getObjectType()));
        ValidationUtils.validate(effectiveReqVO);
        return effectiveReqVO;
    }

    private MenuSaveVO normalizeScopeReqVO(MenuSaveVO reqVO) {
        MenuSaveVO effectiveReqVO = reqVO == null ? new MenuSaveVO() : reqVO;
        String scopeType = normalizeScopeType(effectiveReqVO.getScopeType());
        effectiveReqVO.setScopeType(scopeType);
        effectiveReqVO.setObjectType(normalizeObjectType(scopeType, effectiveReqVO.getObjectType()));
        ValidationUtils.validate(effectiveReqVO);
        return effectiveReqVO;
    }

    private String normalizeScopeType(String scopeType) {
        return StrUtil.blankToDefault(StrUtil.trim(scopeType), GLOBAL_SCOPE_TYPE);
    }

    private String normalizeObjectType(String scopeType, String objectType) {
        return OBJECT_SCOPE_TYPE.equals(scopeType) ? StrUtil.trim(objectType) : GLOBAL_OBJECT_TYPE;
    }

}
