package com.fshark.overseas.advert.sink;

import com.fshark.overseas.advert.entity.dao.OrderDao;
import com.fshark.overseas.advert.modle.OrderData;
import com.fshark.overseas.advert.modle.SinkMetricEvent;
import com.fshark.overseas.advert.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;

public class PurchaseSink extends RichSinkFunction<SinkMetricEvent> {

    private AppConfig appConfig;

    private JdbiContext jdbiContext;
    private OrderDao orderDao;

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

    @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());
        }
        orderDao = jdbiContext.getJdbi().onDemand(OrderDao.class);
    }

    @Override
    public void invoke(SinkMetricEvent value, Context context) throws Exception {
        super.invoke(value, context);
        if (Constants.TYPE_SINK_ORDER.equals(value.getEventType())) {
            OrderData eventData = value.getOrderData();
            orderDao.insertOrder(eventData);
            if (!StringUtils.isBlank(eventData.getReg_server_time())) {
                eventData.setServer_reg_date(DateUtils.formatAsYMD(eventData.getReg_server_time()));
                eventData.setServer_reg_hour(DateUtils.formatAsHH(eventData.getReg_server_time()));
            } else {
                eventData.setServer_reg_date("-1");
                eventData.setServer_reg_hour("-1");
            }
            orderDao.insertServerOrder(eventData);
        }
    }


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

    }
}
