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

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.MapUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * 推荐漏斗日志：一次请求一条记录，包含 8 个 step JSON 字段。
 */
@Service
@Slf4j
public class FunnelLogService {

    @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 = "funnel-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> row) {
        if (MapUtils.isEmpty(row)) return;
        try {
            LogItem logItem = new LogItem();
            row.forEach(logItem::PushBack);
            producer.send(project, logStore, logItem);
        } catch (InterruptedException e) {
            log.warn("funnel log interrupted");
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            log.error("Failed to send funnel log", e);
        }
    }
}
