package com.gingersoft.gsa.cloud.common.utils.crash;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.gingersoft.gsa.cloud.common.Api;
import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.constans.HttpsConstans;
import com.gingersoft.gsa.cloud.common.core.user.UserContext;
import com.gingersoft.gsa.cloud.common.logan.LoganManager;
import com.gingersoft.gsa.cloud.common.utils.FileUtils;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.common.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.common.utils.okhttpUtils.OkHttp3Utils;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DeviceUtils;
import com.jess.arms.utils.PermissionUtil;
import com.qmuiteam.qmui.BuildConfig;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.gingersoft.gsa.cloud.common.constans.AppConstans.RP_ERROR;

public class AppCrashHandler implements UncaughtExceptionHandler {
    /**
     * Debug Log tag
     */
    public static final String TAG = "AppCrashHandler";
    /**
     * 是否开启日志输出,在Debug状态下开启,
     * 在Release状态下关闭以提示程序性能
     */
    public static final boolean DEBUG = true;
    /**
     * 系统默认的UncaughtException处理类
     */
    private UncaughtExceptionHandler mDefaultHandler;
    /**
     * CrashHandler实例
     */
    private static AppCrashHandler INSTANCE;
    /**
     * 程序的Context对象
     */
    private Context mContext;
    /**
     * 出错的提示串头
     **/
    private String ErrorStr = "發生錯誤, 請聯絡支援人員!";
    /**
     * 错误报告文件的扩展名
     */
    private static final String CRASH_REPORTER_EXTENSION = ".json";

    // 用于格式化日期,作为日志文件名的一部分
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
    // 用来存储设备信息和异常信息
    private Map<String, String> info = new HashMap<>();

    /**
     * 保证只有一个CrashHandler实例
     */
    private AppCrashHandler() {
    }

    /**
     * 获取CrashHandler实例 ,单例模式
     */
    public static AppCrashHandler getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new AppCrashHandler();
        }
        return INSTANCE;
    }

    /**
     * 初始化,注册Context对象,
     * 获取系统默认的UncaughtException处理器,
     * 设置该CrashHandler为程序的默认处理器
     *
     * @param ctx
     */
    public void init(Context ctx) {
        mContext = ctx;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
        File file = new File(FileUtils.ERRORLOG_PATH);
        if (file.exists()) {
            sendCrashReportsToServer();
        }
    }

    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {
            //如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            //Sleep一会后结束程序
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                Log.e(TAG, "Error : ", e);
            }
            appExit(mContext);
        }
    }

    /**
     * 自定义错误处理,收集错误信息
     * 发送错误报告等操作均在此完成.
     * 开发者可以根据自己的情况来自定义异常处理逻辑
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        Observable.just(0)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Integer integer) throws Exception {
                        String showText = ErrorStr;
                        Throwable cause = ex.getCause();
                        if (cause != null && BuildConfig.DEBUG) {
                            StackTraceElement[] stackTrace = cause.getStackTrace();
                            if (stackTrace != null && stackTrace.length > 0) {
                                String causeName = cause.getClass().getSimpleName();

                                String fileName = stackTrace[0].getFileName();
                                fileName = fileName.substring(0, fileName.length() - 4);
                                int lineNumber = stackTrace[0].getLineNumber();
                                showText += "-" + fileName + "-" + lineNumber + "-" + causeName;
                                OkHttp3Utils.noticePersonnel(RP_ERROR, showText);
                            }
                        }
                        Toast.makeText(mContext, showText, Toast.LENGTH_LONG).show();
                        Looper.loop();
                    }
                });

        final Writer result = new StringWriter();
        final PrintWriter printWriter = new PrintWriter(result);
        // 获取跟踪的栈信息，除了系统栈信息，还把手机型号、系统版本、编译版本的唯一标示
        StackTraceElement[] trace = ex.getStackTrace();
        StackTraceElement[] trace2 = new StackTraceElement[trace.length + 5];
        System.arraycopy(trace, 0, trace2, 0, trace.length);
        trace2[trace.length + 0] = new StackTraceElement("Android", "MODEL", Build.MODEL, -1);
        trace2[trace.length + 1] = new StackTraceElement("Android", "VERSION", Build.VERSION.RELEASE, -1);
        trace2[trace.length + 2] = new StackTraceElement("Gsa-Could", "APP_VERSION_CODE", DeviceUtils.getVersionCode(mContext) + "", -1);
        trace2[trace.length + 3] = new StackTraceElement("Gsa-Could", "APP_VERSION_NAME", DeviceUtils.getVersionName(mContext), -1);
        trace2[trace.length + 4] = new StackTraceElement("Android", "FINGERPRINT", Build.FINGERPRINT, -1);
        // 追加信息，因为后面会回调默认的处理方法
        ex.setStackTrace(trace2);
        ex.printStackTrace(printWriter);
        // 把上面获取的堆栈信息转为字符串，打印出来
        String stacktrace = result.toString();
        printWriter.close();

        LoganManager.w_crash(stacktrace);

        //保存错误报告到文件
        saveCrashInfo2File(ex);
        //发送错误报告到服务器
        sendCrashReportsToServer();
        return true;
    }

    /**
     * 把错误报告发送给服务器,包含新产生的和以前没发送的.
     */
    private void sendCrashReportsToServer() {
        File file = new File(FileUtils.ERRORLOG_PATH);
        File[] files = file.listFiles();
        if (files != null && files.length > 0) {
            List<File> fileList = Arrays.asList(files);
            HashMap<String, String> params = new HashMap<>();
            params.put("type", "1");
            params.put("uid", String.valueOf(UserContext.newInstance().getMemberId()));
            String url = HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + Api.upload_app_log;
            OkHttp3Utils.sendFileMultipart(url, "files", fileList, params)
                    .subscribeOn(Schedulers.io())
                    .subscribeOn(AndroidSchedulers.mainThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<String>() {

                        @Override
                        public void onSubscribe(Disposable d) {
                        }

                        @Override
                        public void onNext(String data) {
                            if (!TextUtils.isEmpty(data)) {
                                BaseResult result = JsonUtils.parseObject(data, BaseResult.class);
                                if (result != null && result.isSuccess()) {
                                    //上傳成功后刪除對應文件
                                    for (File dfile : file.listFiles()) {
                                        boolean delete = dfile.delete();
                                        LogUtil.d(TAG, "delete result : " + delete);
                                    }
                                }
                            }
                        }

                        @Override
                        public void onError(Throwable t) {
                        }

                        @Override
                        public void onComplete() {
                        }

                    });
        }
    }

    private String saveCrashInfo2File(Throwable ex) {
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : info.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\r\n");
        }
        Writer writer = new StringWriter();
        PrintWriter pw = new PrintWriter(writer);
        ex.printStackTrace(pw);
        Throwable cause = ex.getCause();
        // 循环着把所有的异常信息写入writer中
        while (cause != null) {
            cause.printStackTrace(pw);
            cause = cause.getCause();
        }
        pw.close();// 记得关闭
        String result = writer.toString();
        sb.append(result);
        // 保存文件
        long timetamp = System.currentTimeMillis();
        String time = format.format(new Date());
        String MemberName = UserContext.newInstance().getMemberName();
        String fileName = "crash-" + MemberName + "-" + time + "-" + timetamp + "-" + DeviceUtils.getVersionName(mContext) + CRASH_REPORTER_EXTENSION;
        if (PermissionUtil.isGranted(mContext, Manifest.permission.READ_EXTERNAL_STORAGE) && PermissionUtil.isGranted(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//外部存储卡
                try {
                    File dir = new File(FileUtils.ERRORLOG_PATH);
                    //不存在就創建目錄
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    FileOutputStream fos = new FileOutputStream(new File(FileUtils.ERRORLOG_PATH, fileName));
                    fos.write(sb.toString().getBytes());
                    fos.close();
                    return fileName;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 退出应用程序
     */
    public static void appExit(Context context) {
        AppComponent appComponent = ArmsUtils.obtainAppComponentFromContext(context);
        List<Activity> activityList = appComponent.appManager().getActivityList();
        try {
            for (int i = 0; i < activityList.size(); i++) {
                activityList.get(i).finish();
                activityList.remove(i);
            }
            // 退出程序
            android.os.Process.killProcess(android.os.Process.myPid());
            /**
             * finish()是Activity的类方法，仅仅针对Activity，当调用finish()时，只是将活动推向后台，并没有立即释放内存，
             * 活动的资源并没有被清理；当调用System.exit(0)时，退出当前Activity并释放资源（内存），
             * 但是该方法不可以结束整个App如有多个Activty或者有其他组件service等不会结束。
             * 0表示正常退出,1表示非正常 。
             */
            System.exit(1);
        } catch (Exception e) {
        }
    }

    public void setErrorStr(String ErrorStr) {
        this.ErrorStr = ErrorStr;
    }
}
