package tech.starwin.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Base64;

import com.qmuiteam.qmui.QMUILog;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import tech.starwin.R;

/**
 * Created by SiKang on 2018/9/17.
 * 常用工具
 */
public class GeneralUtils {

    /**
     * 序列化对象
     */
    public static String fromBean(Object obj) {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = null;
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(obj);
            return base64(byteArrayOutputStream.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 反序列化对象
     */
    public static Object toBean(String str) {
        try {
            byte[] bytes = Base64.decode(str, Base64.NO_WRAP);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            return objectInputStream.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * String转base64
     */
    public static String base64(String content) {
        if (!TextUtils.isEmpty(content))
            return Base64.encodeToString(content.getBytes(), Base64.DEFAULT);
        else
            return "";
    }

    /**
     * 格式化金额
     */
    public static String indMoneyFormat(@Nullable Context context, double money) {
        return String.format(context.getString(R.string.moneySymbol) + "%,.0f", money).replaceAll(",", ".");
    }

    public static String moneyFormat(double paidAmount) {
//        return moneyFormat(String.valueOf(paidAmount));
        return String.format("%,.0f", paidAmount).replace(",", ".");
    }

    /**
     * 格式化时间
     */
    @Nullable
    public static CharSequence periodFormate(@Nullable Context context, double term, @NonNull String periodUnit) {
        String result = "" + (int) term + getPeriodTextUnit(context, periodUnit);
        return result;
    }

    private static String getPeriodTextUnit(Context context, String periodUnit) {
        String unit = context.getResources().getString(R.string.days);
        if ("D".equals(periodUnit)) {
            unit = context.getString(R.string.days);
        } else if ("M".equals(periodUnit)) {
            unit = context.getString(R.string.months);
        } else if ("Y".equals(periodUnit)) {
            unit = context.getString(R.string.years);
        }
        return unit;
    }


    /**
     * 转换时间(String -> Date)
     */
    public static Date stringToDate(String time, String format) {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat(format);
            Date date = formatter.parse(time);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 转换时间(Date -> String)
     */
    public static String dateToString(Date date, String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String time = formatter.format(date);
        return time;
    }

    /**
     * List是否无内容
     */
    public static boolean isEmpty(List list) {
        if (list == null || list.size() == 0)
            return true;
        return false;
    }


    /**
     * 获取时间戳 yyyyMMddHHmmss
     */
    public static String getTimeYMDHMS() {
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(new Date());
    }

    /**
     * 获取时间戳 yyyyMMdd
     */
    public static String getTimeYMD() {
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        return formatter.format(new Date());
    }

    /**
     * String转base64
     */
    public static String base64(byte[] bytes) {
        if (bytes != null && bytes.length > 0)
            return Base64.encodeToString(bytes, Base64.DEFAULT);
        else
            return "";
    }


    /**
     * 获取应用程序名称
     */
    public static synchronized String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * MD5
     */
    public static String MD5(String key) {
        String cacheKey;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(key.getBytes());
            cacheKey = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            cacheKey = String.valueOf(key.hashCode());
        }
        return cacheKey;
    }


    private static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }


    /**
     * 获取AndroidID
     */
    @SuppressLint("HardwareIds")
    public static String getAndroidID(Context context) {
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }


    public static void findAndModifyOpInBackStackRecord(FragmentManager fragmentManager, int backStackIndex, OPHandler handler) {
        if (fragmentManager == null || handler == null) {
            return;
        }
        int backStackCount = fragmentManager.getBackStackEntryCount();
        if (backStackCount > 0) {
            if (backStackIndex >= backStackCount || backStackIndex < -backStackCount) {
                QMUILog.d("findAndModifyOpInBackStackRecord", "backStackIndex error: " +
                        "backStackIndex = " + backStackIndex + " ; backStackCount = " + backStackCount);
                return;
            }
            if (backStackIndex < 0) {
                backStackIndex = backStackCount + backStackIndex;
            }
            try {
                FragmentManager.BackStackEntry backStackEntry = fragmentManager.getBackStackEntryAt(backStackIndex);

                Field opsField = backStackEntry.getClass().getDeclaredField("mOps");
                opsField.setAccessible(true);
                Object opsObj = opsField.get(backStackEntry);
                if (opsObj instanceof List<?>) {
                    List<?> ops = (List<?>) opsObj;
                    for (Object op : ops) {
                        if (handler.handle(op)) {
                            return;
                        }
                    }
                }
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    public interface OPHandler {
        boolean handle(Object op);
    }
}
