package com.cool.store.service.menu.impl;

import cn.hutool.core.collection.CollStreamUtil;
import com.cool.store.context.PartnerUserHolder;
import com.cool.store.dao.EnterpriseUserDAO;
import com.cool.store.dao.SysRoleDao;
import com.cool.store.dao.menu.MiniMenuConfigDAO;
import com.cool.store.dao.menu.MiniMenuDAO;
import com.cool.store.entity.EnterpriseUserDO;
import com.cool.store.entity.SysRoleDO;
import com.cool.store.entity.menu.MiniMenuConfigDO;
import com.cool.store.entity.menu.MiniMenuDO;
import com.cool.store.enums.AIEnum;
import com.cool.store.enums.Role;
import com.cool.store.service.menu.MiniMenuService;
import com.cool.store.utils.BeanUtil;
import com.cool.store.vo.PartnerUserInfoVO;
import com.cool.store.vo.menu.MiniMenuConfigVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

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


/**
 * <p>
 * 小程序菜单配置 服务实现类
 * </p>
 *
 * @author wangff
 * @since 2025/10/31
 */
@Service
@RequiredArgsConstructor
public class MiniMenuServiceImpl implements MiniMenuService {
    private final MiniMenuConfigDAO miniMenuConfigDAO;
    private final SysRoleDao sysRoleDao;
    private final EnterpriseUserDAO enterpriseUserDAO;
    private final MiniMenuDAO miniMenuDAO;


    @Override
    public List<MiniMenuConfigVO> getUserMiniMenu() {
        PartnerUserInfoVO user = PartnerUserHolder.getUser();
        if (StringUtils.isBlank(user.getMobile())) {
            return Collections.emptyList();
        }
        SysRoleDO highestRole = getHighestRoleByMobile(user.getMobile());
        if (Objects.isNull(highestRole)) {
            return Collections.emptyList();
        }
        List<MiniMenuConfigDO> list = miniMenuConfigDAO.getListByRoleId(highestRole.getId());
        List<Long> menuIds = CollStreamUtil.toList(list, MiniMenuConfigDO::getMenuId);
        List<MiniMenuDO> menuList = miniMenuDAO.getByIds(menuIds);
        return BeanUtil.toList(menuList, MiniMenuConfigVO.class);
    }

    /**
     * 根据手机号查询用户优先级最高的角色
     * @param mobile 手机号
     * @return 角色信息
     */
    private SysRoleDO getHighestRoleByMobile(String mobile) {
        if (StringUtils.isBlank(mobile)) {
            return null;
        }
        EnterpriseUserDO userDO = enterpriseUserDAO.selectByMobile(mobile);
        if (Objects.isNull(userDO)) {
            return null;
        }
        return getHighestRole(userDO.getUserId());
    }

    /**
     * 查询当前用户优先级最高的角色
     * @param userId 用户id
     * @return 角色信息
     */
    private SysRoleDO getHighestRole(String userId) {
        if(AIEnum.AI_USERID.getCode().equals(userId)){
            return sysRoleDao.getRoleByRoleEnum(Role.MASTER.getRoleEnum());
        }
        return sysRoleDao.getHighestPrioritySysRoleDoByUserId(userId);
    }
}
