package tech.starwin.utils.ui_utils;


import android.app.Activity;
import android.app.Instrumentation;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.graphics.drawable.Icon;
import android.os.Build;
import android.support.annotation.ColorRes;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.annotation.StringRes;
import android.support.v4.app.NotificationCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.common.widget.SpanButton;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.schedulers.Schedulers;
import tech.starwin.LibConfig;
import tech.starwin.base.RecyclerViewHolder;


/**
 * Created by SiKang on 2018/9/14.
 * 常用UI功能
 */
public class UIHelper {

    @RequiresApi(api = Build.VERSION_CODES.O)
    public void addShortCut(Context context, Class target, String shortcutName, String shortcutId) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            return;
        }
        ShortcutManager shortcutManager = (ShortcutManager) context.getSystemService(Context.SHORTCUT_SERVICE);

        List<ShortcutInfo> shortcutInfoList = shortcutManager.getPinnedShortcuts();
        for (ShortcutInfo shortcutInfo : shortcutInfoList) {
            if (shortcutInfo.getId().equals(shortcutId)) {
                return;
            }
        }

        if (shortcutManager.isRequestPinShortcutSupported()) {
            Intent shortcutInfoIntent = new Intent(context, target);
            shortcutInfoIntent.setAction(Intent.ACTION_VIEW);
            shortcutInfoIntent.putExtra("launch_id", shortcutId);

            ShortcutInfo info = new ShortcutInfo.Builder(context, shortcutId)
                    .setIcon(Icon.createWithResource(context, LibConfig.APP_ICON))
                    .setShortLabel(shortcutName)
                    .setIntent(shortcutInfoIntent)
                    .build();

            //当添加快捷方式的确认弹框弹出来时，将被回调
            PendingIntent shortcutCallbackIntent = PendingIntent.getBroadcast(context, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
            shortcutManager.requestPinShortcut(info, shortcutCallbackIntent.getIntentSender());
        }
    }


    /**
     * 为View添加ClickListener
     */
    public static <T extends View.OnClickListener> void bindClickListener(T listener, View... views) {
        if (views.length == 0 || listener == null) {
            return;
        }
        for (View view : views) {
            view.setOnClickListener(listener);
        }
    }

    /**
     * 为View添加ClickListener
     */
    public static <T extends View.OnClickListener> RecyclerViewHolder bindClickListener(ViewGroup viewGroup, T listener, @IdRes int... idSet) {
        if (idSet.length == 0 && listener == null) {
            return null;
        }
        RecyclerViewHolder holder = new RecyclerViewHolder(viewGroup);
        for (int id : idSet) {
            View view = holder.getView(id);
            if (view != null) {
                view.setOnClickListener(listener);
            }
        }
        return holder;
    }


    /**
     * 按默认配置初始化RecylerView 并绑定Adapter
     */
    public static void bindAdapter(RecyclerView recyclerView, RecyclerView.Adapter adapter) {
        recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
        recyclerView.setAdapter(adapter);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    public static void bindAdapter(RecyclerView recyclerView, RecyclerView.Adapter adapter, int spanCount) {
        recyclerView.setLayoutManager(new GridLayoutManager(recyclerView.getContext(), spanCount));
        recyclerView.setAdapter(adapter);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }


    public static boolean hasEmptyValue(View... views) {
        for (View view : views) {
            if (view == null) {
                return true;
            }
            if (view instanceof TextView) {
                if (TextUtils.isEmpty(((TextView) view).getText().toString().replace(" ", ""))) {
                    return true;
                }
            } else if (view instanceof EditText) {
                if (TextUtils.isEmpty(((EditText) view).getText().toString().replace(" ", ""))) {
                    return true;
                }
            } else if (view instanceof SpanButton) {
                if (TextUtils.isEmpty(((SpanButton) view).getText().toString().replace(" ", ""))) {
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 显示Toast
     */
    public static void showToast(@NonNull Context context, @StringRes int str) {
        showToast(context, context.getString(str), Toast.LENGTH_SHORT);
    }

    public static void showToast(@NonNull Context context, String msg) {
        showToast(context, msg, Toast.LENGTH_SHORT);
    }

    public static void showToast(@NonNull Context context, String msg, int time) {
        Toast.makeText(context, msg, time).show();
    }


    /**
     * 显示View
     */
    public static void showViews(View view, View... views) {
        view.setVisibility(View.VISIBLE);
        for (View v : views) {
            v.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 显示View
     */
    public static void showFirst(View view, View... views) {
        view.setVisibility(View.VISIBLE);
        for (View v : views) {
            v.setVisibility(View.GONE);
        }
    }

    /**
     * 隐藏View
     */
    public static void hideViews(View view, View... views) {
        view.setVisibility(View.GONE);
        for (View v : views) {
            v.setVisibility(View.GONE);
        }
    }


    /**
     * 设置View Selected 状态
     */
    public static void unSelectedViews(View view, View... views) {
        view.setSelected(false);
        for (View v : views) {
            v.setSelected(false);
        }
    }

    public static void selectedViews(View view, View... views) {
        view.setSelected(false);
        for (View v : views) {
            v.setSelected(false);
        }
    }


    /**
     * 字符串高亮显示部分文字
     *
     * @param textView  控件
     * @param text      要高亮显示的文字（输入的关键词）
     * @param highTexts 高亮文字
     */
    public static void setTextHighLight(TextView textView, String text, @ColorRes int colorId, String... highTexts) {
        textView.setText(text);
        SpannableStringBuilder builder = new SpannableStringBuilder(text);
        // 遍历要显示的文字
        for (String highText : highTexts) {
            if (!TextUtils.isEmpty(highText) && text.contains(highText)) {
                int index = text.indexOf(highText);
                builder.setSpan(new ForegroundColorSpan(textView.getContext().getResources().getColor(colorId)), index, index + highText.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            }
        }
        // 设置控件
        textView.setText(builder);
    }

    /**
     * set Margin
     */
    public static void setMargins(View view, int left, int top, int right, int bottom) {
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        if (layoutParams instanceof RelativeLayout.LayoutParams) {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) layoutParams;
            if (left >= 0) {
                params.leftMargin = left;
            }
            if (top >= 0) {
                params.topMargin = top;
            }
            if (right >= 0) {
                params.rightMargin = right;
            }
            if (bottom >= 0) {
                params.bottomMargin = bottom;
            }
            view.setLayoutParams(params);
        } else if (layoutParams instanceof LinearLayout.LayoutParams) {
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) layoutParams;
            if (left >= 0) {
                params.leftMargin = left;
            }
            if (top >= 0) {
                params.topMargin = top;
            }
            if (right >= 0) {
                params.rightMargin = right;
            }
            if (bottom >= 0) {
                params.bottomMargin = bottom;
            }
            view.setLayoutParams(params);
        }
    }

    /**
     * 更新View宽高
     */
    public void resizeView(View view, int width, int height) {
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        if (width > 0) {
            layoutParams.width = width;
        }
        if (height > 0) {
            layoutParams.height = height;
        }
        view.setLayoutParams(layoutParams);
    }

    /**
     * 打开软键盘
     *
     * @param mEditText 输入框
     */
    public static void openKeybord(EditText mEditText) {
        if (!isKeyboardOpened(mEditText)) {
            InputMethodManager imm = (InputMethodManager) mEditText.getContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                    InputMethodManager.HIDE_IMPLICIT_ONLY);

        }
    }

    /**
     * 关闭软键盘
     *
     * @param mEditText 输入框
     */
    public static void closeKeybord(EditText mEditText) {
        InputMethodManager imm = (InputMethodManager) mEditText.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    }

    /**
     * 关闭软键盘
     */
    public static void closeKeybord(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        View view = activity.getCurrentFocus();
        if (view == null) {
            view = new View(activity);
        }
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }


    /**
     * 判断软键盘是否弹出
     */
    public static boolean isKeyboardOpened(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(v.getContext().INPUT_METHOD_SERVICE);
        if (imm.hideSoftInputFromWindow(v.getWindowToken(), 0)) {
            imm.showSoftInput(v, 0);
            return true;
            //软键盘已弹出
        } else {
            return false;
            //软键盘未弹出
        }
    }


    /**
     * 获得屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /**
     * 获得屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }


    /**
     * 模拟返回键
     */
    public static void doBack() {
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                try {
                    Instrumentation inst = new Instrumentation();
                    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        })
                .subscribeOn(Schedulers.io())
                .subscribe();
    }


    /**
     * 显示通知
     */
    public static void notifyNotification(Context context, NotificationCompat.Builder builder) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        builder.setWhen(System.currentTimeMillis())
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        // 兼容android O
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(LibConfig.APPLICATION_ID, LibConfig.APPLICATION_ID, NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
            builder.setChannelId(LibConfig.APPLICATION_ID);
        }
        // 通知系统展示通知栏
        notificationManager.notify("test", 111, builder.build());
    }


}
