package com.evobms.project.vehicledata.service.impl;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.evobms.common.utils.DateUtils;
import com.evobms.project.battery.mapper.ExtremeValuesMapper;
import com.evobms.project.system.domain.BmsDevices;
import com.evobms.project.system.mapper.BmsDevicesMapper;
import com.evobms.project.vehicledata.domain.HomeDashboardDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.evobms.project.vehicledata.mapper.VehicleDataMapper;
import com.evobms.project.vehicledata.domain.VehicleData;
import com.evobms.project.vehicledata.service.IVehicleDataService;

/**
 * 整车数据Service业务层处理
 *
 * @author 田志阳
 * @date 2025-11-15
 */
@Service
public class VehicleDataServiceImpl extends ServiceImpl<VehicleDataMapper, VehicleData> implements IVehicleDataService
{
    @Autowired
    private VehicleDataMapper vehicleDataMapper;
    @Autowired
    private BmsDevicesMapper bmsDevicesMapper;

    @Autowired
    private ExtremeValuesMapper extremeValuesMapper;
    /**
     * 查询整车数据
     *
     * @param id 整车数据主键
     * @return 整车数据
     */
    @Override
    public VehicleData selectVehicleDataById(Long id)
    {
        return vehicleDataMapper.selectVehicleDataById(id);
    }

    /**
     * 查询整车数据列表
     *
     * @param vehicleData 整车数据
     * @return 整车数据
     */
    @Override
    public List<VehicleData> selectVehicleDataList(VehicleData vehicleData)
    {
        LambdaQueryWrapper<VehicleData> qw = new LambdaQueryWrapper<>();
        if (vehicleData != null) {
            if (vehicleData.getDeviceId() != null && !vehicleData.getDeviceId().isEmpty()) {
                qw.eq(VehicleData::getDeviceId, vehicleData.getDeviceId());
            }
            if (vehicleData.getTimestamp() != null) {
                qw.ge(VehicleData::getTimestamp, vehicleData.getTimestamp());
            }
            Map<String, Object> params = vehicleData.getParams();
            if (params != null) {
                Date begin = DateUtils.parseDate(params.get("beginTime"));
                Date end = DateUtils.parseDate(params.get("endTime"));
                if (begin != null) {
                    qw.ge(VehicleData::getTimestamp, begin);
                }
                if (end != null) {
                    qw.le(VehicleData::getTimestamp, end);
                }
            }
        }
        qw.orderByDesc(VehicleData::getTimestamp);
        return vehicleDataMapper.selectList(qw);
    }

    /**
     * 新增整车数据
     *
     * @param vehicleData 整车数据
     * @return 结果
     */
    @Override
    public int insertVehicleData(VehicleData vehicleData)
    {
        return vehicleDataMapper.insertVehicleData(vehicleData);
    }

    /**
     * 修改整车数据
     *
     * @param vehicleData 整车数据
     * @return 结果
     */
    @Override
    public int updateVehicleData(VehicleData vehicleData)
    {
        return vehicleDataMapper.updateVehicleData(vehicleData);
    }

    /**
     * 批量删除整车数据
     *
     * @param ids 需要删除的整车数据主键
     * @return 结果
     */
    @Override
    public int deleteVehicleDataByIds(Long[] ids)
    {
        return vehicleDataMapper.deleteVehicleDataByIds(ids);
    }

    /**
     * 删除整车数据信息
     *
     * @param id 整车数据主键
     * @return 结果
     */
    @Override
    public int deleteVehicleDataById(Long id)
    {
        return vehicleDataMapper.deleteVehicleDataById(id);
    }

    @Override
    public List<VehicleData> selectByDeviceAndStartTime(String deviceId, Date startTime) {
        LambdaQueryWrapper<VehicleData> byTimestamp = new LambdaQueryWrapper<>();
        byTimestamp.eq(VehicleData::getDeviceId, deviceId)
                   .ge(VehicleData::getTimestamp, startTime)
                   .orderByAsc(VehicleData::getTimestamp);
        List<VehicleData> rows = vehicleDataMapper.selectList(byTimestamp);
        if (rows == null || rows.isEmpty()) {
            LambdaQueryWrapper<VehicleData> byCreateTime = new LambdaQueryWrapper<>();
            byCreateTime.eq(VehicleData::getDeviceId, deviceId)
                        .ge(VehicleData::getCreateTime, startTime)
                        .orderByAsc(VehicleData::getCreateTime);
            rows = vehicleDataMapper.selectList(byCreateTime);
        }
        return rows;
    }

    @Override
    public VehicleData selectLatestByDeviceId(String deviceId) {
        LambdaQueryWrapper<VehicleData> byTimestamp = new LambdaQueryWrapper<>();
        byTimestamp.eq(VehicleData::getDeviceId, deviceId)
                   .orderByDesc(VehicleData::getTimestamp)
                   .last("limit 1");
        VehicleData latest = vehicleDataMapper.selectOne(byTimestamp);
        if (latest == null) {
            LambdaQueryWrapper<VehicleData> byCreateTime = new LambdaQueryWrapper<>();
            byCreateTime.eq(VehicleData::getDeviceId, deviceId)
                        .orderByDesc(VehicleData::getCreateTime)
                        .last("limit 1");
            latest = vehicleDataMapper.selectOne(byCreateTime);
        }
        return latest;
    }

    @Override
    public HomeDashboardDTO getHomeDashboard() {
        HomeDashboardDTO dto = new HomeDashboardDTO();
        // 1️⃣ 设备总数
        Long deviceCount = bmsDevicesMapper.selectCount(null);
        dto.setDeviceCount(deviceCount);
        return null;
    }

    @Scheduled(fixedDelay = 60000)
    public void checkDeviceOffline() {
        LocalDateTime threshold = LocalDateTime.now().minusMinutes(5);
        bmsDevicesMapper.update(null, new UpdateWrapper<BmsDevices>()
                .set("status", "offline")
                .lt("last_online", threshold));
        bmsDevicesMapper.update(null, new UpdateWrapper<BmsDevices>()
                .set("status", "online")
                .ge("last_online", threshold));
    }
}
