package com.tykj.dev.device.matching.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.device.matching.repository.MatchingDeviceBillDao;
import com.tykj.dev.device.matching.service.MatchingDeviceBillService;
import com.tykj.dev.device.matching.subject.domin.MatchingDeviceBill;
import com.tykj.dev.misc.utils.JacksonUtil;
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.Optional;
import java.util.concurrent.CompletableFuture;

/**
 * @author dengdiyi
 */
@Service
public class MatchingDeviceBillServiceImpl implements MatchingDeviceBillService {

    @Autowired
    private MatchingDeviceBillDao matchingDeviceBillDao;

    @Autowired
    private BlockChainUtil blockChainUtil;

    @Override
    public MatchingDeviceBill addEntity(MatchingDeviceBill matchingDeviceBillEntity) {
        MatchingDeviceBill matchingDeviceBill = matchingDeviceBillDao.save(matchingDeviceBillEntity);
        CompletableFuture.runAsync(()->{
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            MatchingDeviceBill matchingDeviceBill1 = getOne(matchingDeviceBill.getId());
            BcHash bcText = blockChainUtil.sendHash(1000, JacksonUtil.toJSon(matchingDeviceBill1));
            String recordId = bcText.getData().getRecordID();
            matchingDeviceBill1.setRecordId(recordId);
            matchingDeviceBillDao.save(matchingDeviceBill1);
        }, TaskBeanConfig.getThreadPoolTaskScheduler());
        return matchingDeviceBill;
    }

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

    @Override
    public MatchingDeviceBill getOne(Integer id) {
        Optional<MatchingDeviceBill> deviceBillEntity = matchingDeviceBillDao.findById(id);
        return deviceBillEntity.orElse(null);
    }

    @Override
    public MatchingDeviceBill update(MatchingDeviceBill matchingDeviceBillEntity) {
        MatchingDeviceBill matchingDeviceBill = matchingDeviceBillDao.save(matchingDeviceBillEntity);
        CompletableFuture.runAsync(()->blockChainUtil.appendHash(JacksonUtil.toJSon(matchingDeviceBill),matchingDeviceBill.getRecordId()),TaskBeanConfig.getThreadPoolTaskScheduler());
        return matchingDeviceBill;
    }
}
