package org.dromara.system.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.core.constant.HttpStatus;
import org.dromara.common.core.constant.SystemConstants;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.api.model.LoginUser;
import org.dromara.system.controller.constant.BusProjectConstant;
import org.dromara.system.domain.BusProject;
import org.dromara.system.domain.BusProjectFile;
import org.dromara.system.domain.BusProjectPunchrange;
import org.dromara.system.domain.BusUserProjectRelevancy;
import org.dromara.system.domain.bo.Punchrange;
import org.dromara.system.domain.dto.project.*;
import org.dromara.system.domain.vo.project.BusProjectGisVo;
import org.dromara.system.domain.vo.project.BusProjectSafetyDayVo;
import org.dromara.system.domain.vo.project.BusProjectVo;
import org.dromara.system.domain.vo.project.BusSubProjectVo;
import org.dromara.system.mapper.BusProjectMapper;
import org.dromara.system.service.IBusProjectFileService;
import org.dromara.system.service.IBusProjectPunchrangeService;
import org.dromara.system.service.IBusProjectService;
import org.dromara.system.service.IBusUserProjectRelevancyService;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static org.dromara.common.satoken.utils.LoginHelper.LOGIN_USER_KEY;

/**
 * 项目Service业务层处理
 *
 * @author lilemy
 * @date 2025-03-04
 */
@Slf4j
@Service
public class BusProjectServiceImpl extends ServiceImpl<BusProjectMapper, BusProject>
    implements IBusProjectService {

    @Lazy
    @Resource
    private IBusUserProjectRelevancyService userProjectRelevancyService;

    @Lazy
    @Resource
    private IBusProjectFileService projectFileService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IBusProjectPunchrangeService busProjectPunchrangeService;

    /**
     * 查询项目
     *
     * @param id 主键
     * @return 项目
     */
    @Override
    public BusProjectVo queryById(Long id) {
        BusProject project = this.getById(id);
        if (project == null) {
            throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
        }
        BusProjectVo vo = this.getVo(project);
        //成功获取项目信息过后，还需要获取打卡范围
        List<BusProjectPunchrange> punchrangeList = busProjectPunchrangeService.lambdaQuery()
            .eq(BusProjectPunchrange::getProjectId, id)
            .list();
        if (!punchrangeList.isEmpty()) {
            List<Punchrange> punchranges = BeanUtil.copyToList(punchrangeList, Punchrange.class);
            vo.setPunchrangeList(punchranges);
        }
        return vo;
    }

    /**
     * 分页查询项目列表
     *
     * @param req       查询条件
     * @param pageQuery 分页参数
     * @return 项目分页列表
     */
    @Override
    public TableDataInfo<BusProjectVo> queryPageList(BusProjectQueryReq req, PageQuery pageQuery) {
        LambdaQueryWrapper<BusProject> lqw = this.buildQueryWrapper(req);
        // 查询数据库
        Page<BusProject> result = this.page(pageQuery.build(), lqw);
        return TableDataInfo.build(this.getVoPage(result));
    }

    /**
     * 查询符合条件的项目列表
     *
     * @param req 查询条件
     * @return 项目列表
     */
    @Override
    public List<BusProjectVo> queryList(BusProjectQueryReq req) {
        LambdaQueryWrapper<BusProject> lqw = this.buildQueryWrapper(req);
        return this.list(lqw).stream().map(this::getVo).toList();
    }

    /**
     * 查询项目下的子项目列表
     *
     * @param id 父项目id
     * @return 项目下的子项目列表
     */
    @Override
    public List<BusSubProjectVo> querySubList(Long id) {
        BusProject project = this.getById(id);
        if (project == null) {
            throw new ServiceException("查询项目不存在", HttpStatus.NOT_FOUND);
        }
        List<BusProject> subProjectList = this.list(new LambdaQueryWrapper<BusProject>()
            .eq(BusProject::getParentId, id));
        return subProjectList.stream().map(subProject -> {
            BusSubProjectVo subProjectVo = new BusSubProjectVo();
            BeanUtils.copyProperties(subProject, subProjectVo);
            return subProjectVo;
        }).toList();
    }

    /**
     * 新增项目
     *
     * @param req 项目
     * @return 新项目 id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertByBo(BusProjectCreateReq req) {
        // 将实体类和 DTO 进行转换
        BusProject project = new BusProject();
        BeanUtils.copyProperties(req, project);
        String playCardStart = req.getPlayCardStart();
        String playCardEnd = req.getPlayCardEnd();
        String punchRange = playCardStart + "," + playCardEnd;
        project.setPunchRange(punchRange);
        // 数据校验
        validEntityBeforeSave(project, true);
        if (this.lambdaQuery().eq(BusProject::getProjectName, req.getProjectName()).count() > 0) {
            throw new ServiceException("项目名称已存在", HttpStatus.BAD_REQUEST);
        }
        if (this.lambdaQuery().eq(BusProject::getShortName, req.getShortName()).count() > 0) {
            throw new ServiceException("项目简称已存在", HttpStatus.BAD_REQUEST);
        }
        // 写入数据库
        boolean save = this.save(project);
        if (!save) {
            throw new ServiceException("新增项目失败，数据库异常", HttpStatus.ERROR);
        }
        Long projectId = project.getId();
        // 保存管理员与项目关联
        BusUserProjectRelevancy userProjectRelevancy = new BusUserProjectRelevancy();
        userProjectRelevancy.setUserId(SystemConstants.SUPER_ADMIN_ID);
        userProjectRelevancy.setProjectId(projectId);
        boolean saveRelevancy = userProjectRelevancyService.save(userProjectRelevancy);
        if (!saveRelevancy) {
            throw new ServiceException("新增用户与项目关联失败，数据库异常", HttpStatus.ERROR);
        }
        // 返回新写入的数据 projectId
        return projectId;
    }

    /**
     * 新增子项目
     *
     * @param dto 子项目
     * @return 子项目 id
     */
    @Override
    public Long insertSubByProject(BusProjectCreateSubReq dto) {
        String projectName = dto.getProjectName();
        Long parentId = dto.getParentId();
        if (StringUtils.isBlank(projectName)) {
            throw new ServiceException("子项目名称不能为空", HttpStatus.BAD_REQUEST);
        }
        BusProject project = this.getById(parentId);
        if (project == null) {
            throw new ServiceException("父项目不存在", HttpStatus.NOT_FOUND);
        }
        // 权限校验
        Long userId = LoginHelper.getUserId();
        validAuth(project.getId(), userId);
        BusProject subProject = new BusProject();
        subProject.setParentId(parentId);
        subProject.setProjectName(projectName);
        subProject.setProjectType(project.getProjectType());
        boolean save = this.save(subProject);
        if (!save) {
            throw new ServiceException("新增子项目失败，数据库异常", HttpStatus.ERROR);
        }
        Long subProjectId = subProject.getId();
        // 同步保存用户与项目关联
        Set<Long> userIdList = new HashSet<>(List.of(userId, SystemConstants.SUPER_ADMIN_ID));
        List<BusUserProjectRelevancy> userProjectRelevancyList = userIdList.stream().map(id -> {
            BusUserProjectRelevancy userProjectRelevancy = new BusUserProjectRelevancy();
            userProjectRelevancy.setUserId(id);
            userProjectRelevancy.setProjectId(subProjectId);
            return userProjectRelevancy;
        }).toList();
        boolean saveRelevancy = userProjectRelevancyService.saveBatch(userProjectRelevancyList);
        if (!saveRelevancy) {
            throw new ServiceException("新增用户与项目关联失败，数据库异常", HttpStatus.ERROR);
        }
        return subProjectId;
    }

    /**
     * 修改项目
     *
     * @param req 项目
     * @return 是否修改成功
     */
    @Override
    @Transactional
    public Boolean updateByBo(BusProjectUpdateReq req) {
        // 将实体类和 DTO 进行转换
        BusProject project = new BusProject();
        BeanUtils.copyProperties(req, project);
        String playCardStart = req.getPlayCardStart();
        String playCardEnd = req.getPlayCardEnd();
        if (StringUtils.isNotBlank(playCardStart) && StringUtils.isNotBlank(playCardEnd)) {
            String punchRange = playCardStart + "," + playCardEnd;
            project.setPunchRange(punchRange);
        }
        // 数据校验
        validEntityBeforeSave(project, false);
        // 权限校验
        Long userId = LoginHelper.getUserId();
        validAuth(project.getId(), userId);
        // 判断是否存在
        BusProject oldProject = this.getById(project.getId());
        if (oldProject == null) {
            throw new ServiceException("修改项目失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 判断名称是否重复
        if (req.getProjectName() != null && !req.getProjectName().equals(oldProject.getProjectName())) {
            Long count = this.lambdaQuery().eq(BusProject::getProjectName, req.getProjectName()).count();
            if (count > 0) {
                throw new ServiceException("项目名称重复", HttpStatus.BAD_REQUEST);
            }
        }
        // 操作数据库
        if (this.updateById(project)) {
            if (CollUtil.isNotEmpty(req.getPunchrangeList())) {
                //删除所有旧的范围
                busProjectPunchrangeService.remove(Wrappers.lambdaQuery(BusProjectPunchrange.class).eq(BusProjectPunchrange::getProjectId, project.getId()));
                //新增打卡范围
                List<BusProjectPunchrange> busProjectPunchranges = BeanUtil.copyToList(req.getPunchrangeList(), BusProjectPunchrange.class);
                if (!busProjectPunchrangeService.saveBatch(busProjectPunchranges)) {
                    throw new ServiceException("打卡范围增加失败", HttpStatus.ERROR);
                }
            }
            return true;
        }
        return false;
    }

    /**
     * 保存项目招标文件
     *
     * @param req 项目招标文件
     * @return 是否保存成功
     */
    @Override
    public Boolean saveTenderFile(BusProjectSaveTenderFileReq req) {
        BusProject project = this.getById(req.getId());
        if (project == null) {
            throw new ServiceException("保存项目招标文件失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        BusProject newProject = new BusProject();
        newProject.setId(project.getId());
        newProject.setTenderFiles(req.getTenderFiles());
        boolean b = this.updateById(newProject);
        if (!b) {
            throw new ServiceException("保存项目招标文件失败", HttpStatus.ERROR);
        }
        // todo 通知给各部⻔主任
        return true;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusProject entity, Boolean create) {
        // TODO 做一些数据校验,如唯一约束
        String projectName = entity.getProjectName();
        String principalPhone = entity.getPrincipalPhone();
        // 新增项目参数验证
        if (create) {
            if (StringUtils.isBlank(projectName)) {
                throw new ServiceException("项目名称不能为空", HttpStatus.BAD_REQUEST);
            }
            if (StringUtils.isBlank(principalPhone)) {
                throw new ServiceException("负责人电话不能为空", HttpStatus.BAD_REQUEST);
            }
        }
        if (StringUtils.isNotBlank(principalPhone) && !PhoneUtil.isPhone(principalPhone)) {
            throw new ServiceException("负责人手机号格式不正确", HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 校验并批量删除项目信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        Long userId = LoginHelper.getUserId();
        if (isValid) {
            // 做一些业务上的校验,判断是否需要校验
            this.validAuth(ids, userId);
            // 查看是否有子项目
            Long count = this.lambdaQuery()
                .in(BusProject::getParentId, ids)
                .count();
            if (count > 0) {
                throw new ServiceException("删除项目中存在子项目，请先删除子项目", HttpStatus.BAD_REQUEST);
            }
        }
        // 删除项目
        boolean removeProjectList = this.removeBatchByIds(ids);
        if (!removeProjectList) {
            throw new ServiceException("删除项目失败，数据库异常", HttpStatus.ERROR);
        }
        // 删除用户与项目关联表
        LambdaQueryWrapper<BusUserProjectRelevancy> lqw = new LambdaQueryWrapper<>();
        lqw.in(BusUserProjectRelevancy::getProjectId, ids);
        boolean removeRelevancyList = userProjectRelevancyService.remove(lqw);
        if (!removeRelevancyList) {
            throw new ServiceException("删除项目与用户关联失败，数据库异常", HttpStatus.ERROR);
        }
        return true;
    }

    /**
     * 获取项目视图对象
     *
     * @param project 项目对象
     * @return 项目视图对象
     */
    @Override
    public BusProjectVo getVo(BusProject project) {
        if (project == null) {
            return null;
        }
        // 对象转封装类
        BusProjectVo projectVo = new BusProjectVo();
        BeanUtils.copyProperties(project, projectVo);
        String punchRange = project.getPunchRange();
        if (StringUtils.isNotBlank(punchRange)) {
            String[] split = punchRange.split(",");
            projectVo.setPlayCardStart(split[0]);
            projectVo.setPlayCardEnd(split[1]);
        }
        // 关联子项目列表
        List<BusProject> subProjectList = this.lambdaQuery()
            .select(BusProject::getId, BusProject::getProjectName, BusProject::getCreateTime)
            .eq(BusProject::getParentId, project.getId())
            .list();
        if (CollUtil.isNotEmpty(subProjectList)) {
            List<Long> subIdList = subProjectList.stream().map(BusProject::getId).toList();
            // 关联设计id
            List<BusProjectFile> projectFileList = projectFileService.lambdaQuery()
                .in(BusProjectFile::getProjectId, subIdList)
                .list();
            Map<Long, List<BusProjectFile>> map = projectFileList.stream().collect(Collectors.groupingBy(BusProjectFile::getProjectId));
            List<BusSubProjectVo> subProjectVoList = subProjectList.stream().map(subProject -> {
                BusSubProjectVo subProjectVo = new BusSubProjectVo();
                BeanUtils.copyProperties(subProject, subProjectVo);
                Long id = subProject.getId();
                if (map.containsKey(id)) {
                    subProjectVo.setDesignId(map.get(id).getFirst().getId());
                }
                return subProjectVo;
            }).toList();
            projectVo.setChildren(subProjectVoList);
        }
        return projectVo;
    }

    /**
     * 获取项目查询条件封装（不查询子项目）
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusProject> buildQueryWrapper(BusProjectQueryReq req) {
        LambdaQueryWrapper<BusProject> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        // 从对象中取值
        String projectName = req.getProjectName();
        String shortName = req.getShortName();
        Long parentId = req.getParentId();
        String status = req.getStatus();
        String projectType = req.getProjectType();
        String projectCategory = req.getProjectStage();
        String projectSite = req.getProjectSite();
        String principal = req.getPrincipal();
        String principalPhone = req.getPrincipalPhone();
        String showHidden = req.getShowHidden();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(projectName), BusProject::getProjectName, projectName);
        lqw.like(StringUtils.isNotBlank(shortName), BusProject::getShortName, shortName);
        lqw.like(StringUtils.isNotBlank(projectSite), BusProject::getProjectSite, projectSite);
        lqw.like(StringUtils.isNotBlank(principal), BusProject::getPrincipal, principal);
        lqw.like(StringUtils.isNotBlank(principalPhone), BusProject::getPrincipalPhone, principalPhone);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(status), BusProject::getStatus, status);
        lqw.eq(ObjectUtils.isNotEmpty(projectType), BusProject::getProjectType, projectType);
        lqw.eq(ObjectUtils.isNotEmpty(projectCategory), BusProject::getProjectStage, projectCategory);
        lqw.eq(ObjectUtils.isNotEmpty(showHidden), BusProject::getShowHidden, showHidden);
        if (ObjectUtils.isNotEmpty(parentId)) {
            lqw.eq(BusProject::getParentId, parentId);
        } else {
            // 不查询子项目
            final Long PID = 0L;
            lqw.eq(BusProject::getParentId, PID);
        }
        // 排序
        lqw.orderByAsc(BusProject::getSort);
        return lqw;
    }


    @Override
    public Page<BusProjectVo> getVoPage(Page<BusProject> projectPage) {
        List<BusProject> projectList = projectPage.getRecords();
        Page<BusProjectVo> projectVoPage = new Page<>(projectPage.getCurrent(), projectPage.getSize(), projectPage.getTotal());
        if (CollUtil.isEmpty(projectList)) {
            return projectVoPage;
        }
        // 获取项目文件id
        Set<Long> projectIdList = projectList.stream().map(BusProject::getId).collect(Collectors.toSet());
        // 获取子项目列表
        List<BusProject> subProjectList = this.lambdaQuery()
            .select(BusProject::getId, BusProject::getParentId, BusProject::getProjectName, BusProject::getCreateTime)
            .in(BusProject::getParentId, projectIdList)
            .list();
        Set<Long> subIdList = subProjectList.stream().map(BusProject::getId).collect(Collectors.toSet());
        Map<Long, List<BusProject>> subProjectMap = subProjectList.stream().collect(Collectors.groupingBy(BusProject::getParentId));
        Map<Long, List<BusProjectFile>> projectFileMap = projectFileService.lambdaQuery()
            .in(CollUtil.isNotEmpty(subIdList), BusProjectFile::getProjectId, subIdList).list()
            .stream().collect(Collectors.groupingBy(BusProjectFile::getProjectId));

        // 对象列表 => 封装对象列表
        List<BusProjectVo> projectVoList = projectList.stream().map(project -> {
            // 对象转封装类
            BusProjectVo projectVo = new BusProjectVo();
            BeanUtils.copyProperties(project, projectVo);
            String punchRange = project.getPunchRange();
            if (StringUtils.isNotBlank(punchRange)) {
                String[] split = punchRange.split(",");
                projectVo.setPlayCardStart(split[0]);
                projectVo.setPlayCardEnd(split[1]);
            }
            // 关联子项目
            List<BusSubProjectVo> subProjectVoList = new ArrayList<>();
            if (subProjectMap.containsKey(project.getId())) {
                subProjectVoList = subProjectMap.get(project.getId()).stream().map(subProject -> {
                    BusSubProjectVo subProjectVo = new BusSubProjectVo();
                    BeanUtils.copyProperties(subProject, subProjectVo);
                    Long id = subProject.getId();
                    // 关联设计id
                    if (projectFileMap.containsKey(id)) {
                        subProjectVo.setDesignId(projectFileMap.get(id).getFirst().getId());
                    }
                    return subProjectVo;
                }).toList();
            }
            projectVo.setChildren(subProjectVoList);
            return projectVo;
        }).toList();
        projectVoPage.setRecords(projectVoList);
        return projectVoPage;
    }

    /**
     * 校验用户是否拥有操作项目的权限
     *
     * @param projectId 项目对象
     * @param userId    需要鉴权的用户id
     */
    @Override
    public void validAuth(Long projectId, Long userId) {
        LambdaQueryWrapper<BusUserProjectRelevancy> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BusUserProjectRelevancy::getProjectId, projectId);
        lqw.eq(BusUserProjectRelevancy::getUserId, userId);
        if (userProjectRelevancyService.count(lqw) <= 0) {
            throw new ServiceException("当前用户无该项目权限操作", HttpStatus.FORBIDDEN);
        }
    }

    /**
     * 校验用户是否拥有操作项目的权限
     *
     * @param projectIdList 项目id列表
     * @param userId        需要鉴权的用户id
     */
    @Override
    public void validAuth(Collection<Long> projectIdList, Long userId) {
        // 查询关联表，返回和用户关联的项目ID列表
        Set<Long> collect = userProjectRelevancyService.listObjs(
            new LambdaQueryWrapper<BusUserProjectRelevancy>()
                .select(BusUserProjectRelevancy::getProjectId)
                .in(BusUserProjectRelevancy::getProjectId, projectIdList)
                .eq(BusUserProjectRelevancy::getUserId, userId)
                .groupBy(BusUserProjectRelevancy::getProjectId)
        ).stream().map(obj -> (Long) obj).collect(Collectors.toSet());
        // 找出没有关联数据的项目ID
        List<Long> invalidIds = projectIdList.stream()
            .filter(id -> !collect.contains(id))
            .toList();
        if (!invalidIds.isEmpty()) {
            throw new ServiceException("操作失败，项目编号为：" + invalidIds + "，没有操作权限", HttpStatus.FORBIDDEN);
        }
    }

    /**
     * 获取项目安全天数
     *
     * @param id 项目id
     * @return 安全天数
     */
    @Override
    public BusProjectSafetyDayVo getSafetyDay(Long id) {
        // 构建缓存 key
        String cacheKey = String.format("%s:%s", BusProjectConstant.PROJECT_SAFETY_DAYS_REDIS_KEY_PREFIX, id);
        // 查询分布式缓存（Redis）
        ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();
        String cachedValue = valueOps.get(cacheKey);
        if (cachedValue != null) {
            // 如果命中Redis，返回结果
            return JSONUtil.toBean(cachedValue, BusProjectSafetyDayVo.class);
        }
        BusProject project = this.getById(id);
        if (project == null) {
            throw new ServiceException("项目信息不存在", HttpStatus.NOT_FOUND);
        }
        long days = DateUtils.difference(project.getCreateTime(), new Date(), TimeUnit.DAYS);
        BusProjectSafetyDayVo safetyDayVo = new BusProjectSafetyDayVo();
        safetyDayVo.setSafetyDay(days);
        // 更新缓存
        String cacheValue = JSONUtil.toJsonStr(safetyDayVo);
        // 更新 Redis 缓存
        int cacheExpireTime = 12;
        valueOps.set(cacheKey, cacheValue, cacheExpireTime, TimeUnit.HOURS);
        // 返回结果
        return safetyDayVo;
    }

    /**
     * 获取项目地址信息
     *
     * @return 项目地址信息列表
     */
    @Override
    public List<BusProjectGisVo> getGisList() {
        // 查询所有的顶级项目
        List<BusProject> projects = this.lambdaQuery()
            .eq(BusProject::getParentId, BusProjectConstant.PARENT_ID)
            .eq(BusProject::getStatus, "0")
            .list();
        return projects.stream().map(project -> {
            BusProjectGisVo vo = new BusProjectGisVo();
            BeanUtils.copyProperties(project, vo);
            return vo;
        }).toList();
    }

    /**
     * 改变项目所属用户
     *
     * @param id 项目id
     * @return 是否成功
     */
    @Override
    public Boolean changeUserProject(Long id) {
        // 将用户选择项目设置到缓存中
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser != null) {
            loginUser.setProjectId(id);
            StpUtil.getTokenSession().set(LOGIN_USER_KEY, loginUser);
            return true;
        }
        return false;
    }

    @Override
    public BusProjectVo selectById(Long projectId) {
        return baseMapper.selectVoById(projectId);
    }

    @Override
    public List<BusProjectVo> selectProjectVoList() {
        return baseMapper.selectVoList();
    }

    /**
     * 通过项目ID查询项目名称
     *
     * @param projectId 项目ID
     * @return 项目名称
     */
    @Cacheable(cacheNames = CacheNames.PROJECT_NAME, key = "#projectId")
    @Override
    public String getProjectNameById(Long projectId) {
        if (projectId == 0) {
            return null;
        }
        BusProject project = this.lambdaQuery()
            .select(BusProject::getProjectName)
            .eq(BusProject::getId, projectId)
            .one();
        return project != null ? project.getProjectName() : null;
    }
}
