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.service.IBusProjectService;
import org.dromara.safety.domain.BusSafetyWeeklyReport;
import org.dromara.safety.domain.req.safetyweeklyreport.SafetyWeeklyReportCreateReq;
import org.dromara.safety.domain.req.safetyweeklyreport.SafetyWeeklyReportQueryReq;
import org.dromara.safety.domain.req.safetyweeklyreport.SafetyWeeklyReportUpdateReq;
import org.dromara.safety.domain.vo.BusSafetyWeeklyReportVo;
import org.dromara.safety.mapper.BusSafetyWeeklyReportMapper;
import org.dromara.safety.service.IBusSafetyWeeklyReportService;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysOssService;
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 BusSafetyWeeklyReportServiceImpl extends ServiceImpl<BusSafetyWeeklyReportMapper, BusSafetyWeeklyReport>
    implements IBusSafetyWeeklyReportService {

    @Resource
    private ISysOssService ossService;

    @Resource
    private IBusProjectService projectService;

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

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

    /**
     * 查询符合条件的安全周报列表
     *
     * @param req 查询条件
     * @return 安全周报列表
     */
    @Override
    public List<BusSafetyWeeklyReportVo> queryList(SafetyWeeklyReportQueryReq req) {
        List<BusSafetyWeeklyReport> safetyWeeklyReportList = this.list(this.buildQuery(req));
        return safetyWeeklyReportList.stream().map(this::getVo).toList();
    }

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

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

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusSafetyWeeklyReport 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 safetyWeeklyReport 安全周报对象
     * @return 安全周报视图对象
     */
    @Override
    public BusSafetyWeeklyReportVo getVo(BusSafetyWeeklyReport safetyWeeklyReport) {
        // 对象转封装类
        BusSafetyWeeklyReportVo safetyWeeklyReportVo = new BusSafetyWeeklyReportVo();
        if (safetyWeeklyReport == null) {
            return safetyWeeklyReportVo;
        }
        BeanUtils.copyProperties(safetyWeeklyReport, safetyWeeklyReportVo);
        // 获取文件信息
        String path = safetyWeeklyReport.getPath();
        if (StringUtils.isNotBlank(path)) {
            SysOssVo ossVo = ossService.getById(Long.valueOf(path));
            safetyWeeklyReportVo.setPathUrl(ossVo.getUrl());
        }
        return safetyWeeklyReportVo;
    }

    /**
     * 获取安全周报查询条件封装
     *
     * @param req 安全周报查询条件
     * @return 安全周报查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusSafetyWeeklyReport> buildQuery(SafetyWeeklyReportQueryReq req) {
        LambdaQueryWrapper<BusSafetyWeeklyReport> lqw = Wrappers.lambdaQuery();
        if (req == null) {
            return lqw;
        }
        Long id = req.getId();
        Long projectId = req.getProjectId();
        String week = req.getWeek();
        List<String> scopeDate = req.getScopeDate();
        String remark = req.getRemark();
        // 时间范围查询
        if (ObjectUtils.isNotEmpty(scopeDate)) {
            lqw.ge(BusSafetyWeeklyReport::getScopeEnd, scopeDate.get(0))
                .le(BusSafetyWeeklyReport::getScope, scopeDate.get(1));
        }
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(remark), BusSafetyWeeklyReport::getRemark, remark);
        // 精准查询
        lqw.eq(ObjectUtils.isNotEmpty(id), BusSafetyWeeklyReport::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), BusSafetyWeeklyReport::getProjectId, projectId);
        lqw.eq(ObjectUtils.isNotEmpty(week), BusSafetyWeeklyReport::getWeek, week);
        return lqw;
    }

    /**
     * 获取安全周报分页对象视图
     *
     * @param safetyWeeklyReportPage 安全周报分页对象
     * @return 安全周报分页对象视图
     */
    @Override
    public Page<BusSafetyWeeklyReportVo> getVoPage(Page<BusSafetyWeeklyReport> safetyWeeklyReportPage) {
        // 获取安全周报列表
        List<BusSafetyWeeklyReport> safetyWeeklyReportList = safetyWeeklyReportPage.getRecords();
        // 添加分页信息
        Page<BusSafetyWeeklyReportVo> safetyWeeklyReportVoPage = new Page<>(
            safetyWeeklyReportPage.getCurrent(),
            safetyWeeklyReportPage.getSize(),
            safetyWeeklyReportPage.getTotal());
        if (CollUtil.isEmpty(safetyWeeklyReportList)) {
            return safetyWeeklyReportVoPage;
        }
        // 对象列表 => 封装对象列表
        List<BusSafetyWeeklyReportVo> safetyWeeklyReportVoList = safetyWeeklyReportList.stream().map(this::getVo).toList();
        safetyWeeklyReportVoPage.setRecords(safetyWeeklyReportVoList);
        return safetyWeeklyReportVoPage;
    }
}
