package com.tykj.dev.device.library.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.library.repository.DeviceChangeDao;
import com.tykj.dev.device.library.service.DeviceChangeService;
import com.tykj.dev.device.library.subject.domin.DeviceChange;
import com.tykj.dev.misc.exception.ApiException;
import com.tykj.dev.misc.utils.JacksonUtil;
import com.tykj.dev.misc.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author dengdiyi
 */
@Service
public class DeviceChangeServiceImpl implements DeviceChangeService {

    @Autowired
    private DeviceChangeDao deviceChangeDao;

    @Autowired
    private BlockChainUtil blockChainUtil;

    @Override
    public DeviceChange add(DeviceChange deviceChange) {
        DeviceChange deviceChange1 = deviceChangeDao.save(deviceChange);
        CompletableFuture.runAsync(()->{
            DeviceChange deviceChange2 = getOne(deviceChange1.getId());
            BcHash bcText = blockChainUtil.sendHash(1000, JacksonUtil.toJSon(deviceChange2));
            String recordId = bcText.getData().getRecordID();
            deviceChange2.setRecordId(recordId);
            deviceChangeDao.save(deviceChange2);
        }, TaskBeanConfig.getThreadPoolTaskScheduler());
        return deviceChange1;
    }

    @Override
    public DeviceChange getOne(Integer id) {
        Optional<DeviceChange> deviceChange = deviceChangeDao.findById(id);
        if (deviceChange.isPresent()) {
            return deviceChange.get();
        } else {
            throw new ApiException(ResultUtil.failed("所查询id不存在"));
        }
    }

    @Override
    public Integer getOldDeviceId(Integer newDeviceId) {
        DeviceChange deviceChange = deviceChangeDao.findByNewDeviceId(newDeviceId);
        if (deviceChange != null) {
            return deviceChange.getOldDeviceId();
        } else {
            return 0;
        }
    }

    /**
     * @param newDeviceId 新装备id
     *                    获取所有以前的旧装备id列表
     */
    @Override
    public List<Integer> getAllFatherDevice(Integer newDeviceId) {
        List<Integer> ids = new ArrayList<>();
        Integer id = getOldDeviceId(newDeviceId);
        if (id > 0) {
            ids.add(id);
            ids.addAll(getAllFatherDevice(id));
        }
        return ids;
    }
}
