package com.xxfc.rv;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;

import com.base.utils.tools.android.NetworkUtil;
import com.ruiwenliu.wrapper.SPConstance;
import com.ruiwenliu.wrapper.base.BaseActivity;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.util.permission.RxPermission;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.utils.AppCookie;
import com.rv.component.utils.CacheEnum;
import com.rv.component.utils.Cookie;
import com.rv.component.utils.LogUtil;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.rv.component.utils.RvCache;
import com.rv.im.AppConfig;
import com.rv.im.bean.ImConfig;
import com.rv.im.bean.ImConfigBean;
import com.yuyife.okgo.OkGoUtil;

import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class WelcomeActivity extends BaseActivity<CommonPresenter> {

    private static final int CODE_REQUEST_POISITION = 1000;

    private Disposable mDisposable = null;

    private boolean isImInitOk = false;

    private boolean isInterval = false;

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        if (requestType == 0) {
            ImConfigBean bean = (ImConfigBean) result;
            ImConfig config;
            if (bean != null && bean.resultCode == 1 && ((ImConfigBean) result).getData() != null) {
                LogUtil.e("zq", "获取网络配置成功，使用服务端返回的配置并更新本地配置");
                isImInitOk = true;
                config = bean.getData();
                AppConfig appConfig = AppConfig.initConfig(config);
                RvCache.getInstance().save(appConfig, CacheEnum.IM_CONFIG);
                if (isInterval && !isFinishing()) {
                    go();
                }
            }
        }
    }

    @Override
    protected int setLayout() {
        return R.layout.rv_act_weclome;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        showTitle(false);//隐藏菜单栏
        permissionProcess();
    }

    private void init() {
        AppConfig appConfig = (AppConfig) RvCache.getInstance().get(CacheEnum.IM_CONFIG);
        if (appConfig == null) {
            if (!NetworkUtil.isNetworkAvailable(getApplicationContext())) {
                showToast("网络异常，初始化失败,请退出重试", 1);
            }
        } else {
            isImInitOk = true;
        }
        interval();
        LogUtil.d("start");
    }

    /**
     * 定位权限处理
     */
    @SuppressLint("CheckResult")
    private void permissionProcess() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            new RxPermission(mActivity).request(
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
            ).subscribe(aBoolean -> {
                if (aBoolean == true) {
                    init();
                } else {
                    new AlertDialog.Builder(this).setTitle("需要定位权限")
                            .setMessage("位置权限已关闭，开启以便滴房车正常使用")
                            .setNegativeButton("取消", (dialogInterface, i) -> {
                                finish();
                                dialogInterface.dismiss();
                            })
                            .setPositiveButton("设置", (dialogInterface, i) -> {
                                Intent in = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                                        .setData(Uri.fromParts("package", getPackageName(), null));
                                startActivityForResult(in, CODE_REQUEST_POISITION);
                                dialogInterface.dismiss();
                            }).setCancelable(false).show();
                }
            });
        } else {
            init();
        }
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        mPresenter.saveOnclick("8", "");
        getImConfig();
    }

    private void getImConfig() {
        mPresenter.getData(0, AppConfig.CONFIG_URL, ImConfigBean.class, false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopCarousel();
    }

    /**
     * 计时器
     */
    private void interval() {
        mDisposable = Flowable.interval(1, TimeUnit.SECONDS)
                .doOnNext(aLong -> {
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    isInterval = true;
                    try {
                        String token = Cookie.getStringValue(getApplicationContext(), SPConstance.USER_JSON_TOKEN, "");
                        String tokenTime = Cookie.getStringValue(getApplicationContext(), SPConstance.USER_JSON_TOKE_TIME, "");
                        if (!TextUtils.isEmpty(token)) {
                            OkGoUtil.setToken(token, tokenTime);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (isImInitOk) {
                        go();
                    }
                });

    }

    /**
     * 停止计时
     */
    public void stopCarousel() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

    private void go() {
        if (AppCookie.getBooleanValue("first_open", true)) {
            AppCookie.save("first_open", false);
            startActivity(GuideActivity.getIntent(mActivity));
        } else {
            startActivity(MainActivity.getIntent(mActivity));
        }
        mDisposable.dispose();
        finish();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
//            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_REQUEST_POISITION) {
            permissionProcess();
        }
    }
}
