package com.tzld.piaoquan.recommend.server.service;

import com.aliyun.openservices.aliyun.log.producer.LogProducer;
import com.aliyun.openservices.aliyun.log.producer.Producer;
import com.aliyun.openservices.aliyun.log.producer.ProducerConfig;
import com.aliyun.openservices.aliyun.log.producer.ProjectConfig;
import com.aliyun.openservices.log.common.LogItem;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class StatisticsLogService {

    @Value("${aliyun.log.project}")
    private String project;
    @Value("${aliyun.log.endpoint}")
    private String endpoint;
    @Value("${aliyun.log.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.log.accessKeySecret}")
    private String accessKeySecret;

    private String logStore = "statistics-log";

    private Producer producer;


    @PostConstruct
    public void init() {
        ProducerConfig producerConfig = new ProducerConfig();
        producer = new LogProducer(producerConfig);
        producer.putProjectConfig(new ProjectConfig(project, endpoint, accessKeyId, accessKeySecret));
    }

    public void log(Map<String, String> data) {
        if (MapUtils.isEmpty(data)) {
            return;
        }
        try {
            LogItem logItem = new LogItem();
            data.entrySet().stream().forEach(e -> {
                logItem.PushBack(e.getKey(), e.getValue());
            });
            producer.send(project, logStore, logItem);
        } catch (InterruptedException e) {
            log.warn("The current thread has been interrupted during send logs.");
        } catch (Exception e) {
            log.error("Failed to send logs", e);
        }
    }

    public void log(List<Map<String, String>> data) {
        if (CollectionUtils.isEmpty(data)) {
            return;
        }
        try {
            List<LogItem> items = data.stream().map(d -> {
                LogItem logItem = new LogItem();
                d.entrySet().stream().forEach(e -> {
                    logItem.PushBack(e.getKey(), e.getValue());
                });
                return logItem;
            }).collect(Collectors.toList());
            producer.send(project, logStore, items);
        } catch (InterruptedException e) {
            log.warn("The current thread has been interrupted during send logs.");
        } catch (Exception e) {
            log.error("Failed to send logs", e);
        }
    }

}