package com.tykj.dev.device.loss.service.impl;

import com.tykj.dev.blockcha.subject.service.BlockChainUtil;
import com.tykj.dev.device.loss.entity.domain.DeviceLoss;
import com.tykj.dev.device.loss.repository.LossDao;
import com.tykj.dev.device.loss.service.DeviceLossService;
import com.tykj.dev.misc.utils.JacksonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author zjm
 * @version 1.0.0
 * @ClassName DeviceLossServiceImpl.java
 * @Description TODO
 * @createTime 2021年01月30日 11:17:00
 */
@Service
@Slf4j
public class DeviceLossServiceImpl implements DeviceLossService {
    @Autowired
    LossDao lossDao;
    @Autowired
    BlockChainUtil blockChainUtil;

    @Override
    public DeviceLoss save(DeviceLoss deviceLoss) {
        CompletableFuture.runAsync(()-> {
            if (deviceLoss.getRecordId() == null || deviceLoss.getRecordId().equals("")) {
                deviceLoss.setRecordId(blockChainUtil.sendText(1000, JacksonUtil.toJSon(deviceLoss)).getData().getRecordID());
                lossDao.save(deviceLoss);
                log.info("[丢失-找回]上链数据时间本次");
            } else {
                deviceLoss.setRecordId(blockChainUtil.appendText(JacksonUtil.toJSon(deviceLoss), deviceLoss.getRecordId()).getData().getRecordID());
                lossDao.save(deviceLoss);
            }
        });
       return lossDao.save(deviceLoss);
    }

    @Override
    public DeviceLoss findByDeviceLoss(Integer lossId) {
        return lossDao.findById(lossId).get();
    }

    @Override
    public List<DeviceLoss> findByListLoss() {
        return lossDao.findAll();
    }

    @Override
    public List<DeviceLoss> findByListLossUnitId(Integer unitId) {
        return lossDao.findAllByUnitId(unitId);
    }

}
