package com.rehome.mqttclienttemperature.utils;


import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rehome.mqttclienttemperature.datasource.DataSource;
import com.rehome.mqttclienttemperature.dto.ResponseDto;
import lombok.extern.slf4j.Slf4j;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

@Slf4j
public class JdbcUtil {
    /**
     * 执行sql并返回结果
     *
     * @param datasource      数据源连接
     * @param sql             语句
     */
    public static ResponseDto executeSql(DataSource datasource, String sql) {
        return executeSql(datasource,sql,new ArrayList<Object>());
    }

    /**
     * 执行sql并返回结果
     *
     * @param datasource      数据源连接
     * @param sql             语句
     * @param jdbcParamValues
     */
    public static ResponseDto executeSql(DataSource datasource, String sql, List<Object> jdbcParamValues) {
        log.info(sql);
        log.info(JSON.toJSONString(jdbcParamValues));
        DruidPooledConnection connection = null;
        try {
            connection = PoolManager.getPooledConnection(datasource);
            PreparedStatement statement = connection.prepareStatement(sql);
            for (int i = 1; i <= jdbcParamValues.size(); i++) {
                statement.setObject(i, jdbcParamValues.get(i - 1));
            }
            boolean hasResultSet = statement.execute();
            if (hasResultSet) {
                ResultSet rs = statement.getResultSet();
                int columnCount = rs.getMetaData().getColumnCount();
                List<String> columns = new ArrayList<>();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = rs.getMetaData().getColumnLabel(i);
                    columns.add(columnName);
                }
                List<JSONObject> list = new ArrayList<>();
                while (rs.next()) {
                    JSONObject jo = new JSONObject();
                    columns.stream().forEach(t -> {
                        try {
                            if(t.equals("create_date")){
                                Timestamp timestamp = rs.getTimestamp("create_date");
                                Date date = new Date(timestamp.getTime());
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                jo.put(t, sdf.format(date));
                            }else{
                                Object value = rs.getObject(t);
                                String key = t;
                                String keyLow = key.toLowerCase(Locale.ROOT);
                                jo.put(keyLow, value);
                            }
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    });
                    list.add(jo);
                }
                return ResponseDto.apiSuccess(list);
            } else {
                int updateCount = statement.getUpdateCount();
                if(updateCount==-1){
                    return ResponseDto.fail("sql执行失败：" + updateCount);
                }
                return ResponseDto.apiSuccess("sql修改数据行数：" + updateCount);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDto.fail(e.getMessage());
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
