package com.gingersoft.gsa.cloud.base.application;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.RemoteException;

import com.billy.cc.core.component.CC;
import com.elvishew.xlog.LogConfiguration;
import com.elvishew.xlog.LogLevel;
import com.elvishew.xlog.XLog;
import com.elvishew.xlog.interceptor.BlacklistTagsFilterInterceptor;
import com.elvishew.xlog.printer.AndroidPrinter;
import com.elvishew.xlog.printer.ConsolePrinter;
import com.elvishew.xlog.printer.Printer;
import com.elvishew.xlog.printer.file.FilePrinter;
import com.elvishew.xlog.printer.file.clean.FileLastModifiedCleanStrategy;
import com.elvishew.xlog.printer.file.naming.DateFileNameGenerator;
import com.gingersoft.gsa.cloud.base.BuildConfig;
import com.gingersoft.gsa.cloud.base.R;
import com.gingersoft.gsa.cloud.base.common.bean.CurrentAndroidSetting;
import com.gingersoft.gsa.cloud.base.utils.AidlUtil;
import com.gingersoft.gsa.cloud.base.utils.constans.Constans;
import com.gingersoft.gsa.cloud.base.utils.constans.HttpsConstans;
import com.gingersoft.gsa.cloud.base.utils.constans.UserConstans;
import com.gingersoft.gsa.cloud.base.utils.crash.AppCrashHandler;
import com.gingersoft.gsa.cloud.base.utils.file.FileUtils;
import com.gingersoft.gsa.cloud.base.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.base.utils.xlog.MyBackupStrategy;
import com.gingersoft.gsa.cloud.database.DaoManager;
import com.hyweb.n5.lib.exception.NoInitPrinterException;
import com.hyweb.n5.lib.util.PrinterUtil;
import com.jess.arms.base.BaseApplication;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;

import me.jessyan.retrofiturlmanager.RetrofitUrlManager;

/**
 * Created by Wyh on 2019/12/21.
 */
public class GsaCloudApplication extends BaseApplication {

    /**
     * 系统上下文
     */
    private static GsaCloudApplication mAppContext;
    private Activity mCurrentActivity;
    /**
     * 设置请求超时默认15秒钟
     */
    public static int REQUEST_TIMEOUT = 15;

    public static boolean isLogin = false;
    public static CurrentAndroidSetting androidSetting;
    public static String userName = "";
    /**
     * 商米:V2、V2_PRO   N5:N5
     */
    public static String mV2 = "V2,V2_PRO";
    public static String mN5 = "N5";

    /**
     * 全局設置上下拉刷新框架Header 和 Footer
     */
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.theme_color, android.R.color.white);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    @Override
    public void onCreate() {
        super.onCreate();
        this.mAppContext = this;
        CC.enableVerboseLog(true);
        CC.enableDebug(true);
        CC.enableRemoteCC(true);
        //初始化上下拉刷新
        initRefresh();
        //初始化日誌管理庫
        initXLog();
        //初始化數據庫框架
        initGreenDao();
        //初始化打印相關
        initPrint();
        //初始化crash記錄
        AppCrashHandler.getInstance().init(this);

        androidSetting = new CurrentAndroidSetting();
    }

    public Activity getCurrentActivity() {
        return mCurrentActivity;
    }

    public void setCurrentActivity(Activity mCurrentActivity) {
        this.mCurrentActivity = mCurrentActivity;
    }

    private void initRefresh() {
        ClassicsHeader.REFRESH_HEADER_PULLING = getString(R.string.srl_header_pulling);//"下拉可以刷新";
        ClassicsHeader.REFRESH_HEADER_REFRESHING = getString(R.string.srl_header_refreshing);//"正在刷新...";
        ClassicsHeader.REFRESH_HEADER_LOADING = getString(R.string.srl_header_loading);//"正在加载...";
        ClassicsHeader.REFRESH_HEADER_RELEASE = getString(R.string.srl_header_release);//"释放立即刷新";
        ClassicsHeader.REFRESH_HEADER_FINISH = getString(R.string.srl_header_finish);//"刷新完成";
        ClassicsHeader.REFRESH_HEADER_FAILED = getString(R.string.srl_header_failed);//"刷新失败";
        ClassicsHeader.REFRESH_HEADER_UPDATE = getString(R.string.srl_header_update);//"上次更新 M-d HH:mm";
        ClassicsHeader.REFRESH_HEADER_UPDATE = getString(R.string.srl_header_update);//"'Last update' M-d HH:mm";
        ClassicsHeader.REFRESH_HEADER_SECONDARY = getString(R.string.srl_header_secondary);//"释放进入二楼"

        ClassicsFooter.REFRESH_FOOTER_PULLING = getString(R.string.srl_footer_pulling);//"上拉加载更多";
        ClassicsFooter.REFRESH_FOOTER_RELEASE = getString(R.string.srl_footer_release);//"释放立即加载";
        ClassicsFooter.REFRESH_FOOTER_LOADING = getString(R.string.srl_footer_loading);//"正在刷新...";
        ClassicsFooter.REFRESH_FOOTER_REFRESHING = getString(R.string.srl_footer_refreshing);//"正在加载...";
        ClassicsFooter.REFRESH_FOOTER_FINISH = getString(R.string.srl_footer_finish);//"加载完成";
        ClassicsFooter.REFRESH_FOOTER_FAILED = getString(R.string.srl_footer_failed);//"加载失败";
        ClassicsFooter.REFRESH_FOOTER_NOTHING = getString(R.string.srl_footer_nothing);//"全部加载完成";
    }

    private void initPrint() {
        if (GsaCloudApplication.mV2.contains(Build.MODEL)) {
            //商米打印
            AidlUtil.getInstance().connectPrinterService(this);
        } else if (GsaCloudApplication.mN5.contains(Build.MODEL)) {
            try {
                //初始化N5打印
                PrinterUtil.initPrinter(this);
            } catch (NoInitPrinterException | RemoteException e) {
                e.printStackTrace();
            }
        } else {
            //如果當前機型不是上面兩種，那麼設置默認打印為ip打印
            SPUtils.put(this, Constans.DEFAULT_PRINT_METHOD, Constans.IP_PRINT);
        }
        //需要單獨配置域名URL的，在接口上添加@Headers({"Domain-Name: settlement_report_server"})，不添加則是使用默認域名
        setGlobalDomain();
        //清機報表請求地址
        RetrofitUrlManager.getInstance().putDomain("settlement_report_server", HttpsConstans.ROOT_SETTLEMENT_REPORT_SERVER_ADDRESS_FORMAL);
        //gsa報表請求地址
        RetrofitUrlManager.getInstance().putDomain("gsa_report", HttpsConstans.REPORT_SERVER_ADDRESS);
        //微信報表請求地址
        RetrofitUrlManager.getInstance().putDomain("wechat_report", HttpsConstans.WECHAR_REPORT_SERVER_ADDRESS);
    }

    public static void setGlobalDomain() {
        //配置全局默認URL
        RetrofitUrlManager.getInstance().setGlobalDomain(HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL);
    }

    private void initXLog() {
        LogConfiguration config = new LogConfiguration.Builder()
                .logLevel(BuildConfig.DEBUG ? LogLevel.ALL             // 指定日志级别，低于该级别的日志将不会被打印，默认为 LogLevel.ALL
                        : LogLevel.NONE)
                .tag("GSA_Cloud_TAG")                                         // 指定 TAG，默认为 "X-LOG"
                .addInterceptor(new BlacklistTagsFilterInterceptor(    // 添加黑名单 TAG 过滤器
                        "blacklist1", "blacklist2", "blacklist3"))
                .build();

        Printer androidPrinter = new AndroidPrinter();             // 通过 android.util.Log 打印日志的打印器
        Printer consolePrinter = new ConsolePrinter();             // 通过 System.out 打印日志到控制台的打印器
        Printer filePrinter = new FilePrinter                      // 打印日志到文件的打印器
                .Builder(FileUtils.ACTIONLOG_PATH)                              // 指定保存日志文件的路径
                .fileNameGenerator(new DateFileNameGenerator())        // 指定日志文件名生成器，默认为 ChangelessFileNameGenerator("log")
                .backupStrategy(new MyBackupStrategy(FileUtils.ACTION_MAX_SIZE))         // 指定日志文件备份策略，默认为 FileSizeBackupStrategy(1024 * 1024)
                .cleanStrategy(new FileLastModifiedCleanStrategy(FileUtils.ACTION_MAX_FILE_TIME))     // 指定日志文件清除策略，默认为 NeverCleanStrategy()
                .build();

        XLog.init(                                                 // 初始化 XLog
                config,                                                // 指定日志配置，如果不指定，会默认使用 new LogConfiguration.Builder().build()
                androidPrinter,                                        // 添加任意多的打印器。如果没有添加任何打印器，会默认使用 AndroidPrinter(Android)/ConsolePrinter(java)
                consolePrinter,
                filePrinter);
    }

    private void initGreenDao() {
        DaoManager mManager = DaoManager.getInstance();
        mManager.init(this);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }


    /**
     * 获取系统上下文：用于ToastUtil类
     */
    public static GsaCloudApplication getAppContext() {
        return mAppContext;
    }


    //获取登陆token
    public static String getLoginToken(Context context) {
        return (String) SPUtils.get(context, UserConstans.token, "");
    }

    public static int getMemberId(Context context) {
        return (int) SPUtils.get(context, UserConstans.memberId, 0);
    }

    public static int getBrandId(Context context) {
        return (int) SPUtils.get(context, UserConstans.brandId, 0);
    }

    public static String getBrandName(Context context) {
        return (String) SPUtils.get(context, UserConstans.brandName, "");
    }

    public static int getRestaurantId(Context context) {
        return (int) SPUtils.get(context, UserConstans.restaurantId, 0);
    }

    public static String getRestaurantName(Context context) {
        return (String) SPUtils.get(context, UserConstans.restaurantName, "");
    }

    public static String getMemberName(Context context) {
        return (String) SPUtils.get(context, UserConstans.memberName, "");
    }

    public static String getBrandRestaurantInfos(Context context) {
        return (String) SPUtils.get(context, UserConstans.brandRestaurantInfos, "");
    }

    public static void setLoginToken(Context context, String token) {
        SPUtils.put(context, UserConstans.token, token);
    }

    public static void setMemberId(Context context, int memberId) {
        SPUtils.put(context, UserConstans.memberId, memberId);
    }

    public static void setMemberName(Context context, String memberName) {
        SPUtils.put(context, UserConstans.memberName, memberName);
    }

    public static void setBrandId(Context context, int restaurantId) {
        SPUtils.put(context, UserConstans.brandId, restaurantId);
    }

    public static void setBrandName(Context context, String restaurantName) {
        SPUtils.put(context, UserConstans.brandName, restaurantName);
    }

    public static void setRestaurantId(Context context, int restaurantId) {
        SPUtils.put(context, UserConstans.restaurantId, restaurantId);
    }

    public static void setRestaurantName(Context context, String restaurantName) {
        SPUtils.put(context, UserConstans.restaurantName, restaurantName);
    }

    public static void setBrandRestaurantInfos(Context context, String brandRestaurantIds) {
        SPUtils.put(context, UserConstans.brandRestaurantInfos, brandRestaurantIds);
    }

    public static void clearMemberInfo() {
        setLoginToken(mAppContext, "");
        setMemberId(mAppContext, 0);
        setMemberName(mAppContext, "");
        setBrandId(mAppContext, 0);
        setBrandName(mAppContext, "");
        setRestaurantId(mAppContext, 0);
        setRestaurantName(mAppContext, "");
        setBrandRestaurantInfos(mAppContext, "");
    }

}
