package com.fshark.overseas.advert.sink;


import com.fshark.overseas.advert.entity.dao.EventInfoDao;
import com.fshark.overseas.advert.modle.AppsFlyerEvent;
import com.fshark.overseas.advert.modle.SinkMetricEvent;
import com.fshark.overseas.advert.modle.metrics.EventMetrics;
import com.fshark.overseas.advert.util.*;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class EventTimesSinkProcess extends ProcessAllWindowFunction<SinkMetricEvent, Object, TimeWindow> {
    private AppConfig appConfig;

    public EventTimesSinkProcess(AppConfig appConfig) {
        this.appConfig = appConfig;
    }

    //定义连接、预编译语句
    private Connection conn;

    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);
        if (appConfig.getSinkType().equals(Constants.TYPE_SINK)){
            Class.forName("com.mysql.cj.jdbc.Driver");
        } else {
            Class.forName("ru.yandex.clickhouse.ClickHouseDriver");
        }
        conn = DriverManager.getConnection(appConfig.getDbHost(), appConfig.getDbUser(), appConfig.getDbPassword());
    }

    @Override
    public void close() throws Exception {
        super.close();
        if (conn != null) {
            conn.close();
        }
    }

    @Override
    public void process(Context context, Iterable<SinkMetricEvent> elements, Collector<Object> out) throws Exception {
        try {
            PreparedStatement insertStmt = conn.prepareStatement("insert into appsflyer_event_times (`data_date`,`region`, `platform`, `game_id`, `media_source`, `campaign_id` ,`event_name`,`event_date`,`times`) " +
                    "values (?,?,?,?,?,?,?,?,?)");
            for (SinkMetricEvent sinkMetricEvent : elements) {
                EventMetrics element = sinkMetricEvent.getEventMetrics();
                insertStmt.setLong(1, element.getDataDate());
                insertStmt.setString(2, element.getRegion());
                insertStmt.setString(3, element.getPlatform());
                insertStmt.setString(4, element.getGameId());
                insertStmt.setString(5, element.getMediaSource());
                insertStmt.setString(6, element.getCampaignId());
                insertStmt.setString(7, element.getEvent_name());
                insertStmt.setLong(8, element.getEvent_date());
                insertStmt.setLong(9, element.getTimes());
                insertStmt.addBatch();
            }
            insertStmt.executeBatch(); //批量执行
            conn.commit();
            insertStmt.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
