package com.casic.dcms.view;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
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.databinding.ActivityMainBinding;
import com.casic.dcms.fragment.HomePageFragment;
import com.casic.dcms.fragment.MinePageFragment;
import com.casic.dcms.fragment.NoticePageFragment;
import com.casic.dcms.fragment.PhonePageFragment;
import com.casic.dcms.model.BridgeConfigBean;
import com.casic.dcms.model.LayerConfigBean;
import com.casic.dcms.model.MapConfigModel;
import com.casic.dcms.model.ToiletListModel;
import com.casic.dcms.service.UpdateLocationService;
import com.casic.dcms.utils.DataBaseManager;
import com.casic.dcms.utils.HttpRequestManager;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.LocationHelper;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.ViewGroupKit;
import com.casic.dcms.vm.MapConfigViewModel;
import com.casic.dcms.vm.PushViewModel;
import com.casic.dcms.vm.ToiletViewModel;
import com.casic.dcms.vm.UploadViewModel;
import com.google.android.material.navigation.NavigationBarView;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.pengxh.androidx.lite.base.AndroidxBaseActivity;
import com.pengxh.androidx.lite.kit.ContextKit;
import com.pengxh.androidx.lite.kit.StringKit;
import com.pengxh.androidx.lite.utils.WeakReferenceHandler;

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

public class MainActivity extends AndroidxBaseActivity<ActivityMainBinding> implements Handler.Callback {

    private static final String TAG = "MainActivity";
    public static WeakReferenceHandler weakReferenceHandler;
    private final Context context = this;
    private final Gson gson = new Gson();
    private final List<Fragment> fragmentPages = new ArrayList<>();
    private MenuItem menuItem;
    private String imei = "";
    private UploadViewModel positionViewModel;
    private PushViewModel pushViewModel;
    private long clickTime = 0;

    @Override
    protected void setupTopBarLayout() {
        ViewGroupKit.initImmersionBar(binding.rootView, this, false, R.color.mainThemeColor);
        ImmersionBar.with(this).statusBarDarkFont(false).init();

        binding.titleView.setText("首页");
    }

    @Override
    protected void observeRequestState() {

    }

    @Override
    public boolean handleMessage(@NonNull Message msg) {
        if (msg.what == LocaleConstant.PUSH_REGISTER) {
            pushViewModel.registerPush(context, (String) msg.obj);
        } else if (msg.what == LocaleConstant.MESSAGE_NUMBER) {
            updateMessageNumber();
        } else if (msg.what == LocaleConstant.UPDATE_LOCATION) {
            AMapLocation aMapLocation = (AMapLocation) msg.obj;
            try {
                double[] gcjToWgs = LocationHelper.get().gcjToWgs(aMapLocation.getLongitude(), aMapLocation.getLatitude());
                positionViewModel.uploadPosition(context, imei, String.valueOf(gcjToWgs[1]), String.valueOf(gcjToWgs[0]));
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    @Override
    protected void initOnCreate(@Nullable Bundle savedInstanceState) {
        //配置页面
        fragmentPages.add(new HomePageFragment());
        fragmentPages.add(new PhonePageFragment());
        fragmentPages.add(new NoticePageFragment());
        fragmentPages.add(new MinePageFragment());
        MainPageAdapter mainPageAdapter = new MainPageAdapter(getSupportFragmentManager(), fragmentPages);
        binding.mainViewPager.setAdapter(mainPageAdapter);

        weakReferenceHandler = new WeakReferenceHandler(this);

        MapConfigViewModel mapConfigViewModel = new ViewModelProvider(this).get(MapConfigViewModel.class);
        mapConfigViewModel.getMapConfig(this);
        mapConfigViewModel.mapConfigModel.observe(this, new Observer<MapConfigModel>() {
            @Override
            public void onChanged(MapConfigModel resultBean) {
                if (resultBean.getCode() == 200) {
                    DataBaseManager.get().deleteAllMapConfig();
                    for (MapConfigModel.DataBean.RowsBean rowsBean : resultBean.getData().getRows()) {
                        DataBaseManager.get().saveMapConfig(rowsBean);
                    }
                }
            }
        });

        ToiletViewModel toiletViewModel = new ViewModelProvider(this).get(ToiletViewModel.class);
        toiletViewModel.getToilets(this);
        toiletViewModel.toiletListModel.observe(this, new Observer<ToiletListModel>() {
            @Override
            public void onChanged(ToiletListModel resultBean) {
                if (resultBean.getCode() == 200) {
                    DataBaseManager.get().deleteAllToiletList();
                    for (ToiletListModel.DataBean dataBean : resultBean.getData()) {
                        DataBaseManager.get().saveToilets(dataBean);
                    }
                }
            }
        });

        positionViewModel = new ViewModelProvider(this).get(UploadViewModel.class);
        pushViewModel = new ViewModelProvider(this).get(PushViewModel.class);

        //获取配置项
        getProjectConfig();
        startForegroundService(new Intent(this, UpdateLocationService.class));
    }

    @Override
    protected void initEvent() {
        binding.bottomNavigation.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int itemId = item.getItemId();
                if (itemId == R.id.navigation_home) {
                    binding.mainViewPager.setCurrentItem(0);
                    binding.titleView.setText("首页");
                } else if (itemId == R.id.navigation_phone) {
                    binding.mainViewPager.setCurrentItem(1);
                    binding.titleView.setText("通讯录");
                } else if (itemId == R.id.navigation_dashboard) {
                    binding.mainViewPager.setCurrentItem(2);
                    binding.titleView.setText("消息");
                } else if (itemId == R.id.navigation_mine) {
                    binding.mainViewPager.setCurrentItem(3);
                    binding.titleView.setText("我的");
                }
                return false;
            }
        });
        binding.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 {
                    binding.bottomNavigation.getMenu().getItem(0).setChecked(false);
                }
                menuItem = binding.bottomNavigation.getMenu().getItem(position);
                menuItem.setChecked(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void getProjectConfig() {
        imei = ContextKit.getSimCardSerialNumber(this);

        //公厕图层ID
        new HttpRequestManager.Builder()
                .setRequestTarget(LocaleConstant.LAYER_CONFIG)
                .setOnHttpRequestListener(new HttpRequestManager.OnHttpRequestListener() {
                    @Override
                    public void onSuccess(String result) {
                        List<LayerConfigBean.PartsLayerBean> partsLayer = gson.fromJson(result, LayerConfigBean.class).getPartsLayer();
                        List<LayerConfigBean.PartsLayerBean.ChildrenBean> childrenBeans = partsLayer.get(2).getChildren();
                        StringHelper.saveToiletLayerId(String.valueOf(childrenBeans.get(0).getLayer()));
                    }

                    @Override
                    public void onFailure(Throwable throwable) {

                    }
                }).build().start();

        //桥梁数据
        new HttpRequestManager.Builder()
                .setRequestTarget(LocaleConstant.PROJECT_CONFIG)
                .setOnHttpRequestListener(new HttpRequestManager.OnHttpRequestListener() {
                    @Override
                    public void onSuccess(String result) {
                        List<BridgeConfigBean.BridgesBean> bridges = gson.fromJson(result, BridgeConfigBean.class).getBridges();
                        StringHelper.saveBridgeList(gson.toJson(bridges));
                    }

                    @Override
                    public void onFailure(Throwable throwable) {

                    }
                }).build().start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateMessageNumber();
    }

    private void updateMessageNumber() {
        int unReadNotice = DataBaseManager.get().queryUnReadNotice();
        if (unReadNotice <= 0) {
            binding.messageNumView.setVisibility(View.GONE);
        } else {
            binding.messageNumView.setVisibility(View.VISIBLE);
            if (unReadNotice > 9) {
                binding.messageNumView.setText("9+");
            } else {
                binding.messageNumView.setText(String.valueOf(unReadNotice));
            }
        }
    }

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