package org.dromara.project.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
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.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.project.domain.BusProject;
import org.dromara.project.domain.BusUserProjectRelevancy;
import org.dromara.project.domain.req.project.ProjectCreateReq;
import org.dromara.project.domain.req.project.ProjectQueryReq;
import org.dromara.project.domain.req.project.ProjectUpdateReq;
import org.dromara.project.domain.vo.BusProjectVo;
import org.dromara.project.mapper.BusProjectMapper;
import org.dromara.project.service.IBusProjectService;
import org.dromara.project.service.IBusUserProjectRelevancyService;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

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

    @Resource
    private BusProjectMapper baseMapper;

    @Lazy
    @Resource
    private IBusUserProjectRelevancyService userProjectRelevancyService;

    /**
     * 查询项目
     *
     * @param id 主键
     * @return 项目
     */
    @Override
    public BusProjectVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

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

    /**
     * 查询符合条件的项目列表
     *
     * @param req 查询条件
     * @return 项目列表
     */
    @Override
    public List<BusProjectVo> queryList(ProjectQueryReq req) {
        LambdaQueryWrapper<BusProject> lqw = this.buildQuery(req);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 新增项目
     *
     * @param dto 项目
     * @return 新项目 id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertByBo(ProjectCreateReq dto) {
        // 将实体类和 DTO 进行转换
        BusProject project = new BusProject();
        BeanUtils.copyProperties(dto, project);
        // 数据校验
        validEntityBeforeSave(project, true);
        // 写入数据库
        boolean save = this.save(project);
        if (!save) {
            throw new ServiceException("新增项目失败，数据库异常", HttpStatus.ERROR);
        }
        Long projectId = project.getId();
        Long userId = LoginHelper.getUserId();
        // 同步保存用户与项目关联
        List<Long> userIdList = List.of(userId, SystemConstants.SUPER_ADMIN_ID);
        List<BusUserProjectRelevancy> userProjectRelevancyList = userIdList.stream().map(id -> {
            BusUserProjectRelevancy userProjectRelevancy = new BusUserProjectRelevancy();
            userProjectRelevancy.setUserId(id);
            userProjectRelevancy.setProjectId(projectId);
            return userProjectRelevancy;
        }).toList();
        boolean saveRelevancy = userProjectRelevancyService.saveBatch(userProjectRelevancyList);
        if (!saveRelevancy) {
            throw new ServiceException("新增用户与项目关联失败，数据库异常", HttpStatus.ERROR);
        }
        // 返回新写入的数据 projectId
        return projectId;
    }

    /**
     * 修改项目
     *
     * @param req 项目
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ProjectUpdateReq req) {
        // 将实体类和 DTO 进行转换
        BusProject project = new BusProject();
        BeanUtils.copyProperties(req, project);
        // 数据校验
        validEntityBeforeSave(project, false);
        // 权限校验
        validPermission(project);
        // 判断是否存在
        BusProject oldProject = this.getById(project.getId());
        if (oldProject == null) {
            throw new ServiceException("修改项目失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 操作数据库
        return this.updateById(project);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusProject entity, Boolean create) {
        // TODO 做一些数据校验,如唯一约束
        String projectName = entity.getProjectName();
        // 新增项目参数验证
        if (create) {
            if (StringUtils.isBlank(projectName)) {
                throw new ServiceException("项目名称不能为空", HttpStatus.BAD_REQUEST);
            }
        }
    }

    /**
     * 权限判断
     */
    private void validPermission(BusProject entity) {
        Long entityId = entity.getId();
        // 获取当前登录用户
        Long userId = LoginHelper.getUserId();
        // 判断是否存在项目与登录用户关联
        QueryWrapper<BusUserProjectRelevancy> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id", entityId);
        queryWrapper.eq("user_id", userId);
        if (userProjectRelevancyService.count(queryWrapper) <= 0) {
            throw new ServiceException("当前用户无权限操作", HttpStatus.FORBIDDEN);
        }
    }

    /**
     * 校验并批量删除项目信息
     *
     * @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);
        }
        // 删除项目
        boolean removeProjectList = this.removeBatchByIds(ids);
        if (!removeProjectList) {
            throw new ServiceException("删除项目失败，数据库异常", HttpStatus.ERROR);
        }
        // 删除用户与项目关联表
        QueryWrapper<BusUserProjectRelevancy> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.in("project_id", ids);
        boolean removeRelevancyList = userProjectRelevancyService.remove(queryWrapper);
        if (!removeRelevancyList) {
            throw new ServiceException("删除项目与用户关联失败，数据库异常", HttpStatus.ERROR);
        }
        return true;
    }

    /**
     * 获取项目视图对象
     *
     * @param project 项目对象
     * @return 项目视图对象
     */
    @Override
    public BusProjectVo getProjectVo(BusProject project) {
        if (project == null) {
            return null;
        }
        // 对象转封装类
        BusProjectVo projectVo = new BusProjectVo();
        BeanUtils.copyProperties(project, projectVo);
        return projectVo;
    }

    /**
     * 获取项目查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusProject> buildQuery(ProjectQueryReq req) {
        LambdaQueryWrapper<BusProject> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        // 从对象中取值
        Long id = req.getId();
        String projectName = req.getProjectName();
        String shortName = req.getShortName();
        Long pId = req.getPId();
        String status = req.getStatus();
        String remark = req.getRemark();
        String type = req.getType();
        String isType = req.getIsType();
        String projectSite = req.getProjectSite();
        String principal = req.getPrincipal();
        String principalPhone = req.getPrincipalPhone();
        String actual = req.getActual();
        String plan = req.getPlan();
        String onStreamTime = req.getOnStreamTime();
        String punchRange = req.getPunchRange();
        Long designTotal = req.getDesignTotal();
        String showHidden = req.getShowHidden();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(projectName), BusProject::getProjectName, projectName);
        lqw.like(StringUtils.isNotBlank(shortName), BusProject::getShortName, shortName);
        lqw.like(StringUtils.isNotBlank(remark), BusProject::getRemark, remark);
        lqw.like(StringUtils.isNotBlank(type), BusProject::getType, type);
        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.like(StringUtils.isNotBlank(actual), BusProject::getActual, actual);
        lqw.like(StringUtils.isNotBlank(plan), BusProject::getPlan, plan);
        lqw.like(StringUtils.isNotBlank(onStreamTime), BusProject::getOnStreamTime, onStreamTime);
        lqw.like(StringUtils.isNotBlank(punchRange), BusProject::getPunchRange, punchRange);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(pId), BusProject::getPId, pId);
        lqw.eq(ObjectUtils.isNotEmpty(status), BusProject::getStatus, status);
        lqw.eq(ObjectUtils.isNotEmpty(id), BusProject::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(isType), BusProject::getIsType, isType);
        lqw.eq(ObjectUtils.isNotEmpty(designTotal), BusProject::getDesignTotal, designTotal);
        lqw.eq(ObjectUtils.isNotEmpty(showHidden), BusProject::getShowHidden, showHidden);
        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;
        }
        // 对象列表 => 封装对象列表
        List<BusProjectVo> projectVoList = projectList.stream().map(this::getProjectVo).toList();
        projectVoPage.setRecords(projectVoList);
        return projectVoPage;
    }

    /**
     * 校验用户是否拥有操作项目的权限
     *
     * @param projectId 项目对象
     * @param userId    需要鉴权的用户id
     */
    @Override
    public void validAuth(Long projectId, Long userId) {
        QueryWrapper<BusUserProjectRelevancy> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id", projectId);
        queryWrapper.eq("user_id", userId);
        if (userProjectRelevancyService.count(queryWrapper) <= 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);
        }
    }

}
