package com.ihooyah.flume.sink;

import com.alibaba.fastjson.JSONObject;
import org.apache.flume.Event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.*;

/**
 * 描述
 *
 * @author fatiaojie
 * @date 2020/4/1 16:16
 */
public class DAOClass {

    private static final Logger logger = LoggerFactory.getLogger(DAOClass.class);
    private static Map<String, String> columnsMap = new HashMap();
    private static String INSERT_QUERY;
    private static String DELETE_QUERY;
    private Connection connection;

    public DAOClass() {
    }

    public void insertData(Event event, Map<String, String> params) throws Exception {
        //同步json文件的逻辑
        try {
            String body = new String(event.getBody(),"UTF-8");
            Map<String, String> headers = event.getHeaders();
            String fileName = (String)headers.get("fileName");
            String tableName = (String)params.get("tableName");
            String iscustom = (String)params.get("iscustom");
            JSONObject initObject=JSONObject.parseObject(body);
            String dataObject=initObject.getString("data");
            String operation = initObject.getString("operation");
            if (!"false".equals(iscustom)) {
                if ("true".equals(iscustom)) {
                    ;
                }
            } else {
                String columns = "";
                List<String> columnList = new ArrayList<>();
                Statement st = this.connection.createStatement();
                String isTableExist = "select table_name from INFORMATION_SCHEMA.Tables where table_name='flume_json'";
                ResultSet tableResult = st.executeQuery(isTableExist);
                if ("false".equals(tableResult.next()+"")) {
                    String createTableSql = "create table flume_json (id int PRIMARY key AUTO_INCREMENT,type varchar(20),data text," +
                            "file_name varchar(40),create_time datetime,status varchar(5));";
                    st.execute(createTableSql);
                }
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Calendar c=Calendar.getInstance();
                c.setTime(new Date());
                c.add(Calendar.MONTH, -1);
                Date m = c.getTime();
                String mon = sdf.format(m);
                DELETE_QUERY="DELETE FROM flume_json where create_time<'"+mon+"';";
                st.execute(DELETE_QUERY);
                String values = "";
                columns="type,operation,data,file_name,create_time,status";
                values="'"+initObject.getString("type")+"','"+ operation + "','" + dataObject+"','"+fileName+"','"+sdf.format(new Date())+"','0'";
                INSERT_QUERY = "INSERT INTO flume_json (" + columns + ") values (" + values + ")";
                System.out.println("数据新增语句:"+INSERT_QUERY);
                PreparedStatement insertStmnt = this.connection.prepareStatement(INSERT_QUERY);
                insertStmnt.execute();
            }
        } catch (SQLException var20) {
            var20.printStackTrace();
        }finally {

        }
    }

    public void createConnection(String driver, String db_url, String user, String password) throws SQLException {
        if (this.connection == null || this.connection.isClosed() || !this.connection.isValid(1)) {
            try {
                Class.forName(driver);
                this.connection = DriverManager.getConnection(db_url, user, password);
            } catch (ClassNotFoundException var6) {
                var6.printStackTrace();
            } catch (SQLException var7) {
                var7.printStackTrace();
            }
        }

    }

    public void destroyConnection(String db_url, String user) {
        if (this.connection != null) {
            logger.debug("Destroying connection to: {}:{}", db_url, user);

            try {
                this.connection.close();
            } catch (SQLException var4) {
                var4.printStackTrace();
            }
        }

        this.connection = null;
    }

    public static String escapeSQL(String s) {
        return s.replaceAll("'", "\\'");
    }

    public Connection getConnection() {
        return this.connection;
    }

    private static String getNowDate() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String INSERT_DATE = df.format(new Date());
        return INSERT_DATE;
    }
}
