package org.dromara.project.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
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.CommonConstant;
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.core.utils.sql.SqlUtil;
import org.dromara.project.domain.BusConstructionUser;
import org.dromara.project.domain.BusContractor;
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.IBusConstructionUserService;
import org.dromara.project.service.IBusContractorService;
import org.dromara.project.service.IBusProjectService;
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 BusConstructionUserServiceImpl extends ServiceImpl<BusConstructionUserMapper, BusConstructionUser>
    implements IBusConstructionUserService {

    @Resource
    private IBusProjectService projectService;

    @Resource
    private IBusContractorService contractorService;

    /**
     * 查询施工人员
     *
     * @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 查询条件
     * @return 施工人员分页列表
     */
    @Override
    public Page<BusConstructionUserVo> queryPageList(ConstructionUserQueryReq req) {
        long current = req.getCurrent();
        long size = req.getPageSize();
        // 查询数据库
        Page<BusConstructionUser> result = this.page(new Page<>(current, size), this.getQueryWrapper(req));
        return this.getVoPage(result);
    }

    /**
     * 查询符合条件的施工人员列表
     *
     * @param req 查询条件
     * @return 施工人员列表
     */
    @Override
    public List<BusConstructionUserVo> queryList(ConstructionUserQueryReq req) {
        QueryWrapper<BusConstructionUser> queryWrapper = this.getQueryWrapper(req);
        List<BusConstructionUser> list = this.list(queryWrapper);
        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) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        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));
        }
        return constructionUserVo;
    }

    /**
     * 获取施工人员查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public QueryWrapper<BusConstructionUser> getQueryWrapper(ConstructionUserQueryReq req) {
        QueryWrapper<BusConstructionUser> queryWrapper = new QueryWrapper<>();
        if (req == null) {
            return queryWrapper;
        }
        // 从对象中取值
        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 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();
        Long typeOfWork = req.getTypeOfWork();
        Long clock = req.getClock();
        Long salary = req.getSalary();
        String remark = req.getRemark();
        String sortField = req.getSortField();
        String sortOrder = req.getSortOrder();
        String underlineSortField = StrUtil.toUnderlineCase(sortField);
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(nickName), "nick_name", nickName);
        queryWrapper.like(StringUtils.isNotBlank(userName), "user_name", userName);
        queryWrapper.like(StringUtils.isNotBlank(remark), "remark", remark);
        queryWrapper.like(StringUtils.isNotBlank(phone), "phone", phone);
        queryWrapper.like(StringUtils.isNotBlank(nation), "nation", nation);
        queryWrapper.like(StringUtils.isNotBlank(sfzNumber), "sfz_number", sfzNumber);
        queryWrapper.like(StringUtils.isNotBlank(sfzStart), "sfz_start", sfzStart);
        queryWrapper.like(StringUtils.isNotBlank(sfzEnd), "sfz_end", sfzEnd);
        queryWrapper.like(StringUtils.isNotBlank(sfzSite), "sfz_site", sfzSite);
        queryWrapper.like(StringUtils.isNotBlank(sfzBirth), "sfz_birth", sfzBirth);
        queryWrapper.like(StringUtils.isNotBlank(nativePlace), "native_place", nativePlace);
        queryWrapper.like(StringUtils.isNotBlank(yhkNumber), "yhk_number", yhkNumber);
        queryWrapper.like(StringUtils.isNotBlank(yhkOpeningBank), "yhk_opening_bank", yhkOpeningBank);
        queryWrapper.like(StringUtils.isNotBlank(yhkCardholder), "yhk_cardholder", yhkCardholder);
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(openid), "openid", openid);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(projectId), "project_id", projectId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(contractorId), "contractor_id", contractorId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(teamId), "team_id", teamId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(isPinch), "is_pinch", isPinch);
        queryWrapper.eq(ObjectUtils.isNotEmpty(sex), "sex", sex);
        queryWrapper.eq(ObjectUtils.isNotEmpty(typeOfWork), "type_of_work", typeOfWork);
        queryWrapper.eq(ObjectUtils.isNotEmpty(clock), "clock", clock);
        queryWrapper.eq(ObjectUtils.isNotEmpty(salary), "salary", salary);
        // 排序规则
        queryWrapper.orderBy(SqlUtil.validSortField(sortField),
            sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
            underlineSortField);
        return queryWrapper;
    }

    /**
     * 获取施工人员分页对象视图
     *
     * @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;
    }
}
