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.domain.vo.IdAndNameVO;
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.service.IBusConstructionUserService;
import org.dromara.project.service.IBusProjectService;
import org.dromara.safety.domain.BusSafetyLog;
import org.dromara.safety.domain.req.safetylog.SafetyLogCreateReq;
import org.dromara.safety.domain.req.safetylog.SafetyLogQueryReq;
import org.dromara.safety.domain.req.safetylog.SafetyLogUpdateReq;
import org.dromara.safety.domain.vo.BusSafetyLogVo;
import org.dromara.safety.mapper.BusSafetyLogMapper;
import org.dromara.safety.service.IBusSafetyLogService;
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-20
 */
@Service
public class BusSafetyLogServiceImpl extends ServiceImpl<BusSafetyLogMapper, BusSafetyLog>
    implements IBusSafetyLogService {

    @Resource
    private IBusConstructionUserService constructionUserService;

    @Resource
    private IBusProjectService projectService;

    /**
     * 查询安全日志
     *
     * @param id 主键
     * @return 安全日志
     */
    @Override
    public BusSafetyLogVo queryById(Long id) {
        BusSafetyLog safetyLog = this.getById(id);
        if (safetyLog == null) {
            throw new ServiceException("安全日志信息不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(safetyLog);
    }

    /**
     * 分页查询安全日志列表
     *
     * @param req       查询条件
     * @param pageQuery 分页参数
     * @return 安全日志分页列表
     */
    @Override
    public TableDataInfo<BusSafetyLogVo> queryPageList(SafetyLogQueryReq req, PageQuery pageQuery) {
        Page<BusSafetyLog> result = this.page(pageQuery.build(), this.buildQuery(req));
        return TableDataInfo.build(this.getVoPage(result));
    }

    /**
     * 查询符合条件的安全日志列表
     *
     * @param req 查询条件
     * @return 安全日志列表
     */
    @Override
    public List<BusSafetyLogVo> queryList(SafetyLogQueryReq req) {
        List<BusSafetyLog> safetyLogList = this.list(this.buildQuery(req));
        return safetyLogList.stream().map(this::getVo).toList();
    }

    /**
     * 新增安全日志
     *
     * @param req 安全日志
     * @return 新增id
     */
    @Override
    public Long insertByBo(SafetyLogCreateReq req) {
        // 将实体类和 DTO 进行转换
        BusSafetyLog safetyLog = new BusSafetyLog();
        BeanUtils.copyProperties(req, safetyLog);
        // 数据校验
        validEntityBeforeSave(safetyLog, true);
        // 写入数据库
        boolean save = this.save(safetyLog);
        if (!save) {
            throw new ServiceException("新增安全日志信息失败，数据库异常", HttpStatus.ERROR);
        }
        // 返回新写入的数据
        return safetyLog.getId();
    }

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

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusSafetyLog entity, Boolean create) {
        // TODO 做一些数据校验,如唯一约束
        Long projectId = entity.getProjectId();
        if (create) {
            if (projectId == null) {
                throw new ServiceException("项目id不能为空", HttpStatus.BAD_REQUEST);
            }
        }
        if (projectId != null && 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 safetyLog 安全日志对象
     * @return 安全日志视图对象
     */
    @Override
    public BusSafetyLogVo getVo(BusSafetyLog safetyLog) {
        // 对象转封装类
        BusSafetyLogVo safetyLogVo = new BusSafetyLogVo();
        if (safetyLog == null) {
            return safetyLogVo;
        }
        BeanUtils.copyProperties(safetyLog, safetyLogVo);
        // 关联创建用户信息
        Long createBy = safetyLog.getCreateBy();
        if (createBy != null) {
            BusConstructionUser createUser = constructionUserService.getById(createBy);
            safetyLogVo.setCreator(IdAndNameVO.build(createUser.getId(), createUser.getUserName()));
        }
        return safetyLogVo;
    }

    /**
     * 获取安全日志查询条件封装
     *
     * @param req 安全日志查询条件
     * @return 安全日志查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusSafetyLog> buildQuery(SafetyLogQueryReq req) {
        LambdaQueryWrapper<BusSafetyLog> lqw = Wrappers.lambdaQuery();
        if (req == null) {
            return lqw;
        }
        Long id = req.getId();
        String dateOfOccurrence = req.getDateOfOccurrence();
        Long airTemperatureMax = req.getAirTemperatureMax();
        Long airTemperatureMin = req.getAirTemperatureMin();
        String weather = req.getWeather();
        String progress = req.getProgress();
        String jobContent = req.getJobContent();
        String discloseCondition = req.getDiscloseCondition();
        String activityCondition = req.getActivityCondition();
        String examineCondition = req.getExamineCondition();
        String implementCondition = req.getImplementCondition();
        String safetyInspectionCondition = req.getSafetyInspectionCondition();
        String stoppageOrOvertime = req.getStoppageOrOvertime();
        String otherCondition = req.getOtherCondition();
        String remark = req.getRemark();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(progress), BusSafetyLog::getProgress, progress);
        lqw.like(StringUtils.isNotBlank(jobContent), BusSafetyLog::getJobContent, jobContent);
        lqw.like(StringUtils.isNotBlank(discloseCondition), BusSafetyLog::getDiscloseCondition, discloseCondition);
        lqw.like(StringUtils.isNotBlank(activityCondition), BusSafetyLog::getActivityCondition, activityCondition);
        lqw.like(StringUtils.isNotBlank(examineCondition), BusSafetyLog::getExamineCondition, examineCondition);
        lqw.like(StringUtils.isNotBlank(implementCondition), BusSafetyLog::getImplementCondition, implementCondition);
        lqw.like(StringUtils.isNotBlank(safetyInspectionCondition), BusSafetyLog::getSafetyInspectionCondition, safetyInspectionCondition);
        lqw.like(StringUtils.isNotBlank(stoppageOrOvertime), BusSafetyLog::getStoppageOrOvertime, stoppageOrOvertime);
        lqw.like(StringUtils.isNotBlank(otherCondition), BusSafetyLog::getOtherCondition, otherCondition);
        lqw.like(StringUtils.isNotBlank(remark), BusSafetyLog::getRemark, remark);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(id), BusSafetyLog::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(dateOfOccurrence), BusSafetyLog::getDateOfOccurrence, dateOfOccurrence);
        lqw.eq(ObjectUtils.isNotEmpty(airTemperatureMax), BusSafetyLog::getAirTemperatureMax, airTemperatureMax);
        lqw.eq(ObjectUtils.isNotEmpty(airTemperatureMin), BusSafetyLog::getAirTemperatureMin, airTemperatureMin);
        lqw.eq(ObjectUtils.isNotEmpty(weather), BusSafetyLog::getWeather, weather);
        return lqw;
    }

    /**
     * 获取安全日志分页对象视图
     *
     * @param safetyLogPage 安全日志分页对象
     * @return 安全日志分页对象视图
     */
    @Override
    public Page<BusSafetyLogVo> getVoPage(Page<BusSafetyLog> safetyLogPage) {
        // 获取安全日志列表
        List<BusSafetyLog> safetyLogList = safetyLogPage.getRecords();
        // 添加分页信息
        Page<BusSafetyLogVo> safetyLogVoPage = new Page<>(
            safetyLogPage.getCurrent(),
            safetyLogPage.getSize(),
            safetyLogPage.getTotal());
        if (CollUtil.isEmpty(safetyLogList)) {
            return safetyLogVoPage;
        }
        // 对象列表 => 封装对象列表
        List<BusSafetyLogVo> safetyLogVoList = safetyLogList.stream().map(this::getVo).toList();
        safetyLogVoPage.setRecords(safetyLogVoList);
        return safetyLogVoPage;
    }
}
