package com.chexiang.myhome.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.os.MessageQueue;
import android.support.annotation.AnimRes;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.chexiang.myhome.BuildConfig;
import com.chexiang.myhome.base.http.retrofit.model.LoginModel;
import com.chexiang.myhome.base.load.ProgressManager;
import com.chexiang.myhome.base.model.CModel;
import com.chexiang.myhome.event.ExpiredEvent;
import com.chexiang.myhome.module.login.LoginActivity;
import com.chexiang.myhome.utils.InputUtils;
import com.chexiang.myhome.utils.LogUtil;
import com.chexiang.myhome.utils.TestInject;
import com.chexiang.myhome.utils.ToastUtil;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import okhttp3.Response;

public class BActivity extends AppCompatActivity implements ProgressManager {

    public static final int PLATS_RESOURCE = 1001;
    public static final int VIN_RESOURCE = 1002;
    public static final int PLATS_RESOURCE_ORDERMANAGE = 1003;
    public static final int PLATS_ADDCAR = 1004;
    public static final int VIN_ADDCAR = 1005;
    public static boolean DEBUG;
    protected BActivity activity;
    protected BApplication app;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CUIAgent.fixFontScale(this);

        DEBUG = BApplication.DEBUG;
        OkHttpUtils.getInstance();
        app = (BApplication) getApplication();
        BApplication.addActivity(this);
        activity = this;
        if (BuildConfig.DEBUG) testInject();

        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    private void testInject() {
        Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
            @Override
            public boolean queueIdle() {
                TestInject annotation = BActivity.this.getClass().getAnnotation(TestInject.class);
                if (annotation != null) {
                    if (annotation.value() != null) {
                        startActivity(new Intent(BActivity.this, annotation.value()));
                    }
                }
                return false;

            }
        });

    }

    /**
     * 获取堆栈淋面的
     *
     * @return
     */
    public void getStackNum() {
        int num = getSupportFragmentManager().getBackStackEntryCount();
        String numString = "++++++++++++++++++++++++++++++++++Fragment回退栈数量:" + num;
        LogUtil.d("Fragment", numString);
        for (int i = 0; i < num; i++) {
            FragmentManager.BackStackEntry backstatck = getSupportFragmentManager().getBackStackEntryAt(i);
//            Log.d("Fragment=name", backstatck.getName());
        }
    }

    //okhttp接口自定义解析
    public abstract class MyCallback extends Callback<CModel> {
        //非UI线程,支持任何耗时操作

        @Override
        public CModel parseNetworkResponse(Response response, int id) throws Exception {
            String string = response.body().string();
            return new Gson().fromJson(string, CModel.class);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BApplication.removeActivity(this);
        CUIAgent.clearCache(this);
    }

    /**
     * 显示 Loading
     */
    @Override
    public void showProgress() {
        CUIAgent.showProgress(this);
    }

    /**
     * 取消 Loading
     */
    @Override
    public void dismissProgress() {
        CUIAgent.dismissProgress(this);
    }

    public void replaceFragment(int id_content, Fragment fragment) {
        replaceFragment(id_content, 0, 0, fragment);
    }

    /**
     * 替换fragement 并添加动画
     */
    public void replaceFragment(@IdRes int id_content, @AnimRes int anim_in, @AnimRes int anim_out, Fragment fragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//        transaction.setCustomAnimations(anim_in, anim_out);
        transaction.replace(id_content, fragment);
        transaction.commit();
    }

    /**
     * 在当前activity的fragment栈的栈顶压入新的fragment
     *
     * @param resId
     * @param fragment
     */
    public void pushFragment(int resId, BFragment fragment) {
        String tag = fragment.getClass().getSimpleName();
        InputUtils.hideInput(this);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.addToBackStack(tag).add(resId, fragment, tag).commitAllowingStateLoss();
    }

    /**
     * 从当前activity的fragment栈的栈顶弹出当前fragment
     */
    public void popFragment() {
        popFragment(true);
    }

    public void popFragment(boolean notify) {
        onBackPressed(notify);
    }

    @Override
    public void onBackPressed() {
        onBackPressed(true);
    }

    public void onBackPressed(boolean notify) {
        InputUtils.hideInput(this);
        super.onBackPressed();
    }

    /**
     * 替换fragement 并添加动画
     * 替换fragement的同时对fragment进行“入back栈”操作 ,据我所知并不是真正的进入内存栈
     *
     * @param id_content
     * @param anim_in
     * @param anim_out
     * @param fragment
     */
    @Deprecated
    public void replaceFragmentWithBackStack(@IdRes int id_content, @AnimRes int anim_in, @AnimRes int anim_out, Fragment fragment) {
        String tag = fragment.getClass().getSimpleName();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//        transaction.setCustomAnimations(anim_in, anim_out);
        transaction.replace(id_content, fragment, tag);
        //记录commit一次操作,与mFragmentManager.popBackStack();匹配使用
        transaction.addToBackStack(tag);
        //commitAllowingStateLoss 优于 commit 方法,当使用commit方法时,系统将进行状态判断,如果状态(mStateSaved)已经保存,将发生"Can not perform this action after onSaveInstanceState"错误。
        //如果mNoTransactionsBecause已经存在,将发生"Can not perform this action inside of " + mNoTransactionsBecause错误。
        transaction.commitAllowingStateLoss();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    protected void onResume() {
        super.onResume();
        active = true;
        CUIAgent.fixFontScale(this); //  2017/7/20 临时解决切换客服回来后字体变大问题
//        MobclickAgent.onResume(this);
    }

    protected void onPause() {
        super.onPause();
        active = false;
//        MobclickAgent.onPause(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    private boolean active; // 是否为当前显示界面

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ExpiredEvent event) {
        if (active) {
            if (!(this instanceof LoginActivity)) {
                logout();
            }
        }
    }

    public void logout() {
        BApplication.closeAllActivities();
        app.saveUser((LoginModel) null);
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘,因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件,忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略,这个发生在视图刚绘制完,第一个焦点不在EditText上,和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager,隐藏软键盘
     *
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public void showToast(String msg) {
        ToastUtil.showToast(this, msg);
    }

    public void showToast(int msg) {
        ToastUtil.showToast(this, msg);
    }

    /**
     * 保证app字体不随系统字体改变大小
     */
//    @Override
//    public Resources getResources() {
//        Resources res = super.getResources();
//        Configuration config=new Configuration();
//        config.setToDefaults();
//        res.updateConfiguration(config,res.getDisplayMetrics() );
//        return res;
//    }
}