package com.fshark.overseas.advert.processor;


import com.fshark.overseas.advert.entity.GameAccount;
import com.fshark.overseas.advert.entity.dao.GameAccountDao;
import com.fshark.overseas.advert.modle.AppsFlyerEvent;
import com.fshark.overseas.advert.modle.EventTypeEnum;
import com.fshark.overseas.advert.modle.metrics.ActivationMetrics;
import com.fshark.overseas.advert.modle.metrics.BaseMetrics;
import com.fshark.overseas.advert.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.util.Collector;

import java.util.Date;
import java.util.Locale;
import java.util.Optional;

public class RoleLoginProcess extends RichFlatMapFunction<AppsFlyerEvent, ActivationMetrics> {

    private AppConfig appConfig;
    private JdbiContext jdbiContext;
    private GameAccountDao gameAccountDao;

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

    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);
        jdbiContext = DatabaseUtils.getCHGenJdbiClient(appConfig.getDbHost(), appConfig.getDbUser(), appConfig.getDbPassword());
        gameAccountDao = jdbiContext.getJdbi().onDemand(GameAccountDao.class);
    }

    @Override
    public void flatMap(AppsFlyerEvent value, Collector<ActivationMetrics> out) throws Exception {
        ActivationMetrics activationMetrics = new ActivationMetrics();
        copyBaseMetrics(value, activationMetrics);
        activationMetrics.setUid(value.getUid());
        Optional<GameAccount> account = gameAccountDao.findByPrimary(value, Constants.TYPE_ACTIVIYION);
        String event_time = DateUtils.formatAsYMDHMS(value.getEvent_time());

        if (!account.isPresent()) { // 设备未激活
            activationMetrics.setData_date(Long.parseLong(DateUtils.formatAsYMD(event_time)));
            activationMetrics.setData_hour(Integer.parseInt(DateUtils.formatAsHH(event_time)));
            gameAccountDao.insertActivition(value, event_time);
            activationMetrics.setData_activation(1L);
        } else {
            GameAccount gameAccount = account.get();
            String activationTime = gameAccount.getEvent_time();
            activationMetrics.setData_date(Long.parseLong(DateUtils.formatAsYMD(activationTime)));
            activationMetrics.setData_hour(Integer.parseInt(DateUtils.formatAsHH(activationTime)));
            CommonUtils.setType(activationMetrics);
            Date activition = DateUtils.formatAsDate(activationTime);
            Optional<GameAccount> accountRegister = gameAccountDao.findByPrimary(value, Constants.TYPE_REGISTER);
            if (!accountRegister.isPresent()) {                                                                                                                                                                          //设备未注册
                gameAccountDao.insertRegister(value, event_time);
                activationMetrics.setData_register(1L);
                activationMetrics.setData_device_register(1L);
                if (DateUtils.daysBetween(activition, value.getEvent_time()) == 0) { //当日激活并且注册
                    activationMetrics.setData_day_act_register(1L);
                }
            }
            Optional<GameAccount> accountRoleLogin = gameAccountDao.findByPrimary(value, Constants.TYPE_ROLELOGIN);
            if (accountRoleLogin.isPresent()) {
                String last_login_time = accountRoleLogin.get().getEvent_time();
                if (!StringUtils.isBlank(last_login_time)) {
                    Date date = DateUtils.formatAsDate(last_login_time);
                    if (DateUtils.daysBetween(date, value.getEvent_time()) > 0) { //排除当日登录用户
                        long daysBetween = DateUtils.daysBetween(activition, value.getEvent_time());
                        if (daysBetween > 0) {
                            activationMetrics.setDateRemind(daysBetween); //留存天数
                            ActivationMetrics dauMetric = new ActivationMetrics();
                            copyBaseMetrics(value, dauMetric);
                            dauMetric.setUid(value.getUid());
                            dauMetric.setData_date(Long.valueOf(DateUtils.formatAsYMD(value.getEvent_time())));
                            dauMetric.setData_hour(Integer.valueOf(DateUtils.formatAsHH(value.getEvent_time())));
                            dauMetric.setData_active_day_dau(1L);
                            out.collect(dauMetric);
                        }
                    }
                }
            } else {
                long daysBetween = DateUtils.daysBetween(activition, value.getEvent_time());
                if (daysBetween > 0) {
                    activationMetrics.setDateRemind(daysBetween); //留存天数
                    ActivationMetrics dauMetric = new ActivationMetrics();
                    copyBaseMetrics(value, dauMetric);
                    dauMetric.setUid(value.getUid());
                    dauMetric.setData_date(Long.valueOf(DateUtils.formatAsYMD(value.getEvent_time())));
                    dauMetric.setData_hour(Integer.valueOf(DateUtils.formatAsHH(value.getEvent_time())));
                    dauMetric.setData_active_day_dau(1L);
                    out.collect(dauMetric);
                }
            }
        }
        gameAccountDao.insertRoleLogin(value);
        out.collect(activationMetrics);
    }


    private void copyBaseMetrics(AppsFlyerEvent value, BaseMetrics metrics) {
        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.setChannel(value.getChannel());

        metrics.setData_type(1);
        if (value.getIs_retargeting()) { //再营销数据
            metrics.setData_type(2);
        }
        if (value.getCampaign().toLowerCase(Locale.ROOT).startsWith("acp")) { //预注册数据
            metrics.setData_type(3);
        }
    }

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

}
