package shop.alien.storeplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import shop.alien.entity.store.StorePlatformMenu;
import shop.alien.mapper.StorePlatformMenuMapper;
import shop.alien.storeplatform.service.StorePlatformMenuService;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 商家PC菜单权限表 服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class StorePlatformMenuServiceImpl extends ServiceImpl<StorePlatformMenuMapper, StorePlatformMenu> implements StorePlatformMenuService {

    private final StorePlatformMenuMapper storePlatformMenuMapper;

    @Override
    public IPage<StorePlatformMenu> getMenuPage(int page, int size, String menuName, String menuType, String status) {
        LambdaQueryWrapper<StorePlatformMenu> queryWrapper = new LambdaQueryWrapper<>();
        
        // 菜单名称模糊查询
        if (StringUtils.hasText(menuName)) {
            queryWrapper.like(StorePlatformMenu::getMenuName, menuName);
        }
        // 菜单类型查询
        if (StringUtils.hasText(menuType)) {
            queryWrapper.eq(StorePlatformMenu::getMenuType, menuType);
        }
        // 菜单状态查询
        if (StringUtils.hasText(status)) {
            queryWrapper.eq(StorePlatformMenu::getStatus, status);
        }
        
        // 按显示顺序和创建时间排序
        queryWrapper.orderByAsc(StorePlatformMenu::getMenuSort);
        queryWrapper.orderByDesc(StorePlatformMenu::getCreatedTime);

        return storePlatformMenuMapper.selectPage(new Page<>(page, size), queryWrapper);
    }

    @Override
    public StorePlatformMenu getMenuById(Long menuId) {
        return storePlatformMenuMapper.selectById(menuId);
    }

    @Override
    public boolean saveMenu(StorePlatformMenu menu) {
        // 校验必填字段
        if (!StringUtils.hasText(menu.getMenuName())) {
            log.error("菜单名称不能为空");
            return false;
        }
        if (!StringUtils.hasText(menu.getMenuType())) {
            log.error("菜单类型不能为空");
            return false;
        }
        // 设置默认值
        if (menu.getMenuSort() == null) {
            menu.setMenuSort(0);
        }
        if (menu.getParentId() == null) {
            menu.setParentId(0L);
        }
        // 自动计算菜单层级
        if (menu.getLevel() == null) {
            menu.setLevel(calculateMenuLevel(menu.getParentId()));
        }
        if (!StringUtils.hasText(menu.getStatus())) {
            menu.setStatus("0"); // 默认正常
        }
        if (!StringUtils.hasText(menu.getDelFlag())) {
            menu.setDelFlag("0"); // 默认未删除
        }
        if (!StringUtils.hasText(menu.getVisible())) {
            menu.setVisible("0"); // 默认显示
        }
        if (!StringUtils.hasText(menu.getIsFrame())) {
            menu.setIsFrame("1"); // 默认非外链
        }
        if (!StringUtils.hasText(menu.getIsCache())) {
            menu.setIsCache("0"); // 默认缓存
        }
        int result = storePlatformMenuMapper.insert(menu);
        return result > 0;
    }

    @Override
    public boolean updateMenu(StorePlatformMenu menu) {
        if (menu.getMenuId() == null) {
            log.error("菜单ID不能为空");
            return false;
        }

        int result = storePlatformMenuMapper.updateById(menu);
        return result > 0;
    }

    @Override
    public boolean deleteMenu(Long menuId) {
        // 逻辑删除
        LambdaUpdateWrapper<StorePlatformMenu> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(StorePlatformMenu::getMenuId, menuId);
        updateWrapper.set(StorePlatformMenu::getDelFlag, "2"); // 2代表删除
        
        int result = storePlatformMenuMapper.update(null, updateWrapper);
        return result > 0;
    }

    @Override
    public boolean updateStatus(Long menuId, String status) {
        if (menuId == null) {
            log.error("菜单ID不能为空");
            return false;
        }
        if (!StringUtils.hasText(status)) {
            log.error("菜单状态不能为空");
            return false;
        }
        
        LambdaUpdateWrapper<StorePlatformMenu> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(StorePlatformMenu::getMenuId, menuId);
        updateWrapper.set(StorePlatformMenu::getStatus, status);
        
        int result = storePlatformMenuMapper.update(null, updateWrapper);
        return result > 0;
    }

    @Override
    public List<StorePlatformMenu> getMenuTree() {
        // 查询所有未删除的菜单
        LambdaQueryWrapper<StorePlatformMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StorePlatformMenu::getDelFlag, "0");
        queryWrapper.eq(StorePlatformMenu::getStatus, "0"); // 正常状态
        queryWrapper.orderByAsc(StorePlatformMenu::getMenuSort);
        List<StorePlatformMenu> allMenus = storePlatformMenuMapper.selectList(queryWrapper);
        

        return buildMenuTree(allMenus, 0L);
    }

    @Override
    public List<StorePlatformMenu> getMenusByParentId(Long parentId) {
        LambdaQueryWrapper<StorePlatformMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StorePlatformMenu::getParentId, parentId);
        queryWrapper.eq(StorePlatformMenu::getDelFlag, "0");
        queryWrapper.eq(StorePlatformMenu::getStatus, "0");
        queryWrapper.orderByAsc(StorePlatformMenu::getMenuSort);
        
        return storePlatformMenuMapper.selectList(queryWrapper);
    }

    @Override
    public List<StorePlatformMenu> getMenusByLevel(Integer level) {
        LambdaQueryWrapper<StorePlatformMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StorePlatformMenu::getLevel, level);
        queryWrapper.eq(StorePlatformMenu::getDelFlag, "0");
        queryWrapper.eq(StorePlatformMenu::getStatus, "0");
        queryWrapper.orderByAsc(StorePlatformMenu::getMenuSort);
        
        return storePlatformMenuMapper.selectList(queryWrapper);
    }

    /**
     * 构建菜单树
     */
    private List<StorePlatformMenu> buildMenuTree(List<StorePlatformMenu> allMenus, Long parentId) {
        return allMenus.stream()
                .filter(menu -> parentId.equals(menu.getParentId()))
                .map(menu -> {
                    menu.setChildren(buildMenuTree(allMenus, menu.getMenuId()));
                    return menu;
                })
                .collect(Collectors.toList());
    }

    /**
     * 计算菜单层级
     * 根据父菜单ID计算当前菜单的层级
     *
     * @param parentId 父菜单ID
     * @return 菜单层级（1一级菜单 2二级菜单 3三级菜单）
     */
    private Integer calculateMenuLevel(Long parentId) {
        if (parentId == null || parentId == 0L) {
            return 1; // 一级菜单
        }
        // 查询父菜单的层级
        StorePlatformMenu parentMenu = storePlatformMenuMapper.selectById(parentId);
        if (parentMenu == null) {
            return 1; // 如果父菜单不存在，默认为一级菜单
        }
        // 父菜单层级 + 1
        Integer parentLevel = parentMenu.getLevel();
        if (parentLevel == null) {
            return 2; // 如果父菜单没有层级信息，默认为二级菜单
        }
        return parentLevel + 1;
    }
}
