package com.tofly.ghrq_route.common.ui.activity;

import android.annotation.TargetApi;
import android.app.ActivityGroup;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TabHost;

import androidx.core.app.NotificationCompat;

import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.common.util.badgenumberlibrary.BadgeNumberManager;
import com.tofly.ghrq_route.common.util.badgenumberlibrary.BadgeNumberManagerXiaoMi;
import com.tofly.ghrq_route.common.util.badgenumberlibrary.MobileBrand;
import com.tofly.ghrq_route.base.C;
import com.tofly.ghrq_route.module.deviceInfo.DeviceInfoTool;
import com.tofly.ghrq_route.module.message.controller.MessageCallBack;
import com.tofly.ghrq_route.module.message.controller.MessageController;
import com.tofly.ghrq_route.module.message.domain.InMessageBean;
import com.tofly.ghrq_route.common.util.EventBusUtil;

import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import q.rorbin.badgeview.QBadgeView;

public class HomeActivity extends ActivityGroup {
    @BindView(android.R.id.tabcontent)
    FrameLayout tabcontent;
    @BindView(R.id.radio_btn_home)
    RadioButton radioBtnHome;
    @BindView(R.id.radio_btn_addr_book)
    RadioButton radioBtnAddrBook;
    @BindView(R.id.radio_btn_map)
    RadioButton radioBtnMap;
    @BindView(R.id.radio_btn_message)
    RadioButton radioBtnMessage;
    @BindView(R.id.radio_btn_me)
    RadioButton radioBtnMe;
    @BindView(R.id.radio_group_home)
    RadioGroup radioGroupHome;
    @BindView(R.id.tab_host)
    TabHost tabHost;
    @BindArray(R.array.home_tab_tab_titles)
    String[] tabTitles;

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

    public static final String INDEX_HOME_ACTIVITY_KEY = "index_home_activity_key";

    private QBadgeView badgeViewMain;
    private QBadgeView badgeViewMessage;
    private MessageController messageController;
    private int size1 = -1;
    private Handler handler = new Handler();
    private Runnable runnable = this::getUnread;

    //Activity
    private Class home_activitys[] = {UiMain.class, UiPhoneCall.class, UiMapTool.class, UiMessage.class, UiProfile.class};//跳转的Activity

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);

        initView();
        initData();

        EventBusUtil.register(this);
    }

    private void initView() {
        initTabView();
        initBadgeView();
        //setTranslucentStatus();
        setLightStatusBar();
    }

    public void setDarkStatusBar() {
        Window window = getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
    }

    public void setLightStatusBar() {
        Window window = getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
    }


    @TargetApi(19)
    public void setTranslucentStatus() {
        Window window = getWindow();
        int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        int flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
        WindowManager.LayoutParams attributes = window.getAttributes();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(flagTranslucentStatus);
            window.addFlags(flagTranslucentNavigation);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else {
            attributes.flags |= flagTranslucentStatus | flagTranslucentNavigation;
            window.setAttributes(attributes);
        }
    }

    private void initTabView() {
        tabHost.setup(getLocalActivityManager());

        for (int i = 0; i < home_activitys.length; i++) {
            Class activity = home_activitys[i];
            Intent intent = new Intent(this, activity);
            TabHost.TabSpec tabSpec = tabHost.newTabSpec(activity.getSimpleName())
                    .setIndicator(tabTitles[i]).setContent(intent);
            tabHost.addTab(tabSpec);
        }
        radioBtnHome.setChecked(true);
    }

    private void initData() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            initData(bundle);
        }
    }

    private void initData(Bundle bundle) {
        if (bundle != null) {
            if (bundle.containsKey(HomeActivity.INDEX_HOME_ACTIVITY_KEY)) {
                int id = bundle.getInt(HomeActivity.INDEX_HOME_ACTIVITY_KEY, R.id.radio_btn_home);
                radioGroupHome.check(id);
            }
        }
    }


    @Subscribe()
    public void onMessageEvent(DeviceInfoTool.DeviceInfoToolEvent event) {
        if (event.message.equals(DeviceInfoTool.DEVICEINFO_UNREAD_MESSAGE)) {
            List<InMessageBean> messageList = (List<InMessageBean>) event.arg;
            if (messageList != null) {
                int unreadCount = messageList.size();
                badgeViewMessage.setBadgeNumber(unreadCount);
            }
        }
    }

    private void getUnread() {
        if (messageController == null) {
            messageController = new MessageController(this);
        }
        messageController.getRecvMsgList("", -1, 1, C.DEFAULT_MAX_LOAD_PAGESIZE, new MessageCallBack() {
            @Override
            public void onGetRecvMsgList(boolean isSuccess, int errorCode, String errMsg, List<InMessageBean> messageList, int total) {
                super.onGetRecvMsgList(isSuccess, errorCode, errMsg, messageList, total);
                int size = 0;
                if (isSuccess && messageList != null) {
                    for (InMessageBean inMessageBean : messageList) {
                        if (inMessageBean.getFlag().equals("0")) {
                            size++;
                        }
                    }
                }
                if (size1 != size) {
                    size1 = size;
                    badgeViewMessage.setBadgeNumber(size1);
                    if (!Build.MANUFACTURER.equalsIgnoreCase(MobileBrand.XIAOMI)) {
                        BadgeNumberManager.from(HomeActivity.this).setBadgeNumber(size1);
                    } else {
                        setXiaomiBadgeNumber(size);
                    }
                }
                handler.postDelayed(runnable, 10 * 1000);
            }
        });
    }

    private void setXiaomiBadgeNumber(int size) {
        NotificationManager notificationManager = (NotificationManager) HomeActivity.this.
                getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new NotificationCompat.Builder(HomeActivity.this)
                .setSmallIcon(this.getApplicationInfo().icon)
                .setWhen(System.currentTimeMillis())
                .setContentTitle("推送标题")
                .setContentText("我是推送内容")
                .setTicker("ticker")
                .setAutoCancel(true)
                .build();
        //相邻的两次角标设置如果数字相同的话，好像下一次会不生效
        BadgeNumberManagerXiaoMi.setBadgeNumber(notification, size);
        notificationManager.notify(1000, notification);

    }

    private void initBadgeView() {
/*        Button btnMain = findViewById(R.id.btn_main);
        badgeViewMain = new QBadgeView(this);
        badgeViewMain.bindTarget(btnMain);
        badgeViewMain.setBadgeGravity(Gravity.END | Gravity.TOP);
        badgeViewMain.setGravityOffset(16, 2, true);
        badgeViewMain.setBadgeNumber(-1);*/

        Button btnMsg = findViewById(R.id.btn_msg);
        badgeViewMessage = new QBadgeView(this);
        badgeViewMessage.bindTarget(btnMsg);
        badgeViewMessage.setBadgeGravity(Gravity.END | Gravity.TOP);
        badgeViewMessage.setGravityOffset(6, -2, true);
        badgeViewMessage.setBadgePadding(4, true);
        //getUnread();
    }

    @OnCheckedChanged({R.id.radio_btn_home, R.id.radio_btn_addr_book, R.id.radio_btn_map, R.id.radio_btn_message, R.id.radio_btn_me})
    void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.radio_btn_home: {
                if (isChecked)
                    tabHost.setCurrentTab(0);
            }
            break;
            case R.id.radio_btn_addr_book: {
                if (isChecked)
                    tabHost.setCurrentTab(1);
            }
            break;
            case R.id.radio_btn_map: {
                if (isChecked)
                    tabHost.setCurrentTab(2);
            }
            break;
            case R.id.radio_btn_message: {
                if (isChecked)
                    tabHost.setCurrentTab(3);
            }
            break;
            case R.id.radio_btn_me: {
                if (isChecked)
                    tabHost.setCurrentTab(4);
            }
            break;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            initData(bundle);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);

        EventBusUtil.unregister(this);
    }
}
