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.service.IBusProjectService;
import org.dromara.safety.domain.HseSafetyLog;
import org.dromara.safety.domain.dto.safetylog.HseSafetyLogCreateReq;
import org.dromara.safety.domain.dto.safetylog.HseSafetyLogQueryReq;
import org.dromara.safety.domain.dto.safetylog.HseSafetyLogUpdateReq;
import org.dromara.safety.domain.vo.safetylog.HseSafetyLogVo;
import org.dromara.safety.mapper.HseSafetyLogMapper;
import org.dromara.safety.service.IHseSafetyLogService;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.mapper.SysUserMapper;
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 HseSafetyLogServiceImpl extends ServiceImpl<HseSafetyLogMapper, HseSafetyLog>
    implements IHseSafetyLogService {

    @Resource
    private IBusProjectService projectService;

    @Resource
    private SysUserMapper userMapper;

    /**
     * 查询安全日志
     *
     * @param id 主键
     * @return 安全日志
     */
    @Override
    public HseSafetyLogVo queryById(Long id) {
        HseSafetyLog 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<HseSafetyLogVo> queryPageList(HseSafetyLogQueryReq req, PageQuery pageQuery) {
        Page<HseSafetyLog> result = this.page(pageQuery.build(), this.buildQueryWrapper(req));
        return TableDataInfo.build(this.getVoPage(result));
    }

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

    /**
     * 新增安全日志
     *
     * @param req 安全日志
     * @return 新增id
     */
    @Override
    public Long insertByBo(HseSafetyLogCreateReq req) {
        // 将实体类和 DTO 进行转换
        HseSafetyLog safetyLog = new HseSafetyLog();
        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(HseSafetyLogUpdateReq req) {
        // 将实体类和 DTO 进行转换
        HseSafetyLog safetyLog = new HseSafetyLog();
        BeanUtils.copyProperties(req, safetyLog);
        // 数据校验
        validEntityBeforeSave(safetyLog, false);
        // 判断是否存在
        HseSafetyLog oldSafetyLog = this.getById(safetyLog.getId());
        if (oldSafetyLog == null) {
            throw new ServiceException("修改安全日志信息失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 操作数据库
        return this.updateById(safetyLog);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HseSafetyLog 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 HseSafetyLogVo getVo(HseSafetyLog safetyLog) {
        // 对象转封装类
        HseSafetyLogVo safetyLogVo = new HseSafetyLogVo();
        if (safetyLog == null) {
            return safetyLogVo;
        }
        BeanUtils.copyProperties(safetyLog, safetyLogVo);
        // 关联创建用户信息
        Long createBy = safetyLog.getCreateBy();
        if (createBy != null) {
            SysUserVo sysUserVo = userMapper.selectVoById(createBy);
            safetyLogVo.setCreator(IdAndNameVO.build(sysUserVo.getUserId(), sysUserVo.getNickName()));
        }
        return safetyLogVo;
    }

    /**
     * 获取安全日志查询条件封装
     *
     * @param req 安全日志查询条件
     * @return 安全日志查询条件封装
     */
    @Override
    public LambdaQueryWrapper<HseSafetyLog> buildQueryWrapper(HseSafetyLogQueryReq req) {
        LambdaQueryWrapper<HseSafetyLog> lqw = Wrappers.lambdaQuery();
        if (req == null) {
            return lqw;
        }
        Long id = req.getId();
        Long projectId = req.getProjectId();
        String dateOfOccurrence = req.getDateOfOccurrence();
        String creatorName = req.getCreatorName();
        // 联表查询
        if (StringUtils.isNotBlank(creatorName)) {
            LambdaQueryWrapper<SysUser> userQueryWrapper = new LambdaQueryWrapper<>();
            userQueryWrapper.like(SysUser::getUserName, creatorName);
            List<SysUserVo> sysUserVos = userMapper.selectUserList(userQueryWrapper);
            if (CollUtil.isNotEmpty(sysUserVos)) {
                List<Long> userIds = sysUserVos.stream().map(SysUserVo::getUserId).toList();
                lqw.in(HseSafetyLog::getCreateBy, userIds);
            }
        }
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(id), HseSafetyLog::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), HseSafetyLog::getProjectId, projectId);
        lqw.eq(ObjectUtils.isNotEmpty(dateOfOccurrence), HseSafetyLog::getDateOfOccurrence, dateOfOccurrence);
        return lqw;
    }

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