package com.iwunu.nbiot.lock.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.iwunu.nbiot.common.util.DateUtil;
import com.iwunu.nbiot.common.util.PitNumUtil;
import com.iwunu.nbiot.lock.entity.CmdData;
import com.iwunu.nbiot.lock.repository.IotCmdDataRepository;
import com.iwunu.nbiot.lock.service.IotCmdDataService;
import java.util.List;
@Service
public class IotCmdDataServiceImpl implements IotCmdDataService{
	@Autowired
	private IotCmdDataRepository iotCmdDataRepository;

	@Override
	public Integer getPitNumByCmdType(String deviceId, String cmdType) {
		List<Integer> list = iotCmdDataRepository.findListByCmdType(deviceId, cmdType);
		return PitNumUtil.getPitNum(list);
	}

	@Override
	public CmdData save(String deviceId,JSONObject cmdData) {
		CmdData cmd = new CmdData();
		cmd.setDeviceId(deviceId);
		cmd.setPitNum(cmdData.getInteger("pitNum"));
		cmd.setSendContext(cmdData.getString("cmdContext"));
		cmd.setCmdSeq(cmdData.getString("cmdType")+cmdData.getString("random"));
		cmd.setCmdType(cmdData.getString("cmdType"));
		cmd.setData(cmdData.getString("cmdContext"));
		cmd.setSendParam(cmdData.toJSONString());
		cmd.setSendTime(DateUtil.nowDate());
		cmd.setServiceType(1);
		cmd.setStatus(0);
		cmd.setRandom(cmdData.getString("random"));
		cmd.setStamptime(cmdData.getString("stamptime"));
		return iotCmdDataRepository.saveAndFlush(cmd);
	}

	@Override
	public CmdData findListByCmdStampAndDeviceId(String deviceId, String random, String stamptime) {
		return iotCmdDataRepository.findListByCmdStampAndDeviceId(deviceId, random, stamptime);
	}

	@Override
	public CmdData update(CmdData cmdData) {
		return iotCmdDataRepository.saveAndFlush(cmdData);
	}
	@Override
	public void delete(CmdData cmdData) {
		 iotCmdDataRepository.delete(cmdData);
	}

	@Override
	public void deleteByDeviceId(String deviceId) {
		iotCmdDataRepository.deleteByDeviceId(deviceId);
		
	}

	@Override
	public void deleteByDeviceIdAndCmdType(String deviceId, String cmdType) {
		iotCmdDataRepository.deleteByDeviceIdAndCmdType(deviceId, cmdType);
		
	}
}
