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.LambdaQueryWrapper;
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.BusProjectTeam;
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.vo.BusProjectTeamVo;
import org.dromara.project.mapper.BusProjectTeamMapper;
import org.dromara.project.service.IBusProjectTeamService;
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;

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

    @Resource
    private IBusProjectService projectService;

    /**
     * 查询项目班组
     *
     * @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 查询条件
     * @return 项目班组分页列表
     */
    @Override
    public Page<BusProjectTeamVo> queryPageList(ProjectTeamQueryReq req) {
        long current = req.getCurrent();
        long size = req.getPageSize();
        // 查询数据库
        Page<BusProjectTeam> result = this.page(new Page<>(current, size), this.getQueryWrapper(req));
        return this.getVoPage(result);
    }

    /**
     * 查询符合条件的项目班组列表
     *
     * @param req 查询条件
     * @return 项目班组列表
     */
    @Override
    public List<BusProjectTeamVo> queryList(ProjectTeamQueryReq req) {
        QueryWrapper<BusProjectTeam> queryWrapper = this.getQueryWrapper(req);
        List<BusProjectTeam> list = this.list(queryWrapper);
        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);
        }
    }

    /**
     * 校验并批量删除项目班组信息
     *
     * @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 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 QueryWrapper<BusProjectTeam> getQueryWrapper(ProjectTeamQueryReq req) {
        QueryWrapper<BusProjectTeam> queryWrapper = new QueryWrapper<>();
        if (req == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = req.getId();
        Long projectId = req.getProjectId();
        String teamName = req.getTeamName();
        Long isClockIn = req.getIsClockIn();
        String remark = req.getRemark();
        String sortField = req.getSortField();
        String sortOrder = req.getSortOrder();
        String underlineSortField = StrUtil.toUnderlineCase(sortField);
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(teamName), "team_name", teamName);
        queryWrapper.like(StringUtils.isNotBlank(remark), "remark", remark);
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(projectId), "project_id", projectId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(isClockIn), "is_clock_in", isClockIn);
        // 排序规则
        queryWrapper.orderBy(SqlUtil.validSortField(sortField),
            sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
            underlineSortField);
        return queryWrapper;
    }

    /**
     * 获取项目班组分页对象视图
     *
     * @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;
    }
}
