package com.offcn.im.demo.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;
import com.jyall.base.adapter.BaseVPAdapter;
import com.jyall.base.base.BaseActivity;
import com.jyall.base.util.AppManager;
import com.jyall.base.util.CommonUtils;
import com.jyall.base.util.EventBusCenter;
import com.offcn.im.demo.R;
import com.offcn.im.demo.bean.UserBean;
import com.offcn.im.demo.util.Constants;
import com.offcn.im.demo.util.LoginManager;
import com.offcn.live.im.OIMCallback;
import com.offcn.live.im.OIMSDK;
import com.offcn.live.im.bean.OIMCode;
import com.offcn.live.im.util.ZGLLogUtils;
import com.offcn.live.imkit.view.ScrollEnabledViewPager;

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

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

import androidx.fragment.app.Fragment;

/**
 * tab主页。业务页面
 * <p>
 * 会话列表：引用SDK 内部的 ChatListFragment
 * 通讯录：业务页面，平台没有通讯录
 * 我的：业务页面，模拟登录
 */
public class MainActivity extends BaseActivity {
    private static final String TAG = MainActivity.class.getSimpleName();

    TabLayout mTabLayout;
    ScrollEnabledViewPager mViewPager;
    TextView mRedDot;

    String[] titles = new String[]{"聊天", "通讯录", "我的"};

    private UserBean mUserBean;


    @Override
    protected int getContentViewLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void initViewsAndEvents() {
        mTabLayout = findViewById(R.id.tab_layout);
        mViewPager = findViewById(R.id.view_pager);

        mUserBean = LoginManager.getUser(this);
        if (mUserBean == null) {
            CommonUtils.showToast(this, "用户信息获取失败");
            finish();
            return;
        }

        // 中公IM 连接操作
        OIMSDK.getInstance().connect(mUserBean.getUser_id(), mUserBean.getToken(), new OIMCallback.OnConnectListener() {
            @Override
            public void onStateConnected() {
                ZGLLogUtils.e(TAG, "IM连接成功");
//                ZGLCommonUtils.showToast(MainActivity.this, "IM连接成功");
            }

            @Override
            public void onStateDisconnected(int code, String error) {

                // ------------连接失败的业务处理----------------


                ZGLLogUtils.e(TAG, "IM连接失败 " + code + " " + error);
//                ZGLCommonUtils.showToast(MainActivity.this, "IM连接失败 " + code + " " + error);

                // 连接失败。需作特殊处理如退出页面：token失效、被踢等
                if (code == OIMCode.Code_IM_Connect_Fail
                        || code == OIMCode.Code_IM_Connect_Timeout
                        || code == OIMCode.Code_IM_Error_TokenInvalid
                        || code == OIMCode.Code_IM_Disconnect_Kick
                        || code == OIMCode.Code_IM_Error_NoExist) {

                    // 退出登录、清除用户信息
                    LoginManager.logout(MainActivity.this);
//                    UserBeanDaoManager.getInstance().deleteAll();

                    if (code == OIMCode.Code_IM_Disconnect_Kick) {
                        // 已经连接上中途异常断开：被踢，需弹窗提示重新登录
                        Activity curActivity = AppManager.getAppManager().getCurrentActivity();
                        if (curActivity != null) {
                            AlertDialog dialog = new AlertDialog.Builder(curActivity)
                                    .setTitle("下线通知")
                                    .setMessage("你的帐号已在另一台设备登录，如非本人操作，则密码可能已泄漏，为了你的帐号安全，建议尽快修改密码。")
                                    .setPositiveButton("重新登录", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            startActivity(new Intent(curActivity, LoginActivity.class));
                                            AppManager.getAppManager().finishAllActivity();
                                        }
                                    })
                                    .setNegativeButton("我知道了", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            AppManager.getAppManager().AppExit(curActivity);
                                        }
                                    })
                                    .setCancelable(false)
                                    .create();
                            dialog.setCanceledOnTouchOutside(false);
                            dialog.show();
                        }
                    } else {
                        // 此时错误为：第一次连接时提示 用户不存在、token失效，连接超时，对应操作应该为重新登录
                        CommonUtils.showToast(MainActivity.this, "请求失败，请重新登录");
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                        AppManager.getAppManager().finishAllActivity();
                    }
                }
            }

            @Override
            public void onStateReconnecting() {
                ZGLLogUtils.e(TAG, "IM重连");
            }
        });


        // 设置首页fragment
        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(new ChatListFragmentWrapper());
        fragmentList.add(new ContactListFragment());
        fragmentList.add(new MeFragment());
        for (int i = 0; i < titles.length; i++) {
            mTabLayout.addTab(mTabLayout.newTab());
        }
        BaseVPAdapter adapter = new BaseVPAdapter(getSupportFragmentManager(), fragmentList);
        mViewPager.setOffscreenPageLimit(fragmentList.size());
        mViewPager.setAdapter(adapter);
        mViewPager.setPagingEnabled(false);
        for (int i = 0; i < titles.length; i++) {
            mTabLayout.getTabAt(i).setCustomView(getTabView(i));
        }
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mViewPager.setCurrentItem(tab.getPosition(), false);
                changeTabSelect(tab);   //Tab获取焦点
                if (tab.getPosition() == 0) {
                    showDot(false);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                changeTabNormal(tab);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    protected void loadData() {

    }

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

        // 清除通知栏消息
        OIMSDK.getInstance().clearNotification();
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        // 退到桌面
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }


    //-----------TabLayout 代码设置 开始-------------------------------------------------
    private View getTabView(int index) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_tab, null);
        TextView title = (TextView) view.findViewById(R.id.tv_title);
        ImageView iv = (ImageView) view.findViewById(R.id.iv_pic);
        title.setText(titles[index]);
        if (index == 0) {
            iv.setImageResource(R.mipmap.ic_chat_tab_on);
            title.setTextColor(getResources().getColor(R.color.colorPrimary));
            mRedDot = view.findViewById(R.id.dot);
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mRedDot.getLayoutParams();
            layoutParams.rightMargin = CommonUtils.getScreenWidth(this) / 6 - CommonUtils.dp2px(this, 25);
        } else if (index == 1) {
            iv.setImageResource(R.mipmap.ic_contact_tab_off);
            title.setTextColor(getResources().getColor(R.color.color_333333));
        } else if (index == 2) {
            iv.setImageResource(R.mipmap.ic_me_off);
            title.setTextColor(getResources().getColor(R.color.color_333333));
        }
        return view;
    }

    private void changeTabSelect(TabLayout.Tab tab) {
        final View view = tab.getCustomView();
        int index = tab.getPosition();
        TextView title = (TextView) view.findViewById(R.id.tv_title);
        ImageView iv = (ImageView) view.findViewById(R.id.iv_pic);
        title.setText(titles[index]);
        setTabView(true, index, title, iv);
    }

    /**
     * 改变TabLayout的View到未选中状态
     */
    private void changeTabNormal(TabLayout.Tab tab) {
        final View view = tab.getCustomView();
        int index = tab.getPosition();
        TextView title = (TextView) view.findViewById(R.id.tv_title);
        ImageView iv = (ImageView) view.findViewById(R.id.iv_pic);
        title.setText(titles[index]);
        setTabView(false, index, title, iv);
    }

    private void setTabView(boolean isSelected, int index, TextView title, ImageView iv) {
        switch (index) {
            case 0:
                if (isSelected) {
                    iv.setImageResource(R.mipmap.ic_chat_tab_on);
                    title.setTextColor(getResources().getColor(R.color.colorPrimary));
                } else {
                    iv.setImageResource(R.mipmap.ic_chat_tab_off);
                    title.setTextColor(getResources().getColor(R.color.color_333333));
                }
                break;
            case 1:
                if (isSelected) {
                    iv.setImageResource(R.mipmap.ic_contact_tab_on);
                    title.setTextColor(getResources().getColor(R.color.colorPrimary));
                } else {
                    iv.setImageResource(R.mipmap.ic_contact_tab_off);
                    title.setTextColor(getResources().getColor(R.color.color_333333));
                }
                break;
            case 2:
                if (isSelected) {
                    iv.setImageResource(R.mipmap.ic_me_on);
                    title.setTextColor(getResources().getColor(R.color.colorPrimary));
                } else {
                    iv.setImageResource(R.mipmap.ic_me_off);
                    title.setTextColor(getResources().getColor(R.color.color_333333));
                }
                break;
        }
    }
    //-----------TabLayout 代码设置 结束-------------------------------------------------


    // 收到新消息，更新UI
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBus(EventBusCenter eventBusCenter) {
        int eventCode = eventBusCenter.getEvenCode();
        if (eventCode == Constants.EventCode.Code_New_Msg) {
            try {
                if (mViewPager.getCurrentItem() != 0) {
                    showDot(true);
                }
            } catch (Exception e) {

            }
        }


    }

    private void showDot(boolean show) {
        mRedDot.setVisibility(show ? View.VISIBLE : View.GONE);
    }
}
