package com.fshark.overseas.advert.sink;


import com.fshark.overseas.advert.entity.dao.MetricsDao;
import com.fshark.overseas.advert.modle.metrics.ActivationMetrics;
import com.fshark.overseas.advert.modle.metrics.BaseMetrics;
import com.fshark.overseas.advert.modle.metrics.RemainMetrics;
import com.fshark.overseas.advert.util.AppConfig;
import com.fshark.overseas.advert.util.Constants;
import com.fshark.overseas.advert.util.DatabaseUtils;
import com.fshark.overseas.advert.util.JdbiContext;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;

public class ActicitionSink extends RichSinkFunction<ActivationMetrics> {

    private AppConfig appConfig;

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

    private JdbiContext jdbiContext;

    private MetricsDao metricsDao;

    @Override
    public void invoke(ActivationMetrics value, Context context) throws Exception {
        super.invoke(value, context);
        if (value.getData_activation() + value.getData_register() + value.getData_device_register() + value.getData_create_role() + value.getData_day_act_register()
                + value.getData_day_register_create() + value.getData_active_day_dau() + value.getData_sdk_activation() + value.getData_sdk_register() > 0) {
            metricsDao.insertActivationMetrics(value);
        }
//        if (value.getData_register() > 0){
//            metricsDao.insertRegisterNum(value);
//        }
        //短留存写入
        if (value.getDateRemind() == 0L) {
            return;
        }
        RemainMetrics remainMetrics = new RemainMetrics();
        copyBaseMetrics(value, remainMetrics);
        remainMetrics.setDays(value.getDateRemind());
        remainMetrics.setUser_num(1L);
//短线留存
        insertRemain(remainMetrics);
    }

    private void insertRemain(RemainMetrics value) {
        Long days = value.getDays();
        days = days + 1;
        if (days == 2 || days == 3 || days == 7 || days == 15 || days == 30) {
            String column = "data_active_" + days + "day";
            jdbiContext.getJdbi().withHandle(handle -> {
                String sql = String.format("insert into appsflyer_metrics" +
                                " (`data_date`,`data_hour`,`time_zone`,`region`, `platform`, `game_id`, `media_source`, `campaign_id` ,`ad_set_id`,`ad_id`,`channel`,`data_type`,`%s`)" +
                                " values ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',%s,'%s') ",
                        column, value.getData_date(), value.getData_hour(), value.getTime_zone(), value.getRegion(), value.getPlatform(), value.getGame_id(), value.getMedia_source(), value.getCampaign_id()
                        , value.getAd_set_id(), value.getAd_id(), value.getChannel(), value.getData_type(), value.getUser_num()
                );
                handle.createUpdate(sql).execute();
                return null;
            });
        }
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);
        if (appConfig.getSinkType().equals(Constants.TYPE_SINK)) {
            jdbiContext = DatabaseUtils.getGenJdbiClient(appConfig.getDbHost(), appConfig.getDbUser(), appConfig.getDbPassword());
        } else {
            jdbiContext = DatabaseUtils.getCHGenJdbiClient(appConfig.getDbHost(), appConfig.getDbUser(), appConfig.getDbPassword());
        }
        metricsDao = jdbiContext.getJdbi().onDemand(MetricsDao.class);
    }

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

    private void copyBaseMetrics(ActivationMetrics value, BaseMetrics metrics) {
        metrics.setData_date(value.getData_date());
        metrics.setData_hour(value.getData_hour());
        metrics.setTime_zone(value.getTime_zone());
        metrics.setPlatform(value.getPlatform());
        metrics.setMedia_source(value.getMedia_source());
        metrics.setGame_id(value.getGame_id());
        metrics.setCampaign_id(value.getCampaign_id());
        metrics.setAd_set_id(value.getAd_set_id());
        metrics.setAd_id(value.getAd_id());
        metrics.setRegion(value.getRegion());
        metrics.setData_type(value.getData_type());
        metrics.setChannel(value.getChannel());
    }
}
