package com.wuban.tron.explore.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.gson.JsonObject;
import com.wuban.tron.explore.dao.ContractEventRepository;
import com.wuban.tron.explore.domain.TronTransEvent;
import com.wuban.tron.explore.entity.ContractEvent;
import com.wuban.tron.explore.entity.example.ContractEventExample;
import com.wuban.tron.explore.service.ContractEventService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <core>合约事件服务接口实现类</core>
 *
 * @author sky
 * @date 2020/12/3
 */
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class ContractEventServiceImpl implements ContractEventService {

    private final ContractEventRepository contractEventRepository;

    @Override
    public int insert(ContractEvent record) {
        return this.contractEventRepository.insert(record);
    }

    @Override
    public int batchInsert(List<TronTransEvent> records) {
        List<ContractEvent> list = new ArrayList<>();

        if (!CollectionUtils.isEmpty(records)) {

            /*
                根据合约地址查询表（tron_contract_event）中是否存在记录，如果存在删除记录
             */
            String contractAddress = records.get(0).getContract_address();
            ContractEventExample example = new ContractEventExample();
            example.createCriteria().andContractAddressEqualTo(contractAddress);
            int count = this.contractEventRepository.countByExample(example);
            if (count != 0) {
                this.contractEventRepository.deleteByExample(example);
            }

            records.forEach(o -> {
                ContractEvent event = new ContractEvent();
                event.setBlockNumber(o.getBlock_number());
                event.setBlockTimestamp(o.getBlock_timestamp());
                event.setCallerContractAddress(o.getCaller_contract_address());
                event.setContractAddress(o.getContract_address());
                event.setEventIndex(o.getEvent_index());
                event.setEventName(o.getEvent_name());
                event.setTransactionId(o.getTransaction_id());
                String result = JSON.toJSONString(o.getResult());
                String resultType = JSON.toJSONString(o.getResult_type());
                event.setResult(result);
                event.setResultType(resultType);
                list.add(event);
            });
        }

        return this.contractEventRepository.batchInsert(list);
    }

    /**
     * 根据检索条件获取数据
     *
     * @param example
     * @return
     */
    @Override
    public List<ContractEvent> selectByExample(ContractEventExample example) {
        return this.contractEventRepository.selectByExample(example);
    }


}
