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.AccessControlName;
import com.tykj.dev.rfid.repository.AccessControlNameDao;
import com.tykj.dev.rfid.service.AccessControlNameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

/**
 * @author dengdiyi
 */
@Service
public class AccessControlNameServiceImpl implements AccessControlNameService {

    @Autowired
    private AccessControlNameDao accessControlNameDao;

    @Autowired
    private BlockChainUtil blockChainUtil;

    @Override
    public AccessControlName add(AccessControlName accessControlName) {
        AccessControlName accessControlName1 = accessControlNameDao.save(accessControlName);
        CompletableFuture.runAsync(()->{
            AccessControlName accessControlName2 = accessControlNameDao.findById(accessControlName1.getId()).get();
            BcHash bcText = blockChainUtil.sendHash(1000, JacksonUtil.toJSon(accessControlName2));
            String recordId = bcText.getData().getRecordID();
            accessControlName2.setRecordId(recordId);
            accessControlNameDao.save(accessControlName2);
        }, TaskBeanConfig.getThreadPoolTaskScheduler());
        return accessControlName1;
    }

    @Override
    public AccessControlName getByDeviceNo(String deviceNo) {
        return accessControlNameDao.findByDeviceNo(deviceNo);
    }
}
