package com.xxfc.rv;

import android.app.AlertDialog;
import android.app.Notification;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.base.utils.ui.image.round.RoundImageView;
import com.bumptech.glide.Glide;
import com.frame.base.url.Constance;
import com.frame.base.url.ImageUrl;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.MessageEventLogout;
import com.ruiwenliu.wrapper.MessageEventRemoteLogin;
import com.ruiwenliu.wrapper.SPConstance;
import com.ruiwenliu.wrapper.adapter.TabAdapter;
import com.ruiwenliu.wrapper.base.BaseActivity;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseWrapperFragment;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.ruiwenliu.wrapper.bean.ActBean;
import com.ruiwenliu.wrapper.bean.CodeInfoBean;
import com.ruiwenliu.wrapper.bean.UpdateTokenBean;
import com.ruiwenliu.wrapper.inter.ImInitListenter;
import com.ruiwenliu.wrapper.receiver.NetWorkReceiver;
import com.ruiwenliu.wrapper.statusbar.StatusBarUtil;
import com.ruiwenliu.wrapper.util.GpsManager;
import com.ruiwenliu.wrapper.util.UtilsManager;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.util.glide.GlideManager;
import com.ruiwenliu.wrapper.util.glide.GlideOptions;
import com.ruiwenliu.wrapper.util.listener.SwitchFragment;
import com.ruiwenliu.wrapper.weight.CustomScrollViewPager;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.camp.CampFragment;
import com.rv.component.dialog.ConferenceEventDialog;
import com.rv.component.utils.AppCookie;
import com.rv.component.utils.CacheEnum;
import com.rv.component.utils.Cookie;
import com.rv.component.utils.DateUtils;
import com.rv.component.utils.LogUtil;
import com.rv.component.utils.RvCache;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.ui.main.home.HomeFragment;
import com.rv.home.rv.module.ui.main.home.bean.EffectiveTimeBean;
import com.rv.im.AppConfig;
import com.rv.im.ImService;
import com.rv.im.ImSetting;
import com.rv.im.bean.ImConfig;
import com.rv.im.bean.ImConfigBean;
import com.rv.im.call.AudioOrVideoController;
import com.rv.im.db.table.ChatMessage;
import com.rv.im.view.TitleTextWindow;
import com.rv.im.xmpp.ListenerManager;
import com.rv.im.xmpp.listener.ChatMessageListener;
import com.rv.plugin.calendar.bean.PreRentDaysBean;
import com.rv.rvmine.MineFragment;
import com.rv.share.WebViewActivity;
import com.rv.share.utils.TransformationUtils;
import com.rv.share.view.PromotionDialog;
import com.rv.tourism.R2;
import com.rv.tourism.TourismFragment;
import com.rv.version.DownListenerManager;
import com.rv.version.bean.VersionCheckBean;
import com.rv.version.util.DownloadAppUtils;
import com.rv.version.util.UpdateAppUtils;
import com.sh.sdk.shareinstall.ShareInstall;
import com.xxfc.discovery.DiscoveryFragment;
import com.xxfc.discovery.api.DiscoveryApi;
import com.xxfc.discovery.bean.DiscoveryIMTokenBean;
import com.xxfc.rv.other.RvActivityLifecycleCallbacks;
import com.yuyife.okgo.OkGoUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;


public class MainActivity extends BaseActivity<CommonPresenter> implements DownListenerManager.DownListener, ChatMessageListener, ImInitListenter {

    private boolean hasGetVersionInfo = false; // 判断是否已经获取过版本信息

    private VersionCheckBean versionCheckBean = null;


    private static final String TAG = MainActivity.class.getSimpleName();

    //    @BindView(R2.id.pager_view_fragment)
    CustomScrollViewPager viewPager;
    @BindView(R2.id.iv_home)
    ImageView ivHome;
    @BindView(R2.id.tv_home)
    TextView tvHome;
    @BindView(R2.id.iv_travel)
    ImageView ivTravel;
    @BindView(R2.id.tv_travel)
    TextView tvTravel;
    @BindView(R2.id.iv_camp)
    ImageView ivCamp;
    @BindView(R2.id.tv_camp)
    TextView tvCamp;
    @BindView(R2.id.iv_found)
    ImageView ivFound;
    @BindView(R2.id.tv_found)
    TextView tvFound;
    @BindView(R2.id.iv_mine)
    ImageView ivMine;
    @BindView(R2.id.tv_mine)
    TextView tvMine;
    private TabAdapter mAdapter;
    private final int TYPE_HOME_PAGE = 0;//首页
    private final int TYPE_TRAVEL = 1;//旅行
    private final int TYPE_CAMP = 2;//营地
    private final int TYPE_FOUND = 3;//旅行
    private final int TYPE_MINE = 4;//我的
    private long exitTime = 0;


    private UpdateAppUtils updateAppUtils;
    private PromotionDialog promotionDialog;

    private NetWorkReceiver netReceiver = null;

    private boolean hasBindService = false; //是否已经绑定了服务

//    private ImService mService;

    private String imToken;

    private String imPassword;

    private LocationManager locationManager;
    private ClipboardManager cm;

    public static Intent getIntent(Context context) {
        return new Intent(context, MainActivity.class);
    }

    @Override
    public boolean isBindService() {
        return hasBindService && !isImNoInit();
    }

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

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setRootViewFitsSystemWindows(mActivity, false);
        AudioOrVideoController.init(getApplicationContext(), logoutListener);
        EventBus.getDefault().register(this);
        DownListenerManager.getInstance().addDownListener(this);
        ListenerManager.getInstance().addChatMessageListener(this);
//        AppUtils.setBadger(ImSetting.getContext(), ChatMessageServiceImp.getInstance(ImSetting.getContext()).getUnReadMsg());
        GpsManager.getInstance(this).rigister();

    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {

        updateAppUtils = UpdateAppUtils.from(MainActivity.this);
        viewPager = findViewById(R.id.pager_view_fragment);
        showTitle(false);

        mAdapter = new TabAdapter(getSupportFragmentManager(), getListFragment());
        viewPager.setAdapter(mAdapter);
        viewPager.setOffscreenPageLimit(5);
        setCurrent(TYPE_HOME_PAGE);
        registerNetWorkListener();
        initNotification();
        SwitchFragment.setFragmentSelected(postion -> setCurrent(postion));

        if (!isGpsOpen()) {
            new AlertDialog.Builder(this).setTitle("提示")
                    .setMessage("定位服务尚未打开，定位导航功能可能无法正常使用，是否进入设置界面打开定位服务")
                    .setNegativeButton("下次再说", (dialogInterface, i) -> {
                        dialogInterface.dismiss();
                    })
                    .setPositiveButton("好的", (dialogInterface, i) -> {
                        Intent in = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(in);
                        dialogInterface.dismiss();
                    }).setCancelable(false).show();
        }
    }


    private void initNotification() {
        BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(mActivity);
        builder.statusBarDrawable = R.drawable.logo_title;
        builder.notificationFlags = Notification.FLAG_AUTO_CANCEL
                | Notification.FLAG_SHOW_LIGHTS;  //设置为自动消失和呼吸灯闪烁
        builder.notificationDefaults = Notification.DEFAULT_SOUND
                | Notification.DEFAULT_VIBRATE
                | Notification.DEFAULT_LIGHTS;  // 设置为铃声、震动、呼吸灯闪烁都要
        JPushInterface.setPushNotificationBuilder(1, builder);
        JPushInterface.setDefaultPushNotificationBuilder(builder);
    }


    private boolean isGpsOpen() {
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    private void registerNetWorkListener() {
        netReceiver = NetWorkReceiver.getInstance();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netReceiver, filter);
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        wakeUp(intent);
        getEffectiveTime();
        getActivityPopup();
        checkVersion();
        checkToken();
        getPreRentDays();
        initShareCode();
        checkImConfig();
    }

    /***********
     * 检测im的配置
     */
    private void checkImConfig() {
        if (isImNoInit()) {
            mPresenter.getData(8, AppConfig.CONFIG_URL, ImConfigBean.class, false);
        }
    }


    private boolean isImNoInit() {
        AppConfig appConfig = (AppConfig) RvCache.getInstance().get(CacheEnum.IM_CONFIG);
        return appConfig == null;
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                versionCheckBean = (VersionCheckBean) result;
                if (versionCheckBean != null && versionCheckBean.isRel() == false) {
                    if (versionCheckBean != null && !TextUtils.isEmpty(versionCheckBean.getData().getDownloadUrl())) {
                        checkUpdateInfo();
                    }
                }
                break;
            case 1:
                EffectiveTimeBean bean = (EffectiveTimeBean) result;
                if (bean != null && bean.isRel() && bean.getData() != null) {
                    AppCookie.save("actRent", bean.getData().getActRent());
                    AppCookie.save("actTour", bean.getData().getActTour());
                    AppCookie.save("insurePrice", bean.getData().getInsurePrice());
                    AppCookie.save("actMember", bean.getData().getActMember());
                }
                break;
            case 2:
                final ActBean actBean = (ActBean) result;
                if (actBean != null && actBean.isRel() && actBean.getData() != null && actBean.getData().size() > 0) {
                    final ActBean.Act act = actBean.getData().get(0);
                    mPresenter.saveOnclick("0", String.valueOf(act.getId()));
                    promotionDialog = new PromotionDialog.Builder(this, view -> {
                        promotionDialog.dismiss();
                        mPresenter.saveOnclick("1", String.valueOf(act.getId()));
                        postActivityPopup(act.getId());
                        startActivity(WebViewActivity.getIntent(getApplicationContext(), act.getUrl(), act.getName()));
                    }).setData(act).create();
                    promotionDialog.show();
                }
                break;
            case 3:
                imToken = ((DiscoveryIMTokenBean) result).getData();
                getImPassword();
                break;

            case 4:
                UpdateTokenBean updateTokenBean = (UpdateTokenBean) result;
                if (updateTokenBean != null && !TextUtils.isEmpty(updateTokenBean.getData())) {
                    OkGoUtil.setToken(updateTokenBean.getData(), DateUtils.getCurDate());
                    Cookie.save(getApplicationContext(), SPConstance.USER_JSON_TOKEN, updateTokenBean.getData());
                    Cookie.save(getApplicationContext(), SPConstance.USER_JSON_TOKE_TIME, DateUtils.getCurDate());
                }
                break;
            case 5:
                imPassword = ((DiscoveryIMTokenBean) result).getData();
                if (!TextUtils.isEmpty(imToken) && !TextUtils.isEmpty(imPassword)) {
                    initIm();
                }
                break;
            case 6:
                PreRentDaysBean daysBean = (PreRentDaysBean) result;
                if (daysBean != null && daysBean.isRel() && daysBean.getData() != null &&
                        daysBean.getData().size() > 0) {
                    PreRentDaysBean.Data data = daysBean.getData().get(0);
                    if (data != null) {
                        try {
                            int value = Integer.parseInt(data.getParams());
                            AppCookie.save(AppCookie.KEY_PRERENT_DAYS, value);
                        } catch (Exception e) {
                            showToast("传入的预租车天数格式有误");
                        }
                    }
                }
                break;
            case 7:
                CodeInfoBean codeInfoBean = (CodeInfoBean) result;
                showConferenceEvent(codeInfoBean);
                break;
            case 8:
                ImConfigBean imConfigBean = (ImConfigBean) result;
                ImConfig config;
                if (imConfigBean != null && imConfigBean.resultCode == 1 && imConfigBean.getData() != null) {
                    LogUtil.e("zq", "获取网络配置成功，使用服务端返回的配置并更新本地配置");
                    config = imConfigBean.getData();
                    AppConfig appConfig = AppConfig.initConfig(config);
                    RvCache.getInstance().save(appConfig, CacheEnum.IM_CONFIG);
                }
                break;
            default:
                break;
        }
    }

    private void checkUpdateInfo() {
        updateAppUtils.serverVersionCode(versionCheckBean.getData().getWeigh())
                .serverVersionName(versionCheckBean.getData().getVersionName())
                .apkPath(versionCheckBean.getData().getDownloadUrl())
                .updateInfo(versionCheckBean.getData().getContent())
                .apkSize(versionCheckBean.getData().getPackagesize())
                .isForce(versionCheckBean.getData().getIsCompel() == 0 ? false : true)
                .update();
    }


    /********
     * 保存分享的code
     */
    private void initShareCode() {

        if (TextUtils.isEmpty(AppCookie.getStringValue("code")))
            ShareInstall.getInstance().getInfo(getIntent(), info -> {
                // 客户端获取到的参数是json字符串格式
                LogUtil.d("ShareInstall", "info = " + info);
                JSONObject object;
                try {
                    object = new JSONObject(info);
                    String inviteCode = object.optString("code");
                    if (!TextUtils.isEmpty(inviteCode)) {
                        AppCookie.save("code", inviteCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            });
    }

    /**
     * 设置token时间检测
     */
    private void checkToken() {
        String time = OkGoUtil.getTime();
        if (!TextUtils.isEmpty(time)) {
            if (DateUtils.compareDateDay(DateUtils.getCurDate(), time) > 6) {
                getToken();
            }
        } else {
            getToken();
        }
    }


    /**
     * 获取新token
     */
    private void getToken() {
        Map<String, Object> heapmap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        if (!TextUtils.isEmpty(OkGoUtil.getToken())) {
            heapmap.put("Authorization", OkGoUtil.getToken());
            map.put("token", OkGoUtil.getToken());
            mPresenter.getData(RvFrameConfig.HOST, 4, ApiConfig.HTTP_URL_GET_TOKEN, UpdateTokenBean.class, map, heapmap, false);
        }
    }

    /**
     * 根据code获取分享信息
     */
    private void getShareUser(String code) {
        mPresenter.getData(7, ApiConfig.HTTP_URL_UNAUTH_CODE + code, CodeInfoBean.class, false);
    }

    /**
     * 获取活动弹框
     */
    private void getActivityPopup() {
        if (!TextUtils.isEmpty(getCopy())) {
            return;
        }
        Map<String, Object> map = new HashMap<>();
        if (!TextUtils.isEmpty(OkGoUtil.getToken())) {
            map.put("Authorization", OkGoUtil.getToken());
        }
        mPresenter.getDataHead(RvFrameConfig.HOST, 2, ApiConfig.HTTP_URL_GET_ACT, ActBean.class, map, true);
    }

    /*****
     * 获取提前租车天数
     */
    private void getPreRentDays() {
        mPresenter.getData(6, ApiConfig.HTTP_URL_PRERENT_DAYS, PreRentDaysBean.class, false);
    }

    private void postActivityPopup(int id) {
        if (!TextUtils.isEmpty(OkGoUtil.getToken())) {
            Map<String, Object> map = new HashMap<>();
            map.put("Authorization", OkGoUtil.getToken());
            mPresenter.postData(1000, String.format(ApiConfig.HTTP_URL_POST_ACT, id), BaseBean.class, map, false);
        }
    }


    @OnClick({R2.id.rl_home, R2.id.rl_travel, R2.id.rl_camp, R2.id.rl_found, R2.id.rl_mine})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.rl_home) {
            setCurrent(TYPE_HOME_PAGE);
        } else if (id == R.id.rl_travel) {
            setCurrent(TYPE_TRAVEL);
        } else if (id == R.id.rl_camp) {
            setCurrent(TYPE_CAMP);
        } else if (id == R.id.rl_found) {
            setCurrent(TYPE_FOUND);
        } else if (id == R.id.rl_mine) {
            setCurrent(TYPE_MINE);
            checkToken();
        }
    }

    private List<BaseWrapperFragment> getListFragment() {
        List<BaseWrapperFragment> list = new ArrayList<>();
        list.add(HomeFragment.getInstance(TYPE_HOME_PAGE));
        list.add(TourismFragment.getInstance(TYPE_TRAVEL));
        list.add(CampFragment.getInstance(TYPE_CAMP));
        list.add(DiscoveryFragment.getInstance(TYPE_FOUND));
        list.add(MineFragment.getInstance(TYPE_MINE));
        return list;
    }

    /**
     * 设置切换
     *
     * @param index
     */
    public void setCurrent(int index) {
        setViewStyle(ivHome, tvHome, index == TYPE_HOME_PAGE);
        setViewStyle(ivTravel, tvTravel, index == TYPE_TRAVEL);
        setViewStyle(ivCamp, tvCamp, index == TYPE_CAMP);
        setViewStyle(ivFound, tvFound, index == TYPE_FOUND);
        setViewStyle(ivMine, tvMine, index == TYPE_MINE);
        viewPager.setCurrentItem(index, false);
    }

    /**
     * 设置view的样式
     */
    private void setViewStyle(ImageView imageView, TextView textView, boolean isTrue) {
        imageView.setSelected(isTrue);
        textView.setTextColor(ContextCompat.getColor(this, isTrue ? R.color.gray_FFB74B : R.color.textMain));
    }

//    @Override
//    protected void onSaveInstanceState(Bundle outState) {
//        getSupportFragmentManager().putFragment(outState, HomeFragment.class.getSimpleName(), fragments.get(0));
//        getSupportFragmentManager().putFragment(outState, TourismFragment.class.getSimpleName(), fragments.get(1));
//        getSupportFragmentManager().putFragment(outState, CampFragment.class.getSimpleName(), fragments.get(2));
//        getSupportFragmentManager().putFragment(outState, DiscoveryFragment.class.getSimpleName(), fragments.get(3));
//        getSupportFragmentManager().putFragment(outState, MineFragment.class.getSimpleName(), fragments.get(4));
//        super.onSaveInstanceState(outState);
//    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (mAdapter != null) {
            mAdapter.getCurrentFragment().onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        if (requestCode == 1001) {
//            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                updateAppUtils.download();
//            } else {
//                Toast.makeText(getApplicationContext(), "授权失败,无法下载最新App", Toast.LENGTH_SHORT).show();
//            }
//        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
                exitApp();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null && "home".equals(intent.getStringExtra("to"))) {
            setCurrent(TYPE_HOME_PAGE);
        } else if (intent != null && "travel".equals(intent.getStringExtra("to"))) {
            setCurrent(TYPE_TRAVEL);
        } else if (intent != null && "discovery".equals(intent.getStringExtra("to"))) {
            setCurrent(TYPE_FOUND);
        } else if (intent != null && "mine_coupons".equals(intent.getStringExtra("to"))) {
            setCurrent(TYPE_MINE);
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_COUPONALL)
                    .navigation();
        } else if (intent != null && "mine_wallet".equals(intent.getStringExtra("to"))) {
            setCurrent(TYPE_MINE);
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_WALLET)
                    .navigation();
        } else {
            wakeUp(intent);
        }
    }

    /****
     * 检测版本
     */
    private void checkVersion() {
        hasGetVersionInfo = true;
        Map<String, Object> headMap = new LinkedHashMap<>();
        String versionName = updateAppUtils.getAppVersionName(this);
        if (!TextUtils.isEmpty(versionName)) {
            mPresenter.getData(0, String.format(ApiConfig.HTTP_URL_VERSION_CHECK, versionName), VersionCheckBean.class, headMap, false);
        }
    }

    private void getEffectiveTime() {
        mPresenter.getData(1, ApiConfig.HTTP_URL_EFFECTIVE_TIME, EffectiveTimeBean.class, false);
    }

    /**
     * 退出APP
     */
    private void exitApp() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            showToast("再按一次，退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }

    /**
     * 判断是否登录
     *
     * @return
     */
    private boolean isLogin() {
        if (TextUtils.isEmpty(OkGoUtil.getToken())) {
            return false;
        }
        return true;
    }

    /******
     * 唤醒Apk，跳转到webView页面
     * @param intent
     */
    private void wakeUp(Intent intent) {

        if ("webView".equals(intent.getStringExtra("to"))) {
            if (!TextUtils.isEmpty(OkGoUtil.getToken())) {
                Map<String, Object> header = new HashMap<>();
                header.put("Authorization", OkGoUtil.getToken());

                Map<String, Object> body = new HashMap<>();
                body.put("code", AppCookie.getStringValue("code"));

                mPresenter.postData(RvFrameConfig.HOST, 10000, ApiConfig.HTTP_URL_RELATION_BIND, null, body, header, false);
            }

            Log.d("type =", "" + intent.getIntExtra("type", 0));
            switch (intent.getIntExtra("type", 0)) {
                case 0:
                case 4:
                    if(!TextUtils.isEmpty(intent.getStringExtra("url")) && !TextUtils.isEmpty(intent.getStringExtra("title"))){
                        ComponentName componentName = new ComponentName(this, "com.rv.share.WebViewActivity");
                        Intent in = new Intent();
                        in.setComponent(componentName);
                        in.putExtra("url", intent.getStringExtra("url"));
                        in.putExtra("title", intent.getStringExtra("title"));
                        startActivity(in);
                    }
                    break;
                case 1:
                    setCurrent(TYPE_HOME_PAGE);
                    break;
                case 2:
                    ARouter.getInstance()
                            .build(Constance.ACTIVITY_URL_TRAVELDETAILS)
                            .withString("id", intent.getStringExtra("id"))
                            .navigation();
                    break;
                case 3:
                    ARouter.getInstance()
                            .build(Constance.ACTIVITY_URL_CAMPDETAIL)
                            .withString("id", intent.getStringExtra("id"))
                            .navigation();
                    break;
                case 5:
                    ARouter.getInstance()
                            .build(Constance.ACTIVITY_URL_DETAILPAT)
                            .withString("id", intent.getStringExtra("id"))
                            .navigation();
                    break;
            }
        }
    }

    /**
     * 获取口令
     *
     * @return
     */

    private String getCopy() {
        String content = null;
        String copyCode = null;
        cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        try {
            ClipData data = cm.getPrimaryClip();
            ClipData.Item item = data.getItemAt(0);
            content = item.getText().toString();
            if (!TextUtils.isEmpty(content) && content.contains("⇥") && content.contains("⇤")) {
                int i = content.lastIndexOf("⇥") + 1;
                int i2 = content.lastIndexOf("⇤");
                String password = content.substring(i, i2);
                int length = password.length();
                copyCode = password.substring(14, length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return copyCode;
    }

    /**
     * 获取粘贴板数据
     */
    private void initCopy() {
        String copyCode = getCopy();
        if (!TextUtils.isEmpty(copyCode)) {
            AppCookie.save("code", copyCode);

            if (copyCode.contains("_")) {
                String[] split = copyCode.split("_");
                if (split != null && split.length > 0) {
                    copyCode = split[0];
                }
            }

            String code = Cookie.getStringValue(getApplicationContext(), SPConstance.USER_JSON_CODE, "");
            if (!code.equals(copyCode)) {   //判断是否是自己点分享，防止
                getShareUser(copyCode);
            }
        }

        // 清除剪贴板
        ClipData clip = ClipData.newPlainText("", "");
        cm.setPrimaryClip(clip);
        cm = null;
    }


    /**
     * 发布会活动
     */
    private void showConferenceEvent(CodeInfoBean codeInfoBean) {
        if (codeInfoBean == null || codeInfoBean.getData() == null) {
            return;
        }

        new ConferenceEventDialog(mActivity) {
            @Override
            public void helper(ViewHolder helper) {
                super.helper(helper);
                GlideManager.getInstance(MainActivity.this).loadImage(codeInfoBean.getData().getHeadimgurl(), (RoundImageView) helper.getView(R.id.iv_avatar));
                helper.setText(R.id.tv_name, "#" + codeInfoBean.getData().getNickname() + "#邀请一起参加");
                GlideOptions options = GlideOptions.placeholderOf(com.ruiwenliu.wrapper.R.drawable.glide_icon_placeholder).
                        error(com.ruiwenliu.wrapper.R.drawable.glide_icon_error);

                Glide.with(MainActivity.this)
                        .asBitmap()
                        .load(ImageUrl.IMG_APP_BG_ACTIVITY_50)
                        .apply(options)
                        .into(new TransformationUtils((ImageView) helper.getView(R.id.img_bg)));

                helper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int i = v.getId();
                        if (i == R.id.tv_item_check) {
                            //查看活动判断
                            startActivity(WebViewActivity.getIntent(getApplicationContext(), ApiConfig.HTTP_URL_NEWYEAR_INDEX, "发布会"));
                            dismiss();
                        } else if (i == R.id.img_item_close) {
                            dismiss();
                        }
                    }
                }, R.id.tv_item_check, R.id.img_item_close);
            }
        }.show();
    }


    @Override
    public void onResume() {
        super.onResume();
        imLogin();
        initCopy();
        if (!DownListenerManager.getInstance().isDown() && hasGetVersionInfo && versionCheckBean != null && versionCheckBean.getData() != null && versionCheckBean.getData().getIsCompel() == 1 && !TextUtils.isEmpty(versionCheckBean.getData().getDownloadUrl()))
            checkUpdateInfo();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DownListenerManager.getInstance().removeDownListener(this);
        ListenerManager.getInstance().removeChatMessageListener(this);
        destory();
//        unRegisterUpdateReceiver();
        if (netReceiver != null) {
            unregisterReceiver(netReceiver);
            netReceiver = null;
        }
        GpsManager.getInstance(this).unRigister();

    }

    private ServiceConnection imServiceConnection;

    private void imLogin() {
        if (!hasBindService && isLogin()) {
            Map<String, Object> headMap = new LinkedHashMap<>();
            headMap.put("Authorization", OkGoUtil.getToken());
            mPresenter.postData(RvFrameConfig.HOST, 3, DiscoveryApi.DISCOVERY_IM_LOGIN, DiscoveryIMTokenBean.class, headMap, headMap, false);
        }
    }

    private void getImPassword() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        headMap.put("Authorization", OkGoUtil.getToken());
        mPresenter.getDataHead(RvFrameConfig.HOST, 5, ApiConfig.HTTP_URL_GET_PWD, DiscoveryIMTokenBean.class, headMap, false);
    }

    private void initIm() {
        hasBindService = true;
        ImSetting.setImConfig(Cookie.getStringValue(getApplicationContext(), SPConstance.USER_JSON_IMUSERID),
                Cookie.getStringValue(getApplicationContext(), SPConstance.USER_JSON_NAME), imPassword, imToken);

        Intent intent = new Intent(this, ImService.class);
        bindService(intent, mConnection, BIND_AUTO_CREATE);
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
//            mService = ((ImService.ImServiceBinder) service).getService();
            imServiceConnection = this;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            LogUtil.e("MainActivity", "onServiceDisconnected() called with: name = [" + name + "]");
            imServiceConnection = null;
//            mService = null;
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void logout(MessageEventLogout bean) {
        hasBindService = false;
        ImSetting.logout();
//        if (mService != null) {
//            mService.logout();
        unbindService(imServiceConnection);
//            mService = null;
//        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void remoteLogin(MessageEventRemoteLogin remoteLogin) {
        //退出登录
        Toast.makeText(getApplicationContext(), "帐号远程登录", Toast.LENGTH_SHORT).show();
        hasBindService = false;
        UtilsManager.getInstance(getApplicationContext()).clearShareData("city_json");
        UtilsManager.getInstance(getApplicationContext()).setShNull();
        RvCache.getInstance().clear();
        Cookie.clear(getApplicationContext());
        OkGoUtil.clearToken();
        ImSetting.logout();
//        AppUtils.setBadger(getApplicationContext(), 0);
        showLogoutDialog();
    }

    private void showLogoutDialog() {
        new android.support.v7.app.AlertDialog.Builder(mActivity)
                .setTitle("提示")
                .setMessage("该帐号在其他移动端登录，程序即将退出")
                .setCancelable(false)
                .setPositiveButton("确定", (dialog1, which) -> {
                    dialog1.dismiss();
                    finish();
                }).show();
    }

    private void destory() {
        if (imServiceConnection != null) {
            try {
                unbindService(imServiceConnection);
            } catch (Exception e) {
                LogUtil.e("MainActivity", "destory" + e.getMessage());
            }
        }
        AudioOrVideoController.init(getApplicationContext(), logoutListener).release();
        EventBus.getDefault().unregister(this);
    }

    private AudioOrVideoController.LogoutListener logoutListener = () -> {

    };

    @Override
    public void pending() {

    }

    @Override
    public void paused() {

    }

    @Override
    public void progress(int progerss) {

    }

    @Override
    public void completed() {
        // 安装apk
        if (!TextUtils.isEmpty(DownloadAppUtils.downloadUpdateApkFilePath)) {
            toInstall();
        }
    }

    @Override
    public void error() {

    }

    /**
     * 跳转安装
     */
    private void toInstall() {
        Intent i = new Intent(Intent.ACTION_VIEW);
        File apkFile = new File(DownloadAppUtils.downloadUpdateApkFilePath);
        if (!apkFile.exists() || !apkFile.isFile()) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(
                    this, getPackageName() + ".fileprovider", apkFile);
            i.setDataAndType(contentUri, "application/vnd.android.package-archive");

        } else {
            i.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
    }

    @Override
    public void onMessageSendStateChange(int messageState, String msgId) {

    }

    @Override
    public void onNewMessage(String fromUserId, ChatMessage message, boolean isGroupMsg) {
        boolean canShow = true;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            canShow = false;
            if (Settings.canDrawOverlays(this)) {
                canShow = true;
            }
        }
        if (canShow && (RvActivityLifecycleCallbacks.isAppBackground() || !RvActivityLifecycleCallbacks.isAppInChatView())) {
            TitleTextWindow view = new TitleTextWindow(this);
            view.show();
        }
    }
}
