package com.yutou.qqbot;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.napcat.QQDatabase;
import com.yutou.napcat.handle.*;
import com.yutou.napcat.http.NapCatApi;
import com.yutou.napcat.model.FriendBean;
import com.yutou.napcat.model.GroupBean;
import com.yutou.napcat.model.GroupUserBean;
import com.yutou.napcat.model.SendMessageResponse;
import com.yutou.okhttp.BaseBean;
import com.yutou.okhttp.HttpBody;
import com.yutou.okhttp.HttpCallback;
import com.yutou.qqbot.data.MessageChainBuilder;
import com.yutou.qqbot.interfaces.ObjectInterface;
import com.yutou.qqbot.utlis.*;
import retrofit2.Response;


import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class QQBotManager {

    public static Long defGroup = 891655174L;
    public static Long defQQ = 583819556L;


    private static QQBotManager botManager = null;
    private static final long qqGroup = 891655174L;
    private boolean isLogin = false;
    private static boolean isInit = false;


    private QQBotManager() {
        Object isRun = ConfigTools.load(ConfigTools.CONFIG, "qq_bot");
        if (isRun != null && (boolean) isRun) {
            isLogin = true;
            init();
        }
    }

    private void init() {
        sendMessage(true, 583819556L, "姬妻酱上线拉~☆Daze~  当前版本:" + QQBotApplication.version);
        NapCatApi.getGroupApi().getGroupList().enqueue(new HttpCallback<List<GroupBean>>() {
            @Override
            public void onResponse(int code, String status, List<GroupBean> response, String rawResponse) {
                for (GroupBean groupBean : response) {
                    QQDatabase.addGroup(groupBean.getGroupId(), groupBean);
                    QQNumberManager.getManager().addNumber(groupBean.getGroupId(), true);
                }
            }

            @Override
            public void onFailure(Throwable throwable) {

            }
        });
        NapCatApi.getFriendApi().getFriendList().enqueue(new HttpCallback<List<FriendBean>>() {
            @Override
            public void onResponse(int code, String status, List<FriendBean> response, String rawResponse) {
                for (FriendBean friendBean : response) {
                    QQDatabase.addUser(friendBean.getUserId(), friendBean);
                    QQNumberManager.getManager().addNumber(friendBean.getUserId(), false);
                }
            }

            @Override
            public void onFailure(Throwable throwable) {

            }
        });
        NapCatApi.getUtilsApi().getLoginInfo().enqueue(new HttpCallback<FriendBean>() {
            @Override
            public void onResponse(int code, String status, FriendBean response, String rawResponse) {
                QQDatabase.setMe(response);
            }

            @Override
            public void onFailure(Throwable throwable) {

            }
        });
        isInit = true;
    }

    public synchronized static QQBotManager getInstance() {
        if (botManager == null && !isInit) {
            botManager = new QQBotManager();
        }
        return botManager;
    }


    private String getNotLoginQQ() {
        return "没有登录QQ";
    }

    public SendMessageResponse sendPrivateMessage(Long qq, BaseHandle<?>... items) {
        return sendMessage(true, qq, items);
    }

    private SendMessageResponse sendGroupMessage(Long group, BaseHandle<?>... items) {
        return sendMessage(false, group, items);
    }

    public SendMessageResponse sendMessage(boolean user, Long qq, String msg) {
        return sendMessage(user, qq, new Text(msg));
    }

    public SendMessageResponse sendMessage(Long qq, BaseHandle<?>... items) {
        return sendMessage(QQDatabase.checkFriend(qq), qq, Arrays.asList(items));
    }

    public SendMessageResponse sendMessage(boolean isUser, Long qq, BaseHandle<?>... items) {
        return sendMessage(isUser, qq, Arrays.asList(items));
    }

    public SendMessageResponse sendMessage(boolean isUser, Long qq, List<BaseHandle<?>> items) {
        try {
            if (!ConfigTools.load(ConfigTools.CONFIG, ConfigTools.QQ, Boolean.class)) {
                return null;
            }
            MessageHandleBuild handleBuild = MessageHandleBuild
                    .create()
                    .setGroup(!isUser)
                    .setQQNumber(qq);
            for (BaseHandle<?> item : items) {
                if (item.getData() == null) {
                    continue;
                }
                if (item instanceof Reply) {
                    if (((Reply) item).getData().getId() == -1) {
                        continue;
                    }
                }
                handleBuild.add(item);
            }
            Response<HttpBody<SendMessageResponse>> response;
            if (isUser) {
                response = NapCatApi.getMessageApi().sendPrivateMsg(
                        handleBuild.build()
                ).execute();
            } else {
                response = NapCatApi.getMessageApi().sendGroupMsg(
                        handleBuild.build()
                ).execute();
            }
            if (response.body() != null) {
                return response.body().getData();
            }
        } catch (Exception e) {
            e.printStackTrace();
            SendMessageResponse response = new SendMessageResponse();
            response.setId(-1);
            response.setE(e.getMessage());
            return response;
        }
        return null;
    }

    public String sendMessage(String text) {

        return sendMessage(false,defGroup,text).toString();
    }

    public SendMessageResponse sendMessage(Long group, String text) {
        return sendMessage(QQDatabase.checkFriend(group), group, new Text(text));
    }

    public void sendMessage(Long group, MessageChainBuilder builder) {
        if (QQNumberManager.getManager().isGroup(group)) {
            System.out.println("发群");
        } else {
            System.out.println("发个人");
        }
    }

    public void sendMessage(File imageFile, Long qq, String text) {
        sendMessage(imageFile, qq, null, text);
    }

    public void sendMessage(File imageFile, Long qq, String replyMessageId, String text) {
        List<BaseHandle<?>> items = new ArrayList<>();

        if (imageFile != null) {
            items.add(new Image(imageFile));
        }

        if (replyMessageId != null && !replyMessageId.isEmpty()) {
            items.add(new Reply(Long.parseLong(replyMessageId)));
        }

        if (text != null && !text.isEmpty()) {
            items.add(new Text(text));
        }

        if (!items.isEmpty()) {
            sendMessage(QQDatabase.checkFriend(qq),qq, items);
        }
    }

    public void sendMessage(File imageFile, String text) {
        sendMessage(true,defQQ,new Image(imageFile),new Text(text));
    }

    public void sendMessage(List<File> imgs, Long qq, String text) {

    }

    public void groupBan(long qqGroup, long user, int timer, ObjectInterface objectInterface) {
        NapCatApi.getGroupApi().groupBan(qqGroup, user, timer).enqueue(new HttpCallback<BaseBean>() {
            @Override
            public void onResponse(int code, String status, BaseBean response, String rawResponse) {
                if (objectInterface != null) {
                    objectInterface.out("1");
                }
            }

            @Override
            public void onFailure(Throwable throwable) {
                if (objectInterface != null) {
                    objectInterface.out(null);
                }
            }
        });
    }

    public void getShutUpList(long qqGroup, HttpCallback<List<GroupUserBean>> callback) {
        NapCatApi.getGroupApi().getGroupUserList(qqGroup,true).enqueue(callback);
    }

    public void setGroupSpecialTitle(long group,
                                     long user,
                                     String title,
                                     long duration) {
        NapCatApi.getGroupApi().setGroupSpecialTitle(group, user, title, duration).enqueue(new HttpCallback<BaseBean>() {

            @Override
            public void onResponse(int code, String status, BaseBean response, String rawResponse) {

            }

            @Override
            public void onFailure(Throwable throwable) {

            }
        });
    }

    public static void main(String[] args) {
        JSONObject json = new JSONObject();
        json.put("t1", 3234567890L);
        System.out.println("json = " + json);

        String tmp = json.toString();
        JSONObject json2 = JSON.parseObject(tmp);
        System.out.println("json2 = " + json2);
    }

    public void sendVersion() {
        String localVersion = QQBotApplication.version;
        String serverVersion = HttpTools.get("https://tools.yutou233.cn/public/version.do?token=zIrsh9TUZP2lfRW753PannG49E7VJvor");
        String msg = "本地版本：" + localVersion + "\n" + "服务器版本：" + serverVersion;
        QQBotManager.getInstance().sendMessage(msg);
      //  AppTools.sendServer("服务版本查询", msg);
    }

    public boolean isLogin() {
        return true;
    }


}
