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.RfidChangeBill;
import com.tykj.dev.rfid.repository.RfidChangeBillDao;
import com.tykj.dev.rfid.repository.RfidChangeLogDao;
import com.tykj.dev.rfid.service.RfidChangeBillService;
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 RfidChangeBillEntityServiceImpl
 * @packageName com.tykj.dev.rfid.service.impl
 **/
@Service
public class RfidChangeBillServiceImpl implements RfidChangeBillService {

    @Autowired
    RfidChangeBillDao rfidChangeBillDao;

    @Autowired
    RfidChangeLogDao rfidChangeLogDao;

    @Autowired
    private BlockChainUtil blockChainUtil;

    @Override
    public RfidChangeBill addEntity(RfidChangeBill libraryWarningLogEntity) {
        RfidChangeBill rfidChangeBill = rfidChangeBillDao.save(libraryWarningLogEntity);
        CompletableFuture.runAsync(()->{
            RfidChangeBill rfidChangeBill1 = getOne(rfidChangeBill.getId());
            BcHash bcText = blockChainUtil.sendHash(1000, JacksonUtil.toJSon(rfidChangeBill1));
            String recordId = bcText.getData().getRecordID();
            rfidChangeBill1.setRecordId(recordId);
            rfidChangeBillDao.save(rfidChangeBill1);
        }, TaskBeanConfig.getThreadPoolTaskScheduler());
        return rfidChangeBill;
    }

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

    @Override
    public RfidChangeBill updateEntity(RfidChangeBill libraryWarningLogEntity) {
        RfidChangeBill rfidChangeBill = rfidChangeBillDao.save(libraryWarningLogEntity);
        CompletableFuture.runAsync(()->blockChainUtil.appendHash(JacksonUtil.toJSon(rfidChangeBill),rfidChangeBill.getRecordId()), TaskBeanConfig.getThreadPoolTaskScheduler());
        return rfidChangeBill;
    }

    @Override
    public RfidChangeBill getOne(Integer id) {
        return rfidChangeBillDao.getOne(id);
    }

}
