package com.zhaohaoting.framework.abs.presenter;

import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.databinding.ViewDataBinding;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
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.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.zhaohaoting.framework.R;
import com.zhaohaoting.framework.abs.contract.BaseContract;
import com.zhaohaoting.framework.mvchelper.task.TaskHelper;
import com.zhaohaoting.framework.ui.dialog.loading.LoadingDialog;
import com.zhaohaoting.framework.utils.ToastUtils;
import com.zhaohaoting.framework.utils.Utils;

import java.util.ArrayList;
import java.util.List;


/**
 * author：Created by ZHT on 2017/11/1 11:15
 * email：526309416@qq.com
 * desc：activity基类
 */
public abstract class AbsActivity<PRESENTER extends BaseContract.BasePresenter> extends AppCompatActivity implements BaseContract.BaseView {
    public final String TAG = this.getClass().getSimpleName();

    protected Bundle savedInstanceState;
    private PRESENTER presenter;
    private TaskHelper taskHelper;
    protected FragmentManager fragmentManager;
    protected LoadingDialog loadingDialog;
    protected ViewDataBinding rootDataBinding;
    protected boolean isTouchHide = true;

    public Bundle getSavedInstanceState() {
        return savedInstanceState;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setLightMode(getResources().getColor(R.color.title_bg_color), false, false);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        loadingDialog = new LoadingDialog(this);
        //设置状态栏文字颜色及图标为深色
        fragmentManager = getSupportFragmentManager();
        this.savedInstanceState = savedInstanceState;
        PRESENTER presenter = getPresenter();
        if (presenter != null) {
            getLifecycle().addObserver(presenter);//添加LifecycleObserver
        }
        getLifecycle().addObserver(getTaskHelper());
    }

    /**
     * 21以上可以设置状态栏颜色
     * 23以上才可以设置状态栏文字颜色
     * 避免背景和文字颜色冲突
     * 文字设置最好大于等于23
     *
     * @param statusColor      状态栏颜色
     * @param isBlackTextColor 状态栏是否是黑色文字
     * @param isFull           是否全屏(状态栏透明)
     */
    protected void setLightMode(int statusColor, boolean isBlackTextColor, boolean isFull) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 设置状态栏字体黑色
            if (isBlackTextColor) {
                if (isFull) {
                    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
                        getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                    } else {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                        } else {
                            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
                        }
                    }
                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                    }
                }
            } else {
                if (isFull) {
                    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
                        getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                    } else {
                        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                    }
                } else {
                    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                }
            }
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(statusColor);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (isTouchHide) {
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                View v = getCurrentFocus();
                if (Utils.isShouldHideInput(v, ev)) {
                    Utils.hideInputMethod(this);
                }
                return super.dispatchTouchEvent(ev);
            }
            // 必不可少，否则所有的组件都不会有TouchEvent了
            if (getWindow().superDispatchTouchEvent(ev)) {
                return true;
            }
            return onTouchEvent(ev);
        } else {
            return super.dispatchTouchEvent(ev);
        }
    }

    protected PRESENTER getPresenter() {
        if (presenter == null) {
            presenter = initPresenter();
        }
        return presenter;
    }

    protected abstract PRESENTER initPresenter();

    private List<String> permissionsList = new ArrayList<>();

    public void judgePermission(int requestCode, String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            permissionsList.clear();
            for (String permission : permissions) {
                if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                    permissionsList.add(permission);
                }
            }
            if (permissionsList.size() == 0) {
                requestPermissionSuccess(requestCode);
            } else {
                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]), requestCode);
            }
        } else {
            requestPermissionSuccess(requestCode);
        }
    }


    @Override
    public TaskHelper getTaskHelper() {
        if (taskHelper == null) {
            taskHelper = new TaskHelper();
        }
        return taskHelper;
    }

    @Override
    public void showLoading(final Object... task) {
        loadingDialog.show();
        if (task != null && task.length > 0)
            loadingDialog.setOnDismissListener(dialog -> getTaskHelper().cancel(task));
    }

    @Override
    public void dismissLoading(Object... task) {
        loadingDialog.dismiss();
    }

    @Override
    public void onRequestPermissionsResult(final int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        for (int i = 0; i < grantResults.length; i++) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                requestPermissionFailure(requestCode);
                ToastUtils.show(getResources().getString(R.string.need_permission));
                return;
                // 用户不同意，却还要展示 向用户展示该权限作用
//                if (ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) {
//                    if (customDialog == null) {
//                        customDialog = UIutils.showCustomDialog(this, getString(R.string.tips), getResources().getString(R.string.need_permission), true)
//                                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        getPermissionSuccess(requestCode,false);
//                                    }
//                                })
//                                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        getPermissionSuccess(requestCode,false);
//                                    }
//                                }).create();
//                        customDialog.show();
//                    }
//                    return;
//                }
            }
        }
        requestPermissionSuccess(requestCode);
    }

    /**
     * 成功获取权限
     *
     * @param requestCode
     */
    public void requestPermissionSuccess(int requestCode) {
    }

    /**
     * 获取权限失败
     *
     * @param requestCode
     */
    public void requestPermissionFailure(int requestCode) {
    }

    protected List<Fragment> fragments = new ArrayList<>(10);

    protected void addFragment(Fragment fragment, int container) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        for (Fragment currentFragment : fragments) {
            if (currentFragment.isAdded()) {
                fragmentTransaction.hide(currentFragment);
            }
        }
        if (fragment.isAdded()) {
            fragmentTransaction.show(fragment).commitAllowingStateLoss();
        } else {
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.add(container, fragment).commitAllowingStateLoss();
            fragments.add(fragment);
        }
    }

    protected Fragment removeFragment(Fragment fragment) {
        if (fragments.contains(fragment)) {
            fragmentManager.beginTransaction().remove(fragment).commitAllowingStateLoss();
            fragments.remove(fragment);
        }
        Fragment topFragment = null;
        if (fragments.size() >= 1) {
            topFragment = fragments.get(fragments.size() - 1);
            for (Fragment fragment2 : fragments) {
                if (topFragment == fragment2) {
                    fragmentManager.beginTransaction().show(fragment2).commitAllowingStateLoss();
                } else {
                    fragmentManager.beginTransaction().hide(fragment2).commitAllowingStateLoss();
                }
            }
        }
        return topFragment;
    }

    protected void clearFragment() {
        while (fragmentManager.getBackStackEntryCount() != 0) {
            fragmentManager.popBackStackImmediate();
            fragments.remove(fragments.size() - 1);
        }
    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) closeActivity();
        return super.onOptionsItemSelected(item);
    }


    /**
     * 默认点击导航图标是关闭Activity,当需要执行其他操作时，可重载此方法
     */
    protected void closeActivity() {
        onBackPressed();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (rootDataBinding != null) {
            rootDataBinding.unbind();
        }
    }

    @Override
    public void onBackPressed() {
        hideSoftInput();
        if (fragmentManager.getBackStackEntryCount() > 1) {
            fragmentManager.popBackStackImmediate();
            fragments.remove(fragments.size() - 1);
        } else {
            finish();
        }
    }

    protected void hideSoftInput() {
        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


}
