package com.ruoyi.iot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.iot.domain.TChargeRecord;
import com.ruoyi.iot.mapper.TChargeRecordMapper;
import com.ruoyi.iot.service.DeviceControlerService;
import com.ruoyi.iot.service.ITChargeRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j
@Service
public class TChargeRecordServiceImpl extends ServiceImpl<TChargeRecordMapper, TChargeRecord> implements ITChargeRecordService {

    @Autowired
    private DeviceControlerService deviceControlerService;
    @Override
    public void startCharge(String deviceId, String ccid, Long userId) {
        deviceControlerService.startCharge(deviceId,ccid);
        TChargeRecord tChargeRecord = new TChargeRecord();
        tChargeRecord.setCreateTime(LocalDateTime.now());
        tChargeRecord.setDeviceId(deviceId);
        tChargeRecord.setStatus(0L);
        tChargeRecord.setUserId(userId);
        this.save(tChargeRecord);
    }

    @Override
    public void endChargeNotice(String deviceId) {
        LambdaQueryWrapper<TChargeRecord> objectLambdaQueryWrapper = Wrappers.lambdaQuery();
        objectLambdaQueryWrapper.orderByDesc(TChargeRecord::getCreateTime);
        objectLambdaQueryWrapper.eq(TChargeRecord::getDeviceId,deviceId).eq(TChargeRecord::getStatus,0);
        objectLambdaQueryWrapper.last(" limit 1");
        TChargeRecord one = this.getOne(objectLambdaQueryWrapper);
        if(one != null){
            one.setStatus(1L);
            one.setEndTime(LocalDateTime.now());
            this.updateById(one);
        }

    }


}
