package com.navinfo.outdoor.fragment;

import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.slidingpanelayout.widget.SlidingPaneLayout;

import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.kongzue.dialog.interfaces.OnMenuItemClickListener;
import com.kongzue.dialog.v3.BottomMenu;
import com.navinfo.outdoor.R;
import com.navinfo.outdoor.adapter.FilterAdapter;
import com.navinfo.outdoor.api.Constant;
import com.navinfo.outdoor.base.BaseDrawerFragment;
import com.navinfo.outdoor.bean.HasSubmitBean;
import com.navinfo.outdoor.bean.JobSearchBean;
import com.navinfo.outdoor.room.ChargingPileEntity;
import com.navinfo.outdoor.room.PoiDao;
import com.navinfo.outdoor.room.PoiDatabase;
import com.navinfo.outdoor.room.PoiEntity;
import com.navinfo.outdoor.util.GeometryTools;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.vividsolutions.jts.geom.Geometry;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.jetbrains.annotations.NotNull;

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

/**
 * 筛选的Fragment
 */
public class FilterFragment extends BaseDrawerFragment implements View.OnClickListener {
    private Button btnFilter;
    private XRecyclerView recyclerFilter;
    private TextView tvType, tvExclusive, tvPhotograph, tvNumber;
    private ConstraintLayout clPhotograph, clExclusive, clType, clNumber;
    private PoiDatabase poiDatabase;
    private PoiDao poiDao;
    private FilterAdapter filterAdapter;
    private ArrayList<PoiEntity> poiEntities;
    private List<PoiEntity> allPoi;



    public static FilterFragment newInstance(Bundle bundle) {
        FilterFragment fragment = new FilterFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            setSlidingUpPanelLayout(Constant.SLIDING_LAYOUT);
            if (slidingPaneLayout!=null) {
                slidingPaneLayout.setScrollableView(recyclerFilter);
            }
            initHeader();
        }
    }

    private void initHeader() {
        View header = mView.findViewById(R.id.frame_header);
        header.findViewById(R.id.iv_filter_final).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle arguments = getArguments();
                if (arguments != null) {
                    isSliding = arguments.getBoolean("isSliding", true);
                    Log.d("TAG", "onCreatessss: " + isSliding);
                }
                if (isSliding) {
                    // 监听到返回按钮点击事件
                    Message obtain = Message.obtain();
                    obtain.what = Constant.TREASURE_FRAGMENT;
                    obtain.obj = isSliding;
                    EventBus.getDefault().post(obtain);
                }
                onBackPressed();
            }

        });
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }

    }

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

    @Override
    protected int getLayout() {
        return R.layout.fragment_filter;
    }


    @Override
    protected void initView() {
        super.initView();
       /* JobSearchBean jobSearchBean = (JobSearchBean) getArguments().getSerializable("body");//服务数据
        ArrayList<PoiEntity> showAllPoi = (ArrayList<PoiEntity>) getArguments().getSerializable("showAllPoi");//本地数据
        if (jobSearchBean != null) {
            List<JobSearchBean.BodyBean.ListBean> list = jobSearchBean.getBody().getList();
            for (int i = 0; i < list.size(); i++) {
                PoiEntity poiEntity = new PoiEntity();
                poiEntity.setTaskId(list.get(i).getId());
                poiEntity.setName(list.get(i).getName());
                poiEntity.setAddress(list.get(i).getAddress());
                poiEntity.setTelPhone(list.get(i).getTelephone() + "");
                poiEntity.setPrecision(list.get(i).getPrice());
                poiEntity.setDist(list.get(i).getDist());
                poiEntity.setType(Integer.valueOf(list.get(i).getType()));
                String geo = list.get(i).getGeo();
                Geometry geometry = GeometryTools.createGeometry(geo);
                if (geometry.getGeometryType().equals("Point")) {//点
                    LatLng latLng = GeometryTools.createLatLng(geo);
                    poiEntity.setX(latLng.longitude + "");
                    poiEntity.setY(latLng.altitude + "");
                } else if (geometry.getGeometryType().equals("LineString")) {//线
                } else if (geometry.getGeometryType().equals("Polygon")) {//面

                }
                poiEntities.add(poiEntity);
            }
        }
        if (showAllPoi != null) {
            poiEntities.addAll(showAllPoi);
        }
        filterAdapter.setAllPoi(poiEntities);*/
    }

    @Subscribe
    public void onEvent(@NotNull Message data) {
        if (data.what == Constant.JOB_SEARCH_POI_WORD) {
            allPoi = (List<PoiEntity>) data.obj;
            if (allPoi != null) {
                for (int i = 0; i < allPoi.size(); i++) {
                    if (allPoi.get(i).getTaskStatus()==0||allPoi.get(i).getTaskStatus()==1){
                        poiEntities.add(allPoi.get(i));
                    }
                }

            }
        } else if (data.what == Constant.JOB_SEARCH_WORD) {
            JobSearchBean jobSearchBean = (JobSearchBean) data.obj;
            if (jobSearchBean != null) {
                List<JobSearchBean.BodyBean.ListBean> list = jobSearchBean.getBody().getList();
                for (int i = 0; i < list.size(); i++) {
                    PoiEntity poiEntity = new PoiEntity();
                    poiEntity.setTaskId(list.get(i).getId());
                    poiEntity.setName(list.get(i).getName());
                    poiEntity.setAddress(list.get(i).getAddress());
                    poiEntity.setTelPhone(list.get(i).getTelephone() + "");
                    poiEntity.setPrecision(list.get(i).getPrice()+"");
                    poiEntity.setDist(list.get(i).getDist()+"");
                    poiEntity.setType(Integer.valueOf(list.get(i).getType()));
                    String geo = list.get(i).getGeo();
                    Geometry geometry = GeometryTools.createGeometry(geo);
                    if (geometry.getGeometryType().equals("Point")) {//点
                        LatLng latLng = GeometryTools.createLatLng(geo);
                        poiEntity.setX(latLng.longitude + "");
                        poiEntity.setY(latLng.altitude + "");
                    } else if (geometry.getGeometryType().equals("LineString")) {//线
                        List<LatLng> latLineString = GeometryTools.getLatLngs(geo);
                        poiEntity.setX(latLineString.get(0).longitude + "");
                        poiEntity.setY(latLineString.get(0).latitude + "");
                    } else if (geometry.getGeometryType().equals("Polygon")) {//面
                        List<LatLng> latPolygon = GeometryTools.getLatLngs(geo);
                        poiEntity.setX(latPolygon.get(0).longitude + "");
                        poiEntity.setY(latPolygon.get(0).latitude + "");
                    }
                    poiEntities.add(poiEntity);
                }
            }
        } else if (data.what == Constant.FILTER_DATA_CLEAR) {
            poiEntities.clear();
        }
        filterAdapter.notifyDataSetChanged();
    }

    @Override
    protected void initData() {
        super.initData();
        poiDatabase = PoiDatabase.getInstance(getContext());
        poiDao = poiDatabase.getPoiDao();
        poiEntities = new ArrayList<>();
        clNumber = findViewById(R.id.cl_number);
        clNumber.setOnClickListener(this::onClick);
        tvNumber = findViewById(R.id.tv_number);
        tvNumber.setText(Constant.NUMBER + "");
        clPhotograph = findViewById(R.id.cl_photograph);
        clPhotograph.setOnClickListener(this::onClick);
        tvPhotograph = findViewById(R.id.tv_photograph);
        if (Constant.LIMIT_TTPE == -1) {//"全部", "普通任务", "专属任务"
            tvPhotograph.setText("全部");
        } else if (Constant.LIMIT_TTPE == 0) {
            tvPhotograph.setText("普通任务");
        } else if (Constant.LIMIT_TTPE == 1) {
            tvPhotograph.setText("专属任务");
        }
        clExclusive = findViewById(R.id.cl_exclusive);
        clExclusive.setOnClickListener(this::onClick);
        tvExclusive = findViewById(R.id.tv_exclusive);
        if (Constant.TASK_TYPE == -1) {//"全部", "poi", "充电站", "POI录像", "道路录像", "其他", "面状任务"
            tvExclusive.setText("全部");
        } else if (Constant.TASK_TYPE == 1) {
            tvExclusive.setText("poi");
        } else if (Constant.TASK_TYPE == 2) {
            tvExclusive.setText("充电站");
        } else if (Constant.TASK_TYPE == 3) {
            tvExclusive.setText("POI录像");
        } else if (Constant.TASK_TYPE == 4) {
            tvExclusive.setText("道路录像");
        } else if (Constant.TASK_TYPE == 5) {
            tvExclusive.setText("其他");
        } else if (Constant.TASK_TYPE == 6) {
            tvExclusive.setText("面状任务");
        }
        clType = findViewById(R.id.cl_type);
        clType.setOnClickListener(this::onClick);
        tvType = findViewById(R.id.tv_type);
        if (Constant.TASK_STASTUS == -1) {//"未领取", "已领取", "未保存", "已保存"
            tvType.setText("全部");
        } else if (Constant.TASK_STASTUS == 0) {
            tvType.setText("未领取");
        } else if (Constant.TASK_STASTUS == 1) {
            tvType.setText("已领取");
        }/* else if (Constant.TASK_STASTUS == 2) {
            tvType.setText("未保存");
        } else if (Constant.TASK_STASTUS == 3) {
            tvType.setText("已保存");
        }*/

        btnFilter = findViewById(R.id.btn_filter);
        btnFilter.setOnClickListener(this::onClick);
        setSlidingUpPanelLayout(Constant.SLIDING_LAYOUT);
        recyclerFilter = findViewById(R.id.recycler_filter);
        if (slidingPaneLayout!=null) {
            slidingPaneLayout.setScrollableView(recyclerFilter);
        }
        //设置下划线
        recyclerFilter.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerFilter.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        recyclerFilter.setRefreshProgressStyle(ProgressStyle.SemiCircleSpin);
        recyclerFilter.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);

        //取消上啦加载下拉刷新
        recyclerFilter.setPullRefreshEnabled(false);
        recyclerFilter.setLoadingMoreEnabled(false);
        filterAdapter = new FilterAdapter(getContext(), poiEntities);
        recyclerFilter.setAdapter(filterAdapter);
        recyclerFilter.setScrollAlphaChangeListener(new XRecyclerView.ScrollAlphaChangeListener() {
            @Override
            public void onAlphaChange(int alpha) {

            }

            @Override
            public int setLimitHeight() {
                return 0;
            }
        });

        recyclerFilter.getDefaultFootView().setNoMoreHint("成功加载完毕");
        recyclerFilter.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {

            }


            @Override
            public void onLoadMore() {

            }
        });
        filterAdapter.setItemCLick(new FilterAdapter.ItemCLick() {
            @Override
            public void item(PoiEntity poiEntity) {
                if (poiEntity.getTaskStatus()!=1) {
                    Message obtain = Message.obtain();
                    obtain.what = Constant.GATHER_GET;
                    obtain.obj = poiEntity;
                    EventBus.getDefault().post(obtain);
                } else {//1:表示領取的本地認爲
                    Message obtain = Message.obtain();
                    obtain.what = Constant.TREASURE_FRAGMENT;
                    obtain.obj = true;
                    EventBus.getDefault().post(obtain);
                    Message obtains = Message.obtain();
                    obtains.what = Constant.FILTER_LIST_ITEM;
                    obtains.obj = poiEntity;
                    EventBus.getDefault().post(obtains);

                }
            }
        });
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_filter:
                Message obtain = Message.obtain();
                obtain.what = Constant.TREASURE_FRAGMENT;
                obtain.obj = true;
                EventBus.getDefault().post(obtain);
                Message obtains = Message.obtain();
                obtains.what = Constant.JOB_WORD_MONITOR;
                obtains.obj = true;
                EventBus.getDefault().post(obtains);
                onBackPressed();
                break;
            case R.id.cl_number:
                BottomMenu.show((AppCompatActivity) getContext(), new String[]{"200", "500", "1000"}, new OnMenuItemClickListener() {
                    @Override
                    public void onClick(String text, int index) {
                        tvNumber.setText(text);
                        switch (index) {
                            case 0:
                                Constant.NUMBER = 200;
                                break;
                            case 1:
                                Constant.NUMBER = 500;
                                break;
                            case 2:
                                Constant.NUMBER = 1000;
                                break;
                        }
                        Message obtain = Message.obtain();
                        obtain.what = Constant.JOB_WORD_MONITOR;
                        obtain.obj = true;
                        EventBus.getDefault().post(obtain);
                    }
                });
                break;

            case R.id.cl_photograph:
                BottomMenu.show((AppCompatActivity) getContext(), new String[]{"全部", "普通任务", "专属任务"}, new OnMenuItemClickListener() {
                    @Override
                    public void onClick(String text, int index) {
                        tvPhotograph.setText(text);
                        switch (index) {
                            case 0:
                                Constant.LIMIT_TTPE = -1;
                                break;
                            case 1:
                                Constant.LIMIT_TTPE = 0;
                                break;
                            case 2:
                                Constant.LIMIT_TTPE = 1;
                                break;
                        }
                        Message obtain = Message.obtain();
                        obtain.what = Constant.JOB_WORD_MONITOR;
                        obtain.obj = true;
                        EventBus.getDefault().post(obtain);
                    }
                });
                break;


            /**
             1 "POI"
             2 "充电站"
             3 "POI录像"
             4 "道路录像"
             5 "其他"
             6 "面状任务"
             */
            case R.id.cl_exclusive:
                BottomMenu.show((AppCompatActivity) getContext(), new String[]{"全部", "poi", "充电站", "POI录像", "道路录像", "其他", "面状任务"}, new OnMenuItemClickListener() {
                    @Override
                    public void onClick(String text, int index) {
                        tvExclusive.setText(text);
                        switch (index) {
                            case 0:
                                Constant.TASK_TYPE = -1;
                                break;
                            case 1:
                                Constant.TASK_TYPE = 1;
                                break;
                            case 2:
                                Constant.TASK_TYPE = 2;
                                break;
                            case 3:
                                Constant.TASK_TYPE = 3;
                                break;
                            case 4:
                                Constant.TASK_TYPE = 4;
                                break;
                            case 5:
                                Constant.TASK_TYPE = 5;
                                break;
                            case 6:
                                Constant.TASK_TYPE = 6;
                                break;

                        }
                        Message obtain = Message.obtain();
                        obtain.what = Constant.JOB_WORD_MONITOR;
                        obtain.obj = true;
                        EventBus.getDefault().post(obtain);
                    }
                });
                break;

            case R.id.cl_type://任务状态 0.未领取 1.已领取，2.未保存(保存到本地但未提交成功),3.已保存(保存到本地提交成功)，4已上传（结束采集）,
                BottomMenu.show((AppCompatActivity) getContext(), new String[]{"全部", "未领取", "已领取"/*, "未保存", "已保存"*/}, new OnMenuItemClickListener() {
                    @Override
                    public void onClick(String text, int index) {
                        tvType.setText(text);
                        switch (index) {
                            case 0:
                                Constant.TASK_STASTUS = -1;
                                break;
                            case 1:
                                Constant.TASK_STASTUS = 0;
                                break;
                            case 2:
                                Constant.TASK_STASTUS = 1;
                                break;
                          /*  case 3:
                                Constant.TASK_STASTUS = 2;
                                break;
                            case 4:
                                Constant.TASK_STASTUS = 3;
                                break;*/
                        }
                        Message obtain = Message.obtain();
                        obtain.what = Constant.JOB_WORD_MONITOR;
                        obtain.obj = true;
                        EventBus.getDefault().post(obtain);
                    }
                });
                break;

        }
    }

    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this))//加上判断
            EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected PoiEntity initPoiEntityByUI(PoiEntity entity) {
        return null;
    }
    @Override
    protected PoiCheckResult checkPoiEntity(PoiEntity entity) {
        return null;
    }

    @Override
    protected ChargingPileEntity initChargingPileEntityByUI(ChargingPileEntity entity) {
        return null;
    }

    @Override
    protected PoiCheckResult checkChargingPileEntity(ChargingPileEntity entity) {
        return null;
    }

}
