package com.casic.dcms.ui;

import android.app.Notification;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;

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

import com.amap.api.location.AMapLocation;
import com.casic.dcms.R;
import com.casic.dcms.adapter.MainPageAdapter;
import com.casic.dcms.base.AndroidxBaseActivity;
import com.casic.dcms.base.BaseApplication;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.BridgeConfigBean;
import com.casic.dcms.bean.LayerConfigBean;
import com.casic.dcms.bean.MapConfigBean;
import com.casic.dcms.bean.NoticeBean;
import com.casic.dcms.bean.ToiletListBean;
import com.casic.dcms.databinding.ActivityMainBinding;
import com.casic.dcms.greendao.NoticeBeanDao;
import com.casic.dcms.mvp.presenter.impl.MapConfigPresenterImpl;
import com.casic.dcms.mvp.presenter.impl.PushRegisterPresenterImpl;
import com.casic.dcms.mvp.presenter.impl.ToiletListPresenterImpl;
import com.casic.dcms.mvp.presenter.impl.UploadPositionPresenterImpl;
import com.casic.dcms.mvp.view.IMapConfigView;
import com.casic.dcms.mvp.view.IPushRegisterView;
import com.casic.dcms.mvp.view.IToiletListView;
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.HttpRequestHelper;
import com.casic.dcms.utils.LocationHelper;
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.utils.StringHelper;
import com.casic.dcms.utils.ToastHelper;
import com.casic.dcms.utils.callback.IHttpRequestListener;
import com.google.android.material.navigation.NavigationBarView;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.igexin.sdk.PushManager;

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

import okhttp3.ResponseBody;

public class MainActivity extends AndroidxBaseActivity<ActivityMainBinding> implements IUploadPositionView, IPushRegisterView, IMapConfigView, IToiletListView {

    private static final String TAG = "MainActivity";
    private static WeakReferenceHandler weakReferenceHandler;
    private final Gson gson = new Gson();
    private final List<Fragment> pageList = new ArrayList<>();
    private MenuItem menuItem;
    private String imei = "";
    private UploadPositionPresenterImpl uploadPositionPresenter;
    private PushRegisterPresenterImpl registerPresenter;
    private MapConfigPresenterImpl mapConfigPresenter;
    private ToiletListPresenterImpl toiletListPresenter;
    private long clickTime = 0;

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

    @Override
    protected void initData() {
        //个推初始化
        PushManager.getInstance().initialize(this);
        weakReferenceHandler = new WeakReferenceHandler(this);
        uploadPositionPresenter = new UploadPositionPresenterImpl(this);
        registerPresenter = new PushRegisterPresenterImpl(this);
        mapConfigPresenter = new MapConfigPresenterImpl(this);
        toiletListPresenter = new ToiletListPresenterImpl(this);
        //获取配置项
        obtainProjectConfig();
        //配置页面
        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));
        }
        updateMessageNumber();
    }

    private void obtainProjectConfig() {
        //地图配置项
        mapConfigPresenter.onReadyRetrofitRequest();
        //桥梁数据
        HttpRequestHelper.doRequest(Constant.PROJECT_CONFIG, new IHttpRequestListener() {
            @Override
            public void onSuccess(ResponseBody resultBean) {
                try {
                    String resultStr = resultBean.string();
                    List<BridgeConfigBean.BridgesBean> bridges = gson.fromJson(resultStr, BridgeConfigBean.class).getBridges();
                    StringHelper.saveBridgeList(gson.toJson(bridges));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable throwable) {

            }
        });
        //公厕数据
        toiletListPresenter.onReadyRetrofitRequest();
        //公厕图层ID
        HttpRequestHelper.doRequest(Constant.LAYER_CONFIG, new IHttpRequestListener() {
            @Override
            public void onSuccess(ResponseBody resultBean) {
                try {
                    String resultStr = resultBean.string();
                    List<LayerConfigBean.PartsLayerBean> partsLayer = gson.fromJson(resultStr, LayerConfigBean.class).getPartsLayer();
                    List<LayerConfigBean.PartsLayerBean.ChildrenBean> childrenBeans = partsLayer.get(2).getChildren();
                    StringHelper.saveToiletLayerID(String.valueOf(childrenBeans.get(0).getLayer()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable throwable) {

            }
        });
    }

    @Override
    protected void initEvent() {
        viewBinding.bottomNavigation.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int itemId = item.getItemId();
                if (itemId == R.id.navigation_home) {
                    viewBinding.mainViewPager.setCurrentItem(0);
                    viewBinding.titleView.setText("首页");
                } else if (itemId == R.id.navigation_phone) {
                    viewBinding.mainViewPager.setCurrentItem(1);
                    viewBinding.titleView.setText("通讯录");
                } else if (itemId == R.id.navigation_dashboard) {
                    viewBinding.mainViewPager.setCurrentItem(2);
                    viewBinding.titleView.setText("消息");
                } else if (itemId == R.id.navigation_mine) {
                    viewBinding.mainViewPager.setCurrentItem(3);
                    viewBinding.titleView.setText("我的");
                }
                return false;
            }
        });
        viewBinding.mainViewPager.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

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

            @Override
            public void onPageScrollStateChanged(int state) {

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

    private static class WeakReferenceHandler extends Handler {

        private final WeakReference<MainActivity> reference;

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

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            MainActivity mainActivity = reference.get();
            if (msg.what == Constant.PUSH_REGISTER) {
                String clientId = (String) msg.obj;
                Log.d(TAG, "注册个推Client: $clientId");
                mainActivity.registerPresenter.onReadyRetrofitRequest(clientId);
            } else if (msg.what == Constant.PUSH_CREATE_NOTIFICATION) {
                //显示小红点
                try {
                    mainActivity.updateMessageNumber();
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
                NoticeBean noticeBean = (NoticeBean) msg.obj;
                NotificationHelper notificationHelper = NotificationHelper.getInstance(mainActivity);
                Notification notification = notificationHelper.createDefault(
                        noticeBean.getTitle(),
                        noticeBean.getContent(),
                        noticeBean.getCaseId(),
                        CaseDetailActivity.class
                );
                notificationHelper.push(1, notification);
            } else if (msg.what == Constant.MESSAGE_NUMBER) {
                mainActivity.updateMessageNumber();
            } else if (msg.what == Constant.UPLOAD_LOCATION) {
                AMapLocation aMapLocation = (AMapLocation) msg.obj;
                try {
                    double[] gcjToWgs = LocationHelper.gcjToWgs(aMapLocation.getLongitude(), aMapLocation.getLatitude());
                    mainActivity.uploadPositionPresenter.onReadyRetrofitRequest(mainActivity.imei,
                            String.valueOf(gcjToWgs[1]),
                            String.valueOf(gcjToWgs[0]));
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            } else if (msg.what == Constant.LOGIN_OUT) {
                Log.d(TAG, "退出登录");
                //回到登录页
                SaveKeyValues.putValue("autoLogin", false);
                mainActivity.startActivity(new Intent(mainActivity, LoginActivity.class));
                mainActivity.finish();
            }
        }
    }

    private void updateMessageNumber() {
        List<NoticeBean> list = BaseApplication.getDaoSession()
                .getNoticeBeanDao()
                .queryBuilder()
                .where(NoticeBeanDao.Properties.IsRead.eq("1"))
                .list();
        int size = list.size();
        if (size <= 0) {
            viewBinding.messageNumView.setVisibility(View.GONE);
        } else {
            viewBinding.messageNumView.setVisibility(View.VISIBLE);
            if (size > 9) {
                viewBinding.messageNumView.setText("9+");
            } else {
                viewBinding.messageNumView.setText(String.valueOf(size));
            }
        }
    }

    @Override
    public void obtainUploadPositionResult(ActionResultBean resultBean) {

    }

    @Override
    public void obtainRegisterResult(ActionResultBean resultBean) {

    }

    @Override
    public void obtainMapConfig(MapConfigBean resultBean) {
        if (resultBean.getCode() == 200) {
            StringHelper.saveMapConfigList(gson.toJson(resultBean.getData().getRows()));
        }
    }

    @Override
    public void obtainToiletListData(ToiletListBean resultBean) {
        if (resultBean.getCode() == 200) {
            StringHelper.saveToiletList(gson.toJson(resultBean.getData()));
        }
    }

    @Override
    protected void onDestroy() {
        uploadPositionPresenter.disposeRetrofitRequest();
        registerPresenter.disposeRetrofitRequest();
        toiletListPresenter.disposeRetrofitRequest();
        super.onDestroy();
    }

    public static void sendMessage(Message msg) {
        if (weakReferenceHandler == null) {
            return;
        }
        weakReferenceHandler.sendMessage(msg);
    }

    public static void sendEmptyMessage(int what) {
        if (weakReferenceHandler == null) {
            return;
        }
        weakReferenceHandler.sendEmptyMessage(what);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - clickTime > 2000) {
                ToastHelper.showToast("再按一次退出程序", ToastHelper.DEFAULT);
                clickTime = System.currentTimeMillis();
                return true;
            } else {
                return super.onKeyDown(keyCode, event);
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}