package com.zhangxin.starlight.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.heytap.msp.push.HeytapPushManager;
import com.heytap.msp.push.callback.ICallBackResultService;
import com.huawei.hms.aaid.HmsInstanceId;
import com.huawei.hms.common.ApiException;
import com.meizu.cloud.pushsdk.PushManager;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMConversationListener;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMOfflinePushConfig;
import com.tencent.imsdk.v2.V2TIMUserFullInfo;
import com.umeng.analytics.MobclickAgent;
import com.vivo.push.PushClient;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.ym.chat.fragment.ChatFragment;
import com.ym.chat.utils.TUIUtils;
import com.zhangxin.starlight.R;
import com.zhangxin.starlight.entity.HWPushBean;
import com.zhangxin.starlight.utils.AndroidDeviceUtils;
import com.zxhl.cms.AppContext;
import com.zxhl.cms.ad.upload.model.NewsEntity;
import com.zxhl.cms.common.Constant;
import com.zxhl.cms.common.base.BaseActivity;
import com.zxhl.cms.net.ApiClient;
import com.zxhl.cms.net.RxSchedulers;
import com.zxhl.cms.net.SettingPreference;
import com.zxhl.cms.net.callback.BaseObserver;
import com.zxhl.cms.net.model.chat.IMSignEntity;
import com.zxhl.cms.net.model.chat.LocationEntity;
import com.zxhl.cms.net.model.uc.UserInfo;
import com.zxhl.cms.runtimepermission.NicePermission;
import com.zxhl.cms.runtimepermission.NicePermissionListener;
import com.zxhl.cms.utils.AdCallback;
import com.zxhl.cms.utils.AdDataSupport;
import com.zxhl.cms.utils.EventUtils;
import com.zxhl.cms.utils.JumpUtils;
import com.zxhl.cms.utils.LogUtils;
import com.zxhl.cms.utils.RxBus;
import com.zxhl.cms.utils.UserDataUtils;
import com.zxhl.cms.utils.Utils;
import com.zxhl.cms.widget.ChatDialogUtils;
import com.zxhl.cms.widget.LoadingDialog;
import com.zxhl.main.page.fragment.ConstellationMachFragment;
import com.zxhl.main.page.fragment.HomeFragment;
import com.zxhl.main.page.fragment.MessageFragment;
import com.zxhl.main.page.fragment.PopularFragment;
import com.zxhl.main.page.view.NavigationBottomView;
import com.zxhl.uc.page.fragment.UserCenterFragment;

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

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

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import me.jessyan.autosize.internal.CancelAdapt;

/**
 * Copyright @ 2018 Bitgoose All rights reserved.
 *
 * @class name: MainActivity
 * @class describe:
 * @author: fuxin
 * @date: 2019/3/15 下午2:19
 */
public class MainActivity extends BaseActivity implements NavigationBottomView.NavifationCallback/*, IDialogCloseCallback, MemberContract.View*/, CancelAdapt {

    private List<Fragment> fragments = new ArrayList<>();
    private NavigationBottomView navigationView;
    private LoadingDialog mLoading;
    private Dialog mDialog;
    private Context context;
    private Observable<String> mRestartLoginObservable;
    private Observable<Integer> mSwitchMainObservable;
    private String hwPushToken = "";
    private TextView msgtv;

    @Override
    public int layoutID() {
        return R.layout.activity_main;
    }

    @Override
    public void before() {
        super.before();

        setStatusBarBackground(AppContext.get().getResources().getColor(R.color.transparent));

    }

    @Override
    public void init() {
        context = this;
        msgtv = findViewById(R.id.id_tv_msg_num);
        if (showCheckPermissions()) {
            checkLocation();
        }
        mLoading = LoadingDialog.getLoadingDialog(
                this,
                getString(com.zxhl.cms.R.string.wait_ing),
                false,
                false
        );
        navigationView = findViewById(R.id.id_activity_main_fragment_navigation);
//        memberPresenter = new MemberPresenter(this);
        initListener();
        AdDataSupport.INSTANCE.init(this);
        initFragment();
        mRestartLoginObservable = RxBus.get().register(Constant.REFRESH_LOGIN_STATS, String.class);
        mRestartLoginObservable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
//                deviceLogin();
                JumpUtils.loginBeforeJump();
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {

            }
        });

        mSwitchMainObservable = RxBus.get().register(Constant.SWITCH_PAGE, Integer.class);
        mSwitchMainObservable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer s) throws Exception {
                switchFragment(s);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {

            }
        });
        setTotalUnreadMessageCountChanged(0);
        EventBus.getDefault().register(this);
        getNotificationMessage(getIntent());
    }

    private void initListener() {
        navigationView.setNavifationCallback(this);
    }

    private void initFragment() {
        fragments.add(new HomeFragment());
        fragments.add(new ConstellationMachFragment());
        fragments.add(new MessageFragment());
        fragments.add(new UserCenterFragment());

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        for (Fragment fragment : fragments) {
            transaction.add(R.id.id_activity_main_fragment_layout, fragment);
        }
        hideFragment(transaction);
        transaction.show(fragments.get(0)).commit();
        EventUtils.INSTANCE.onEvent("tab_imp", "home");
    }

    private void switchFragment(int index) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        hideFragment(transaction);
        transaction.show(fragments.get(index)).commitAllowingStateLoss();
        getSupportFragmentManager().executePendingTransactions();
    }

    private void switchFragment(Fragment fragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        hideFragment(transaction);
        transaction.show(fragment).commit();
    }

    private void hideFragment(FragmentTransaction transaction) {
        for (Fragment fragment : fragments) {
            transaction.hide(fragment);
        }
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onNavigationClick(int vId) {
        if (vId == R.id.id_ll_bottom_user) {
            switchFragment(3);
            EventUtils.INSTANCE.onEvent("tab_imp", "user");
        } else if (vId == R.id.id_ll_bottom_shouye) {
            switchFragment(0);
            EventUtils.INSTANCE.onEvent("tab_imp", "home");
        } else if (vId == R.id.id_ll_bottom_xingzuo) {
            switchFragment(1);
        } else if (vId == R.id.id_ll_bottom_msg) {
            switchFragment(2);
        }
    }

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

    private void getNotificationMessage(Intent intent) {
        if (intent == null) {
            return;
        }
//        String title = "";
//        String senderId = "";
////        if (HmsProfile.getInstance(this).isSupportProfile()) {
////            title = intent.getData().getQueryParameter("title");
////            senderId = intent.getData().getQueryParameter("senderId");
////        }else {
//            title = intent.getStringExtra("title");
//            senderId = intent.getStringExtra("senderId");
////        }
//
//        if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(senderId)) {
////            JumpUtils.startC2CChatActivity(senderId, title);
//        }
    }

    private boolean mPrepareExit = false;

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        exitBy2Click();
    }

    private void exitBy2Click() {
        if (!mPrepareExit) {
            mPrepareExit = true;// 准备退出
            Utils.showToast(this, getResources().getString(R.string.nav_back_again_finish));
            navigationView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mPrepareExit = false;// 取消退出
                }
            }, 1500);
        } else {
            Utils.onExit(this);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        login(SettingPreference.getUserInfoData().uid + "");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("MXL", "onResume");
        MobclickAgent.onResume(this);
    }


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

        MobclickAgent.onPause(this);
    }

    private void deviceLogin() {
        ApiClient.INSTANCE.getUserInfoAPi().deviceLogin().compose(RxSchedulers.observableIO2Main()).subscribe(new BaseObserver<UserInfo>() {
            @Override
            public void onSuccess(UserInfo result) {
                if (result != null) {
                    SettingPreference.saveToken(result.token);
                    UserDataUtils.INSTANCE.updateUserInfo(null);
                }
            }

            @Override
            public void onFailure(Throwable e, String code, String errorMsg) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(Constant.REFRESH_LOGIN_STATS, mRestartLoginObservable);
        RxBus.get().unregister(Constant.SWITCH_PAGE, mSwitchMainObservable);
        EventBus.getDefault().unregister(this);
    }

    private void requestRewardVidedo(AdCallback<String> adCallback) {
        String slotId = "video";
        ApiClient.INSTANCE.getAdApi().getAds(slotId).compose(RxSchedulers.observableIO2Main())
                .subscribe(new BaseObserver<List<NewsEntity>>() {
                    @Override
                    public void onSuccess(List<NewsEntity> result) {
                        if (result != null && result.size() > 0) {
                            AdDataSupport.INSTANCE.requestByteRewardVideoAd(result.get(0), MainActivity.this, adCallback);

                        } else {
                            adCallback.onResult(-1, "失败");
                        }

                    }

                    @Override
                    public void onFailure(Throwable e, String code, String errorMsg) {
                        adCallback.onResult(-1, "失败");
                    }
                });
    }


    private void login(String userId) {
        // 获取userSig函数
        ApiClient.INSTANCE.getHomeApi().getAdminKey().compose(RxSchedulers.observableIO2Main())
                .subscribe(new BaseObserver<IMSignEntity>() {

                    @Override
                    public void onSuccess(IMSignEntity result) {
                        if (result != null) {
                            String sign = result.getKey();
                            if (TextUtils.isEmpty(sign)) {
                                return;
                            }
                            SettingPreference.setImSignInfo(sign);
                            TUIUtils.login(userId, sign, new V2TIMCallback() {
                                @Override
                                public void onSuccess() {
//                                    XGPushManager.registerPush(getApplication(), new XGIOperateCallback() {
//                                        @Override
//                                        public void onSuccess(Object data, int i) {
//                                            //token在设备卸载重装的时候有可能会变
//                                            Log.d("TPush", "注册成功，设备token为：" + data);
//                                            V2TIMManager.getOfflinePushManager().setOfflinePushConfig(new V2TIMOfflinePushConfig(i, data.toString()), new V2TIMCallback() {
//                                                @Override
//                                                public void onSuccess() {
//                                                    LogUtils.d("111");
//                                                }
//
//                                                @Override
//                                                public void onError(int i, String s) {
//
//                                                }
//                                            });
//                                        }
//
//                                        @Override
//                                        public void onFail(Object o, int errCode, String msg) {
//                                            Log.d("TPush", "注册失败，错误码：" + errCode + ",错误信息：" + msg);
//                                        }
//                                    });
                                    if (AndroidDeviceUtils.isXiaoMiDevice()) {
                                        String xiaomiRegId = MiPushClient.getRegId(getApplication());
                                        if (!TextUtils.isEmpty(xiaomiRegId)) {
                                            setOfflinePushConfig(21959, xiaomiRegId);
                                        }
                                    }
                                    new Thread(() -> {
                                        String huaweiToken = null;
                                        try {
                                            // 从agconnect-services.json文件中读取APP_ID
                                            String appId = "105341515";
                                            // 输入token标识"HCM"
                                            String tokenScope = "HCM";
                                            huaweiToken = HmsInstanceId.getInstance(MainActivity.this).getToken(appId, tokenScope);
                                        } catch (ApiException e) {
                                            e.printStackTrace();
                                        }
                                        if (!TextUtils.isEmpty(huaweiToken)) {
                                            setOfflinePushConfig(21963, huaweiToken);
                                        } else if (!TextUtils.isEmpty(hwPushToken)) {
                                            setOfflinePushConfig(21963, hwPushToken);
                                        }
                                    }).start();
                                    //oppo
                                    if (HeytapPushManager.isSupportPush()) {
                                        /**
                                         * 注册MSP推送服务
                                         * @param applicatoinContext必须传入当前app的applicationcontet
                                         * @param appKey 在开发者网站上注册时生成的，与AppKey相对应
                                         * @param appSecret 与AppSecret相对应
                                         * @param ICallBackResultService SDK操作的回调
                                         */
                                        HeytapPushManager.register(
                                                getApplication(),
                                                "1ddb362c8cb1482ea6375233c65d26ff",
                                                "1ca85798cc1f4abf91b00b49b538bdd1",
                                                new ICallBackResultService() {
                                                    @Override
                                                    public void onRegister(int responseCode, String registerID) {
                                                        if (!TextUtils.isEmpty(registerID)) {
                                                            setOfflinePushConfig(21960, registerID);
                                                        }
                                                    }

                                                    @Override
                                                    public void onUnRegister(int i) {

                                                    }

                                                    @Override
                                                    public void onSetPushTime(int i, String s) {

                                                    }

                                                    @Override
                                                    public void onGetPushStatus(int i, int i1) {

                                                    }

                                                    @Override
                                                    public void onGetNotificationStatus(int i, int i1) {

                                                    }
                                                });
                                    }
                                    //vivo
                                    if (PushClient.getInstance(getApplication()).isSupport()) {
                                        PushClient.getInstance(getApplication()).turnOnPush(state -> {
                                            //开关状态处理， 0代表成功
                                            if (state == 0) {
                                                String vivoRegId = PushClient.getInstance(getApplication()).getRegId();
                                                if (!TextUtils.isEmpty(vivoRegId)) {
                                                    setOfflinePushConfig(21961, vivoRegId);
                                                }
                                            }
                                        });
                                    }
                                    //魅族
                                    String meizuPushId = PushManager.getPushId(getApplication());
                                    if (!TextUtils.isEmpty(meizuPushId)) {
                                        setOfflinePushConfig(21962, meizuPushId);
                                    }
                                    V2TIMUserFullInfo userFullInfo = new V2TIMUserFullInfo();
                                    UserInfo userInfo = SettingPreference.getUserInfoData();
                                    userFullInfo.setNickname(userInfo.nickname);
                                    userFullInfo.setFaceUrl(userInfo.headImage);
//                    HashMap < String, byte[]> customHashMap = new HashMap<>();
//                    customHashMap.put("phone", userBean.getPhone().getBytes());
//                    userFullInfo.setCustomInfo(customHashMap);
                                    userFullInfo.setGender(userInfo.sex);
                                    V2TIMManager.getInstance().setSelfInfo(userFullInfo, new V2TIMCallback() {
                                        @Override
                                        public void onSuccess() {

                                        }

                                        @Override
                                        public void onError(int code, String desc) {

                                        }
                                    });
                                    LogUtils.d("IM登录成功");
                                    V2TIMManager.getConversationManager().addConversationListener(new V2TIMConversationListener() {
                                        @Override
                                        public void onTotalUnreadMessageCountChanged(long totalUnreadCount) {
                                            super.onTotalUnreadMessageCountChanged(totalUnreadCount);
                                            setTotalUnreadMessageCountChanged(totalUnreadCount);
                                        }
                                    });
                                }

                                @Override
                                public void onError(int i, String s) {
                                    LogUtils.d("IM登录失败");
                                }
                            });
                        }
                    }

                    @Override
                    public void onFailure(Throwable e, String code, String errorMsg) {

                    }
                });
    }

    private void setOfflinePushConfig(int businessId, String regid) {
        V2TIMManager.getOfflinePushManager().setOfflinePushConfig(new V2TIMOfflinePushConfig(businessId, regid), new V2TIMCallback() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }

    /**
     * 设置未读消息角标方法
     *
     * @param totalUnreadCount
     */
    private void setTotalUnreadMessageCountChanged(long totalUnreadCount) {
        if (totalUnreadCount > 0) {
            msgtv.setVisibility(View.VISIBLE);
            if (totalUnreadCount < 10) {
                msgtv.setBackgroundResource(R.drawable.icon_2);
                msgtv.setText("" + totalUnreadCount);
            } else {
                msgtv.setBackgroundResource(R.drawable.icon_3);
                if(totalUnreadCount<100){
                    msgtv.setText("" + totalUnreadCount);
                }else {
                    msgtv.setText("99+");
                }
            }
        } else {
            msgtv.setVisibility(View.GONE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiverHWPushToken(HWPushBean hwPushBean) {
        if (hwPushBean != null && !TextUtils.isEmpty(hwPushBean.token)) {
            hwPushToken = hwPushBean.token;
            setOfflinePushConfig(21963, hwPushBean.token);
        }
    }

    /**
     * 是否应该检查权限
     *
     * @return
     */
    public boolean showCheckPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return true;
        } else {
            return false;
        }
    }

    boolean isHaveAudioPermission = false;

    private void checkLocation() {
        new NicePermission(this, new NicePermissionListener() {
            @Override
            public void onGranted() {
                Log.e("MXL", "用户同意");
                if (isHaveAudioPermission) {
                    getLocation();
                }
                isHaveAudioPermission = true;
            }

            @Override
            public void onRefused() {
                Log.e("MXL", "用户拒绝");
                isHaveAudioPermission = false;
                ChatDialogUtils.showPermissionDialog((Activity) mActivity, "请开启定位权限");
            }
        }).requestPermission(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION});
    }

    /**
     * 实现定位回调
     */
    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            //获取纬度信息
            double latitude = location.getLatitude();
            //获取经度信息
            double longitude = location.getLongitude();
            //获取定位精度，默认值为0.0f
            float radius = location.getRadius();
            //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
            String coorType = location.getCoorType();
            //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
            int errorCode = location.getLocType();
            Log.e("MXL", "定位" + location.getCity() + location.getLocType());
            if (!TextUtils.isEmpty(location.getCity())) {
                ApiClient.INSTANCE.getHomeApi().syncPositon("" + latitude, "" + longitude, location.getCity()).compose(RxSchedulers.observableIO2Main())
                        .subscribe(new BaseObserver<LocationEntity>() {
                            @Override
                            public void onSuccess(LocationEntity result) {

                            }

                            @Override
                            public void onFailure(Throwable e, String code, String errorMsg) {

                            }
                        });
            }
        }
    }

    private void getLocation() {
        //定位服务的客户端。宿主程序在客户端声明此类，并调用，目前只支持在主线程中启动
        LocationClient locationClient = new LocationClient(AppContext.get());
        LocationClientOption locationOption = new LocationClientOption();
        MyLocationListener myLocationListener = new MyLocationListener();
        locationClient.registerLocationListener(myLocationListener);
        locationOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        locationOption.setCoorType("gcj02");
        locationOption.setScanSpan(1000);
        locationOption.setIsNeedAddress(true);
        locationOption.setIsNeedLocationDescribe(true);
        locationOption.setNeedDeviceDirect(false);
        locationOption.setLocationNotify(true);
        locationOption.setIgnoreKillProcess(true);
        locationOption.setIsNeedLocationDescribe(true);
        locationOption.setIsNeedLocationPoiList(true);
        locationOption.SetIgnoreCacheException(false);
        locationOption.setOpenGps(true);
//可选，默认false，设置定位时是否需要海拔信息，默认不需要，除基础定位版本都可用
        locationOption.setIsNeedAltitude(false);
//设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者，该模式下开发者无需再关心定位间隔是多少，定位SDK本身发现位置变化就会及时回调给开发者
        locationOption.setOpenAutoNotifyMode();
//设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者
        locationOption.setOpenAutoNotifyMode(3000, 1, LocationClientOption.LOC_SENSITIVITY_HIGHT);
//需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        locationClient.setLocOption(locationOption);
//开始定位
        locationClient.start();
    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        if (grantResults.length > 0
//                && grantResults[0] == PackageManager.PERMISSION_GRANTED
//                && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
//            // 权限被用户同意。
//            // 执形我们想要的操作
//           // getLocation();
//        } else {
//            return;
//        }
//
//    }

}
