package com.casic.dcms.view;

import android.content.Intent;
import android.os.Build;
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.core.content.ContextCompat;
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.HttpRequestHelper;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.LocationHelper;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.callback.IHttpRequestListener;
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.hub.ContextHub;
import com.pengxh.androidx.lite.hub.StringHub;
import com.pengxh.androidx.lite.utils.ImmerseStatusBarManager;
import com.pengxh.androidx.lite.utils.WeakReferenceHandler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;

public class MainActivity extends AndroidxBaseActivity<ActivityMainBinding> {

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

    @Override
    protected void setupTopBarLayout() {
        ImmerseStatusBarManager.setColor(this, ContextCompat.getColor(this, R.color.mainThemeColor));
        ImmersionBar.with(this).statusBarDarkFont(false).init();

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

    @Override
    protected void observeRequestState() {

    }


    private final Handler.Callback callback = new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == LocaleConstant.PUSH_REGISTER) {
                pushViewModel.registerPush((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.gcjToWgs(aMapLocation.getLongitude(), aMapLocation.getLatitude());
                    positionViewModel.uploadPosition(imei, String.valueOf(gcjToWgs[1]), String.valueOf(gcjToWgs[0]));
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }
            return true;
        }
    };

    @Override
    protected void initData() {
        //配置页面
        pageViews.add(new HomePageFragment());
        pageViews.add(new PhonePageFragment());
        pageViews.add(new NoticePageFragment());
        pageViews.add(new MinePageFragment());
        MainPageAdapter mainPageAdapter = new MainPageAdapter(getSupportFragmentManager(), pageViews);
        viewBinding.mainViewPager.setOffscreenPageLimit(pageViews.size());
        viewBinding.mainViewPager.setAdapter(mainPageAdapter);

        weakReferenceHandler = new WeakReferenceHandler(callback);
        dataBaseManager = DataBaseManager.get();

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

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

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

        //获取配置项
        obtainProjectConfig();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(new Intent(this, UpdateLocationService.class));
        } else {
            startService(new Intent(this, UpdateLocationService.class));
        }
    }

    @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) {

            }
        });
    }

    private void obtainProjectConfig() {
        imei = ContextHub.getSimCardSerialNumber(this);

        //公厕图层ID
        HttpRequestHelper.doRequest(LocaleConstant.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) {

            }
        });

        //桥梁数据 TODO-待调试
        HttpRequestHelper.doRequest(LocaleConstant.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) {

            }
        });
    }

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

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

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