package com.bbitcn.silk.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.view.View;
import android.view.animation.LinearInterpolator;

import com.bbitcn.silk.model.net.Login;
import com.bbitcn.silk.utils.global.Global;
import com.bbitcn.silk.utils.log.MyLog;
import com.bbitcn.silk.utils.network.Url;
import com.bbitcn.silk.utils.network.XHttpManager;
import com.bbitcn.silk.utils.network.XHttpShorthand;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.xuexiang.rxutil2.rxjava.RxJavaUtils;
import com.xuexiang.rxutil2.rxjava.task.RxUITask;

import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import me.samlss.broccoli.Broccoli;
import me.samlss.broccoli.BroccoliGradientDrawable;
import me.samlss.broccoli.PlaceholderParameter;

public class MyUtil {

    public static Broccoli getMyBroccoli(View... v) {
        Broccoli broccoli = new Broccoli();
        for (int i = 0; i < v.length; i++) {
            broccoli.addPlaceholders(new PlaceholderParameter.Builder()
                    .setView(v[i])
                    .setDrawable(new BroccoliGradientDrawable(Color.parseColor("#DDDDDD"),
                            Color.parseColor("#CCCCCC"), 0, 1000, new LinearInterpolator()))
                    .build());
        }
        return broccoli;
    }


    /***
     * 获得格式化后的时间
     */
    public static int[] getHourAndMinuteUsingLocalTime(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);

        return new int[]{hour, minute};
    }


    /**
     * 获取当前版本号
     */
    public static int getVersion(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * 静默登录
     */
    public static void login() {
        login(null);
    }

    public static void login(Runnable runnable) {
        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.login, false);
        params.addParameter("Platform", "1");
        params.addParameter("TenantCode", Global.getCompanyId());
        params.addParameter("HardwareId", Global.getDeviceId());
        params.addParameter("Account", Global.getUserAccount());
        params.addParameter("Password", EncryptUtils.encryptMD5ToString(Global.getPassword()));
        x.http().post(params, new XHttpShorthand<Login>() {
            @Override
            public void success(Login model) {
                MyLog.app("登录成功");
                if (model.getResult()) {
                    MMKVUtil.put(Global.TOKEN, model.getData().getTokenType() + " " + model.getData().getAccessToken());
                    MMKVUtil.put(Global.TOKEN_TIME, TimeUtils.string2Millis(model.getData().getExpireTime()));
                }
                if (runnable != null) {
                    runnable.run();
                }
            }

            @Override
            public void error(Throwable e) {
                MyLog.appError("Token获取失败");
            }

        });
    }

    /**
     * 获取当前版本号
     */
    public static String getVersionId(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return String.valueOf(packageInfo.versionCode);
        } catch (Exception e) {
            e.printStackTrace();
            return "Err";
        }
    }

    /**
     * 获取当前版本名称
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return "Err";
        }
    }

    /**
     * 获取当前时间
     */
    public static String getDateTime() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    /**
     * 获取当前日期
     */
    public static String getDateDay() {
        return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    }

    /**
     * 转换date格式为标准时间String
     */
    public static String getFormatDateTime(Date date) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
    }

    /**
     * 关闭APP
     */
    public static void exit(Context mContext, String tip) {
        DialogUtil.showLoadingDialogInIO(mContext, tip);
        RxJavaUtils.delay(1, aLong -> {
            DialogUtil.hideLoadingDialog();
            AppUtils.exitApp();
        });
    }

    /**
     * 重启APP
     */
    public static void relaunchApp(Context mContext, String tip) {
        RxJavaUtils.doInUIThread(new RxUITask<Object>(null) {
            @Override
            public void doInUIThread(Object o) {
                if (mContext != null) {
                    DialogUtil.showLoadingDialogInIO(mContext, tip);
                }
                RxJavaUtils.delay(2, aLong -> {
                    AppUtils.relaunchApp(true);
                    DialogUtil.hideLoadingDialog();
                });
            }
        });
    }

}
