package org.dromara.project.service.impl;

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 org.dromara.common.core.constant.HttpStatus;
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.BusConstructionBlacklist;
import org.dromara.project.domain.BusConstructionUser;
import org.dromara.project.domain.BusProjectTeamMember;
import org.dromara.project.domain.dto.constructionblacklist.BusConstructionBlacklistCreateReq;
import org.dromara.project.domain.dto.constructionblacklist.BusConstructionBlacklistQueryReq;
import org.dromara.project.domain.vo.constructionblacklist.BusConstructionBlacklistVo;
import org.dromara.project.mapper.BusConstructionBlacklistMapper;
import org.dromara.project.service.IBusConstructionBlacklistService;
import org.dromara.project.service.IBusConstructionUserService;
import org.dromara.project.service.IBusProjectService;
import org.dromara.project.service.IBusProjectTeamMemberService;
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;

/**
 * 黑名单Service业务层处理
 *
 * @author lcj
 * @date 2025-03-27
 */
@Service
public class BusConstructionBlacklistServiceImpl extends ServiceImpl<BusConstructionBlacklistMapper, BusConstructionBlacklist>
    implements IBusConstructionBlacklistService {

    @Resource
    private IBusProjectService projectService;

    @Resource
    private IBusConstructionUserService constructionUserService;

    @Lazy
    @Resource
    private IBusProjectTeamMemberService projectTeamMemberService;

    /**
     * 查询黑名单
     *
     * @param id 主键
     * @return 黑名单
     */
    @Override
    public BusConstructionBlacklistVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询黑名单列表
     *
     * @param req       查询条件
     * @param pageQuery 分页参数
     * @return 黑名单分页列表
     */
    @Override
    public TableDataInfo<BusConstructionBlacklistVo> queryPageList(BusConstructionBlacklistQueryReq req, PageQuery pageQuery) {
        LambdaQueryWrapper<BusConstructionBlacklist> lqw = buildQueryWrapper(req);
        Page<BusConstructionBlacklistVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的黑名单列表
     *
     * @param req 查询条件
     * @return 黑名单列表
     */
    @Override
    public List<BusConstructionBlacklistVo> queryList(BusConstructionBlacklistQueryReq req) {
        LambdaQueryWrapper<BusConstructionBlacklist> lqw = buildQueryWrapper(req);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据项目id查询黑名单用户id列表
     *
     * @param projectId 项目id
     * @return 黑名单用户id列表
     */
    @Override
    public List<Long> queryIdListByProjectId(Long projectId) {
        LambdaQueryWrapper<BusConstructionBlacklist> lqw = Wrappers.lambdaQuery(BusConstructionBlacklist.class)
            .select(BusConstructionBlacklist::getUserId)
            .eq(projectId != null, BusConstructionBlacklist::getProjectId, projectId);
        return this.listObjs(lqw, obj -> (Long) obj);
    }

    /**
     * 新增黑名单
     *
     * @param req 黑名单
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertByBo(BusConstructionBlacklistCreateReq req) {
        // 将实体类和 DTO 进行转换
        BusConstructionBlacklist constructionBlacklist = new BusConstructionBlacklist();
        BeanUtils.copyProperties(req, constructionBlacklist);
        // 数据校验
        validEntityBeforeSave(constructionBlacklist);
        // 填充默认值
        Long userId = req.getUserId();
        if (userId == null) {
            throw new ServiceException("用户 id 不能为空", HttpStatus.BAD_REQUEST);
        }
        BusConstructionUser constructionUser = constructionUserService.getById(userId);
        if (constructionUser == null) {
            throw new ServiceException("对应用户不存在", HttpStatus.NOT_FOUND);
        }
        constructionBlacklist.setUserName(constructionUser.getUserName());
        constructionBlacklist.setSfzNumber(constructionUser.getSfzNumber());
        // 操作数据库
        boolean result = this.save(constructionBlacklist);
        if (!result) {
            throw new ServiceException("新增黑名单失败，数据库异常", HttpStatus.ERROR);
        }
        return constructionBlacklist.getId();
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusConstructionBlacklist entity) {
        // TODO 做一些数据校验,如唯一约束
        Long projectId = entity.getProjectId();
        Long userId = entity.getUserId();
        if (projectId == null) {
            throw new ServiceException("项目 id 不能为空", HttpStatus.BAD_REQUEST);
        }
        if (projectService.getById(projectId) == null) {
            throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
        }
        // 判断用户是否退场
        Long count = projectTeamMemberService.lambdaQuery()
            .eq(BusProjectTeamMember::getProjectId, projectId)
            .eq(BusProjectTeamMember::getMemberId, userId)
            .count();
        if (count > 0) {
            throw new ServiceException("请将施工人员退场后，再加入黑名单", HttpStatus.BAD_REQUEST);
        }
        // 判断是否已经存在该用户
        this.validUserInBlacklist(userId, projectId);
    }

    /**
     * 校验并批量删除黑名单信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        Long userId = LoginHelper.getUserId();
        List<BusConstructionBlacklist> constructionBlacklistList = this.listByIds(ids);
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
            List<Long> projectId = constructionBlacklistList.stream().map(BusConstructionBlacklist::getProjectId).toList();
            projectService.validAuth(projectId, userId);
        }
        return this.removeBatchByIds(ids);
    }

    /**
     * 校验用户是否在黑名单中
     *
     * @param userId    用户id
     * @param projectId 项目id
     */
    @Override
    public void validUserInBlacklist(Long userId, Long projectId) {
        LambdaQueryWrapper<BusConstructionBlacklist> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BusConstructionBlacklist::getUserId, userId)
            .eq(BusConstructionBlacklist::getProjectId, projectId);
        if (this.count(lqw) > 0) {
            throw new ServiceException("用户已存在黑名单中", HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 获取黑名单查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusConstructionBlacklist> buildQueryWrapper(BusConstructionBlacklistQueryReq req) {
        LambdaQueryWrapper<BusConstructionBlacklist> lqw = new LambdaQueryWrapper<>();
        Long id = req.getId();
        Long userId = req.getUserId();
        Long projectId = req.getProjectId();
        String userName = req.getUserName();
        String sfzNumber = req.getSfzNumber();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(userName), BusConstructionBlacklist::getUserName, userName);
        lqw.like(StringUtils.isNotBlank(sfzNumber), BusConstructionBlacklist::getSfzNumber, sfzNumber);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(id), BusConstructionBlacklist::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(userId), BusConstructionBlacklist::getUserId, userId);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), BusConstructionBlacklist::getProjectId, projectId);
        return lqw;
    }
}
