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.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.BusConstructionUser;
import org.dromara.project.domain.BusProjectTeam;
import org.dromara.project.domain.BusProjectTeamMember;
import org.dromara.project.domain.enums.ProjectTeamMemberPostEnum;
import org.dromara.project.domain.req.projectteam.ProjectTeamCreateReq;
import org.dromara.project.domain.req.projectteam.ProjectTeamQueryReq;
import org.dromara.project.domain.req.projectteam.ProjectTeamUpdateReq;
import org.dromara.project.domain.resp.projectteam.ProjectTeamForemanResp;
import org.dromara.project.domain.vo.BusProjectTeamVo;
import org.dromara.project.mapper.BusProjectTeamMapper;
import org.dromara.project.service.IBusConstructionUserService;
import org.dromara.project.service.IBusProjectService;
import org.dromara.project.service.IBusProjectTeamMemberService;
import org.dromara.project.service.IBusProjectTeamService;
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.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 项目班组Service业务层处理
 *
 * @author lcj
 * @date 2025-03-07
 */
@Service
public class BusProjectTeamServiceImpl extends ServiceImpl<BusProjectTeamMapper, BusProjectTeam>
    implements IBusProjectTeamService {

    @Resource
    private IBusProjectService projectService;

    @Lazy
    @Resource
    private IBusProjectTeamMemberService projectTeamMemberService;

    @Lazy
    @Resource
    private IBusConstructionUserService constructionUserService;

    /**
     * 查询项目班组
     *
     * @param id 主键
     * @return 项目班组
     */
    @Override
    public BusProjectTeamVo queryById(Long id) {
        BusProjectTeam projectTeam = this.getById(id);
        if (projectTeam == null) {
            throw new ServiceException("对应项目班组不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(projectTeam);
    }

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

    /**
     * 查询符合条件的项目班组列表
     *
     * @param req 查询条件
     * @return 项目班组列表
     */
    @Override
    public List<BusProjectTeamVo> queryList(ProjectTeamQueryReq req) {
        LambdaQueryWrapper<BusProjectTeam> lqw = this.buildQuery(req);
        List<BusProjectTeam> list = this.list(lqw);
        return list.stream().map(this::getVo).toList();
    }

    /**
     * 新增项目班组
     *
     * @param req 项目班组
     * @return 是否新增成功
     */
    @Override
    public Long insertByBo(ProjectTeamCreateReq req) {
        // 将实体类和 DTO 进行转换
        BusProjectTeam projectTeam = new BusProjectTeam();
        BeanUtils.copyProperties(req, projectTeam);
        // 数据校验
        validEntityBeforeSave(projectTeam);
        // 操作数据库
        boolean save = this.save(projectTeam);
        if (!save) {
            throw new ServiceException("新增项目班组失败，数据库异常", HttpStatus.ERROR);
        }
        return projectTeam.getId();
    }

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

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusProjectTeam entity) {
        // TODO 做一些数据校验,如唯一约束
        Long projectId = entity.getProjectId();
        // 判断是否重名
        String teamName = entity.getTeamName();
        LambdaQueryWrapper<BusProjectTeam> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusProjectTeam::getTeamName, teamName);
        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new ServiceException("项目组名重复", HttpStatus.BAD_REQUEST);
        }
        if (projectId == null) {
            throw new ServiceException("项目 id 不能为空", HttpStatus.BAD_REQUEST);
        }
        // 查询项目是否存在
        if (projectService.getById(projectId) == null) {
            throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
        }
        // 判断用户是否对项目下的内容有操作权限
        Long userId = LoginHelper.getUserId();
        projectService.validAuth(projectId, userId);
    }

    /**
     * 校验并批量删除项目班组信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        // 获取当前登录用户
        Long userId = LoginHelper.getUserId();
        // 获取待删除数据详情
        List<BusProjectTeam> projectTeamList = this.listByIds(ids);
        if (isValid) {
            // 做一些业务上的校验,判断是否需要校验
            // 获取项目id列表
            List<Long> projectIdList = projectTeamList.stream().map(BusProjectTeam::getProjectId).toList();
            // 判断是否有权限操作对应项目下的内容
            projectService.validAuth(projectIdList, userId);
        }
        // 判断对应数据是否都存在
        if (projectTeamList.size() != ids.size()) {
            throw new ServiceException("删除项目班组失败，数据缺失", HttpStatus.BAD_REQUEST);
        }
        return this.removeBatchByIds(ids);
    }

    /**
     * 查询项目班组和班组长分页列表
     *
     * @param projectId 项目id
     * @return 项目班组和班组长分页列表
     */
    @Override
    public List<ProjectTeamForemanResp> queryForemanList(Long projectId) {
        List<BusProjectTeam> projectTeamList = this.list(Wrappers.lambdaQuery(BusProjectTeam.class).eq(BusProjectTeam::getProjectId, projectId));
        if (CollUtil.isEmpty(projectTeamList)) {
            return List.of();
        }
        // 获取项目班组id列表
        List<Long> teamIdList = projectTeamList.stream().map(BusProjectTeam::getId).toList();
        // 获取项目班组班组长id列表
        LambdaQueryWrapper<BusProjectTeamMember> lqw = Wrappers.lambdaQuery(BusProjectTeamMember.class)
            .select(BusProjectTeamMember::getMemberId)
            .eq(BusProjectTeamMember::getProjectId, projectId)
            .in(BusProjectTeamMember::getTeamId, teamIdList)
            .eq(BusProjectTeamMember::getPostId, ProjectTeamMemberPostEnum.FOREMAN.getValue());
        Set<Long> foremanIdList = projectTeamMemberService.list(lqw).stream()
            .map(BusProjectTeamMember::getMemberId).collect(Collectors.toSet());
        // 获取项目班组长信息
        Map<Long, List<BusConstructionUser>> foremanMap = constructionUserService.listByIds(foremanIdList).stream()
            .collect(Collectors.groupingBy(BusConstructionUser::getTeamId));
        // 封装数据
        return projectTeamList.stream().map(projectTeam -> {
            ProjectTeamForemanResp projectTeamForemanResp = new ProjectTeamForemanResp();
            projectTeamForemanResp.setId(projectTeam.getId());
            projectTeamForemanResp.setTeamName(projectTeam.getTeamName());
            projectTeamForemanResp.setProjectId(projectTeam.getProjectId());
            if (foremanMap.containsKey(projectTeam.getId())) {
                BusConstructionUser constructionUser = foremanMap.get(projectTeam.getId()).get(0);
                projectTeamForemanResp.setForemanId(constructionUser.getId());
                projectTeamForemanResp.setForemanName(constructionUser.getUserName());
            }
            return projectTeamForemanResp;
        }).toList();
    }

    /**
     * 获取项目班组视图对象
     *
     * @param projectTeam 项目班组对象
     * @return 项目班组视图对象
     */
    @Override
    public BusProjectTeamVo getVo(BusProjectTeam projectTeam) {
        // 对象转封装类
        BusProjectTeamVo projectTeamVo = new BusProjectTeamVo();
        if (projectTeam == null) {
            return projectTeamVo;
        }
        BeanUtils.copyProperties(projectTeam, projectTeamVo);
        return projectTeamVo;
    }

    /**
     * 获取项目班组查询条件封装
     *
     * @param req 项目班组查询条件
     * @return 项目班组查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusProjectTeam> buildQuery(ProjectTeamQueryReq req) {
        LambdaQueryWrapper<BusProjectTeam> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        // 从对象中取值
        Long id = req.getId();
        Long projectId = req.getProjectId();
        String teamName = req.getTeamName();
        String isClockIn = req.getIsClockIn();
        String remark = req.getRemark();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(teamName), BusProjectTeam::getTeamName, teamName);
        lqw.like(StringUtils.isNotBlank(remark), BusProjectTeam::getRemark, remark);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(id), BusProjectTeam::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), BusProjectTeam::getProjectId, projectId);
        lqw.eq(ObjectUtils.isNotEmpty(isClockIn), BusProjectTeam::getIsClockIn, isClockIn);
        return lqw;
    }

    /**
     * 获取项目班组分页对象视图
     *
     * @param projectTeamPage 项目班组分页对象
     * @return 项目班组分页对象视图
     */
    @Override
    public Page<BusProjectTeamVo> getVoPage(Page<BusProjectTeam> projectTeamPage) {
        List<BusProjectTeam> projectTeamList = projectTeamPage.getRecords();
        Page<BusProjectTeamVo> projectTeamVoPage = new Page<>(
            projectTeamPage.getCurrent(),
            projectTeamPage.getSize(),
            projectTeamPage.getTotal());
        if (CollUtil.isEmpty(projectTeamList)) {
            return projectTeamVoPage;
        }
        List<BusProjectTeamVo> projectTeamVoList = projectTeamList.stream().map(this::getVo).toList();
        projectTeamVoPage.setRecords(projectTeamVoList);
        return projectTeamVoPage;
    }
}
