package com.cooleshow.student.ui.main;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.common.im.ui.MessageFragment;
import com.cooleshow.base.bean.RouteBean;
import com.cooleshow.base.common.BaseApplication;
import com.cooleshow.base.constanst.EventConstants;
import com.cooleshow.base.constanst.LoginStatusConstants;
import com.cooleshow.base.event.LoginStatusEvent;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.FileUtils;
import com.cooleshow.base.utils.GsonUtils;
import com.cooleshow.base.utils.JumpUtils;
import com.cooleshow.base.utils.LogUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.helper.MidiFileHelper;
import com.cooleshow.base.utils.helper.QMUIStatusBarHelper;
import com.cooleshow.base.utils.helper.UpdateAppHelper;
import com.cooleshow.base.widgets.TabAnimationView;
import com.cooleshow.student.App;
import com.cooleshow.student.R;
import com.cooleshow.student.adapter.HomePageAdapter;
import com.cooleshow.student.constants.CommonConfig;
import com.cooleshow.student.contract.MainContract;
import com.cooleshow.student.databinding.ActivityMainBinding;
import com.cooleshow.student.helper.EventHelper;
import com.cooleshow.student.helper.PushIntentParseHelper;
import com.cooleshow.student.presenter.main.MainPresenter;
import com.cooleshow.usercenter.bean.UserInfo;
import com.cooleshow.usercenter.helper.UserHelper;
import com.daya.live_teaching.common.ResultCallback;
import com.daya.live_teaching.im.IMManager;
import com.google.android.material.bottomnavigation.BottomNavigationItemView;
import com.google.android.material.bottomnavigation.BottomNavigationMenuView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.gson.Gson;
import com.rong.io.live.config.LiveConfig;
import com.tbruyelle.rxpermissions3.RxPermissions;
import com.tencent.bugly.crashreport.CrashReport;

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

import java.util.ArrayList;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;
import io.rong.imkit.manager.UnReadMessageManager;
import io.rong.imlib.RongIMClient;

import static com.cooleshow.base.constanst.Constants.MAIN_PAGE_SELECT_POTION_KEY;

/**
 * 创建日期：2022/5/25 18:02
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.APPCenter.PATH_HOME)
public class MainActivity extends BaseMVPActivity<ActivityMainBinding, MainPresenter> implements MainContract.MainView, UnReadMessageManager.IUnReadMessageObserver {

    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private HomeFragment mHomeFragment;
    private MineFragment mMineFragment;
    private MallFragment shopMallFragment;
    private TextView tvMsgCount;
    private static final int EXIT_APP_DELAY = 1000;
    private long lastTime = 0;
    private boolean isNeedSetPushId = true;

    /**
     * 打开首页并选中指定tab
     *
     * @param context
     * @param pos
     */
    public static void openAndSelectPos(Context context, int pos) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra(MAIN_PAGE_SELECT_POTION_KEY, pos);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        QMUIStatusBarHelper.setStatusBarLightMode(this);
        EventBus.getDefault().register(this);
        parseIntent(getIntent());
    }

    private void checkAppVersion() {
        UpdateAppHelper.getInstance().checkUpdate(this, "android-student");
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        parseIntent(intent);
    }

    private void parseIntent(Intent intent) {
        if (intent.hasExtra(MAIN_PAGE_SELECT_POTION_KEY)) {
            //跳转选中某个tab
            int selectPos = intent.getIntExtra(MAIN_PAGE_SELECT_POTION_KEY, 0);
            if (selectPos >= mFragments.size()) {
                return;
            }
            setPositionItem(selectPos);
            return;
        }
        String intentResult = PushIntentParseHelper.getIntentMemoFrom(intent);
        LogUtils.i("pq", "intentResult:" + intentResult);
        if (!TextUtils.isEmpty(intentResult)) {
            if (TextUtils.equals(intentResult, PushIntentParseHelper.RONG_PUSH_ACTION_TAG)) {
                //融云推送相关
                //选中聊天
                setPositionItem(2);
                return;
            }
            try {
                RouteBean routeBean = GsonUtils.fromJson(intentResult, RouteBean.class);
                JumpUtils.jump(routeBean);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void initView() {
        tvMsgCount = viewBinding.tvMsgCount;
        //默认选中第一个
        onTabClick(viewBinding.viewHome);
        HomePageAdapter homePageAdapter = new HomePageAdapter(this);
        mHomeFragment = new HomeFragment();
        NewHomeFragment newHomeFragment = new NewHomeFragment();
        CourseTableFragment courseTableFragment = new CourseTableFragment();
        MessageFragment messageFragment = new MessageFragment();
        shopMallFragment = new MallFragment();
        mMineFragment = new MineFragment();
        mFragments.add(newHomeFragment);
        mFragments.add(courseTableFragment);
        mFragments.add(messageFragment);
        mFragments.add(shopMallFragment);
        mFragments.add(mMineFragment);
        homePageAdapter.setFragments(mFragments);
        getViewBinding().viewPager.setAdapter(homePageAdapter);
        getViewBinding().viewPager.setOffscreenPageLimit(mFragments.size());
        getViewBinding().viewPager.setUserInputEnabled(false);
        getViewBinding().viewPager.setSaveEnabled(false);
        getViewBinding().navigation.setItemIconTintList(null);
        getViewBinding().navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                return onTabClick(item.getItemId());
            }
        });
    }

    @Override
    public void onBackPressed() {
        int currentItem = getViewBinding().viewPager.getCurrentItem();
        if (currentItem == 3) {
            //商城
            if (null != shopMallFragment) {
                shopMallFragment.clickBack();
            }
        } else {
            super.onBackPressed();
        }
    }

    public void setPositionItem(int position) {
        getViewBinding().navigation.setSelectedItemId(getViewBinding().navigation.getMenu().getItem(position).getItemId());
        if (position == 0) {
            onTabClick(viewBinding.viewHome);
        }
        if (position == 1) {
            onTabClick(viewBinding.viewCourse);
        }
        if (position == 2) {
            onTabClick(viewBinding.viewChat);
        }
        if (position == 3) {
            onTabClick(viewBinding.viewMall);
        }
        if (position == 4) {
            onTabClick(viewBinding.viewMine);
        }
    }

    public void clickBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void initData() {
        super.initData();
        requestPermission();
        IMManager.getInstance().addOnUnReadMessageListener(this);
    }

    /**
     * 申请存储权限
     */
    private void requestPermission() {
        new RxPermissions(this)
                .request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> {
                    if (permission) {
                        checkAppVersion();
                        MidiFileHelper.initMidFile();
                    }
                });
    }


    /**
     * 连接rong IM
     */
    private void connectIM() {
        if (UserHelper.isLogin()) {
            String userIMToken = UserHelper.getUserIMToken();
            if (!TextUtils.isEmpty(userIMToken)) {
                RongIMClient.ConnectionStatusListener.ConnectionStatus currentConnectionStatus = RongIMClient.getInstance().getCurrentConnectionStatus();
                if (currentConnectionStatus != RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED) {
                    IMManager.getInstance().login(userIMToken, new ResultCallback<String>() {
                        @Override
                        public void onSuccess(String s) {
                            LogUtils.i("im connect success:" + s);
                        }

                        @Override
                        public void onFail(int errorCode, String errorStr) {
                            LogUtils.i("im connect fail:" + errorStr + "-errorCode:" + errorCode);
                        }
                    });
                }
            }
        }
    }

    private TabAnimationView lastSelectTab;
    private TextView lastSelectText;
    /*
   上一次的tab位置
    */

    public void onTabClick(View view) {
        int id = view.getId();
        if (id == R.id.view_home) {
            getViewBinding().viewPager.setCurrentItem(0, false);
            handleTabAnim(viewBinding.tabHome);
            setTabTextStyle(viewBinding.tvHome);
            return;
        }
        if (id == R.id.view_course) {
            getViewBinding().viewPager.setCurrentItem(1, false);
            handleTabAnim(viewBinding.tabCourse);
            setTabTextStyle(viewBinding.tvCourse);
            return;
        }
        if (id == R.id.view_chat) {
            getViewBinding().viewPager.setCurrentItem(2, false);
            handleTabAnim(viewBinding.tabChat);
            setTabTextStyle(viewBinding.tvChat);
            return;
        }
        if (id == R.id.view_mall) {
            getViewBinding().viewPager.setCurrentItem(3, false);
            handleTabAnim(viewBinding.tabMall);
            setTabTextStyle(viewBinding.tvMall);
            return;
        }
        if (id == R.id.view_mine) {
            getViewBinding().viewPager.setCurrentItem(4, false);
            handleTabAnim(viewBinding.tabMine);
            setTabTextStyle(viewBinding.tvMine);
            return;
        }
    }

    private void setTabTextStyle(TextView textView) {
        if (lastSelectText != null) {
            lastSelectText.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_999999));
            lastSelectText.setTypeface(Typeface.DEFAULT);
        }
        lastSelectText = textView;
        lastSelectText.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_333333));
        lastSelectText.setTypeface(Typeface.DEFAULT_BOLD);
    }

    private void handleTabAnim(TabAnimationView view) {
        if (lastSelectTab != null) {
            lastSelectTab.toggle();
        }
        lastSelectTab = view;
        lastSelectTab.setChecked(true);
    }


    private boolean onTabClick(int viewId) {
        if (viewId == R.id.menu_home) {
            getViewBinding().viewPager.setCurrentItem(0, false);
            return true;
        }
        if (viewId == R.id.menu_coursetable) {
            getViewBinding().viewPager.setCurrentItem(1, false);
            return true;
        }
        if (viewId == R.id.menu_chat) {
            getViewBinding().viewPager.setCurrentItem(2, false);
            return true;
        }
        if (viewId == R.id.menu_mall) {
            getViewBinding().viewPager.setCurrentItem(3, false);
            return true;
        }
        if (viewId == R.id.menu_mine) {
            getViewBinding().viewPager.setCurrentItem(4, false);
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        presenter.getUserInfo();

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loadEventBus(LoginStatusEvent event) {
        if (event != null && event.eventCode == LoginStatusConstants.LOGIN_OUT) {
            IMManager.getInstance().logout();
            LiveConfig.isNeedReInitRTC = true;
            CommonConfig.isShowHomeFlashPage = true;
            isNeedSetPushId = true;
            LogUtils.i("pq", "LoginStatusEvent:logout");
        }
    }

    @Override
    public void getUserInfoSuccess(UserInfo userInfo) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        //存储userInfo信息
        UserHelper.saveUserInfo(userInfo);
        connectIM();
        bindPushId();
    }

    private void bindPushId() {
        if (isNeedSetPushId && UserHelper.isLogin() && !TextUtils.isEmpty(UserHelper.getUserId())) {
            String userId = UserHelper.getUserId();
            LogUtils.i("pq", "registrationId:" + BaseApplication.registrationId);
            JPushInterface.setAlias(getApplicationContext(), 1, userId);
            CrashReport.setDeviceId(getApplicationContext(), userId);
            isNeedSetPushId = false;
        }
    }

    @Override
    protected ActivityMainBinding getLayoutView() {
        return ActivityMainBinding.inflate(getLayoutInflater());
    }

    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1011) {
                String selectAddress = data.getStringExtra("selectAddress");
                if (null != shopMallFragment) {
                    shopMallFragment.selectAddress(selectAddress);
                }
            }
        }
    }

    @Override
    public void onCountChanged(int count) {
        if (count > 0) {
            tvMsgCount.setVisibility(View.VISIBLE);
            if (count <= 99) {
                tvMsgCount.setText(String.valueOf(count));
            } else {
                tvMsgCount.setText("99+");
            }
        } else {
            tvMsgCount.setVisibility(View.GONE);
        }
    }

    /**
     * 监听返回键
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - lastTime) > EXIT_APP_DELAY) {
                ToastUtil.getInstance().showShort(getString(com.cooleshow.base.R.string.press_twice_exit));
                lastTime = System.currentTimeMillis();
            } else {
                moveTaskToBack(true);
            }
            return true;

        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        IMManager.getInstance().removeOnUnReadMessageListener(this);
    }
}
