package gui.tw;

import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import com.alibaba.fastjson.JSONObject;
import database.DBConPool;
import gui.Start;
import provider.MapleData;
import provider.MapleDataTool;
import server.MapleItemInformationProvider;
import server.life.MapleLifeFactory;
import server.life.MapleMonster;
import server.life.MapleMonsterInformationProvider;
import server.life.MonsterGlobalDropEntry;
import tools.FileoutputUtil;
import tools.StringUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.io.File;
import java.sql.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class Drop {

    int id;

    int dropperid;

    int itemId;

    String itenName;
    String dropName;

    int chance;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getDropperid() {
        return dropperid;
    }

    public void setDropperid(int dropperid) {
        this.dropperid = dropperid;
    }

    public int getItemId() {
        return itemId;
    }

    public void setItemId(int itemId) {
        this.itemId = itemId;
    }

    public String getItenName() {
        return itenName;
    }

    public void setItenName(String itenName) {
        this.itenName = itenName;
    }

    public String getDropName() {
        return dropName;
    }

    public void setDropName(String dropName) {
        this.dropName = dropName;
    }

    public int getChance() {
        return chance;
    }

    public void setChance(int chance) {
        this.chance = chance;
    }


    public static List<Drop> mobs =null;
    public static List<Drop> QQS =null;

    public static List<Drop> getMobBLs() {

        if (mobs != null) {
            return mobs;
        }
        mobs = new ArrayList<>();
        try {
            final Connection con = (Connection) DBConPool.getInstance().getDataSource().getConnection();
            PreparedStatement ps = null;
            ResultSet rs = null;

            ps = con.prepareStatement("SELECT * FROM drop_data WHERE itemid !=0");
            rs = ps.executeQuery();
            while (rs.next()) {
                Drop b = new Drop();
                b.setId(rs.getInt("id"));
                b.setDropperid(rs.getInt("dropperid"));
                b.setItemId(rs.getInt("itemid"));
                b.setItenName(MapleItemInformationProvider.getInstance().getName(rs.getInt("itemid")));
                try{

                        String string = MapleDataTool.getString((rs.getInt("dropperid") + "/name"), MapleLifeFactory.mobStringData, "未知怪物");
                        b.setDropName(string);

                }
                catch (Exception e){
                    b.setDropName("无名字");
                };
                b.setChance(rs.getInt("chance"));
                mobs.add(b);
            }
            rs.close();
            ps.close();
            con.close();
        } catch (SQLException ex) {
            System.err.println("[" + FileoutputUtil.CurrentReadable_Time() + "]怪物暴率出错：" + ex.getMessage());
        }
        return mobs;
    }


    public static List<Drop> getKPS() {
        List<Drop> mobBLs = getMobBLs();
        List<Drop> collect = mobBLs.stream()
                .filter(drop -> drop.getItemId() > 2380000 && drop.getItemId() < 2390000)
                .collect(Collectors.toList());
        return collect;
    }



    public static void deleteGWId(int id,int dropperid) {
        try {
            final Connection con = (Connection) DBConPool.getInstance().getDataSource().getConnection();
            PreparedStatement ps = null;

            ps = con.prepareStatement("DELETE FROM drop_data where id = ?");
            ps.setInt(1,id);
            ps.execute();
            ps.close();
            con.close();
        } catch (SQLException ex) {
            System.err.println("[" + FileoutputUtil.CurrentReadable_Time() + "]删除出错：" + ex.getMessage());
        }
        MapleMonsterInformationProvider.getInstance().removeById(dropperid);
        mobs = mobs.stream().filter(drop -> drop.getId() != id)
                .collect(Collectors.toList());
    }


    public static void deleteGWdropperid(int dropperid) {
        try {
            final Connection con = (Connection) DBConPool.getInstance().getDataSource().getConnection();
            PreparedStatement ps = null;

            ps = con.prepareStatement("DELETE FROM drop_data where dropperid = ?");
            ps.setInt(1,dropperid);
            ps.execute();
            ps.close();
            con.close();
        } catch (SQLException ex) {
            System.err.println("[" + FileoutputUtil.CurrentReadable_Time() + "]删除出错：" + ex.getMessage());
        }
        MapleMonsterInformationProvider.getInstance().removeById(dropperid);

        mobs = mobs.stream().filter(drop -> drop.getDropperid() != dropperid)
                .collect(Collectors.toList());
    }


    public static void deleteGWAll() {
        try {
            final Connection con = (Connection) DBConPool.getInstance().getDataSource().getConnection();
            PreparedStatement ps = null;
            ps = con.prepareStatement("TRUNCATE TABLE drop_data ");
            ps.execute();
            ps.close();
            con.close();
        } catch (SQLException ex) {
            System.err.println("[" + FileoutputUtil.CurrentReadable_Time() + "]刷新出错：" + ex.getMessage());
        }
        MapleMonsterInformationProvider.getInstance().removeByAll();
        mobs = null;
    }


    public static void updateGWId(int dropperid, int itemid, int chance, int id) {
        try {
            final Connection con = (Connection) DBConPool.getInstance().getDataSource().getConnection();
            PreparedStatement ps = null;

            ps = con.prepareStatement("UPDATE drop_data set dropperid = ?,itemid = ?,chance = ? where id = ?");
            ps.setInt(1, dropperid);
            ps.setInt(2, itemid);
            ps.setInt(3, chance);
            ps.setInt(4, id);
            ps.execute();
            con.close();
        } catch (SQLException ex) {
            System.err.println("[" + FileoutputUtil.CurrentReadable_Time() + "]刷新出错：" + ex.getMessage());
        }
        MapleMonsterInformationProvider.getInstance().removeById(dropperid);
        mobs.forEach(drop -> {
            if (drop.getId() == id) {
                drop.setDropperid(dropperid);
                drop.setItemId(itemid);
                drop.setChance(chance);
            }
        });
    }


    public static void  insertGWId(int dropperid, int itemid, int chance) {
        try {
            final Connection con = (Connection) DBConPool.getInstance().getDataSource().getConnection();
            PreparedStatement ps = null;

            ps = con.prepareStatement("INSERT INTO drop_data (dropperid,itemid,minimum_quantity,maximum_quantity,chance) VALUES( ?,?,1,1,?)", Statement.RETURN_GENERATED_KEYS);
            ps.setInt(1, dropperid);
            ps.setInt(2, itemid);
            ps.setInt(3, chance);
            int id = ps.executeUpdate();

            ps.close();
            con.close();

            Drop b = new Drop();
            b.setId(id);
            b.setDropperid(dropperid);
            b.setItemId(itemid);
            b.setItenName(MapleItemInformationProvider.getInstance().getName(itemid));
            String string = MapleDataTool.getString((dropperid + "/name"), MapleLifeFactory.mobStringData, "MISSINGNO");

            b.setDropName(string);

            b.setChance(chance);
            mobs.add(b);

        } catch (SQLException ex) {
            System.err.println("[" + FileoutputUtil.CurrentReadable_Time() + "]刷新出错：" + ex.getMessage());
        }
        MapleMonsterInformationProvider.getInstance().removeById(dropperid);
        mobs =null;
    }


    public static List<Drop> getQQS() {
        if (QQS!=null){
            return QQS;
        }
        QQS = new ArrayList<>();
        try {
            final Connection con = (Connection) DBConPool.getInstance().getDataSource().getConnection();
            PreparedStatement ps = null;
            ResultSet rs = null;

            ps = con.prepareStatement("SELECT * FROM drop_data_global WHERE itemid !=0");
            rs = ps.executeQuery();
            while (rs.next()) {
                Drop b = new Drop();
                b.setId(rs.getInt("id"));
                b.setItemId(rs.getInt("itemid"));
                b.setItenName(MapleItemInformationProvider.getInstance().getName(rs.getInt("itemid")));
                b.setChance(rs.getInt("chance"));
                QQS.add(b);
            }
            rs.close();
            ps.close();
            con.close();
        } catch (SQLException ex) {
            System.err.println("[" + FileoutputUtil.CurrentReadable_Time() + "]怪物暴率出错：" + ex.getMessage());
        }
        return QQS;
    }


    public static void deleteQQId(int id) {
        try {
            final Connection con = (Connection) DBConPool.getInstance().getDataSource().getConnection();
            PreparedStatement ps = null;

            ps = con.prepareStatement("DELETE FROM drop_data_global where id = ?");
            ps.setInt(1,id);
            ps.execute();
            ps.close();
            con.close();
        } catch (SQLException ex) {
            System.err.println("[" + FileoutputUtil.CurrentReadable_Time() + "]删除出错：" + ex.getMessage());
        }
        MapleMonsterInformationProvider.getInstance().getGlobalDrop().clear();
        MapleMonsterInformationProvider.getInstance().retrieveGlobal();

        QQS = QQS.stream().filter(drop -> drop.getId() != id)
                .collect(Collectors.toList());
    }


    public static void updateQQId(int itemid, int chance, int id) {
        try {
            final Connection con = (Connection) DBConPool.getInstance().getDataSource().getConnection();
            PreparedStatement ps = null;

            ps = con.prepareStatement("UPDATE drop_data_global set itemid = ?,chance = ? where id = ?");
            ps.setInt(1, itemid);
            ps.setInt(2, chance);
            ps.setInt(3, id);
            ps.execute();
            con.close();
        } catch (SQLException ex) {
            System.err.println("[" + FileoutputUtil.CurrentReadable_Time() + "]刷新出错：" + ex.getMessage());
        }
        MapleMonsterInformationProvider.getInstance().getGlobalDrop().clear();
        MapleMonsterInformationProvider.getInstance().retrieveGlobal();

        QQS.forEach(drop -> {
            if (drop.getId() == id) {
                drop.setItemId(itemid);
                drop.setChance(chance);
            }
        });
    }



    public static void insertQQ(int itemid, int chance ) {
        try {
            final Connection con = (Connection) DBConPool.getInstance().getDataSource().getConnection();
            PreparedStatement ps = null;

            ps = con.prepareStatement("INSERT INTO drop_data_global (continent,droptype,itemid,minimum_quantity,maximum_quantity,chance) VALUES(1,1,?,1,1,?)", Statement.RETURN_GENERATED_KEYS);
            ps.setInt(1, itemid);
            ps.setInt(2, chance);
            int id = ps.executeUpdate();
            ps.close();
            con.close();

            Drop b = new Drop();
            b.setId(id);
            b.setItemId(itemid);
            b.setItenName(MapleItemInformationProvider.getInstance().getName(itemid));
            b.setChance(chance);
            QQS.add(b);
        } catch (SQLException ex) {
            System.err.println("[" + FileoutputUtil.CurrentReadable_Time() + "]刷新出错：" + ex.getMessage());
        }
        MapleMonsterInformationProvider.getInstance().getGlobalDrop().clear();
        MapleMonsterInformationProvider.getInstance().retrieveGlobal();
    }


    public static void insertQQALL(List<Drop> drops) {
        for (Drop drop : drops) {


        try {
            final Connection con = (Connection) DBConPool.getInstance().getDataSource().getConnection();
            PreparedStatement ps = null;

            ps = con.prepareStatement("INSERT INTO drop_data_global (continent,droptype,itemid,minimum_quantity,maximum_quantity,chance) VALUES(1,1,?,1,1,?)", Statement.RETURN_GENERATED_KEYS);
            ps.setInt(1, drop.getItemId());
            ps.setInt(2, drop.getChance());
            int id = ps.executeUpdate();
            ps.close();
            con.close();

            Drop b = new Drop();
            b.setId(id);
            b.setItemId(drop.getItemId());
            b.setItenName(MapleItemInformationProvider.getInstance().getName(drop.getItemId()));
            b.setChance(drop.getChance());
            QQS.add(b);
        } catch (SQLException ex) {
            System.err.println("[" + FileoutputUtil.CurrentReadable_Time() + "]刷新出错：" + ex.getMessage());
        }
        }
        MapleMonsterInformationProvider.getInstance().getGlobalDrop().clear();
        MapleMonsterInformationProvider.getInstance().retrieveGlobal();
    }


    public static void deleteQJAll() {
        try {
            final Connection con = (Connection) DBConPool.getInstance().getDataSource().getConnection();
            PreparedStatement ps = null;
            ps = con.prepareStatement("TRUNCATE TABLE drop_data_global ");
            ps.execute();
            ps.close();
            con.close();
        } catch (SQLException ex) {
            System.err.println("[" + FileoutputUtil.CurrentReadable_Time() + "]刷新出错：" + ex.getMessage());
        }
        MapleMonsterInformationProvider.getInstance().getGlobalDrop().clear();
        MapleMonsterInformationProvider.getInstance().retrieveGlobal();
        QQS = null;
    }

    public static void deleteItemId(int itemId) {

        try {
            final Connection con = (Connection) DBConPool.getInstance().getDataSource().getConnection();
            PreparedStatement ps = null;

            ps = con.prepareStatement("DELETE FROM drop_data where itemid = ?");
            ps.setInt(1,itemId);
            ps.execute();
            ps.close();
            con.close();
        } catch (SQLException ex) {
            System.err.println("[" + FileoutputUtil.CurrentReadable_Time() + "]删除出错：" + ex.getMessage());
        }
        MapleMonsterInformationProvider.getInstance().removeByAll();

        mobs = mobs.stream().filter(drop -> drop.getItemId() != itemId)
                .collect(Collectors.toList());

        try {
            final Connection con = (Connection) DBConPool.getInstance().getDataSource().getConnection();
            PreparedStatement ps = null;

            ps = con.prepareStatement("DELETE FROM drop_data_global where itemid = ?");
            ps.setInt(1,itemId);
            ps.execute();
            ps.close();
        } catch (SQLException ex) {
            System.err.println("[" + FileoutputUtil.CurrentReadable_Time() + "]删除出错：" + ex.getMessage());
        }
        MapleMonsterInformationProvider.getInstance().getGlobalDrop().clear();
        MapleMonsterInformationProvider.getInstance().retrieveGlobal();

        QQS = QQS.stream().filter(drop -> drop.getItemId() != itemId)
                .collect(Collectors.toList());
    }


    public static List<Drop> getItemIdsMob(String itemId) {
        List<Drop> mobBLs = getMobBLs();
        return mobBLs.stream().filter(drop -> String.valueOf(drop.getItemId()).contains(itemId))
                .collect(Collectors.toList());
    }


    public static List<Drop> getItemNamesMob(String itemName) {
        List<Drop> mobBLs = getMobBLs();
        return mobBLs.stream().filter(drop -> String.valueOf(drop.getItenName()).contains(itemName))
                .collect(Collectors.toList());
    }




    public static List<Drop> getItemIdsQQ(String itemId) {
        List<Drop> qqs = getQQS();
        return qqs.stream().filter(drop -> String.valueOf(drop.getItemId()).contains(itemId))
                .collect(Collectors.toList());
    }


    public static List<Drop> getItemNamesQQ(String itemName) {
        List<Drop> qqs = getQQS();
        return qqs.stream().filter(drop -> String.valueOf(drop.getItenName()).contains(itemName))
                .collect(Collectors.toList());
    }


    public static List<Drop> getMobIdsMob(String MobId) {
        List<Drop> mobBLs = getMobBLs();
        return mobBLs.stream().filter(drop -> String.valueOf(drop.getDropperid()).contains(MobId))
                .collect(Collectors.toList());
    }


    public static List<Drop> getMobNames(String MobName) {
        List<Drop> mobBLs = getMobBLs();
        return mobBLs.stream().filter(drop -> String.valueOf(drop.getDropName()).contains(MobName))
                .collect(Collectors.toList());
    }


    public static List<Drop> sort(final List<Drop> drops,int type) {
        switch (type){
            case 1:
                drops.sort(Comparator.comparingInt(Drop::getId));
            break;
            case 2:
                drops.sort(Comparator.comparingInt(Drop::getItemId));
            break;
            case 3:
                drops.sort(Comparator.comparing(Drop::getItenName));
            break;
            case 4:
                drops.sort(Comparator.comparingInt(Drop::getDropperid));
            break;
            case 5:
                drops.sort(Comparator.comparing(Drop::getDropName));
            break;
            case 6:
                drops.sort(Comparator.comparingInt(Drop::getChance));
            break;
        }
        return drops;
    }


    public static void exportData (String file,List<Drop> drops){
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("bl", drops);

        String jsonString1 = jsonObject1.toJSONString();
        FileWriter fileWriter = new FileWriter(file);
        fileWriter.write(jsonString1);
    }


    public static void importDataQQ(String file){
        FileReader fileReader = new FileReader(file);
        String result3 = fileReader.readString();
        
        JSONObject jsonObject1 = JSONObject.parseObject(result3);
        List<Drop> bl = jsonObject1.getJSONArray("bl").toJavaList(Drop.class);

        getQQS();
        insertQQALL(bl);
    }


    public static void importDataMob(String file){
        FileReader fileReader = new FileReader(file);
        String result3 = fileReader.readString();
        
        JSONObject jsonObject1 = JSONObject.parseObject(result3);
        List<Drop> bl = jsonObject1.getJSONArray("bl").toJavaList(Drop.class);

        getMobBLs();
        for (Drop drop : bl) {
            insertGWId(drop.getDropperid(),drop.getItemId(), drop.getChance());
        }
    }

    public static void main(String[] args) {
        List<Drop> qqs = getMobBLs();
        exportData("E:\\MXD\\cs.txt", qqs);

        importDataQQ("E:\\MXD\\cs.txt");


    }

}
