package com.tykj.dev.rfid.service.impl;

import com.tykj.dev.blockcha.subject.entity.BcHash;
import com.tykj.dev.blockcha.subject.service.BlockChainUtil;
import com.tykj.dev.config.TaskBeanConfig;
import com.tykj.dev.misc.utils.JacksonUtil;
import com.tykj.dev.rfid.entity.domin.LibraryWarningLogDetail;
import com.tykj.dev.rfid.repository.LibraryWarningLogDetailDao;
import com.tykj.dev.rfid.service.LibraryWarningLogDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

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

/**
 * @author HuangXiahao
 * @version V1.0
 * @class LibraryWarningLogDetailServiceImp
 * @packageName com.tykj.dev.rfid.service.impl
 **/
@Service
public class LibraryWarningLogDetailServiceImp implements LibraryWarningLogDetailService {

    @Autowired
    LibraryWarningLogDetailDao libraryWarningLogDetailDao;

    @Autowired
    private BlockChainUtil blockChainUtil;

    @Override
    public LibraryWarningLogDetail addEntity(LibraryWarningLogDetail libraryWarningLogDetail) {
        LibraryWarningLogDetail libraryWarningLogDetail1 = libraryWarningLogDetailDao.save(libraryWarningLogDetail);
        CompletableFuture.runAsync(()->{
            LibraryWarningLogDetail libraryWarningLogDetail2 = libraryWarningLogDetailDao.findById(libraryWarningLogDetail1.getId()).get();
            BcHash bcText = blockChainUtil.sendHash(1000, JacksonUtil.toJSon(libraryWarningLogDetail2));
            String recordId = bcText.getData().getRecordID();
            libraryWarningLogDetail2.setRecordId(recordId);
            libraryWarningLogDetailDao.save(libraryWarningLogDetail2);
        }, TaskBeanConfig.getThreadPoolTaskScheduler());
        return libraryWarningLogDetail1;
    }

    /**
     * @param libraryWarningLogDetails 异步上链
     */
    @Override
    @Async
    public void sendHash(List<LibraryWarningLogDetail> libraryWarningLogDetails) {
        libraryWarningLogDetails.forEach(libraryWarningLogDetail1 -> {
            BcHash bcText = blockChainUtil.sendHash(1000, JacksonUtil.toJSon(libraryWarningLogDetail1));
            String recordId = bcText.getData().getRecordID();
            libraryWarningLogDetail1.setRecordId(recordId);
            libraryWarningLogDetailDao.save(libraryWarningLogDetail1);
        });
    }
}
