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

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.telecom.Call;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;

import com.elvishew.xlog.XLog;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.file.FileUtils;
import com.gingersoft.gsa.cloud.base.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.base.utils.okhttpUtils.OkHttp3Utils;
import com.gingersoft.gsa.cloud.base.utils.other.AppUtils;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DeviceUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

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 = "發生錯誤, 請聯絡支援人員!";
    /**
     * 使用Properties来保存设备的信息和错误堆栈信息
     */
    private static final String VERSION_NAME = "versionName";
    private static final String VERSION_CODE = "versionCode";
    private static final String STACK_TRACE = "STACK_TRACE";
    /**
     * 错误报告文件的扩展名
     */
    private static final String CRASH_REPORTER_EXTENSION = ".cyposdebug";

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

    /**
     * 保证只有一个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()) {
            sendPreviousReportsToServer();
            file.delete();
        }
    }

    /**
     * 当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);
        }
    }

    /**
     * 退出应用程序
     */
    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) {
        }
    }

    /**
     * 自定义错误处理,收集错误信息
     * 发送错误报告等操作均在此完成.
     * 开发者可以根据自己的情况来自定义异常处理逻辑
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }

        //使用Toast来显示异常信息
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(mContext, ErrorStr, Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        }.start();

        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-SUPER", "APP_VERSION_CODE", AppUtils.getVerCode(mContext) + "", -1);
        trace2[trace.length + 3] = new StackTraceElement("GSA-SUPER", "APP_VERSION_NAME", AppUtils.getVerName(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();
        LogUtil.d(TAG, stacktrace);
//        XLog.tag(TAG).d(stacktrace);

        //收集设备信息
        collectCrashDeviceInfo(mContext);
        //保存错误报告到SP
        saveCrashInfoToSP(ex);
        //保存错误报告到文件
        saveCrashInfo2File(ex);
        //发送错误报告到服务器
        sendCrashReportsToServer();
        return true;
    }

    /**
     * 在程序启动时候, 可以调用该函数来发送以前没有发送的报告
     */
    public void sendPreviousReportsToServer() {
        sendCrashReportsToServer();
    }

    /**
     * 把错误报告发送给服务器,包含新产生的和以前没发送的.
     */
    private void sendCrashReportsToServer() {
        File file = new File(FileUtils.ERRORLOG_PATH);
        File[] files = file.listFiles();
        if (files != null) {
            List<File> fileList = Arrays.asList(files);
            OkHttp3Utils.sendFileMultipart("", file.getName(), fileList);
        }
    }

    /**
     * 收集程序崩溃的设备信息
     *
     * @param ctx
     */
    public void collectCrashDeviceInfo(Context ctx) {
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "no set" : pi.versionName;
                String versionCode = pi.versionCode + "";
                info.put("versionName", versionName);
                info.put("versionCode", versionCode);
//                mSetup.setSaveValue_Crash(VERSION_NAME, versionName, mContext);
//                mSetup.setSaveValue_Crash(VERSION_CODE, versionCode, mContext);
            }
        } catch (NameNotFoundException e) {
            Log.e(TAG, "Error while collect package info", e);
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                info.put(field.getName(), field.get("").toString());
//                mSetup.setSaveValue_Crash(field.getName(), String.valueOf(field.get(null)), mContext);
                if (DEBUG) {
                    Log.d(TAG, field.getName() + " : " + field.get(null));
                }
            } catch (Exception e) {
                Log.e(TAG, "Error while collect crash info", e);
            }
        }
    }

    /**
     * 保存错误信息到SP
     * @param ex
     * @return
     */
    private String saveCrashInfoToSP(Throwable ex) {
        Writer info = new StringWriter();
        PrintWriter printWriter = new PrintWriter(info);
        ex.printStackTrace(printWriter);

        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        return null;
    }

    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 = GsaCloudApplication.getMemberName(mContext);
        String fileName = "crash-" + MemberName + "-" + time + "-" + timetamp + "-" + info.get("versionName") + ".xml";
        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 (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

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