package com.hotwj.platform.securityManagement.accidentArchive.service.impl;

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.hotwj.platform.securityManagement.accidentArchive.domain.HotAccidentArchive;
import com.hotwj.platform.securityManagement.accidentArchive.domain.bo.HotAccidentArchiveBo;
import com.hotwj.platform.securityManagement.accidentArchive.domain.vo.HotAccidentArchiveVo;
import com.hotwj.platform.securityManagement.accidentArchive.mapper.HotAccidentArchiveMapper;
import com.hotwj.platform.securityManagement.accidentArchive.service.IHotAccidentArchiveService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
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.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 事故档案Service业务层处理
 *
 * @author shihongwei
 * @date 2026-01-04
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotAccidentArchiveServiceImpl implements IHotAccidentArchiveService {

    private final HotAccidentArchiveMapper baseMapper;

    /**
     * 查询事故档案
     *
     * @param id 主键
     * @return 事故档案
     */
    @Override
    public HotAccidentArchiveVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询事故档案列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 事故档案分页列表
     */
    @Override
    public TableDataInfo<HotAccidentArchiveVo> queryPageList(HotAccidentArchiveBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotAccidentArchive> lqw = buildQueryWrapper(bo);
        Page<HotAccidentArchiveVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的事故档案列表
     *
     * @param bo 查询条件
     * @return 事故档案列表
     */
    @Override
    public List<HotAccidentArchiveVo> queryList(HotAccidentArchiveBo bo) {
        LambdaQueryWrapper<HotAccidentArchive> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据车辆ID查询最新的一条事故档案
     *
     * @param vehicleId 车辆ID
     * @return 最新事故档案
     */
    @Override
    public HotAccidentArchiveVo queryLatestByVehicleId(String vehicleId) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<HotAccidentArchive>()
            .eq(HotAccidentArchive::getVehicleId, vehicleId)
            .orderByDesc(HotAccidentArchive::getId)
            .last("LIMIT 1"));
    }

    /**
     * 根据车辆ID查询事故档案列表
     *
     * @param vehicleId 车辆ID
     * @return 事故档案列表
     */
    @Override
    public List<HotAccidentArchiveVo> queryListByVehicleId(String vehicleId) {
        return baseMapper.selectVoList(new LambdaQueryWrapper<HotAccidentArchive>()
            .eq(HotAccidentArchive::getVehicleId, vehicleId)
            .orderByDesc(HotAccidentArchive::getId));
    }

    private LambdaQueryWrapper<HotAccidentArchive> buildQueryWrapper(HotAccidentArchiveBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotAccidentArchive> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(HotAccidentArchive::getAccidentTime);
        if (bo.getAccidentTime() != null) {
            java.util.Calendar calendarStart = java.util.Calendar.getInstance();
            calendarStart.setTime(bo.getAccidentTime());
            calendarStart.set(java.util.Calendar.HOUR_OF_DAY, 0);
            calendarStart.set(java.util.Calendar.MINUTE, 0);
            calendarStart.set(java.util.Calendar.SECOND, 0);
            calendarStart.set(java.util.Calendar.MILLISECOND, 0);
            java.util.Calendar calendarEnd = (java.util.Calendar) calendarStart.clone();
            calendarEnd.add(java.util.Calendar.DAY_OF_MONTH, 1);
            lqw.ge(HotAccidentArchive::getAccidentTime, calendarStart.getTime());
            lqw.lt(HotAccidentArchive::getAccidentTime, calendarEnd.getTime());
        }
        lqw.eq(bo.getCompanyId() != null, HotAccidentArchive::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getCreateBy() != null, HotAccidentArchive::getCreateBy, bo.getCreateBy());
        lqw.eq(StringUtils.isNotBlank(bo.getAccidentNo()), HotAccidentArchive::getAccidentNo, bo.getAccidentNo());
        lqw.eq(bo.getVehicleId() != null, HotAccidentArchive::getVehicleId, bo.getVehicleId());
        lqw.like(StringUtils.isNotBlank(bo.getPlateNumber()), HotAccidentArchive::getPlateNumber, bo.getPlateNumber());
        lqw.eq(bo.getDriverId() != null, HotAccidentArchive::getDriverId, bo.getDriverId());
        lqw.like(StringUtils.isNotBlank(bo.getDriverName()), HotAccidentArchive::getDriverName, bo.getDriverName());
        lqw.eq(StringUtils.isNotBlank(bo.getDriverPhone()), HotAccidentArchive::getDriverPhone, bo.getDriverPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getDriverProfCertNo()), HotAccidentArchive::getDriverProfCertNo, bo.getDriverProfCertNo());
        lqw.eq(StringUtils.isNotBlank(bo.getOperationCertificateNumber()), HotAccidentArchive::getOperationCertificateNumber, bo.getOperationCertificateNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getOccurLocation()), HotAccidentArchive::getOccurLocation, bo.getOccurLocation());
        lqw.eq(StringUtils.isNotBlank(bo.getMainCause()), HotAccidentArchive::getMainCause, bo.getMainCause());
        lqw.eq(StringUtils.isNotBlank(bo.getDivisionResponsibilities()), HotAccidentArchive::getDivisionResponsibilities, bo.getDivisionResponsibilities());
        lqw.eq(bo.getDeathToll() != null, HotAccidentArchive::getDeathToll, bo.getDeathToll());
        lqw.eq(bo.getNumberSeriouslyInjured() != null, HotAccidentArchive::getNumberSeriouslyInjured, bo.getNumberSeriouslyInjured());
        lqw.eq(bo.getNumberMinorInjuries() != null, HotAccidentArchive::getNumberMinorInjuries, bo.getNumberMinorInjuries());
        lqw.eq(bo.getEconomicLoss() != null, HotAccidentArchive::getEconomicLoss, bo.getEconomicLoss());
        lqw.eq(StringUtils.isNotBlank(bo.getAccidentPattern()), HotAccidentArchive::getAccidentPattern, bo.getAccidentPattern());
        lqw.eq(StringUtils.isNotBlank(bo.getWeather()), HotAccidentArchive::getWeather, bo.getWeather());
        lqw.eq(StringUtils.isNotBlank(bo.getRoadTechnicalGrade()), HotAccidentArchive::getRoadTechnicalGrade, bo.getRoadTechnicalGrade());
        lqw.eq(StringUtils.isNotBlank(bo.getRoadLinearityStatus()), HotAccidentArchive::getRoadLinearityStatus, bo.getRoadLinearityStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getRoadSurfaceCondition()), HotAccidentArchive::getRoadSurfaceCondition, bo.getRoadSurfaceCondition());
        lqw.eq(StringUtils.isNotBlank(bo.getAccidentForms()), HotAccidentArchive::getAccidentForms, bo.getAccidentForms());
        lqw.eq(StringUtils.isNotBlank(bo.getAccidentDirectCauses()), HotAccidentArchive::getAccidentDirectCauses, bo.getAccidentDirectCauses());
        lqw.eq(StringUtils.isNotBlank(bo.getRouteType()), HotAccidentArchive::getRouteType, bo.getRouteType());
        lqw.eq(StringUtils.isNotBlank(bo.getVehicleGrade()), HotAccidentArchive::getVehicleGrade, bo.getVehicleGrade());
        lqw.like(StringUtils.isNotBlank(bo.getRouteName()), HotAccidentArchive::getRouteName, bo.getRouteName());
        lqw.eq(StringUtils.isNotBlank(bo.getOriginStation()), HotAccidentArchive::getOriginStation, bo.getOriginStation());
        lqw.eq(StringUtils.isNotBlank(bo.getCompanyQualificationGrade()), HotAccidentArchive::getCompanyQualificationGrade, bo.getCompanyQualificationGrade());
        lqw.like(StringUtils.isNotBlank(bo.getAccidentLevel()), HotAccidentArchive::getAccidentLevel, bo.getAccidentLevel());
        lqw.eq(bo.getIsRectified() != null, HotAccidentArchive::getIsRectified, bo.getIsRectified());
        lqw.eq(StringUtils.isNotBlank(bo.getVehicleType()), HotAccidentArchive::getVehicleType, bo.getVehicleType());
        lqw.eq(bo.getApprovedPersons() != null, HotAccidentArchive::getApprovedPersons, bo.getApprovedPersons());
        lqw.eq(bo.getApprovedTonnage() != null, HotAccidentArchive::getApprovedTonnage, bo.getApprovedTonnage());
        lqw.eq(bo.getCarriedPersons() != null, HotAccidentArchive::getCarriedPersons, bo.getCarriedPersons());
        lqw.eq(bo.getCarriedTonnage() != null, HotAccidentArchive::getCarriedTonnage, bo.getCarriedTonnage());
        lqw.eq(bo.getMissingPersons() != null, HotAccidentArchive::getMissingPersons, bo.getMissingPersons());
        lqw.eq(bo.getInjuredPersons() != null, HotAccidentArchive::getInjuredPersons, bo.getInjuredPersons());
        lqw.eq(StringUtils.isNotBlank(bo.getUnitResponsible()), HotAccidentArchive::getUnitResponsible, bo.getUnitResponsible());
        lqw.eq(StringUtils.isNotBlank(bo.getLeadResponsible()), HotAccidentArchive::getLeadResponsible, bo.getLeadResponsible());
        lqw.like(StringUtils.isNotBlank(bo.getReporterName()), HotAccidentArchive::getReporterName, bo.getReporterName());
        lqw.like(StringUtils.isNotBlank(bo.getReporterPhone()), HotAccidentArchive::getReporterPhone, bo.getReporterPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getAccidentSituation()), HotAccidentArchive::getAccidentSituation, bo.getAccidentSituation());
        lqw.eq(StringUtils.isNotBlank(bo.getAccidentContent()), HotAccidentArchive::getAccidentContent, bo.getAccidentContent());
        lqw.eq(bo.getIsDeleted() != null, HotAccidentArchive::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增事故档案
     *
     * @param bo 事故档案
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotAccidentArchiveBo bo) {
        HotAccidentArchive add = MapstructUtils.convert(bo, HotAccidentArchive.class);
        if (StringUtils.isBlank(add.getAccidentNo())) {
            add.setAccidentNo("SG-" + System.currentTimeMillis() / 1000);
        }
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            bo.setAccidentNo(add.getAccidentNo());
        }
        return flag;
    }

    /**
     * 修改事故档案
     *
     * @param bo 事故档案
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotAccidentArchiveBo bo) {
        HotAccidentArchive update = MapstructUtils.convert(bo, HotAccidentArchive.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HotAccidentArchive entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除事故档案信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
