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.core.conditions.update.LambdaUpdateWrapper;
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.BusProjectTeamMember;
import org.dromara.project.domain.enums.ProjectTeamMemberPostEnum;
import org.dromara.project.domain.req.projectteammember.ProjectTeamMemberCreateReq;
import org.dromara.project.domain.req.projectteammember.ProjectTeamMemberQueryReq;
import org.dromara.project.domain.req.projectteammember.ProjectTeamMemberUpdateReq;
import org.dromara.project.domain.vo.BusProjectTeamMemberVo;
import org.dromara.project.mapper.BusProjectTeamMemberMapper;
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.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 BusProjectTeamMemberServiceImpl extends ServiceImpl<BusProjectTeamMemberMapper, BusProjectTeamMember>
    implements IBusProjectTeamMemberService {

    @Resource
    private IBusConstructionUserService constructionUserService;

    @Resource
    private IBusProjectTeamService projectTeamService;

    @Resource
    private IBusProjectService projectService;

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

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

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

    /**
     * 新增项目班组下的成员
     *
     * @param req 项目班组下的成员
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertByBo(ProjectTeamMemberCreateReq req) {
        // 将实体类和 DTO 进行转换
        BusProjectTeamMember projectTeamMember = new BusProjectTeamMember();
        BeanUtils.copyProperties(req, projectTeamMember);
        // 数据校验
        validEntityBeforeSave(projectTeamMember);
        // 判断对应的用户与项目关联是否存在
        BusProjectTeamMember teamMember = this.getOne(new LambdaQueryWrapper<BusProjectTeamMember>()
            .eq(BusProjectTeamMember::getMemberId, projectTeamMember.getMemberId()));
        if (teamMember != null) {
            throw new ServiceException("当前用户已关联编号为：" + teamMember.getTeamId() + "的班组", HttpStatus.CONFLICT);
        }
        // 操作数据库
        boolean save = this.save(projectTeamMember);
        if (!save) {
            throw new ServiceException("新增项目班组下的成员失败，数据库异常", HttpStatus.ERROR);
        }
        // 同步修改用户表的team_id字段
        BusConstructionUser constructionUser = new BusConstructionUser();
        constructionUser.setId(projectTeamMember.getMemberId());
        constructionUser.setTeamId(projectTeamMember.getTeamId());
        constructionUserService.updateById(constructionUser);
        return projectTeamMember.getId();
    }

    /**
     * 修改项目班组下的成员
     *
     * @param req 项目班组下的成员
     * @return 是否修改成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(ProjectTeamMemberUpdateReq req) {
        // 将实体类和 DTO 进行转换
        BusProjectTeamMember projectTeamMember = new BusProjectTeamMember();
        BeanUtils.copyProperties(req, projectTeamMember);
        // 数据校验
        validEntityBeforeSave(projectTeamMember);
        // 判断是否存在
        BusProjectTeamMember oldProjectTeamMember = this.getById(projectTeamMember.getId());
        if (oldProjectTeamMember == null) {
            throw new ServiceException("修改项目班组下的成员，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 同步修改用户表的team_id字段
        BusConstructionUser constructionUser = new BusConstructionUser();
        constructionUser.setId(projectTeamMember.getMemberId());
        constructionUser.setTeamId(projectTeamMember.getTeamId());
        constructionUserService.updateById(constructionUser);
        // 操作数据库
        return this.updateById(projectTeamMember);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusProjectTeamMember entity) {
        // TODO 做一些数据校验,如唯一约束
        // 判断对应项目是否存在
        Long projectId = entity.getProjectId();
        if (projectId == null) {
            throw new ServiceException("项目 id 不能为空", HttpStatus.BAD_REQUEST);
        }
        if (projectService.getById(projectId) == null) {
            throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
        }
        // 判断对应成员是否存在
        Long memberId = entity.getMemberId();
        if (memberId == null) {
            throw new ServiceException("人员 id 不能为空", HttpStatus.BAD_REQUEST);
        }
        if (constructionUserService.getById(memberId) == null) {
            throw new ServiceException("对应人员不存在", HttpStatus.NOT_FOUND);
        }
        // 判断对应班组是否存在
        Long teamId = entity.getTeamId();
        if (teamId == null) {
            throw new ServiceException("班组 id 不能为空", HttpStatus.BAD_REQUEST);
        }
        if (projectTeamService.getById(teamId) == null) {
            throw new ServiceException("对应班组不存在", HttpStatus.NOT_FOUND);
        }
        // 判断对应班组班组长是否存在
        String postId = entity.getPostId();
        ProjectTeamMemberPostEnum postEnum = ProjectTeamMemberPostEnum.getEnumByValue(postId);
        if (postEnum == null) {
            throw new ServiceException("请选择正确的岗位", HttpStatus.BAD_REQUEST);
        }
        LambdaQueryWrapper<BusProjectTeamMember> lqw = Wrappers.lambdaQuery(BusProjectTeamMember.class)
            .eq(BusProjectTeamMember::getProjectId, projectId)
            .eq(BusProjectTeamMember::getTeamId, teamId)
            .eq(BusProjectTeamMember::getPostId, ProjectTeamMemberPostEnum.FOREMAN.getValue());
        if (this.count(lqw) > 0) {
            throw new ServiceException("当前班组已存在班组长", HttpStatus.CONFLICT);
        }
    }

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

    /**
     * 获取项目班组成员视图对象
     *
     * @param projectTeamMember 项目班组成员对象
     * @return 项目班组成员视图对象
     */
    @Override
    public BusProjectTeamMemberVo getVo(BusProjectTeamMember projectTeamMember) {
        // 对象转封装类
        BusProjectTeamMemberVo projectTeamMemberVo = new BusProjectTeamMemberVo();
        if (projectTeamMember == null) {
            return projectTeamMemberVo;
        }
        BeanUtils.copyProperties(projectTeamMember, projectTeamMemberVo);
        // 关联获取施工人员信息
        Long memberId = projectTeamMember.getMemberId();
        BusConstructionUser constructionUser = constructionUserService.getById(memberId);
        projectTeamMemberVo.setMemberName(constructionUser.getUserName());
        return projectTeamMemberVo;
    }

    /**
     * 获取项目班组成员查询条件封装
     *
     * @param req 项目班组成员查询条件
     * @return 项目班组成员查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusProjectTeamMember> buildQuery(ProjectTeamMemberQueryReq req) {
        LambdaQueryWrapper<BusProjectTeamMember> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        // 从对象中取值
        Long id = req.getId();
        Long teamId = req.getTeamId();
        Long projectId = req.getProjectId();
        Long memberId = req.getMemberId();
        String memberName = req.getMemberName();
        String postId = req.getPostId();
        String remark = req.getRemark();
        // 联表查询
        if (StringUtils.isNotBlank(memberName)) {
            QueryWrapper<BusConstructionUser> constructionUserQueryWrapper = new QueryWrapper<>();
            constructionUserQueryWrapper.select("id");
            constructionUserQueryWrapper.like("user_name", memberName);
            List<Long> constructionUserIdList = constructionUserService.listObjs(constructionUserQueryWrapper, obj -> (Long) obj);
            lqw.in(BusProjectTeamMember::getMemberId, constructionUserIdList);
        }
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(remark), BusProjectTeamMember::getRemark, remark);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(id), BusProjectTeamMember::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), BusProjectTeamMember::getProjectId, projectId);
        lqw.eq(ObjectUtils.isNotEmpty(teamId), BusProjectTeamMember::getTeamId, teamId);
        lqw.eq(ObjectUtils.isNotEmpty(memberId), BusProjectTeamMember::getMemberId, memberId);
        lqw.eq(ObjectUtils.isNotEmpty(postId), BusProjectTeamMember::getPostId, postId);
        return lqw;
    }

    /**
     * 获取项目班组成员分页对象视图
     *
     * @param projectTeamMemberPage 项目班组成员分页对象
     * @return 项目班组成员分页对象视图
     */
    @Override
    public Page<BusProjectTeamMemberVo> getVoPage(Page<BusProjectTeamMember> projectTeamMemberPage) {
        List<BusProjectTeamMember> projectTeamMemberList = projectTeamMemberPage.getRecords();
        Page<BusProjectTeamMemberVo> projectTeamMemberVoPage = new Page<>(
            projectTeamMemberPage.getCurrent(),
            projectTeamMemberPage.getSize(),
            projectTeamMemberPage.getTotal());
        if (CollUtil.isEmpty(projectTeamMemberList)) {
            return projectTeamMemberVoPage;
        }
        // 关联查询施工人员信息
        Set<Long> teamMemberIdSet = projectTeamMemberList.stream().map(BusProjectTeamMember::getMemberId)
            .collect(Collectors.toSet());
        Map<Long, List<BusConstructionUser>> contractorIdContractorList = constructionUserService.listByIds(teamMemberIdSet).stream()
            .collect(Collectors.groupingBy(BusConstructionUser::getId));
        // 填充信息
        List<BusProjectTeamMemberVo> projectTeamMemberVoList = projectTeamMemberList.stream().map(projectTeamMember -> {
            BusProjectTeamMemberVo projectTeamMemberVo = new BusProjectTeamMemberVo();
            BeanUtils.copyProperties(projectTeamMember, projectTeamMemberVo);
            Long memberId = projectTeamMember.getMemberId();
            String memberName = null;
            if (contractorIdContractorList.containsKey(memberId)) {
                memberName = contractorIdContractorList.get(memberId).get(0).getUserName();
            }
            projectTeamMemberVo.setMemberName(memberName);
            return projectTeamMemberVo;
        }).toList();
        projectTeamMemberVoPage.setRecords(projectTeamMemberVoList);
        return projectTeamMemberVoPage;
    }
}
