package com.usky.system.service.impl;

import com.usky.common.core.exception.BusinessException;
import com.usky.system.domain.SysMenu;
import com.usky.system.mapper.SysMenuCascadeMapper;
import com.usky.system.mapper.SysMenuMapper;
import com.usky.system.service.SysMenuCascadeService;
import com.usky.system.service.vo.MenuBindingsResult;
import com.usky.system.service.vo.MenuUnbindRequest;
import com.usky.system.service.vo.MenuUnbindResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

/**
 * 菜单绑定查询 / 解绑实现
 */
@Service
public class SysMenuCascadeServiceImpl implements SysMenuCascadeService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private SysMenuCascadeMapper sysMenuCascadeMapper;

    @Override
    public MenuBindingsResult getMenuBindings(Long menuId) {
        if (menuId == null) {
            throw new BusinessException("lack necessary param:menuId is required!");
        }
        SysMenu menu = sysMenuMapper.selectMenuById(menuId);
        if (menu == null) {
            throw new BusinessException("菜单不存在，menuId=" + menuId);
        }

        MenuBindingsResult result = new MenuBindingsResult();
        result.setMenuId(menu.getMenuId());
        result.setMenuName(menu.getMenuName());
        result.setPath(menu.getPath());

        List<MenuBindingsResult.ChildMenuItem> childMenus = sysMenuCascadeMapper.selectChildMenus(menuId);
        if (childMenus == null) {
            childMenus = Collections.emptyList();
        }
        result.setChildMenus(childMenus);
        result.setChildMenuCount(childMenus.size());

        List<MenuBindingsResult.RoleBindItem> roleBinds = sysMenuCascadeMapper.selectRoleBinds(menuId);
        if (roleBinds == null) {
            roleBinds = Collections.emptyList();
        }
        result.setRoleBinds(roleBinds);
        result.setRoleBindCount(roleBinds.size());

        List<MenuBindingsResult.TenantBindItem> tenantBinds = sysMenuCascadeMapper.selectTenantBinds(menuId);
        if (tenantBinds == null) {
            tenantBinds = Collections.emptyList();
        }
        result.setTenantBinds(tenantBinds);
        result.setTenantBindCount(tenantBinds.size());

        List<MenuBindingsResult.PlatformBindItem> platformBinds = sysMenuCascadeMapper.selectPlatformBinds(menuId);
        if (platformBinds == null) {
            platformBinds = Collections.emptyList();
        }
        result.setPlatformBinds(platformBinds);
        result.setPlatformBindCount(platformBinds.size());

        List<MenuBindingsResult.HceCategoryBindItem> hceCategories = sysMenuCascadeMapper.selectHceCategoryBinds(menuId);
        if (hceCategories == null) {
            hceCategories = Collections.emptyList();
        }
        result.setHceCategories(hceCategories);
        result.setHceCategoryCount(hceCategories.size());

        result.setHasBinding(
                result.getChildMenuCount() > 0
                        || result.getRoleBindCount() > 0
                        || result.getTenantBindCount() > 0
                        || result.getPlatformBindCount() > 0
                        || result.getHceCategoryCount() > 0
        );
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MenuUnbindResult unbindMenu(MenuUnbindRequest request) {
        if (request == null || request.getMenuId() == null) {
            throw new BusinessException("lack necessary param:menuId is required!");
        }
        boolean hasRole = !CollectionUtils.isEmpty(request.getRoleIds());
        boolean hasTenant = !CollectionUtils.isEmpty(request.getTenantIds());
        boolean hasPlatform = !CollectionUtils.isEmpty(request.getPlatformIds());
        if (!hasRole && !hasTenant && !hasPlatform) {
            throw new BusinessException("请指定要解绑的 roleIds / tenantIds / platformIds，禁止整菜单全量解绑");
        }

        SysMenu menu = sysMenuMapper.selectMenuById(request.getMenuId());
        if (menu == null) {
            throw new BusinessException("菜单不存在，menuId=" + request.getMenuId());
        }

        MenuUnbindResult result = new MenuUnbindResult();
        result.setMenuId(menu.getMenuId());
        result.setMenuName(menu.getMenuName());

        // 解绑顺序：角色 → 租户 → 应用(平台)
        if (hasRole) {
            result.setRoleUnbindCount(Math.max(
                    sysMenuCascadeMapper.deleteRoleMenuByMenuIdAndRoleIds(request.getMenuId(), request.getRoleIds()), 0));
        }
        if (hasTenant) {
            result.setTenantUnbindCount(Math.max(
                    sysMenuCascadeMapper.deleteTenantMenuByMenuIdAndTenantIds(request.getMenuId(), request.getTenantIds()), 0));
        }
        if (hasPlatform) {
            result.setPlatformUnbindCount(Math.max(
                    sysMenuCascadeMapper.deletePlatformMenuByMenuIdAndPlatformIds(request.getMenuId(), request.getPlatformIds()), 0));
        }
        return result;
    }
}
