package com.yuyu.srdisassemble.data;

import com.yuyu.srdisassemble.pojo.DisassembleData;
import com.yuyu.srdisassemble.pojo.PauseBox;

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

            //判断是否因为长时间闲置导致连接丢失
            if (con.isClosed()){
                con = DriverManager.getConnection(JdbcSqlClass.url, JdbcSqlClass.user, JdbcSqlClass.password);
            }

            //获取执行者对象
            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);





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


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

            //执行Sql语句

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

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

    public static void createPauseBoxTable(){
        try {
            //此处获取连接并保存
            con = DriverManager.getConnection(JdbcSqlClass.url, JdbcSqlClass.user, JdbcSqlClass.password);

            Statement connection = getConnection();

            //执行Sql语句
            String createTable = "create table if not exists pausebox(\n" +
                    "    username varchar(255) null comment '玩家名称',\n" +
                    "    slotnumber int null comment '槽位',\n" +
                    "    nums int null comment '数量',\n" +
                    "    productindex varchar(255) null comment '原胚索引',\n" +
                    "    guiname varchar(255) null comment 'gui的姓名',\n" +
                    "    lores text null comment '材料的lores'\n" +
            " ) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin";

            boolean rs = connection.execute(createTable);




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

            //手动注入所有列
            List<String> columns = new ArrayList<>();
            columns.add("username");
            columns.add("slotnumber");
            columns.add("nums");
            columns.add("productindex");
            columns.add("guiname");
            columns.add("lores");

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

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


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

    /**
     * 插入数据
     *
     * @param username
     * @param slotNumber
     * @param nums
     * @param productindex
     * @param guiname
     * @param lore
     */
    public static void insertPauseBoxData(String username, int slotNumber, int nums, String productindex, String guiname, String lore){

        try {
            String sql = "insert into pausebox(username, slotnumber, nums, productindex, guiname,lores)" +
                    " VALUES ('"+username+"',"+slotNumber+","+nums+",'"+productindex+"','"+guiname+"','"+lore+"')";

            Statement statement = getConnection();

            int i = statement.executeUpdate(sql);

            if (i > 0) {
                return;
            }else {
                System.out.println(username+"\t"+slotNumber+"\t"+nums+"\t"+productindex+"\t"+guiname+"插入失败");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 清空数据
     */
    public static void clearPauseBoxTable(){


        try {

            Statement statement = getConnection();
            String sql = "delete from pausebox";

            statement.executeUpdate(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    public static int addColumnPauseBox(String columns){
        String sql = null;
        if (columns.equals("username")) {
            sql = "ALTER TABLE pausebox\n" +
                    "ADD username varchar(255) null comment '玩家名称'";
        } else if (columns.equals("slotnumber")) {
            sql = "ALTER TABLE pausebox\n" +
                    "ADD slotnumber int null comment '槽位'";
        } else if (columns.equals("nums")) {
            sql = "ALTER TABLE pausebox\n" +
                    "ADD nums int null comment '数量'";
        } else if (columns.equals("productindex")) {
            sql = "ALTER TABLE pausebox\n" +
                    "ADD productindex varchar(255) null comment '原胚索引'";
        } else if (columns.equals("guiname")) {
            sql = "ALTER TABLE pausebox\n" +
                    "ADD guiname varchar(255) null comment 'gui的姓名'";
        }else if (columns.equals("lores")) {
            sql = "ALTER TABLE pausebox\n" +
                    "ADD lores text  null comment '材料的lores'";
        }

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

        }
        return 0;
    }

    /**
     * 用于新增列
     *
     * @return
     */
    public static int addColumn(String columns) {
        String sql = null;
        if (columns.equals("id")) {
            sql = "ALTER TABLE pausebox\n" +
                    "ADD id BIGINT auto_increment not null PRIMARY KEY  comment 'ID'";
        } else if (columns.equals("playername")) {
            sql = "ALTER TABLE pausebox\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);
                stmt.close();
                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);

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

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

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

    public static List<String> getPlayerList(){

        List<String> userList = new ArrayList<>();

        Statement statement = getConnection();
        String sql = "select username from pausebox";
        try {
            ResultSet resultSet = statement.executeQuery(sql);
            while (resultSet.next()){
                userList.add(resultSet.getString("username"));
            }
            resultSet.close();
            statement.close();

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

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

    /**
     * 用于获取PauseBox gui的数据
     * @param player
     * @return
     */
    public static List<PauseBox> getPauseBoxData(String player) {

        List<PauseBox> pauseBoxList = new ArrayList<>();
        Statement statement = getConnection();
        String sql = "select * from pausebox where username = '"+player+"' and guiname = 'TemporarilyBox'";
        try {
            ResultSet resultSet = statement.executeQuery(sql);
            while (resultSet.next()){
                String lore = resultSet.getString("lores");
                List<String> lores = new ArrayList<>();
                String[] split = lore.split("\\|");
                for (String s : split) {
                    lores.add(s);
                }

                PauseBox pauseBox = new PauseBox(resultSet.getString("username"),
                        resultSet.getInt("slotnumber"),
                        resultSet.getInt("nums"),
                        resultSet.getString("productindex"),
                        resultSet.getString("guiname"),lores);
                pauseBoxList.add(pauseBox);
            }

            resultSet.close();
            statement.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return pauseBoxList;
    }
}
