package com.sjkj.appthreefloor_tsgz.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.sjkj.appthreefloor_tsgz.R;
import com.sjkj.appthreefloor_tsgz.activity.ResourceDetailsActivity;
import com.sjkj.appthreefloor_tsgz.adapter.RecycleviewLeftAdapter;
import com.sjkj.appthreefloor_tsgz.adapter.RecycleviewRightAdapter;
import com.sjkj.appthreefloor_tsgz.app.App;
import com.sjkj.appthreefloor_tsgz.bean.CommonDateBean;
import com.sjkj.appthreefloor_tsgz.bean.ResourcesListBean;
import com.sjkj.appthreefloor_tsgz.databinding.FragmentEventNearbyBinding;
import com.sjkj.appthreefloor_tsgz.fragment.viewModel.EventFargmentViewModel;
import com.sjkj.appthreefloor_tsgz.net.EventDetailsResourcesListRequest;
import com.sjkj.appthreefloor_tsgz.net.EventResourcesListRequest;
import com.sjkj.base_lib.app.AppManager;
import com.sjkj.base_lib.entity.Params;
import com.sjkj.base_lib.net.domain.interactor.ProcessErrorSubscriber;
import com.sjkj.base_lib.utils.CommonUtils;
import com.sjkj.base_lib.utils.LocationUtils;
import com.sjkj.base_lib.utils.MapUtils;
import com.sjkj.base_lib.utils.ToastUtils;
import com.sjkj.base_lib.view.BaseFragment;
import com.sjkj.base_lib.weight.LoadingDialog;

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

public class EventNearByFragment extends BaseFragment {
    private FragmentEventNearbyBinding binding;
    private EventFargmentViewModel viewModel;

    private RecycleviewLeftAdapter leftAdapter;
    private RecycleviewRightAdapter rightAdapter;
    //左侧资源名称列表+范围选择
    private List<ResourcesListBean> resourceSelectTextList = new ArrayList<>();
    //右侧 资源列表
    private List<CommonDateBean> resourceSelectList = new ArrayList<>();
    ResourcesListBean resourcesListBean;
    CommonDateBean commonDateBean;
    //写死的公里数范围
    private List<String> distanceList = new ArrayList<>();
    private EventDetailsResourcesListRequest ResourcesListRequest = new EventDetailsResourcesListRequest(App.getInstance());
    private EventResourcesListRequest eventResourcesListRequest = new EventResourcesListRequest(App.getInstance());
    //右侧公里数选择列表
    List<CommonDateBean> DistancelistChoose = new ArrayList<>();
    private Handler handler = new Handler();
    private String tagVale = "";
    private String tagValeText = "";

    @Override
    protected int initLayout() {
        return R.layout.fragment_event_nearby;
    }

    @Override
    public View initBinding(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        binding = (FragmentEventNearbyBinding) getViewDataBing(inflater, container);
        viewModel = new ViewModelProvider(getActivity(), new ViewModelProvider.NewInstanceFactory()).get(EventFargmentViewModel.class);
        binding.setViewModel(viewModel);
        binding.setLifecycleOwner(this);
        binding.setViewModel(viewModel);
        binding.setLifecycleOwner((LifecycleOwner) this);
        binding.mapView.onCreate(bundle);
        binding.mapView.getMap().getUiSettings().setLogoBottomMargin(-50);
        binding.mapView.getMap().getUiSettings().setZoomControlsEnabled(true);
        binding.mapView.getMap().getUiSettings().setMyLocationButtonEnabled(false);
        //binding.mapView.getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(43.911535, 125.324667), zoomValue));
        viewModel.getMessage().observe(getViewLifecycleOwner(), message -> {
            // 处理消息
            binding.tvTitle.setText(message.getEventName());
            viewModel.eventType.set(message.getEventType());

            viewModel.latitude.set(Double.parseDouble(message.getLatitude()));
            viewModel.longitude.set(Double.parseDouble(message.getLongitude()));
            changeCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(Double.parseDouble(message.getLatitude()), Double.parseDouble(message.getLongitude()), true), 10, 30, 30)));
            LoadListData(message.getEventType(), viewModel.latitude.get(), viewModel.longitude.get());
        });

        return binding.getRoot();
    }

    private void LoadListData(String eventType, Double lat, Double log) {
        resourceSelectTextList.clear();
        showLoadingDialog();
        Params params = new Params();
        params.put("typeId", eventType);
        ResourcesListRequest.setParams(params);
        ResourcesListRequest.execute(new ProcessErrorSubscriber<List<ResourcesListBean>>() {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
                hideLoadingDialog(LoadingDialog.LOADING_FAILED);
                ToastUtils.show(e.getMessage());
            }

            @Override
            public void onNext(List<ResourcesListBean> list) {
                super.onNext(list);
                hideLoadingDialog(LoadingDialog.LOADING_SUCCESS);
                if (list != null && list.size() > 0) {
                    //多加一条
                    ResourcesListBean bean = new ResourcesListBean();
                    bean.setName("范围选择");
                    bean.setValue("zidingyi");
                    resourceSelectTextList.add(bean);

                    for (int i = 0; i < list.size(); i++) {
                        resourcesListBean = new ResourcesListBean();
                        resourcesListBean.setValue(list.get(i).getValue());
                        resourcesListBean.setName(list.get(i).getName());
                        resourceSelectTextList.add(resourcesListBean);

                    }
                    leftAdapter.refreshList(resourceSelectTextList);

                    // Log.d("zhr1121", resourceSelectTextList.get(1).getName());
                    LoadRightList(true, resourceSelectTextList.get(1).getValue(), resourceSelectTextList.get(1).getName(), lat, log, DistancelistChoose.get(rightAdapter.getCheckedPosition()).getName());
                }
            }
        });
    }

    /**
     * 根据动画按钮状态，调用函数animateCamera或moveCamera来改变可视区域
     */
    private void changeCamera(CameraUpdate update) {

        binding.mapView.getMap().moveCamera(update);

    }

    private void requestPermissionsLocation() {
        XXPermissions.with(AppManager.getAppManager().currentActivity())
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .permission(Permission.ACCESS_FINE_LOCATION)
//                .permission(Permission.ACCESS_BACKGROUND_LOCATION)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            //开始定位
                            initLocation();
                        } else {
                            ToastUtils.show("获取部分权限成功，但部分权限未正常授予");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            ToastUtils.show("被永久拒绝授权，请手动授予权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(AppManager.getAppManager().currentActivity(), permissions);
                        } else {
                            ToastUtils.show("获取权限失败");
                        }
                    }
                });
    }

    private void initLocation() {


    }

    @Override
    public void initView() {
        requestPermissionsLocation();
        distanceList.clear();
        distanceList.add("1");
        distanceList.add("2");
        distanceList.add("3");
        distanceList.add("4");
        distanceList.add("5");
        distanceList.add("6");
        distanceList.add("7");
        distanceList.add("8");
        distanceList.add("9");
        distanceList.add("10");

        for (int i = 0; i < distanceList.size(); i++) {
            commonDateBean = new CommonDateBean();
            commonDateBean.setType(1);
            commonDateBean.setName(distanceList.get(i));
            DistancelistChoose.add(commonDateBean);
        }


        //左边recyclerview
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerViewLeft.setLayoutManager(linearLayoutManager);
        leftAdapter = new RecycleviewLeftAdapter(getActivity(), resourceSelectTextList);
        binding.recyclerViewLeft.setAdapter(leftAdapter);
        //左边的RecyclerView被选中时改变背景颜色
        leftAdapter.setSelectedPosition(0);
        //右边recyclerview
        binding.recyclerViewRight.smoothScrollToPosition(0);
        LinearLayoutManager layoutManagerRight = new LinearLayoutManager(getActivity());
        binding.recyclerViewRight.setLayoutManager(layoutManagerRight);

        rightAdapter = new RecycleviewRightAdapter(getActivity(), DistancelistChoose);
        binding.recyclerViewRight.setAdapter(rightAdapter);
        rightAdapter.setCheckedPosition(4);
        rightAdapter.setOnItemClickListener(new RecycleviewRightAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(CommonDateBean bean, int position, int type) {
                if (type == rightAdapter.TYPE_ITEM_ONE) {
                    rightAdapter.setCheckedPosition(position);
                } else {
                    Intent intent = new Intent(getActivity(), ResourceDetailsActivity.class);
                    intent.putExtra("tag", tagVale);
                    intent.putExtra("tagValeText", tagValeText);
                    intent.putExtra("id", bean.getId());
                    startActivity(intent);
                }

            }
        });

        leftAdapter.setOnItemClickListener(new RecycleviewLeftAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                //右边RecyclerView相对应置顶
                binding.recyclerViewRight.smoothScrollToPosition(0);
                //左边的RecyclerView被选中时改变背景颜色
                leftAdapter.setSelectedPosition(position);
                //刷新左边被选中的item，否则背景颜色不改变无效(亲自踩坑)
                leftAdapter.notifyDataSetChanged();
                LoadZiYuanData(resourceSelectTextList.get(position));
            }
        });


    }

    private void LoadZiYuanData(ResourcesListBean resourcesListBean) {
        if (resourcesListBean.getValue().equals("zidingyi")) {
            List<CommonDateBean> list = new ArrayList<>();
            for (int i = 0; i < distanceList.size(); i++) {
                commonDateBean = new CommonDateBean();
                commonDateBean.setType(1);
                commonDateBean.setName(distanceList.get(i));
                list.add(commonDateBean);

            }
            rightAdapter.refush(list);
        } else {

            //根据左侧选中  加载右侧数据
            LoadRightList(false, resourcesListBean.getValue(), resourcesListBean.getName(), viewModel.latitude.get(), viewModel.longitude.get(), DistancelistChoose.get(rightAdapter.getCheckedPosition()).getName());
        }


    }

    private void LoadRightList(boolean isFirst, String tag, String tagText, Double latitude, Double longitude, String distance) {
        showLoadingDialog();
        tagVale = tag;
        tagValeText = tagText;
        if (isFirst) {
            DistancelistChoose.clear();
            for (int i = 0; i < distanceList.size(); i++) {
                commonDateBean = new CommonDateBean();
                commonDateBean.setType(1);
                commonDateBean.setName(distanceList.get(i));
                DistancelistChoose.add(commonDateBean);
            }

        }
        clear();//清除上一个图层
        resourceSelectList.clear();
        Params params = new Params();
        params.put("tag", tag);
        params.put("longitude", longitude);
        params.put("latitude", latitude);
        params.put("distance", distance);
        eventResourcesListRequest.setParams(params);
        eventResourcesListRequest.execute(new ProcessErrorSubscriber<List<CommonDateBean>>() {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
                hideLoadingDialog(LoadingDialog.LOADING_FAILED);
                ToastUtils.show(e.getMessage());
            }

            @Override
            public void onNext(List<CommonDateBean> list) {
                super.onNext(list);
                hideLoadingDialog(LoadingDialog.LOADING_SUCCESS);
                if (list != null && list.size() > 0) {

                    for (int i = 0; i < list.size(); i++) {

                        commonDateBean = new CommonDateBean();
                        commonDateBean.setDistance(list.get(i).getDistance());
                        commonDateBean.setId(list.get(i).getId());
                        commonDateBean.setLatitude(list.get(i).getLatitude());
                        commonDateBean.setLongitude(list.get(i).getLongitude());
                        commonDateBean.setName(list.get(i).getName());
                        commonDateBean.setType(2);
                        resourceSelectList.add(commonDateBean);
                    }
                    if (isFirst) {
                        rightAdapter.refush(DistancelistChoose);
                    } else {
                        rightAdapter.refush(resourceSelectList);
                    }

                    rightAdapter.notifyDataSetChanged();

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        for (CommonDateBean newList : list) {
                                            if (CommonUtils.checkLongitudeLatitude(newList.getLongitude(), newList.getLatitude())) {
                                                MapUtils.GPS gps = MapUtils.gps84_To_Gcj02(Double.parseDouble(newList.getLatitude()), Double.parseDouble(newList.getLongitude()));
                                                if (gps != null) {
                                                    setLocationIcon(gps, newList.getId(), newList.getName() + "", newList);
                                                }
                                            }
                                        }
                                    } catch (NumberFormatException e) {
                                        e.printStackTrace();
                                    }
                                    try {
                                        changeCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(Double.parseDouble(list.get(list.size() - 1).getLatitude()), Double.parseDouble(list.get(list.size() - 1).getLongitude()), true), 10, 30, 30)));
                                    } catch (NumberFormatException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }
                    }).start();
                } else {
                    //Log.d("zhr112", (leftAdapter.getSelectedPosition() == 0) + "");
                    if (leftAdapter.getSelectedPosition() == 0) {
                        rightAdapter.refush(DistancelistChoose);
                    } else {
                        rightAdapter.refush(new ArrayList<CommonDateBean>());
                    }

                    //ToastUtils.show("暂无数据");
                }
            }
        });
    }

    @Override
    public void initListener() {

        binding.ivEventLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.ivLocation.setBackground(getResources().getDrawable(R.drawable.icon_current));
                binding.ivEventLocation.setBackground(getResources().getDrawable(R.drawable.icon_event_current_select));
                //根据事件的经纬度
                LoadRightList(leftAdapter.getSelectedPosition() == 0, tagVale, tagValeText, viewModel.latitude.get(), viewModel.longitude.get(), DistancelistChoose.get(rightAdapter.getCheckedPosition()).getName());
            }
        });
        binding.ivLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                LocationUtils.getInstance().startLocation(true, new LocationUtils.OnLocationListener() {
                    @Override
                    public void onLocationChanged(double lat, double lng, String address, int code) {

                        if (CommonUtils.checkLongitudeLatitude(lng + "", lat + "")) {
                            binding.ivLocation.setBackground(getResources().getDrawable(R.drawable.icon_current_select));
                            binding.ivEventLocation.setBackground(getResources().getDrawable(R.drawable.icon_event_current));
                            //根据当前经纬度
                            LoadRightList(leftAdapter.getSelectedPosition() == 0, tagVale, tagValeText, lat, lng, DistancelistChoose.get(rightAdapter.getCheckedPosition()).getName());

                        } else {
                            ToastUtils.show("定位失败，请检查定位权限或者稍后重试");
                        }
                    }


                });
            }
        });

    }

    @Override
    public void loadData() {
    }

    @Override
    public void onResume() {
        super.onResume();
        binding.mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        binding.mapView.onPause();
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        binding.mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding.mapView.onDestroy();
        handler.removeCallbacksAndMessages(null);

    }

    private void clear() {
        if (binding.mapView.getMap() != null)
            binding.mapView.getMap().clear();
    }

    private void setLocationIcon(MapUtils.GPS gps, String id, String type, CommonDateBean bean) {
        MarkerOptions options = new MarkerOptions();
        options.position(new LatLng(gps.getLat(), gps.getLon()));
        options.visible(true);
        options.snippet(id);
        options.infoWindowEnable(false);
        //options.title(bean.getName());
        options.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_location));//设置图标
        binding.mapView.getMap().addMarker(options);


    }
}
