package com.tengshisoft.mainmodule.base;

import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.toast.ToastUtils;
import com.tengshisoft.mainmodule.R;
import com.tengshisoft.mainmodule.R2;
import com.tenlionsoft.baselib.constant.GlobalProvider;
import com.tenlionsoft.baselib.constant.PathConfig;
import com.tenlionsoft.baselib.core.beans.UserExpandInfoBean;
import com.tenlionsoft.baselib.core.beans.UserInfoBean;
import com.tenlionsoft.baselib.core.network.update.CheckUpdateUtils;
import com.tenlionsoft.baselib.core.network.update.service.DownloadService;
import com.tenlionsoft.baselib.core.network.update.utils.Constants;
import com.tenlionsoft.baselib.core.receiver.NetworkChangeReceiver;
import com.tenlionsoft.baselib.core.retrofit_net.BaseUrlApi;
import com.tenlionsoft.baselib.core.retrofit_net.RetrofitManager;
import com.tenlionsoft.baselib.core.retrofit_net.api.BaseApiService;
import com.tenlionsoft.baselib.core.retrofit_net.bean.VersionBean;
import com.tenlionsoft.baselib.core.retrofit_net.conver.RxTransformer;
import com.tenlionsoft.baselib.core.widget.base.BaseActivity;
import com.tenlionsoft.baselib.core.widget.base.BaseFragment;
import com.tenlionsoft.baselib.core.widget.base.BaseViewPage2Adapter;
import com.tenlionsoft.baselib.core.widget.base.FragmentUtils;
import com.tenlionsoft.baselib.utils.KeyBoardListener;
import com.tenlionsoft.baselib.utils.LogUtils;
import com.tenlionsoft.baselib.utils.UserLgUtils;

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

import androidx.viewpager2.widget.ViewPager2;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

/**
 * 首页 tabbar
 */
@Route(path = PathConfig.PATH_MODULE_MAIN_NAVIGATION_HOME)
public class MainTabActivity extends BaseActivity {

    @BindView(R2.id.vp_content)
    ViewPager2 mVpContent;
    @BindView(R2.id.ll_tabs)
    LinearLayout mLlTabs;
    @BindView(R2.id.rl_content)
    RelativeLayout mRlContent;
    @BindView(R2.id.iv_home)
    ImageView mIvHome;
    @BindView(R2.id.tv_home)
    TextView mTvHome;
    @BindView(R2.id.ll_home)
    LinearLayout mLlHome;
    @BindView(R2.id.iv_doc)
    ImageView mIvDoc;
    @BindView(R2.id.tv_doc)
    TextView mTvDoc;
    @BindView(R2.id.ll_doc)
    LinearLayout mLlDoc;
    @BindView(R2.id.iv_refer)
    ImageView mIvRefer;
    @BindView(R2.id.ll_refer)
    LinearLayout mLlRefer;
    @BindView(R2.id.iv_email)
    ImageView mIvEmail;
    @BindView(R2.id.tv_email)
    TextView mTvEmail;
    @BindView(R2.id.ll_email)
    LinearLayout mLlEmail;
    @BindView(R2.id.tv_email_hint)
    TextView mTvEmailHint;
    @BindView(R2.id.rl_email)
    RelativeLayout mRlEmail;
    @BindView(R2.id.iv_mine)
    ImageView mIvMine;
    @BindView(R2.id.tv_mine)
    TextView mTvMine;
    @BindView(R2.id.ll_mine)
    LinearLayout mLlMine;
    @BindView(R2.id.iv_hint_mine)
    ImageView mIvHintMine;
    @BindView(R2.id.rl_mine)
    RelativeLayout mRlMine;
    private Unbinder mBind;
    private List<BaseFragment> mFragments;
    private long finishTime = 0;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_main_tab;
    }

    @Override
    public void initData() {
        mBind = ButterKnife.bind(this);
        refreshView(STATE_LOAD_SUCCESS);
        mFragments = new ArrayList<>();
        initContentView();
        NetworkChangeReceiver.registerReceiver(mActivity);
        //TODO 检查App版本       checkAppVersion();

    }


    /**
     * 初始化视图
     */
    private void initContentView() {
        mRlTitleBar.setVisibility(View.VISIBLE);
        mTvBaseTitle.setText("办公系统");
        mTvAppBack.setVisibility(View.GONE);
        KeyBoardListener.getInstance(this).init();
        BaseFragment homeFragment = FragmentUtils.getFragment(PathConfig.PATH_MODULE_OA_FRAGMENT_HOME);
        BaseFragment docFragment = FragmentUtils.getFragment(PathConfig.PATH_MODULE_OA_FRAGMENT_DOC);
        BaseFragment emailFragment = FragmentUtils.getFragment(PathConfig.PATH_MODULE_OA_FRAGMENT_EMAIL);
        BaseFragment userFragment = FragmentUtils.getFragment(PathConfig.PATH_MODULE_MAIN_FRAGMENT_USER);
        mFragments.add(homeFragment);
        mFragments.add(docFragment);
        mFragments.add(emailFragment);
        mFragments.add(userFragment);
        mVpContent.setAdapter(new BaseViewPage2Adapter(mActivity, mFragments));
        mVpContent.setUserInputEnabled(false);
        mLlHome.setOnClickListener(v -> chooseItem(1));
        mLlDoc.setOnClickListener(v -> chooseItem(2));
        mLlRefer.setOnClickListener(v -> chooseItem(3));
        mLlEmail.setOnClickListener(v -> chooseItem(4));
        mLlMine.setOnClickListener(v -> chooseItem(5));
        chooseItem(1);
        getUserExpandInfo();
    }

    /**
     * 获取用户拓展信息
     */
    private void getUserExpandInfo() {
        RetrofitManager.getInstance()
            .create(BaseApiService.class)
            .getUserInfoExpand(UserLgUtils.getToken())
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<UserInfoBean>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull UserInfoBean userInfoBean) {
                    List<UserInfoBean.DepartmentsBean> departments = userInfoBean.getDepartments();
                    UserLgUtils.setUserDeptId(new Gson().toJson(departments));
                }

                @Override
                public void onError(@NonNull Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
    }


    @Override
    protected void onDestroy() {
        NetworkChangeReceiver.unRegisterReceiver(mActivity);
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isNavBarHasShown(this)) {
            LogUtils.e("开启的");
            checkNavigation();
        } else {
            LogUtils.e("关闭的");
        }
    }

    //适配虚拟按钮
    private void checkNavigation() {
        int navigationBarHeight = getNavigationBarHeight(this);
        if (navigationBarHeight > 0) {
            FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mRlContent.getLayoutParams();
            params.bottomMargin = navigationBarHeight;
            mRlContent.setLayoutParams(params);
        }
    }


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


    private void goBack() {
        long time = System.currentTimeMillis();
        if ((time - finishTime) < 2000) {
            Intent i = new Intent(Intent.ACTION_MAIN);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.addCategory(Intent.CATEGORY_HOME);
            startActivity(i);
        } else {
            ToastUtils.show("再点击一次退出");
            finishTime = time;
        }
    }

    private void chooseItem(int i) {
        switch (i) {
            case 1://首页
                mVpContent.setCurrentItem(0, false);
//                mIvHome.setBackgroundResource(R.drawable.ic_map_icon);
//                mTvHome.setTextColor(getResources().getColor(R.color.col_main_theme));
//                mIvMine.setBackgroundResource(R.drawable.ic_map_icon);
//                mTvMine.setTextColor(getResources().getColor(R.color.gray_text));
//                mVpContent.setCurrentItem(0, false);
                mRlTitleBar.setVisibility(View.VISIBLE);
                mRlTitleBar.setBackgroundColor(Color.WHITE);
                mTvBaseTitle.setText("OA系统");
                mTvBaseTitle.setTextColor(Color.BLACK);
                ImmersionBar.with(this)
                    .statusBarColor(R.color.white)
                    .statusBarDarkFont(true)
                    .titleBar(mRlTitleBar)
                    .init();
                break;
            case 2://文档
                mRlTitleBar.setVisibility(View.GONE);
                mVStatusBar.setVisibility(View.VISIBLE);
                mVpContent.setCurrentItem(1, false);

                ImmersionBar.with(this)
                    .statusBarColor(R.color.gray)
                    .statusBarDarkFont(true)
                    .titleBar(mVStatusBar)
                    .init();
            case 3://加号

                break;
            case 4://邮件
                mVpContent.setCurrentItem(2, false);
                mRlTitleBar.setVisibility(View.GONE);
                mVStatusBar.setVisibility(View.VISIBLE);

                ImmersionBar.with(this)
                    .statusBarColor(R.color.gray)
                    .statusBarDarkFont(true)
                    .titleBar(mVStatusBar)
                    .init();
                break;
            case 5://我的
                mVpContent.setCurrentItem(3, false);
                mRlTitleBar.setVisibility(View.GONE);
                mVStatusBar.setVisibility(View.VISIBLE);

                ImmersionBar.with(this)
                    .statusBarColor(R.color.gray)
                    .statusBarDarkFont(true)
                    .titleBar(mVStatusBar)
                    .init();
                break;
        }
    }

    /**
     * App版本校验
     */
    private void checkAppVersion() {
        RetrofitManager.getInstance()
            .create(BaseApiService.class)
            .doCheckAppVersion(BaseUrlApi.APP_VERSION_ID)
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<VersionBean>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(VersionBean successBean) {
                    if (successBean != null && successBean.getData() > 0) {
                        if (CheckUpdateUtils.checkcode(MainTabActivity.this, successBean.getData() + "")) {
                            startDownloadApk();
                        }
                    }
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
    }

    /**
     * 开始下载Apk
     */
    private void startDownloadApk() {
        ToastUtils.show("检测到新版本,开始下载,请在通知栏查看下载进度");
        Intent intent = new Intent(mActivity, DownloadService.class);
        intent.putExtra(Constants.APK_DOWNLOAD_URL, BaseUrlApi.APP_DOWNLOAD_URL);
        startService(intent);
    }

    @Override
    protected void doShowOptions() {

    }

    @Override
    protected void clearSearch() {

    }

    @Override
    protected void doSearchByTitle() {
    }
}