package org.springblade.openinterface.iot;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.api.R;
import org.springblade.homecare.alarmlist.entity.Alarm;
import org.springblade.homecare.alarmlist.service.IAlarmService;
import org.springblade.openinterface.dto.AlarmNoticeDto;
import org.springblade.smartapplication.smartsmoke.entity.SmartDevice;
import org.springblade.smartapplication.smartsmoke.service.ISmartDeviceService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("openinterface/iot")
@Api(value = "物联网设备告警开放接口", tags = "开放接口")
public class IotDeviceOpenController {

	private ISmartDeviceService iSmartDeviceService;


	@PostMapping("/device/sync")
	public R iotDeviceSync(@RequestBody List<SmartDevice> smartDeviceList) {
		List<SmartDevice> insertOrUpdateList = new ArrayList<>();
		smartDeviceList.forEach(source -> {
			QueryWrapper<SmartDevice> wrapper = new QueryWrapper<>();
			wrapper.eq("device_id", source.getDeviceId());
			SmartDevice target = this.iSmartDeviceService.getOne(wrapper);
			if (target == null) {
				target = new SmartDevice();
			} else {
				source.setId(target.getId());
				if (target.getLatitudeLongitude() != null) {
					source.setLatitudeLongitude(target.getLatitudeLongitude());
				}
			}

			BeanUtils.copyProperties(source, target);
			target.setLastUpdateTime(LocalDateTime.now());
			insertOrUpdateList.add(target);
		});
		this.iSmartDeviceService.saveOrUpdateBatch(insertOrUpdateList);
		return R.status(true);
	}
}
