package com.hotwj.platform.resourceManagement.vehicleDriveLog.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.resourceManagement.vehicleDriveLog.domain.HotVehicleDriveLog;
import com.hotwj.platform.resourceManagement.vehicleDriveLog.domain.bo.HotVehicleDriveLogBo;
import com.hotwj.platform.resourceManagement.vehicleDriveLog.domain.vo.HotVehicleDriveLogVo;
import com.hotwj.platform.resourceManagement.vehicleDriveLog.mapper.HotVehicleDriveLogMapper;
import com.hotwj.platform.resourceManagement.vehicleDriveLog.service.IHotVehicleDriveLogService;
import com.hotwj.platform.resourceManagement.vehicleMileage.domain.bo.HotVehicleMileageBo;
import com.hotwj.platform.resourceManagement.vehicleMileage.service.IHotVehicleMileageService;
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-02-03
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotVehicleDriveLogServiceImpl implements IHotVehicleDriveLogService {

    private final HotVehicleDriveLogMapper baseMapper;
    private final IHotVehicleMileageService hotVehicleMileageService;

    /**
     * 查询车辆行驶日志
     *
     * @param id 主键
     * @return 车辆行驶日志
     */
    @Override
    public HotVehicleDriveLogVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询车辆行驶日志列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 车辆行驶日志分页列表
     */
    @Override
    public TableDataInfo<HotVehicleDriveLogVo> queryPageList(HotVehicleDriveLogBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotVehicleDriveLog> lqw = buildQueryWrapper(bo);
        Page<HotVehicleDriveLogVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的车辆行驶日志列表
     *
     * @param bo 查询条件
     * @return 车辆行驶日志列表
     */
    @Override
    public List<HotVehicleDriveLogVo> queryList(HotVehicleDriveLogBo bo) {
        LambdaQueryWrapper<HotVehicleDriveLog> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotVehicleDriveLog> buildQueryWrapper(HotVehicleDriveLogBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotVehicleDriveLog> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(HotVehicleDriveLog::getId);
        lqw.eq(bo.getCompanyId() != null, HotVehicleDriveLog::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getVehicleId() != null, HotVehicleDriveLog::getVehicleId, bo.getVehicleId());
        lqw.eq(StringUtils.isNotBlank(bo.getPlateNumber()), HotVehicleDriveLog::getPlateNumber, bo.getPlateNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getDriverId()), HotVehicleDriveLog::getDriverId, bo.getDriverId());
        lqw.like(StringUtils.isNotBlank(bo.getDriverName()), HotVehicleDriveLog::getDriverName, bo.getDriverName());
        lqw.eq(StringUtils.isNotBlank(bo.getDriverPhone()), HotVehicleDriveLog::getDriverPhone, bo.getDriverPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getStartPlace()), HotVehicleDriveLog::getStartPlace, bo.getStartPlace());
        lqw.eq(StringUtils.isNotBlank(bo.getEndPlace()), HotVehicleDriveLog::getEndPlace, bo.getEndPlace());
        lqw.eq(bo.getStartTime() != null, HotVehicleDriveLog::getStartTime, bo.getStartTime());
        lqw.eq(bo.getEndTime() != null, HotVehicleDriveLog::getEndTime, bo.getEndTime());
        lqw.eq(bo.getStartMileageKm() != null, HotVehicleDriveLog::getStartMileageKm, bo.getStartMileageKm());
        lqw.eq(bo.getEndMileageKm() != null, HotVehicleDriveLog::getEndMileageKm, bo.getEndMileageKm());
        lqw.eq(bo.getDriveDistanceKm() != null, HotVehicleDriveLog::getDriveDistanceKm, bo.getDriveDistanceKm());
        lqw.eq(StringUtils.isNotBlank(bo.getUsePurpose()), HotVehicleDriveLog::getUsePurpose, bo.getUsePurpose());
        lqw.like(StringUtils.isNotBlank(bo.getCreateByName()), HotVehicleDriveLog::getCreateByName, bo.getCreateByName());
        lqw.like(StringUtils.isNotBlank(bo.getUpdateByName()), HotVehicleDriveLog::getUpdateByName, bo.getUpdateByName());
        lqw.eq(bo.getIsDeleted() != null, HotVehicleDriveLog::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增车辆行驶日志
     *
     * @param bo 车辆行驶日志
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotVehicleDriveLogBo bo) {
        HotVehicleDriveLog add = MapstructUtils.convert(bo, HotVehicleDriveLog.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            generateMileageRecord(add);
        }
        return flag;
    }

    /**
     * 修改车辆行驶日志
     *
     * @param bo 车辆行驶日志
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotVehicleDriveLogBo bo) {
        HotVehicleDriveLog update = MapstructUtils.convert(bo, HotVehicleDriveLog.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag && bo.getDriveDistanceKm() != null) {
            HotVehicleDriveLog fullLog = baseMapper.selectById(bo.getId());
            generateMileageRecord(fullLog);
        }
        return flag;
    }

    /**
     * 生成车辆行驶里程记录
     *
     * @param entity 车辆行驶日志
     */
    private void generateMileageRecord(HotVehicleDriveLog entity) {
        if (entity.getDriveDistanceKm() != null) {
            HotVehicleMileageBo mileageBo = new HotVehicleMileageBo();
            mileageBo.setCompanyId(entity.getCompanyId());
            mileageBo.setVehicleId(entity.getVehicleId());
            mileageBo.setPlateNumber(entity.getPlateNumber());
            mileageBo.setStartDate(entity.getStartTime());
            mileageBo.setEndDate(entity.getEndTime());
            mileageBo.setMileageKm(entity.getDriveDistanceKm());
            mileageBo.setRemark("由车辆行驶日志自动生成");
            hotVehicleMileageService.insertByBo(mileageBo);
        }
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HotVehicleDriveLog entity) {
        //TODO 做一些数据校验,如唯一约束
        if (entity.getStartTime() != null && entity.getEndTime() != null) {
            long timeDiff = entity.getEndTime().getTime() - entity.getStartTime().getTime();
            if (timeDiff < 0) {
                throw new org.dromara.common.core.exception.ServiceException("到达时间不能早于出发时间");
            }
            if (timeDiff > 0) {
                java.math.BigDecimal distance = entity.getDriveDistanceKm();
                if (distance == null && entity.getStartMileageKm() != null && entity.getEndMileageKm() != null) {
                    distance = entity.getEndMileageKm().subtract(entity.getStartMileageKm());
                }
                if (distance != null) {
                    double hours = timeDiff / (1000.0 * 60 * 60);
                    double speed = distance.doubleValue() / hours;
                    if (speed > 150.0) {
                        throw new org.dromara.common.core.exception.ServiceException("平均速度超过150km/h，请检查行驶里程和时间是否填写正确");
                    }
                }
            }
        }
    }

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