package com.yutou.qqbot.utlis;

import com.alibaba.fastjson2.JSON;
import com.yutou.qqbot.QQBotManager;
import com.yutou.qqbot.interfaces.DownloadInterface;
import com.yutou.qqbot.interfaces.ObjectInterface;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;


public class AppTools {
    public static String getToDayNowTimeToString() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }
    public static String getToDayTime() {
        return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    }
    public static String getHours(){
        return new SimpleDateFormat("HH").format(new Date());
    }
    /**
     * 异常输出
     *
     * @param e 异常
     * @return
     */
    public static String getExceptionString(Exception e) {
        StringWriter writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        e.printStackTrace(printWriter);
        printWriter.close();
        return writer.toString();
    }
    public static String exec(String exec, ObjectInterface objectInterface, boolean isOutQQBot, boolean isInput) {
        try {
            Process process;
            if (AppTools.isRuntimeSystemOfWindow()) {
                process = Runtime.getRuntime().exec(new String[]{
                                "cmd",
                                "/c",
                                exec
                        }
                );
            } else {
                process = Runtime.getRuntime().exec(new String[]{
                                "sh",
                                "-c",
                                exec
                        }
                );
            }
            String ret;
            if (isInput) {
                ret=processOut(process.getInputStream(), objectInterface, isOutQQBot);
                processOut(process.getErrorStream(),null,isOutQQBot);
            } else {
                ret=processOut(process.getErrorStream(), objectInterface, isOutQQBot);
                processOut(process.getInputStream(),null,isOutQQBot);
            }
            process.destroy();
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static boolean isRuntimeSystemOfWindow() {
        return System.getProperty("os.name").contains("Windows");
    }

    public static List<Class<?>> scanClass(String classPath, Class<? extends Annotation> annotation) {
        List<Class<?>> classList = new ArrayList<>();
        if (ObjectUtils.isEmpty(classPath)) {
            return classList;
        }
        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
        TypeFilter includeFilter = (metadataReader, metadataReaderFactory) -> true;
        provider.addIncludeFilter(includeFilter);
        // 指定扫描的包名
        Set<BeanDefinition> candidateComponents = provider.findCandidateComponents(classPath);
        Set<BeanDefinition> beanDefinitionSet = new HashSet<>(candidateComponents);

        beanDefinitionSet.forEach(beanDefinition -> {
            try {
                Class<?> clazz = Class.forName(beanDefinition.getBeanClassName());

                if (!ObjectUtils.isEmpty(annotation)) {
                    if (!ObjectUtils.isEmpty(AnnotationUtils.getAnnotation(clazz, annotation))) {
                        classList.add(clazz);
                    }
                } else {
                    classList.add(clazz);
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
//            System.out.println(definition.getBeanClassName());
        });
        return classList;
    }


    public static void processOut(InputStream inputStream) {
        processOut(inputStream,null,true);
    }
    public static String processOut(InputStream inputStream, ObjectInterface objectInterface, boolean isOutQQBot){
        String tmp;
        StringBuilder str = new StringBuilder();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            while ((tmp = reader.readLine()) != null) {
                str.append(tmp).append("\n");
            }
            reader.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(objectInterface!=null){
            objectInterface.out(str.toString());
        }
        //  com.yutou.nas.utils.Log.i("cmd > " + str);
        if(isOutQQBot) {
            QQBotManager.getInstance().sendMessage(str.toString());
        }
        return str.toString();
    }
    public static void sendServer(String title, String msg) {
        try {
            Log.i("title=" + title + " msg=" + msg);
            HttpTools.post("https://sctapi.ftqq.com/SCT2619Tpqu93OYtQCrK4LOZYEfr2irm.send",
                    ("title="+ URLEncoder.encode(title, "UTF-8") + "&desp=" + URLEncoder.encode(msg, "UTF-8")).getBytes(StandardCharsets.UTF_8));
            if (ConfigTools.load(ConfigTools.CONFIG, ConfigTools.MODEL).equals("nas")) {
                String img = null;
                msg = msg.replace("<br/>", "\n");
                if (msg.contains("![logo]")) {
                    try {
                        img = msg.split("!\\[logo\\]\\(")[1].split("\\)")[0];
                        msg = msg.replace("![logo](" + img + ")", "");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (img == null) {
                    QQBotManager.getInstance().sendMessage(title + "\n" + msg);
                } else {
                    String finalMsg = msg;
                    String finalImg = img;
                    if (QQBotManager.getInstance().isLogin()) {
                        HttpTools.download(img,title+".png", new DownloadInterface() {
                            @Override
                            public void onDownload(File file) {
                                super.onDownload(file);
                                QQBotManager.getInstance().sendMessage(file, title + "\n" + finalMsg);
                            }

                            @Override
                            public void onError(Exception e) {
                                super.onError(e);
                                QQBotManager.getInstance().sendMessage(title + "\n" + finalMsg + "\n" + finalImg);
                            }
                        });
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 保存上传的文件
     *
     * @param path 路径
     * @param file 文件
     * @return
     * @throws Exception
     */
    public static String createFile(String path, MultipartFile file, String newFileName) throws Exception {
        String savePath = new File("").getAbsolutePath() + File.separator + "html" + File.separator + path;
        File servicePath = new File(savePath);
        if (!servicePath.exists()) {
            servicePath.mkdirs();
        }
        String fileName = file.getOriginalFilename();
        if (newFileName != null) {
            fileName = newFileName;
        }
        File saveFile = new File(savePath + "/" + fileName);
        if (saveFile.exists()) {
            if (!saveFile.delete()) {
                saveFile = new File(savePath + "/" + fileName.replace(".", "_" + new Date().getTime() + "."));
            }
        }
        file.transferTo(saveFile);
        System.out.println("上传文件保存路径：" + saveFile.getAbsolutePath());
        return  saveFile.getAbsolutePath();
    }

    public static Date timeToDate(String date,String time){
        String form;
        if(StringUtils.isEmpty(time)){
            form="yyyy-MM-dd";
        }else{
            form="yyyy-MM-dd HH:mm:ss";
        }
        try {
            return new SimpleDateFormat(form).parse(date+" "+time);
        } catch (ParseException e) {
            return null;
        }
    }

    public static String getMD5(String str){
        return DigestUtils.md5Hex(str);
    }
}
