package org.dromara.zjk.event.custom;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.dromara.zjk.config.OnChainUtils;
import org.dromara.zjk.domain.dto.OnchainDto;
import org.dromara.zjk.domain.vo.ZjkExpertItemVo;
import org.dromara.zjk.event.OnchainEvent;
import org.dromara.zjk.service.IZjkExpertItemService;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author : yanguohua
 * @version : 1.0
 * @date : 2024/11/7 16:24
 */
@Component
@Slf4j
public class OnchainListener implements ApplicationListener<OnchainEvent> {
    @Resource
    private OnChainUtils onChainUtils;
    @Resource
    private IZjkExpertItemService zjkExpertItemService;

    /**
     * 保存系统日志记录
     */
    @EventListener
    public void sendChainInfo(OnchainDto onchainDto) {
        log.info("规则id为{}，抽取的专家上区块链开始", onchainDto.getReviewId());
        List<ZjkExpertItemVo> data = zjkExpertItemService.getByReviewId(onchainDto.getReviewId());
        if (!CollectionUtils.isEmpty(data)) {
            String jsonStr = JSONUtil.toJsonStr(data);
            onChainUtils.toChain(jsonStr, onchainDto.getReviewId());
        }
        log.info("规则id为{}，抽取的专家上区块链结束", onchainDto.getReviewId());
    }

    @Override
    public void onApplicationEvent(OnchainEvent event) {
        OnchainDto onchainDto = event.getOnchainDto();
        sendChainInfo(onchainDto);

    }
}
