package com.tenlionsoft.baselib.core.widget.base;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.TouchDelegate;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.toast.ToastUtils;
import com.tenlionsoft.baselib.R;
import com.tenlionsoft.baselib.constant.PathConfig;
import com.tenlionsoft.baselib.core.widget.views.AfxTextView;
import com.tenlionsoft.baselib.utils.LogUtils;
import com.tenlionsoft.baselib.utils.UserLgUtils;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

/**
 * 作者 : Adam on 2018/10/15.
 * 邮箱 : itgaojian@163.com
 * 描述 : 所有Activity的基类
 */
public abstract class BaseActivity extends AppCompatActivity {
    public static final int STATE_LOAD_INIT = 13;
    public static final int STATE_LOAD_LOADING = 14;//加载中
    public static final int STATE_LOAD_SUCCESS = 15;//加载成功
    public static final int STATE_LOAD_EMPTY = 16;//加载失败
    public static final int STATE_LOAD_ERROR = 17;//加载失败
    public static final int TYPE_CREATE_SEARCH = 18;//新建或搜索
    public static final int TYPE_EDIT_DEL = 19;//编辑或删除

    protected View mContentView;                 //每个activity的内容区域
    public FrameLayout flBaseActivityContent;     //内容区域
    public AppCompatActivity mActivity;           //


    protected int mWidth = 0;
    protected TextView mTvBaseTitle;//标题
    protected TextView mTvPublish;//右边文字
    protected ProgressBar mPbLoading;
    protected ImageView mIvEmptyData;
    protected TextView mTvErrorHint;
    protected ImageView mIvUserIcon;
    protected RelativeLayout mRlBack;
    protected RelativeLayout mRlNotify;
    protected ImageView mIvNotify;
    protected TextView mTvNotify;
    protected RelativeLayout mRlTrTitleBar;
    protected Button mBtnTrBack;
    protected TextView mTvTrTitle;
    protected RelativeLayout mRlTitleBar;
    protected ImageView mTvAppBack;
    protected LinearLayout mLlOptions;
    protected ImageView mIvAppSearchIcon;
    protected LinearLayout mLlAppSearchContent;
    protected EditText mEtAppSearchContent;
    protected TextView mTvDoSearch;
    protected TextView mTvCancelSearch;
    private AnimatorSet mAnimatorSet = new AnimatorSet();
    protected ImageView mIvClearSearch;
    protected TextView mTvOptions;
    protected AfxTextView mTvSearchBack;
    private boolean mIsExpand;//搜索框是否展开
    private LocalBroad mLocalBroad;
    private LinearLayout mLlBaseSearch;
    private static final String NAVIGATION = "navigationBarBackground";
    protected View mVStatusBar;


    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.base_activity);
        //默认隐藏键盘
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        //锁定竖屏
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        mWidth = metrics.widthPixels;
        mActivity = this;
        baseActivityInitViews();//初始化视图
        setTouchDelegate(mTvAppBack, 30);
        mTvAppBack.setOnClickListener(v -> {
            hideSoftKeyboard();
            finish();
        });
        mContentView = LayoutInflater.from(this).inflate(setLayoutId(), null);
        flBaseActivityContent.addView(mContentView);
        mRlTrTitleBar.setVisibility(View.GONE);
        refreshView(STATE_LOAD_LOADING);
        initData();
        initMapView(savedInstanceState);//初始化MapView
        mRlNotify.setVisibility(View.GONE);
        String simpleName = getClass().getSimpleName();
        if ("AddressUserDetailActivity".equals(simpleName)) {
            sendBroadcast(new Intent(PathConfig.ACTION_UNREGISTER_BROAD));
        } else {
            sendBroadcast(new Intent(PathConfig.ACTION_REGISTER_BROAD));
        }

    }


    protected boolean isNavBarHasShown(Context ctx) {
        String brand = Build.BRAND;
        LogUtils.e(brand);
        String deviceInfo = null;
        if (brand.equalsIgnoreCase("HUAWEI")) {
            deviceInfo = "navigationbar_is_min";
        } else if (brand.equalsIgnoreCase("xiaomi") || brand.equalsIgnoreCase("blackshark")) {
            deviceInfo = "force_fsg_nav_bar";
        } else if (brand.equalsIgnoreCase("VIVO") || brand.equalsIgnoreCase("OnePlus") || brand.equalsIgnoreCase("OPPO")) {
            return !ImmersionBar.isGesture(this);
        } else {
            deviceInfo = "noah_navi_mode_value";
        }
        if (!TextUtils.isEmpty(deviceInfo)) {
            int navigationBarIsMin = 0;
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                navigationBarIsMin = Settings.System.getInt(ctx.getContentResolver(),
                    deviceInfo, 0);
            } else {
                if (Build.BRAND.equalsIgnoreCase("VIVO") || Build.BRAND.equalsIgnoreCase("OPPO")) {
                    navigationBarIsMin = Settings.Secure.getInt(ctx.getContentResolver(), deviceInfo, 0);
                } else {
                    navigationBarIsMin = Settings.Global.getInt(ctx.getContentResolver(), deviceInfo, 0);
                }
            }
            return navigationBarIsMin != 1;
        }
        Object windowService = ctx.getSystemService(Service.WINDOW_SERVICE);
        if (windowService == null) {
            return false;
        } else {
            WindowManager windowManager = (WindowManager) windowService;
            Display display = windowManager.getDefaultDisplay();
            DisplayMetrics realDisplayMetrics = new DisplayMetrics();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                display.getRealMetrics(realDisplayMetrics);
            }
            int realHeight = realDisplayMetrics.heightPixels;
            int realWidth = realDisplayMetrics.widthPixels;
            DisplayMetrics displayMetrics = new DisplayMetrics();
            display.getMetrics(displayMetrics);
            int displayHeight = displayMetrics.heightPixels;
            int displayWidth = displayMetrics.widthPixels;
            if (displayHeight > displayWidth) {
                if (displayHeight + getNavigationBarHeight(ctx) > realHeight) {
                    return false;
                }
            } else if (displayWidth + getNavigationBarHeight(ctx) > realWidth) {
                return false;
            }
            return realWidth - displayWidth > 0 || realHeight - displayHeight > 0;
        }
    }

    /**
     * 非全面屏下 虚拟键高度(无论是否隐藏)
     *
     * @param context
     * @return
     */
    protected int getNavigationBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    protected void setLocalBroad(LocalBroad localBroad) {
        this.mLocalBroad = localBroad;
    }


    /**
     * 初始化标题布局
     */
    private void baseActivityInitViews() {
        mTvBaseTitle = findViewById(R.id.tv_app_title);//页面标题
        mLlBaseSearch = findViewById(R.id.ll_base_search);
        mVStatusBar = findViewById(R.id.v_status_bar);
        mVStatusBar.setVisibility(View.GONE);
        //页面返回
        mTvAppBack = findViewById(R.id.tv_app_back);
        mRlTitleBar = findViewById(R.id.rl_title_bar);
        mRlTrTitleBar = findViewById(R.id.rl_tr_app_title);
        mBtnTrBack = findViewById(R.id.ib_tr_app_back);
        mTvTrTitle = findViewById(R.id.tv_app_tr_title);
        flBaseActivityContent = findViewById(R.id.fl_app_content);
        mTvPublish = findViewById(R.id.tv_app_publish);
        mPbLoading = findViewById(R.id.pb_app_loading);
        mIvEmptyData = findViewById(R.id.iv_app_empty_data);
        mTvErrorHint = findViewById(R.id.tv_app_error_hint);
        mRlNotify = findViewById(R.id.rl_notify);
        mIvNotify = findViewById(R.id.iv_nootify_point);

        mLlOptions = findViewById(R.id.ll_options);
        mIvAppSearchIcon = findViewById(R.id.iv_app_search_icon);
        mLlAppSearchContent = findViewById(R.id.ll_app_search_content);
        mEtAppSearchContent = findViewById(R.id.et_base_search_content);
        mTvDoSearch = findViewById(R.id.tv_do_search);
        mTvCancelSearch = findViewById(R.id.tv_cancel_search);
        mIvClearSearch = findViewById(R.id.iv_app_clear_search);
        mIvClearSearch.setVisibility(View.GONE);

        mTvOptions = findViewById(R.id.tv_app_options);
        mTvSearchBack = findViewById(R.id.tv_search_back);
        mTvSearchBack.setBackgroundResource(R.drawable.ic_arrow_left_white_48);
        mTvSearchBack.setVisibility(View.VISIBLE);
        mTvSearchBack.setOnClickListener(v -> finish());
        mTvOptions.setVisibility(View.GONE);
        mTvOptions.setOnClickListener(v -> doShowOptions());

        mBtnTrBack.setOnClickListener(v -> {
            hideSoftKeyboard();
            finish();
        });
        mTvNotify = findViewById(R.id.tv_notify);
        mIvEmptyData.setOnClickListener(v -> reLoadData());


        mLlAppSearchContent.setVisibility(View.GONE);
        mTvAppBack.setBackgroundResource(R.drawable.ic_back_white);
        mEtAppSearchContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s.toString())) {
                    mIvClearSearch.setVisibility(View.VISIBLE);
                } else {
                    mIvClearSearch.setVisibility(View.GONE);
                }
            }
        });
        mIvClearSearch.setOnClickListener(v -> clearSearchContent());
        //设置默认title
        mIvAppSearchIcon.setVisibility(View.GONE);
        mTvPublish.setVisibility(View.GONE);
        mIvAppSearchIcon.setOnClickListener(v -> listenerSearch());
        mTvCancelSearch.setOnClickListener(v -> closeSearchContent());
        mTvDoSearch.setOnClickListener(v -> doSearchByTitle());
        setTouchDelegate(mIvAppSearchIcon, 30);
        setTouchDelegate(mTvCancelSearch, 30);
        setTouchDelegate(mTvDoSearch, 30);
        setTouchDelegate(mTvPublish, 35);

    }


    protected void setDarkSearchBar() {
        mTvSearchBack.setBackgroundResource(R.drawable.ic_back_black);
        mTvDoSearch.setTextColor(getResources().getColor(R.color.text_20));
        mTvCancelSearch.setTextColor(getResources().getColor(R.color.text_20));
        mLlBaseSearch.setBackgroundResource(R.drawable.shape_search_bg);
        mIvAppSearchIcon.setImageResource(R.drawable.ic_black_search_icon);
    }

    /**
     * 初始化视图
     */
    protected abstract int setLayoutId();

    /**
     * 初始化数据
     */
    public abstract void initData();

    /**
     * 搜索
     */
    protected abstract void doSearchByTitle();

    /**
     * 子类实现用于恢复默认
     */
    protected abstract void clearSearch();

    /**
     * 子类实现用来显示筛选条件
     */
    protected void doShowOptions() {

    }

    /**
     * 删除输入框内的数据
     */
    private void clearSearchContent() {
        hideSoftKeyboard();
        mEtAppSearchContent.setText("");
        clearSearch();
    }

    /**
     * 关闭标题搜索
     */
    private void closeSearchContent() {
        mEtAppSearchContent.setText("");
        clearSearch();
        hideSoftKeyboard();
        collapse(mLlAppSearchContent);
    }

    /**
     * 搜索
     */
    protected void listenerSearch() {
        expand(mLlAppSearchContent);
    }


    public void setEditTextInhibitInputSpeChat(EditText editText) {
        InputFilter inputFilter = new InputFilter() {
            Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                Matcher emojiMatcher = emoji.matcher(source);
                if (emojiMatcher.find()) {
                    //                    Toast.makeText(MainActivity.this,"不支持输入表情", 0).show();
                    ToastUtils.show("不支持输入表情");
                    return "";
                }
                return null;
            }
        };
        editText.setFilters(new InputFilter[]{inputFilter});
    }

    /**
     * 显示操作的popup
     *
     * @param type
     */
    protected void showPopupByType(int type) {

    }

    /**
     * 显示操作popup
     *
     * @param type
     */
    protected void ShowControlPopup(int type) {
    }

    /**
     * 设置默认搜索titlebar
     */
    protected void setDefaultSearchTitle() {

    }

    /**
     * 设置默认展开搜索
     */
    protected void setDefaultSearch() {
        listenerSearch();
    }

    /**
     * 设置只能输入汉字.字母.数字
     *
     * @param editText
     */
    protected void setEditTextInputSpeChar(EditText editText) {
        InputFilter filter = (source, start, end, dest, dstart, dend) -> {
            Pattern pattern = Pattern.compile("[^a-zA-Z0-9\\u4E00-\\u9FA5_]");
            Matcher matcher = pattern.matcher(source.toString());
            if (matcher.find()) {
                ToastUtils.show("只能输入汉字、字母、数字");
                return "";
            } else {
                return null;
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }

    /**
     * 设置透明状态栏
     */
    protected void setStatusTr(String title) {
        mRlTitleBar.setVisibility(View.GONE);
        mRlTrTitleBar.setVisibility(View.VISIBLE);
        mTvTrTitle.setText(title);
    }


    /**
     * 刷新页面
     *
     * @param state 页面状态码
     */
    public void refreshView(int state) {
        switch (state) {
            case STATE_LOAD_LOADING://加载中
                mPbLoading.setVisibility(View.VISIBLE);
                mIvEmptyData.setVisibility(View.GONE);
                mTvErrorHint.setVisibility(View.VISIBLE);
                mTvErrorHint.setText(getResources().getString(R.string.loading));
                flBaseActivityContent.setVisibility(View.INVISIBLE);
                break;
            case STATE_LOAD_SUCCESS://加载成功
                mPbLoading.setVisibility(View.GONE);
                mIvEmptyData.setVisibility(View.GONE);
                mTvErrorHint.setVisibility(View.GONE);
                flBaseActivityContent.setVisibility(View.VISIBLE);
                break;
            case STATE_LOAD_EMPTY://空数据
                mPbLoading.setVisibility(View.GONE);
                mIvEmptyData.setVisibility(View.VISIBLE);
                mIvEmptyData.setBackgroundResource(R.drawable.ic_empty_data);
                mTvErrorHint.setVisibility(View.VISIBLE);
                mTvErrorHint.setText(getResources().getString(R.string.empty_data));
                flBaseActivityContent.setVisibility(View.INVISIBLE);
                break;
            case STATE_LOAD_ERROR:
                mPbLoading.setVisibility(View.GONE);
                mIvEmptyData.setVisibility(View.VISIBLE);
                mTvErrorHint.setVisibility(View.VISIBLE);
                mIvEmptyData.setBackgroundResource(R.drawable.ic_load_error);
                mTvErrorHint.setText(getResources().getString(R.string.loading_error));
                flBaseActivityContent.setVisibility(View.INVISIBLE);
                break;
        }
    }

    public void reStartApp() {
        UserLgUtils.setToken("");
        UserLgUtils.setPassword("");
        UserLgUtils.setHwPwd("");
        UserLgUtils.setHwAccount("");
        UserLgUtils.setCheckRemember(false);
        Intent broadcast = new Intent();
        broadcast.setAction(PathConfig.ACTION_PUSH_STOP_SOCKET);
        sendBroadcast(broadcast);
        Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();

    }


    protected void reLoadData() {

    }


    private void openActivity(String path) {
        ARouter.getInstance()
            .build(path)
            .navigation();
    }

    private String getRunningTopActivity() {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        String runningActivity = manager.getRunningTasks(1).get(0).topActivity.getClassName();
        return runningActivity;
    }

    /**
     * 显示toast
     *
     * @param content 要显示的内容
     */
    public void showToast(String content) {
        ToastUtils.show(content);
    }


    /**
     * 隐藏软键盘
     */
    public void hideSoftKeyboard() {
        hideSoftKeyboard(getCurrentFocus());
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (v instanceof WebView) {
                return super.dispatchTouchEvent(ev);
            }
            if (v != null) {
                InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (im != null) {
                    im.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public void hideSoftKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (view != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    public void showSoftKeyBoard(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (view != null) {
            imm.showSoftInput(view, 0);
        }
    }

    public void showSoftKeyBoardDialog(EditText editText) {
        if (editText != null) {
            editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            //请求获得焦点
            editText.requestFocus();
            //调用系统输入法
            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(editText, 0);
        }
    }

    /**
     * 初始化高德地图
     * 使用Butterknife注意
     *
     * @param bundle
     */
    protected void initMapView(Bundle bundle) {

    }


    /**
     * 程序字号不随系统设置而改变
     *
     * @return
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }


    @Override
    public void onBackPressed() {
        finish();
//        if (mIsExpand) {
//            collapse(mLlAppSearchContent);
//        } else {
//            finish();
//        }
    }

    /**
     * 无参数跳转
     */
    protected void openArouterActivity(String path) {
        ARouter.getInstance().build(path).navigation();
    }

    public void doExit() {
        android.os.Process.killProcess(android.os.Process.myPid());    //获取PID
        System.exit(0);   //常规java、c#的标准退出法，返回值为0代表正常退出
    }

    /**
     * 浏览图片
     * 需要引入Modulemedia模块
     *
     * @param imageUrls 图片地址Arraylist
     */
    protected void startImageActivity(ArrayList imageUrls) {
//        ARouter.getInstance()
//            .build(PathConfig.PATH_MODULE_CMUTILS_PHOTO_SHOW)
//            .withStringArrayList("imgUrls", imageUrls)
//            .navigation();
    }

    /**
     * 打开拍摄 实现onActivityResult进行处理
     * 需要引入ModuleMedia模块
     * picUrl 返回的拍摄的路径key
     * movUrl 返回的录像的路径key
     * 123    相片响应码
     * 122    录像响应码
     *
     * @param isMovie     是否可以拍摄短视频
     * @param requestCode 请求码
     */
    protected void startCameraActivity(boolean isMovie, int requestCode) {
//        ARouter.getInstance()
//            .build(PathConfig.PATH_MODULEMEDIA_CAMERA)
//            .withBoolean("isMovie", isMovie)
//            .navigation(this, requestCode);
    }

    protected void checkIsLogin(String path) {
        if (TextUtils.isEmpty(UserLgUtils.getToken())) {
            ARouter.getInstance()
                .build(PathConfig.PATH_MODULE_MAIN_LOGIN)
                .navigation(mActivity, 2333);
        } else {
            ARouter.getInstance()
                .build(path)
                .navigation();
        }
    }

    /**
     * 将view的点击区域放大
     *
     * @param view             需要放大的view
     * @param expandTouchWidth 放大的宽度
     */
    public void setTouchDelegate(final View view, final int expandTouchWidth) {
        final View parentView = (View) view.getParent();
        parentView.post(() -> {
            final Rect rect = new Rect();
            view.getHitRect(rect);
            rect.top -= expandTouchWidth;
            rect.bottom += expandTouchWidth;
            rect.left -= expandTouchWidth;
            rect.right += expandTouchWidth;
            TouchDelegate touchDelegate = new TouchDelegate(rect, view);
            parentView.setTouchDelegate(touchDelegate);
        });
    }

    /**
     * 展开
     */
    private void expand(final View view) {
        view.setVisibility(View.VISIBLE);
        ObjectAnimator alpha = ObjectAnimator.ofFloat(view, "alpha", 0F, 1F);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 0F, 1F);
        mAnimatorSet.play(alpha).with(scaleX);
        mAnimatorSet.setDuration(300);
        mAnimatorSet.setInterpolator(new LinearInterpolator());
        mAnimatorSet.start();
        mAnimatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                showSoftKeyBoard(mEtAppSearchContent);
                mIsExpand = true;
                mTvAppBack.setVisibility(View.GONE);
                mIvAppSearchIcon.setVisibility(View.GONE);
                mTvPublish.setVisibility(View.GONE);
                animation.removeAllListeners();
            }
        });
    }

    /**
     * 缩起
     */
    private void collapse(final View view) {
        ObjectAnimator alpha = ObjectAnimator.ofFloat(view, "alpha", 1F, 0F);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1F, 0F);
        mAnimatorSet.play(alpha).with(scaleX);
        mAnimatorSet.setInterpolator(new LinearInterpolator());
        mAnimatorSet.setDuration(300);
        mAnimatorSet.start();
        mAnimatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                mIsExpand = false;
                hideSoftKeyboard();
                mIvAppSearchIcon.setVisibility(View.VISIBLE);
                mTvAppBack.setVisibility(View.VISIBLE);
                mTvPublish.setVisibility(View.VISIBLE);
                view.setVisibility(View.GONE);
                animation.removeAllListeners();
            }
        });
    }

}
