package org.dromara.safety.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.project.domain.BusConstructionUser;
import org.dromara.project.domain.BusProjectTeam;
import org.dromara.project.service.IBusConstructionUserService;
import org.dromara.project.service.IBusProjectService;
import org.dromara.project.service.IBusProjectTeamService;
import org.dromara.safety.domain.BusSafetyInspection;
import org.dromara.safety.domain.req.safetyinspection.SafetyInspectionCreateReq;
import org.dromara.safety.domain.req.safetyinspection.SafetyInspectionQueryReq;
import org.dromara.safety.domain.req.safetyinspection.SafetyInspectionUpdateReq;
import org.dromara.safety.domain.vo.BusSafetyInspectionVo;
import org.dromara.safety.mapper.BusSafetyInspectionMapper;
import org.dromara.safety.service.IBusSafetyInspectionService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 安全巡检工单Service业务层处理
 *
 * @author lcj
 * @date 2025-03-20
 */
@Service
public class BusSafetyInspectionServiceImpl extends ServiceImpl<BusSafetyInspectionMapper, BusSafetyInspection>
    implements IBusSafetyInspectionService {

    @Resource
    private IBusConstructionUserService constructionUserService;

    @Resource
    private IBusProjectTeamService projectTeamService;

    @Resource
    private IBusProjectService projectService;

    /**
     * 查询安全巡检工单
     *
     * @param id 主键
     * @return 安全巡检工单
     */
    @Override
    public BusSafetyInspectionVo queryById(Long id) {
        BusSafetyInspection safetyInspection = this.getById(id);
        if (safetyInspection == null) {
            throw new ServiceException("安全巡检工单信息不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(safetyInspection);
    }

    /**
     * 分页查询安全巡检工单列表
     *
     * @param req       查询条件
     * @param pageQuery 分页参数
     * @return 安全巡检工单分页列表
     */
    @Override
    public TableDataInfo<BusSafetyInspectionVo> queryPageList(SafetyInspectionQueryReq req, PageQuery pageQuery) {
        Page<BusSafetyInspection> result = this.page(pageQuery.build(), buildQuery(req));
        return TableDataInfo.build(this.getVoPage(result));
    }

    /**
     * 查询符合条件的安全巡检工单列表
     *
     * @param req 查询条件
     * @return 安全巡检工单列表
     */
    @Override
    public List<BusSafetyInspectionVo> queryList(SafetyInspectionQueryReq req) {
        List<BusSafetyInspection> safetyInspection = this.list(this.buildQuery(req));
        return safetyInspection.stream().map(this::getVo).toList();
    }

    /**
     * 新增安全巡检工单
     *
     * @param req 安全巡检工单
     * @return 是否新增成功
     */
    @Override
    public Long insertByBo(SafetyInspectionCreateReq req) {
        // 将实体类和 DTO 进行转换
        BusSafetyInspection safetyInspection = new BusSafetyInspection();
        BeanUtils.copyProperties(req, safetyInspection);
        // 数据校验
        validEntityBeforeSave(safetyInspection, true);
        // 写入数据库
        boolean save = this.save(safetyInspection);
        if (!save) {
            throw new ServiceException("新增安全巡检工单信息失败，数据库异常", HttpStatus.ERROR);
        }
        // 返回新写入的数据
        return safetyInspection.getId();
    }

    /**
     * 修改安全巡检工单
     *
     * @param req 安全巡检工单
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SafetyInspectionUpdateReq req) {
        // 将实体类和 DTO 进行转换
        BusSafetyInspection safetyInspection = new BusSafetyInspection();
        BeanUtils.copyProperties(req, safetyInspection);
        // 数据校验
        validEntityBeforeSave(safetyInspection, false);
        // 判断是否存在
        BusSafetyInspection oldSafetyInspection = this.getById(safetyInspection.getId());
        if (oldSafetyInspection == null) {
            throw new ServiceException("修改安全巡检工单信息失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 操作数据库
        return this.updateById(safetyInspection);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusSafetyInspection entity, Boolean create) {
        // TODO 做一些数据校验,如唯一约束
        Long projectId = entity.getProjectId();
        Long correctorId = entity.getCorrectorId();
        String checkType = entity.getCheckType();
        String violationType = entity.getViolationType();
        // 创建时校验
        if (create) {
            if (projectId == null) {
                throw new ServiceException("项目id不能为空", HttpStatus.BAD_REQUEST);
            }
            if (correctorId == null) {
                throw new ServiceException("整改人id不能为空", HttpStatus.BAD_REQUEST);
            }
            if (StringUtils.isBlank(checkType)) {
                throw new ServiceException("检查类型不能为空", HttpStatus.BAD_REQUEST);
            }
            if (StringUtils.isBlank(violationType)) {
                throw new ServiceException("违规类型不能为空", HttpStatus.BAD_REQUEST);
            }
        }
        if (projectId != null && projectService.getById(projectId) == null) {
            throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
        }
        if (correctorId != null && constructionUserService.getById(correctorId) == 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 做一些业务上的校验,判断是否需要校验
            Long count = this.lambdaQuery().in(BusSafetyInspection::getPid, ids).count();
            if (count > 0) {
                throw new ServiceException("所选安全巡检工单包含子数据，不允许删除", HttpStatus.BAD_REQUEST);
            }
        }
        return this.removeBatchByIds(ids);
    }

    /**
     * 获取安全巡检工单视图对象
     *
     * @param safetyInspection 安全巡检工单对象
     * @return 安全巡检工单视图对象
     */
    @Override
    public BusSafetyInspectionVo getVo(BusSafetyInspection safetyInspection) {
        // 对象转封装类
        BusSafetyInspectionVo safetyInspectionVo = new BusSafetyInspectionVo();
        if (safetyInspection == null) {
            return safetyInspectionVo;
        }
        BeanUtils.copyProperties(safetyInspection, safetyInspectionVo);
        // 关联班组信息
        Long teamId = safetyInspection.getTeamId();
        if (teamId != null) {
            LambdaQueryWrapper<BusProjectTeam> teamLambdaQueryWrapper = Wrappers.lambdaQuery(BusProjectTeam.class)
                .select(BusProjectTeam::getId, BusProjectTeam::getTeamName)
                .eq(BusProjectTeam::getId, teamId);
            BusProjectTeam projectTeam = projectTeamService.getOne(teamLambdaQueryWrapper);
            safetyInspectionVo.setTeamId(projectTeam.getId());
            safetyInspectionVo.setTeamName(projectTeam.getTeamName());
        }
        // 关联整改人信息
        Long correctorId = safetyInspection.getCorrectorId();
        if (correctorId != null) {
            LambdaQueryWrapper<BusConstructionUser> constructionUserLambdaQueryWrapper = Wrappers.lambdaQuery(BusConstructionUser.class)
                .select(BusConstructionUser::getId, BusConstructionUser::getUserName)
                .eq(BusConstructionUser::getId, correctorId);
            BusConstructionUser constructionUser = constructionUserService.getOne(constructionUserLambdaQueryWrapper);
            safetyInspectionVo.setCorrectorId(constructionUser.getId());
            safetyInspectionVo.setCorrectorName(constructionUser.getUserName());
        }
        // 关联创建用户信息
        Long createBy = safetyInspection.getCreateBy();
        if (createBy != null) {
            BusConstructionUser createUser = constructionUserService.getById(createBy);
            safetyInspectionVo.setCreatorId(createUser.getId());
            safetyInspectionVo.setCreatorName(createUser.getUserName());
        }
        return safetyInspectionVo;
    }

    /**
     * 获取安全巡检工单查询条件封装
     *
     * @param req 安全巡检工单查询条件
     * @return 安全巡检工单查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusSafetyInspection> buildQuery(SafetyInspectionQueryReq req) {
        LambdaQueryWrapper<BusSafetyInspection> lqw = Wrappers.lambdaQuery();
        if (req == null) {
            return lqw;
        }
        Long id = req.getId();
        Long pid = req.getPid();
        Long projectId = req.getProjectId();
        String checkType = req.getCheckType();
        String violationType = req.getViolationType();
        String inspectionResult = req.getInspectionResult();
        Long teamId = req.getTeamId();
        Long correctorId = req.getCorrectorId();
        String isReply = req.getIsReply();
        String replyDate = req.getReplyDate();
        String status = req.getStatus();
        String hiddenDanger = req.getHiddenDanger();
        String measure = req.getMeasure();
        String review = req.getReview();
        String reviewType = req.getReviewType();
        Date checkTime = req.getCheckTime();
        Date rectificationTime = req.getRectificationTime();
        Date reviewTime = req.getReviewTime();
        String remark = req.getRemark();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(inspectionResult), BusSafetyInspection::getInspectionResult, inspectionResult);
        lqw.like(StringUtils.isNotBlank(hiddenDanger), BusSafetyInspection::getHiddenDanger, hiddenDanger);
        lqw.like(StringUtils.isNotBlank(measure), BusSafetyInspection::getMeasure, measure);
        lqw.like(StringUtils.isNotBlank(review), BusSafetyInspection::getReview, review);
        lqw.like(StringUtils.isNotBlank(remark), BusSafetyInspection::getRemark, remark);
        // 精准查询
        lqw.eq(ObjectUtils.isNotEmpty(id), BusSafetyInspection::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(pid), BusSafetyInspection::getPid, pid);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), BusSafetyInspection::getProjectId, projectId);
        lqw.eq(ObjectUtils.isNotEmpty(checkType), BusSafetyInspection::getCheckType, checkType);
        lqw.eq(ObjectUtils.isNotEmpty(violationType), BusSafetyInspection::getViolationType, violationType);
        lqw.eq(ObjectUtils.isNotEmpty(teamId), BusSafetyInspection::getTeamId, teamId);
        lqw.eq(ObjectUtils.isNotEmpty(correctorId), BusSafetyInspection::getCorrectorId, correctorId);
        lqw.eq(ObjectUtils.isNotEmpty(isReply), BusSafetyInspection::getIsReply, isReply);
        lqw.eq(ObjectUtils.isNotEmpty(replyDate), BusSafetyInspection::getReplyDate, replyDate);
        lqw.eq(ObjectUtils.isNotEmpty(status), BusSafetyInspection::getStatus, status);
        lqw.eq(ObjectUtils.isNotEmpty(reviewType), BusSafetyInspection::getReviewType, reviewType);
        lqw.eq(ObjectUtils.isNotEmpty(checkTime), BusSafetyInspection::getCheckTime, checkTime);
        lqw.eq(ObjectUtils.isNotEmpty(rectificationTime), BusSafetyInspection::getRectificationTime, rectificationTime);
        lqw.eq(ObjectUtils.isNotEmpty(reviewTime), BusSafetyInspection::getReviewTime, reviewTime);
        return lqw;
    }

    /**
     * 获取安全巡检工单分页对象视图
     *
     * @param safetyInspectionPage 安全巡检工单分页对象
     * @return 安全巡检工单分页对象视图
     */
    @Override
    public Page<BusSafetyInspectionVo> getVoPage(Page<BusSafetyInspection> safetyInspectionPage) {
        // 获取安全巡检工单
        List<BusSafetyInspection> safetyInspectionList = safetyInspectionPage.getRecords();
        // 添加分页信息
        Page<BusSafetyInspectionVo> safetyInspectionVoPage = new Page<>(
            safetyInspectionPage.getCurrent(),
            safetyInspectionPage.getSize(),
            safetyInspectionPage.getTotal());
        if (CollUtil.isEmpty(safetyInspectionList)) {
            return safetyInspectionVoPage;
        }
        // 对象列表 => 封装对象列表
        List<BusSafetyInspectionVo> safetyInspectionVoList = safetyInspectionList.stream().map(this::getVo).toList();
        safetyInspectionVoPage.setRecords(safetyInspectionVoList);
        return safetyInspectionVoPage;
    }
}
