package com.cooleshow.teacher.ui.main;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
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 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.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.teacher.App;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.adapter.HomePageAdapter;
import com.cooleshow.teacher.bean.TeacherPromoteIncomeBean;
import com.cooleshow.teacher.bean.TeacherUserInfo;
import com.cooleshow.teacher.contract.MainContract;
import com.cooleshow.teacher.databinding.ActivityMainBinding;
import com.cooleshow.teacher.helper.PushIntentParseHelper;
import com.cooleshow.teacher.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.android.material.snackbar.Snackbar;
import com.rong.io.live.config.LiveConfig;
import com.tbruyelle.rxpermissions3.RxPermissions;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.open.im.IM;

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

import java.util.ArrayList;

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

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;

/**
 * Author by pq, Date on 2022/4/20.
 */
@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-teacher");
    }

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

    @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);
        }
        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() {
        BottomNavigationMenuView menuView = (BottomNavigationMenuView) viewBinding.navigation.getChildAt(0);
        BottomNavigationItemView messageTab = (BottomNavigationItemView) menuView.getChildAt(2);
        View badge = LayoutInflater.from(this).inflate(com.cooleshow.base.R.layout.im_badge, menuView, false);
        tvMsgCount = badge.findViewById(com.cooleshow.base.R.id.tv_msg_count);
        messageTab.addView(badge);

        HomePageAdapter homePageAdapter = new HomePageAdapter(this);
        mHomeFragment = new HomeFragment();
        CourseTableFragment courseTableFragment = new CourseTableFragment();
        MessageFragment messageFragment = new MessageFragment();
        shopMallFragment = new MallFragment();
        mMineFragment = new MineFragment();
        mFragments.add(mHomeFragment);
        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().navigation.setItemIconTintList(null);
        getViewBinding().navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                return onTabClick(item.getItemId());
            }
        });
    }

    public void setPositionItem(int position) {
        viewBinding.navigation.setSelectedItemId(getViewBinding().navigation.getMenu().getItem(position).getItemId());
    }

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

    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) {
                    LogUtils.i("pq", "im connect:" + userIMToken);
                    IMManager.getInstance().login(userIMToken, new ResultCallback<String>() {
                        @Override
                        public void onSuccess(String s) {
                            LogUtils.i("pq", "im connect success:" + s);
                        }

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

    /*
    上一次的tab位置
     */
    private int lastCurrentItemPosition = 0;

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

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

    @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;
        }
    }

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

    @Override
    public void getTeacherInfoSuccess(TeacherUserInfo teacherUserInfo) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        //save达人认证状态和开通直播状态
        UserHelper.saveTeacherCertificationStatus(teacherUserInfo.entryStatus);
        UserHelper.saveTeacherOpenLiveFlag(teacherUserInfo.liveFlag);
        if (mHomeFragment != null) {
            mHomeFragment.getTeacherInfoSuccess(teacherUserInfo);
        }
        if (mMineFragment != null) {
            mMineFragment.getTeacherInfoSuccess(teacherUserInfo);
        }
    }

    @Override
    public void getTeacherPromoteInfoSuccess(TeacherPromoteIncomeBean teacherPromoteIncomeBean) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        if (mMineFragment != null) {
            mMineFragment.getTeacherPromoteInfoSuccess(teacherPromoteIncomeBean);
        }
    }

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

    @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);
    }
}
