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.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.BusContractor;
import org.dromara.project.domain.BusProjectTeamMember;
import org.dromara.project.domain.req.constructionuser.ConstructionUserCreateReq;
import org.dromara.project.domain.req.constructionuser.ConstructionUserQueryReq;
import org.dromara.project.domain.req.constructionuser.ConstructionUserUpdateReq;
import org.dromara.project.domain.vo.BusConstructionUserVo;
import org.dromara.project.domain.vo.BusContractorVo;
import org.dromara.project.mapper.BusConstructionUserMapper;
import org.dromara.project.service.*;
import org.dromara.system.service.ISysOssService;
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 BusConstructionUserServiceImpl extends ServiceImpl<BusConstructionUserMapper, BusConstructionUser>
    implements IBusConstructionUserService {

    @Resource
    private IBusProjectService projectService;

    @Lazy
    @Resource
    private IBusContractorService contractorService;

    @Lazy
    @Resource
    private IBusProjectTeamMemberService projectTeamMemberService;

    @Resource
    private IBusProjectTeamService projectTeamService;

    @Resource
    private ISysOssService ossService;

    /**
     * 查询施工人员
     *
     * @param id 主键
     * @return 施工人员
     */
    @Override
    public BusConstructionUserVo queryById(Long id) {
        BusConstructionUser constructionUser = this.getById(id);
        if (constructionUser == null) {
            throw new ServiceException("施工人员信息不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(constructionUser);
    }

    /**
     * 分页查询施工人员列表
     *
     * @param req       查询条件
     * @param pageQuery 分页参数
     * @return 施工人员分页列表
     */
    @Override
    public TableDataInfo<BusConstructionUserVo> queryPageList(ConstructionUserQueryReq req, PageQuery pageQuery) {
        // 查询数据库
        Page<BusConstructionUser> result = this.page(pageQuery.build(), this.buildQuery(req));
        return TableDataInfo.build(getVoPage(result));
    }

    /**
     * 查询符合条件的施工人员列表
     *
     * @param req 查询条件
     * @return 施工人员列表
     */
    @Override
    public List<BusConstructionUserVo> queryList(ConstructionUserQueryReq req) {
        LambdaQueryWrapper<BusConstructionUser> lqw = this.buildQuery(req);
        List<BusConstructionUser> list = this.list(lqw);
        return list.stream().map(this::getVo).toList();
    }

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

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

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusConstructionUser entity) {
        // TODO 做一些数据校验,如唯一约束
        // 校验项目id和对应项目是否存在
        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);
        }
        // 校验分包公司id和对应项目是否存在
        Long contractorId = entity.getContractorId();
        if (contractorId == null) {
            throw new ServiceException("分包公司 id 不能为空", HttpStatus.BAD_REQUEST);
        }
        if (contractorService.getById(contractorId) == null) {
            throw new ServiceException("对应分包公司不存在", HttpStatus.NOT_FOUND);
        }
    }

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

    /**
     * 获取施工人员视图对象
     *
     * @param constructionUser 施工人员对象
     * @return 施工人员视图对象
     */
    @Override
    public BusConstructionUserVo getVo(BusConstructionUser constructionUser) {
        // 对象转封装类
        BusConstructionUserVo constructionUserVo = new BusConstructionUserVo();
        if (constructionUser == null) {
            return constructionUserVo;
        }
        BeanUtils.copyProperties(constructionUser, constructionUserVo);
        // 关联查询分包公司信息信息
        Long contractorId = constructionUser.getContractorId();
        if (contractorId != null) {
            constructionUserVo.setContractorVo(contractorService.queryById(contractorId));
        }
        // 关联查询用户头像url
        String facePic = constructionUser.getFacePic();
        if (StringUtils.isNotBlank(facePic)) {
            constructionUserVo.setFacePicUrl(ossService.getById(Long.parseLong(facePic)).getUrl());
        }
        // 关联查询班组信息
        Long teamId = constructionUser.getTeamId();
        if (teamId != null) {
            constructionUserVo.setTeamVo(projectTeamService.queryById(teamId));
        }
        return constructionUserVo;
    }

    /**
     * 获取施工人员查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusConstructionUser> buildQuery(ConstructionUserQueryReq req) {
        LambdaQueryWrapper<BusConstructionUser> lqw = Wrappers.lambdaQuery();
        if (req == null) {
            return lqw;
        }
        // 从对象中取值
        Long id = req.getId();
        String openid = req.getOpenid();
        String nickName = req.getNickName();
        String userName = req.getUserName();
        Long projectId = req.getProjectId();
        Long contractorId = req.getContractorId();
        Long teamId = req.getTeamId();
        Long notTeamId = req.getNotTeamId();
        String status = req.getStatus();
        Long isPinch = req.getIsPinch();
        String phone = req.getPhone();
        Long sex = req.getSex();
        String nation = req.getNation();
        String sfzNumber = req.getSfzNumber();
        String sfzStart = req.getSfzStart();
        String sfzEnd = req.getSfzEnd();
        String sfzSite = req.getSfzSite();
        String sfzBirth = req.getSfzBirth();
        String nativePlace = req.getNativePlace();
        String yhkNumber = req.getYhkNumber();
        String yhkOpeningBank = req.getYhkOpeningBank();
        String yhkCardholder = req.getYhkCardholder();
        String typeOfWork = req.getTypeOfWork();
        String clock = req.getClock();
        Long salary = req.getSalary();
        String remark = req.getRemark();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(nickName), BusConstructionUser::getNickName, nickName);
        lqw.like(StringUtils.isNotBlank(userName), BusConstructionUser::getUserName, userName);
        lqw.like(StringUtils.isNotBlank(remark), BusConstructionUser::getRemark, remark);
        lqw.like(StringUtils.isNotBlank(phone), BusConstructionUser::getPhone, phone);
        lqw.like(StringUtils.isNotBlank(nation), BusConstructionUser::getNation, nation);
        lqw.like(StringUtils.isNotBlank(sfzNumber), BusConstructionUser::getSfzNumber, sfzNumber);
        lqw.like(StringUtils.isNotBlank(sfzStart), BusConstructionUser::getSfzStart, sfzStart);
        lqw.like(StringUtils.isNotBlank(sfzEnd), BusConstructionUser::getSfzEnd, sfzEnd);
        lqw.like(StringUtils.isNotBlank(sfzSite), BusConstructionUser::getSfzSite, sfzSite);
        lqw.like(StringUtils.isNotBlank(sfzBirth), BusConstructionUser::getSfzBirth, sfzBirth);
        lqw.like(StringUtils.isNotBlank(nativePlace), BusConstructionUser::getNativePlace, nativePlace);
        lqw.like(StringUtils.isNotBlank(yhkNumber), BusConstructionUser::getYhkNumber, yhkNumber);
        lqw.like(StringUtils.isNotBlank(yhkOpeningBank), BusConstructionUser::getYhkOpeningBank, yhkOpeningBank);
        lqw.like(StringUtils.isNotBlank(yhkCardholder), BusConstructionUser::getYhkCardholder, yhkCardholder);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(openid), BusConstructionUser::getOpenid, openid);
        lqw.eq(ObjectUtils.isNotEmpty(status), BusConstructionUser::getStatus, status);
        lqw.eq(ObjectUtils.isNotEmpty(id), BusConstructionUser::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), BusConstructionUser::getProjectId, projectId);
        lqw.eq(ObjectUtils.isNotEmpty(contractorId), BusConstructionUser::getContractorId, contractorId);
        lqw.eq(ObjectUtils.isNotEmpty(teamId), BusConstructionUser::getTeamId, teamId);
        lqw.eq(ObjectUtils.isNotEmpty(isPinch), BusConstructionUser::getIsPinch, isPinch);
        lqw.eq(ObjectUtils.isNotEmpty(sex), BusConstructionUser::getSex, sex);
        lqw.eq(ObjectUtils.isNotEmpty(typeOfWork), BusConstructionUser::getTypeOfWork, typeOfWork);
        lqw.eq(ObjectUtils.isNotEmpty(clock), BusConstructionUser::getClock, clock);
        lqw.eq(ObjectUtils.isNotEmpty(salary), BusConstructionUser::getSalary, salary);
        // 精准查询，不等于
        if (ObjectUtils.isNotEmpty(notTeamId)) {
            lqw.and(wrapper -> wrapper
                .ne(BusConstructionUser::getTeamId, notTeamId)
                .or().isNull(BusConstructionUser::getTeamId));
        }
        return lqw;
    }

    /**
     * 获取施工人员分页对象视图
     *
     * @param constructionUserPage 施工人员分页对象
     * @return 施工人员分页对象视图
     */
    @Override
    public Page<BusConstructionUserVo> getVoPage(Page<BusConstructionUser> constructionUserPage) {
        List<BusConstructionUser> constructionUserList = constructionUserPage.getRecords();
        Page<BusConstructionUserVo> constructionUserVoPage = new Page<>(
            constructionUserPage.getCurrent(),
            constructionUserPage.getSize(),
            constructionUserPage.getTotal());
        if (CollUtil.isEmpty(constructionUserList)) {
            return constructionUserVoPage;
        }
        // 关联查询分包公司信息
        Set<Long> contractorIdSet = constructionUserList.stream().map(BusConstructionUser::getContractorId)
            .collect(Collectors.toSet());
        Map<Long, List<BusContractor>> contractorIdContractorList = contractorService.listByIds(contractorIdSet).stream()
            .collect(Collectors.groupingBy(BusContractor::getId));
        // 填充信息
        List<BusConstructionUserVo> constructionUserVoList = constructionUserList.stream().map(constructionUser -> {
            BusConstructionUserVo constructionUserVo = new BusConstructionUserVo();
            BeanUtils.copyProperties(constructionUser, constructionUserVo);
            Long contractorId = constructionUser.getContractorId();
            BusContractorVo contractor = null;
            if (contractorIdContractorList.containsKey(contractorId)) {
                contractor = contractorService.getVo(contractorIdContractorList.get(contractorId).get(0));
            }
            constructionUserVo.setContractorVo(contractor);
            return constructionUserVo;
        }).toList();
        constructionUserVoPage.setRecords(constructionUserVoList);
        return constructionUserVoPage;
    }
}
