package com.casic.dcms.ui;

import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.amap.api.location.AMapLocation;
import com.casic.dcms.R;
import com.casic.dcms.adapter.MainPageAdapter;
import com.casic.dcms.base.DoubleClickExitActivity;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.NoticeBean;
import com.casic.dcms.mvp.presenter.PushRegisterPresenterImpl;
import com.casic.dcms.mvp.presenter.UploadPositionPresenterImpl;
import com.casic.dcms.mvp.view.IPushRegisterView;
import com.casic.dcms.mvp.view.IUploadPositionView;
import com.casic.dcms.service.UploadLocationService;
import com.casic.dcms.ui.fragment.HomePageFragment;
import com.casic.dcms.ui.fragment.MinePageFragment;
import com.casic.dcms.ui.fragment.NoticePageFragment;
import com.casic.dcms.ui.fragment.PhonePageFragment;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.NotificationHelper;
import com.casic.dcms.utils.OtherUtils;
import com.casic.dcms.utils.SaveKeyValues;
import com.casic.dcms.utils.StatusBarColorUtil;
import com.casic.dcms.widgets.NoScrollViewPager;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.gyf.immersionbar.ImmersionBar;
import com.igexin.sdk.message.GTTransmitMessage;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class MainActivity extends DoubleClickExitActivity implements IUploadPositionView, IPushRegisterView {

    private static final String TAG = "MainActivity";
    @BindView(R.id.pageTitleView)
    TextView pageTitleView;
    @BindView(R.id.mainViewPager)
    NoScrollViewPager mainViewPager;
    @BindView(R.id.bottomNavigation)
    BottomNavigationView bottomNavigation;

    private MenuItem menuItem;
    private List<Fragment> pageList;
    private UploadPositionPresenterImpl uploadPositionPresenter;
    private PushRegisterPresenterImpl registerPresenter;
    private String imei = "";
    private static WeakReferenceHandler weakReferenceHandler;

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

    @Override
    protected void setupTopBarLayout() {
        StatusBarColorUtil.setColor(this, ContextCompat.getColor(this, R.color.mainThemeColor));
        ImmersionBar.with(this).statusBarDarkFont(false).init();
        pageTitleView.setText("首页");
    }

    @Override
    public void initData() {
        //个推初始化
        com.igexin.sdk.PushManager.getInstance().initialize(this);
        weakReferenceHandler = new WeakReferenceHandler(this);
        uploadPositionPresenter = new UploadPositionPresenterImpl(this);
        registerPresenter = new PushRegisterPresenterImpl(this);
        pageList = new ArrayList<>();
        pageList.add(new HomePageFragment());
        pageList.add(new PhonePageFragment());
        pageList.add(new NoticePageFragment());
        pageList.add(new MinePageFragment());
        imei = OtherUtils.obtainSimCardSerialNumber(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(new Intent(this, UploadLocationService.class));
        } else {
            startService(new Intent(this, UploadLocationService.class));
        }
    }

    @Override
    public void initEvent() {
        bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.navigation_home:
                        mainViewPager.setCurrentItem(0);
                        pageTitleView.setText("首页");
                        break;
                    case R.id.navigation_phone:
                        mainViewPager.setCurrentItem(1);
                        pageTitleView.setText("通讯录");
                        break;
                    case R.id.navigation_dashboard:
                        mainViewPager.setCurrentItem(2);
                        pageTitleView.setText("消息");
                        break;
                    case R.id.navigation_mine:
                        mainViewPager.setCurrentItem(3);
                        pageTitleView.setText("我的");
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
        mainViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (menuItem != null) {
                    menuItem.setChecked(false);
                } else {
                    bottomNavigation.getMenu().getItem(0).setChecked(false);
                }
                menuItem = bottomNavigation.getMenu().getItem(position);
                menuItem.setChecked(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        MainPageAdapter mainPageAdapter = new MainPageAdapter(getSupportFragmentManager(), pageList);
        mainViewPager.setAdapter(mainPageAdapter);
    }

    /**
     * 供{@link com.casic.dcms.service.GeTuiIntentService#onReceiveClientId(Context, String)}页面调用
     * 供{@link com.casic.dcms.service.GeTuiIntentService#onReceiveMessageData(Context, GTTransmitMessage)}页面调用
     * 供{@link com.casic.dcms.service.UploadLocationService#onCreate()}页面调用
     */
    public static void sendMessage(Message msg) {
        if (weakReferenceHandler == null) {
            return;
        }
        weakReferenceHandler.sendMessage(msg);
    }

    /**
     * 供{@link MinePageFragment#obtainLoginOutResult(ActionResultBean)}页面调用
     */
    public static void sendEmptyMessage(int what) {
        if (weakReferenceHandler == null) {
            return;
        }
        weakReferenceHandler.sendEmptyMessage(what);
    }

    private static class WeakReferenceHandler extends Handler {
        private WeakReference<MainActivity> reference;

        private WeakReferenceHandler(MainActivity activity) {
            reference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            MainActivity mainActivity = reference.get();
            switch (msg.what) {
                case Constant.PUSH_REGISTER:
                    String clientId = (String) msg.obj;
                    Log.d(TAG, "注册个推Client: " + clientId);
                    mainActivity.registerPresenter.onReadyRetrofitRequest(clientId);
                    break;
                case Constant.PUSH_CREATE_NOTIFICATION:
                    Log.d(TAG, "创建通知栏");
                    NoticeBean noticeBean = (NoticeBean) msg.obj;
                    if (null == noticeBean) {
                        return;
                    }
                    NotificationHelper notificationHelper = NotificationHelper.getInstance(mainActivity);
                    Notification notification = notificationHelper.createDefault(
                            noticeBean.getTitle(),
                            noticeBean.getContent(),
                            noticeBean.getCaseId(),
                            CaseDetailActivity.class);
                    notificationHelper.push(1, notification);
                    break;
                case Constant.UPLOAD_LOCATION:
                    Log.d(TAG, "位置上报");
                    AMapLocation aMapLocation = (AMapLocation) msg.obj;
                    mainActivity.uploadPositionPresenter.onReadyRetrofitRequest(mainActivity.imei,
                            String.valueOf(aMapLocation.getLatitude()), String.valueOf(aMapLocation.getLongitude()));
                    break;
                case Constant.LOGIN_OUT:
                    Log.d(TAG, "退出登录");
                    //回到登录页
                    SaveKeyValues.putValue("autoLogin", false);
                    mainActivity.startActivity(new Intent(mainActivity, LoginActivity.class));
                    mainActivity.finish();
                    break;
            }
        }
    }


    @Override
    public void obtainUploadPositionResult(ActionResultBean resultBean) {
//        Log.d(TAG, "obtainUploadPositionResult: " + new Gson().toJson(resultBean));
    }

    @Override
    public void obtainRegisterResult(ActionResultBean resultBean) {
//        Log.d(TAG, "obtainRegisterResult: " + new Gson().toJson(resultBean));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (uploadPositionPresenter != null) {
            uploadPositionPresenter.disposeRetrofitRequest();
        }
        if (registerPresenter != null) {
            registerPresenter.disposeRetrofitRequest();
        }
    }
}
