package com.yuyu.srdisassemble.data;

import com.yuyu.srdisassemble.SrDisassemble;
import com.yuyu.srdisassemble.pojo.DisassembleData;
import org.bukkit.ChatColor;

import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 峰。
 * @version 1.0
 * @project SrDisassemble
 * @date 2024/6/19 16:05:42
 * @description JDBC
 */
public class JdbcSqlClass {
    private static String driver;
    private static String url;
    private static String user;
    private static String password;
    private static Connection con;


    public static void openConnection() {
        //注册驱动
        try {
            Class.forName(JdbcSqlClass.driver);

            //获取连接
            Connection conn = DriverManager.getConnection(JdbcSqlClass.url, JdbcSqlClass.user, JdbcSqlClass.password);
            JdbcSqlClass.con = conn;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

    public static Statement getConnection() {
        try {
            //注册驱动
            Class.forName(JdbcSqlClass.driver);

            //获取执行者对象
            Statement stmt = con.createStatement();


            return stmt;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void initTable() {
        try {
            con = DriverManager.getConnection(JdbcSqlClass.url, JdbcSqlClass.user, JdbcSqlClass.password);

            Statement connection = getConnection();

            //执行Sql语句
            String createTable = " create table if not exists srdisassemble\t( id BIGINT auto_increment not null PRIMARY KEY  comment 'ID'," +
                    "            playername      varchar(255) null comment '玩家姓名'," +
                    "            disassembleTime varchar(255) null comment '分解的时间'," +
                    "            target          varchar(255) null comment '分解的目标'," +
                    "            targetIndex     varchar(255) null comment '分解目标的索引'," +
                    "            guiname         varchar(255) null comment '打开gui的名称'," +
                    "            amount            int          null comment '分解的数量')";

            boolean rs = connection.execute(createTable);

            if (rs) {
                SrDisassemble.getInstance().getLogger().info(ChatColor.GREEN + "initTable执行完毕");
            }


            String sql = "select column_name\n" +
                    "from INFORMATION_SCHEMA.COLUMNS\n" +
                    "where TABLE_NAME = 'srdisassemble'";

            //手动注入所有列
            List<String> columns = new ArrayList<>();
            columns.add("id");
            columns.add("playername");
            columns.add("disassembleTime");
            columns.add("target");
            columns.add("targetIndex");
            columns.add("guiname");
            columns.add("amount");

            try {
                ResultSet resultSet = connection.executeQuery(sql);
                List<String> lists = new ArrayList<>();
                int index = 0;
                while (resultSet.next()) {
                    String columnName = resultSet.getString("column_name");
                    lists.add(columnName);
                    index++;
                }
                List<String> missColumn = new ArrayList<>();
                for (String columnName : columns) {
                    if (!lists.contains(columnName)) {
                        missColumn.add(columnName);
                    }
                }
                //新增列
                for (String columnName : missColumn) {
                    addColumn(columnName);
                }

            } catch (SQLException e) {
                throw new RuntimeException(e);
            }


            connection.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 用于新增列
     *
     * @return
     */
    public static int addColumn(String columns) {
        String sql = null;
        if (columns.equals("id")) {
            sql = "ALTER TABLE srdisassemble\n" +
                    "ADD id BIGINT auto_increment not null PRIMARY KEY  comment 'ID'";
        } else if (columns.equals("playername")) {
            sql = "ALTER TABLE srdisassemble\n" +
                    "ADD playername      varchar(255) null comment '玩家姓名'";
        } else if (columns.equals("disassembleTime")) {
            sql = "ALTER TABLE srdisassemble\n" +
                    "ADD disassembleTime varchar(255) null comment '分解的时间'";
        } else if (columns.equals("target")) {
            sql = "ALTER TABLE srdisassemble\n" +
                    "ADD target          varchar(255) null comment '分解的目标'";
        } else if (columns.equals("targetIndex")) {
            sql = "ALTER TABLE srdisassemble\n" +
                    "ADD     targetIndex     varchar(255) null comment '分解目标的索引'";
        } else if (columns.equals("guiname")) {
            sql = "ALTER TABLE srdisassemble\n" +
                    "ADD     guiname         varchar(255) null comment '打开gui的名称'";
        } else if (columns.equals("amount")) {
            sql = "ALTER TABLE srdisassemble\n" +
                    "ADD   amount            int          null comment '分解的数量'";
        }

        if (sql != null) {
            Statement stmt = getConnection();
            try {
                int i = stmt.executeUpdate(sql);
                return i;
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return 0;
    }

    public static void setChartseUtf8() {
        try {
            Statement connection = getConnection();

            //执行Sql语句

            String sql = "ALTER TABLE srdisassemble CONVERT TO CHARACTER SET utf8mb4;";
            boolean rs = connection.execute(sql);

            if (rs) {
                SrDisassemble.getInstance().getLogger().info(ChatColor.GREEN + "修改字符集成功");
            }

            connection.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static int insertData(DisassembleData data) {
        try {
            Statement connection = getConnection();

            //执行Sql语句
            String sql = "insert into srdisassemble(playername, disassembleTime, target, targetIndex, guiname) values('" +
                    data.getPlayername() + "','" + data.getDisassembleTime().toString() + "','" + data.getTarget() + "','" + data.getTargetIndex() + "','" + data.getGuiName() + "')";
            int i = connection.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
            ResultSet generatedKeys = connection.getGeneratedKeys();
            int id = 0;
            if (generatedKeys.next()) {
                id = generatedKeys.getInt(1);
//                SrDisassemble.getInstance().getLogger().info(ChatColor.GREEN+"数据插入成功");
            }

            connection.close();
            connection.close();
            return id;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void deleteData(int id) {
        try {
            Statement connection = getConnection();

            //执行Sql语句

            String sql = "delete from srdisassemble where id=" + id;
            int i = connection.executeUpdate(sql);


            connection.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static DisassembleData getDisassembleData(int id) {
        try {
            Statement connection = getConnection();

            //执行Sql语句

            String sql = "select * from srdisassemble where id=" + id;
            ResultSet rs = connection.executeQuery(sql);

            DisassembleData data = new DisassembleData();
            while (rs.next()) {
                data.setId(rs.getInt("id"));
                data.setPlayername(rs.getString("playername"));
                data.setDisassembleTime(rs.getTimestamp("disassembleTime").toLocalDateTime());
                data.setTarget(rs.getString("target"));
                data.setTargetIndex(rs.getString("targetIndex"));
                data.setGuiName(rs.getString("guiname"));
            }

            rs.close();
            connection.close();
            connection.close();

            return data;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static DisassembleData getDataByGuiAndPlay(String playerName, String guiName) {
        try {
            Statement connection = getConnection();

            //执行Sql语句

            List<DisassembleData> disassembleDataList = new ArrayList<>();
            String sql = "select * from srdisassemble where playername= '" + playerName + "' and guiname= '" + guiName + "'";
            ResultSet rs = connection.executeQuery(sql);

            DisassembleData data = new DisassembleData();

            while (rs.next()) {
                data.setId(rs.getInt("id"));
                data.setPlayername(rs.getString("playername"));
                data.setDisassembleTime(LocalDateTime.parse(rs.getString("disassembleTime")));
                data.setTarget(rs.getString("target"));
                data.setTargetIndex(rs.getString("targetIndex"));
                data.setGuiName(rs.getString("guiname"));
            }

            rs.close();
            connection.close();
            connection.close();

            return data;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String getDriver() {
        return driver;
    }

    public static void setDriver(String driver) {
        JdbcSqlClass.driver = driver;
    }

    public static String getUrl() {
        return url;
    }

    public static void setUrl(String url) {
        JdbcSqlClass.url = url;
    }

    public static String getUser() {
        return user;
    }

    public static void setUser(String user) {
        JdbcSqlClass.user = user;
    }

    public static String getPassword() {
        return password;
    }

    public static void setPassword(String password) {
        JdbcSqlClass.password = password;
    }
}
