package com.tykj.dev.device.apply.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.apply.repository.DeviceApplyBillDao;
import com.tykj.dev.device.apply.service.DeviceApplyBillService;
import com.tykj.dev.device.apply.subject.domin.DeviceApplyBill;
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 DeviceApplyBillServiceImpl implements DeviceApplyBillService {

    @Autowired
    private DeviceApplyBillDao deviceApplyBillDao;

    @Autowired
    private BlockChainUtil blockChainUtil;

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

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

    @Override
    public DeviceApplyBill update(DeviceApplyBill deviceApplyBillEntity) {
        DeviceApplyBill deviceApplyBill = deviceApplyBillDao.save(deviceApplyBillEntity);
        CompletableFuture.runAsync(()->blockChainUtil.appendHash(JacksonUtil.toJSon(deviceApplyBill),deviceApplyBill.getRecordId()),TaskBeanConfig.getThreadPoolTaskScheduler());
        return deviceApplyBill;
    }

    @Override
    public DeviceApplyBill getOne(Integer id) {
        Optional<DeviceApplyBill> deviceApplyBillEntity = deviceApplyBillDao.findById(id);
        return deviceApplyBillEntity.orElse(null);
    }

}
