package com.xy.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xy.dto.DeviceTempRecordsDto;
import com.xy.entity.DeviceTempRecords;
import com.xy.event.DeviceEvent;
import com.xy.mapper.DeviceTempRecordsMapper;
import com.xy.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;

import static com.xy.utils.Beans.copy;
import static com.xy.utils.PlusBeans.toIPage;
import static com.xy.utils.PlusBeans.toPageBean;


/**
 * <p>
 * 设备温度日志表 服务实现类
 * </p>
 *
 * @author lijin
 * @since 2023-01-11
 */
@Service
@AllArgsConstructor
@Api(tags = "设备温度日志表")
public class DeviceTempRecordsServiceImpl extends ServiceImpl<DeviceTempRecordsMapper, DeviceTempRecords> implements DeviceTempRecordsService {

    @Override
    @ApiOperation("分页查询")
    public R<PageBean<DeviceTempRecordsDto.Vo>> page(@RequestBody DeviceTempRecordsDto.Page page) {
        PageBean pageBean = page.getPage();
        LambdaQueryWrapper<DeviceTempRecords> lambdaQueryWrapper = new MybatisPlusQuery().eqWrapper(page, DeviceTempRecords.class)
                .ge(DeviceTempRecords::getCreateTime, page.getBeginCreateTime())
                .le(DeviceTempRecords::getCreateTime, page.getEndCreateTime())
                .build()
                .orderByDesc(!Emptys.check(pageBean.getOrders()), DeviceTempRecords::getCreateTime);
        IPage<DeviceTempRecords> iPage = page(toIPage(pageBean), lambdaQueryWrapper);
        return R.ok(toPageBean(DeviceTempRecordsDto.Vo.class, iPage));
    }

    @PostMapping("save")
    @ApiOperation("添加")
    public R save(@RequestBody @Validated DeviceTempRecordsDto.Save save) {
        DeviceTempRecords saveInfo = copy(DeviceTempRecords.class, save)
                .setCreateTime(LocalDateTime.now());
        save(saveInfo);
        //发布事件
        DeviceEvent.TempEvent tempEvent = new DeviceEvent.TempEvent()
                .setTempValue(save.getTempValue());
        tempEvent.setValue(save.getDeviceId());
        EventUtils.push(() -> tempEvent);
        return R.ok();
    }

}