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.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.util.Collector;

import java.time.LocalDateTime;
import java.util.Locale;
import java.util.Optional;

public class RoleLoginProcess extends RichFlatMapFunction<AppsFlyerEvent, ActivationMetrics> {

    private final 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();
        ActivationMetrics retentMetrics = new ActivationMetrics();
        copyBaseMetrics(value, activationMetrics);
        copyBaseMetrics(value, retentMetrics);
        activationMetrics.setUid(value.getUid());
        retentMetrics.setUid(value.getUid());
        Optional<GameAccount> account = gameAccountDao.findByPrimary(value, Constants.TYPE_ACTIVIYION);
        String event_time = DateUtils.formatAsYMDHMS(value.getEvent_time());
        activationMetrics.setData_date(Long.parseLong(DateUtils.formatAsYMD(event_time)));
        activationMetrics.setData_hour(Integer.parseInt(DateUtils.formatAsHH(event_time)));
        String activationTime = event_time;
        if (!account.isPresent()) { // 设备未激活
//            gameAccountDao.insertActivition(value, event_time);
//            activationMetrics.setData_activation(1L);
//            return;
        } else {
            GameAccount gameAccount = account.get();
            activationTime = gameAccount.getEvent_time();
        }

        if (EventTypeEnum.createRoleEvent(value)) {
            boolean isRole = false;
            Optional<GameAccount> accountCreateRole = gameAccountDao.findByPrimary(value, Constants.TYPE_CREATEROLE);
            if (!accountCreateRole.isPresent()) {
                activationMetrics.setData_create_role(1L);
                gameAccountDao.insertCreateRole(value);
                isRole = true;
            }

            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);
                activationMetrics.setData_day_register_create(1L);//当日注册并创角
                if (DateUtils.daysBetween(DateUtils.formatAsDate(activationTime), value.getEvent_time()) == 0) { //当日激活并且注册
                    activationMetrics.setData_day_act_register(1L);
                }
            } else {
                if (DateUtils.daysBetween(DateUtils.formatAsDate(accountRegister.get().getEvent_time()), value.getEvent_time()) == 0 && isRole) { //当日注册创角
                    activationMetrics.setData_day_register_create(1L);
                }
            }

        } else {

            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(DateUtils.formatAsDate(activationTime), value.getEvent_time()) == 0) { //当日激活并且注册
                    activationMetrics.setData_day_act_register(1L);
                }
            } else {
                activationTime = accountRegister.get().getEvent_time();
                LocalDateTime activition = DateUtils.formatAsDate(activationTime);
                retentMetrics.setData_date(Long.parseLong(DateUtils.formatAsYMD(activationTime)));
                retentMetrics.setData_hour(Integer.parseInt(DateUtils.formatAsHH(activationTime)));
                CommonUtils.setType(activationMetrics);
                CommonUtils.setType(retentMetrics);
                Optional<GameAccount> accountRoleLogin = gameAccountDao.findByPrimary(value, Constants.TYPE_ROLELOGIN);
                if (accountRoleLogin.isPresent()) {
                    String last_login_time = accountRoleLogin.get().getEvent_time();
                    LocalDateTime 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) {
                            retentMetrics.setDateRemind(daysBetween); //留存天数
                            activationMetrics.setData_active_day_dau(1L);

                        }
                    }
                } else {
                    long daysBetween = DateUtils.daysBetween(activition, value.getEvent_time());
                    if (daysBetween > 0) {
                        retentMetrics.setDateRemind(daysBetween); //留存天数
                        activationMetrics.setData_active_day_dau(1L);
                    }
                }
            }
            gameAccountDao.insertRoleLogin(value);
        }
        out.collect(activationMetrics);
        out.collect(retentMetrics);
    }


    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();
        }
    }

}
