package com.rv.camp;

import android.Manifest;
import android.annotation.SuppressLint;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.alibaba.android.arouter.launcher.ARouter;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.frame.base.url.Constance;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseFragment;
import com.ruiwenliu.wrapper.util.GpsManager;
import com.ruiwenliu.wrapper.util.LocationManager;
import com.ruiwenliu.wrapper.util.permission.RxPermission;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshLayout;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshView;
import com.rv.camp.adapter.CampListAdapter;
import com.rv.camp.adapter.CampTypeListAdapter;
import com.rv.camp.api.CampApi;
import com.rv.camp.bean.CampListBean;
import com.rv.camp.bean.CampTypeBean;
import com.rv.camp.camp.CampDetailActivity;
import com.rv.camp.camp.CampShopShowActivity;
import com.rv.camp.presenter.CampPresenter;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import pub.devrel.easypermissions.AppSettingsDialog;

/**
 * 营地
 */
public class CampFragment extends BaseFragment<CampPresenter> implements BaseQuickAdapter.RequestLoadMoreListener, SimpleRefreshLayout.OnSimpleRefreshListener, GpsManager.GpsChangeListener {

    @BindView(R2.id.rv_content)
    RecyclerView rvContent;
    @BindView(R2.id.rv_type)
    RecyclerView rvType;
    @BindView(R2.id.v_shadow)
    View vShadow;
    @BindView(R2.id.refresh)
    SimpleRefreshLayout mSimpleRefreshLayout;


    private boolean isOpen = true;
    private CampListAdapter campAdapter;
    private CampTypeListAdapter campTypeListAdapter;
    private int mPage;
    private int countPage;
    private String type = null;
    private double latLatitude = 0;
    private double lonLongitude;
    private LatLng mLatLng;//当前城市经纬度
    private LocationManager locationManager;


    public static CampFragment getInstance(int type) {
        Bundle bundl = new Bundle();
        bundl.putInt("type", type);
        CampFragment fragment = new CampFragment();
        fragment.setArguments(bundl);
        return fragment;
    }


    @Override
    public int getViewLayout() {
        return R.layout.activity_camp;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        GpsManager.getInstance(_mActivity).bindGpsListener(this);
        mSimpleRefreshLayout.setHeaderView(new SimpleRefreshView(_mActivity));
        mSimpleRefreshLayout.setOnSimpleRefreshListener(this);
        permissionProcess();
        campAdapter = new CampListAdapter();
        rvContent.setItemAnimator(null);
        rvContent.setLayoutManager(new GridLayoutManager(_mActivity, 2));
        rvContent.addItemDecoration(new AbSpacesItemDecoration(20, 10));// 分割线。
//        rvContent.setNestedScrollingEnabled(false);
        rvContent.setAdapter(campAdapter);

        campTypeListAdapter = new CampTypeListAdapter();
        rvType.setLayoutManager(new LinearLayoutManager(_mActivity, LinearLayoutManager.VERTICAL, false));
        rvType.setAdapter(campTypeListAdapter);

        campTypeListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CampTypeBean.DataBean item = (CampTypeBean.DataBean) adapter.getItem(position);
                type = item.getId();
                onRefresh();
                rvType.setVisibility(View.GONE);
                vShadow.setVisibility(View.GONE);
                isOpen = true;
                campTypeListAdapter.setSelectPosition(position);
            }
        });

        campAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CampListBean.DataBeanX.DataBean data = (CampListBean.DataBeanX.DataBean) adapter.getItem(position);
                ARouter.getInstance()
                        .build(Constance.ACTIVITY_URL_CAMPDETAIL)
                        .withString("id", data.getId())
                        .withDouble("longitude", lonLongitude)
                        .withDouble("latitude", latLatitude)
                        .navigation();
            }
        });

        campAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (rvContent != null) {
                    rvContent.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (mPage >= countPage) {
                                campAdapter.loadMoreEnd();
                            } else {
                                mPage++;
                                getCampList(mPage);
                            }
                        }
                    }, 200);
                }
            }
        }, rvContent);

    }

    @Override
    protected void loadData(Bundle savedInstanceState) {
        loadDataList();
        getCampTypeList();
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                processData((CampListBean) result);
                mSimpleRefreshLayout.onRefreshComplete();
                break;
            case 1:
                processTypeData((CampTypeBean) result);
                break;
        }
    }

    @Override
    public void onShowError(String errorMsg, int errorType) {
        super.onShowError(errorMsg, errorType);
        mSimpleRefreshLayout.onRefreshComplete();
    }

    @OnClick({R2.id.tv_camp_type, R2.id.iv_camp_map, R2.id.v_shadow})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.tv_camp_type) {
            //类型
            if (isOpen) {
                rvType.setVisibility(View.VISIBLE);
                vShadow.setVisibility(View.VISIBLE);
            } else {
                rvType.setVisibility(View.GONE);
                vShadow.setVisibility(View.GONE);
            }
            isOpen = !isOpen;
        } else if (id == R.id.iv_camp_map) {
            //地图
            startActivity(CampShopShowActivity.getIntent(_mActivity));
        } else if (id == R.id.v_shadow) {
            rvType.setVisibility(View.GONE);
            vShadow.setVisibility(View.GONE);
            isOpen = true;
        }
    }

    @Override
    public void onLoadMoreRequested() {
//        if (mPage >= countPage) {
//            campAdapter.loadMoreEnd();
//        } else {
//            mPage++;
//            getCampList(mPage);
//        }
    }


    /**
     * 获取营地列表
     */
    private void getCampList(int page) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("pageNo", page);
        if (type != null) {
            map.put("type", type);
        }
        mPresenter.getData(RvFrameConfig.VEHICLE_CAMPLIST, 0, CampApi.TRAVEL_CAMPSITESHOP, CampListBean.class, map, page == 1 ? false : false);
    }

    private void getCampTypeList() {
        mPresenter.getData(RvFrameConfig.VEHICLE_CAMPLIST, 1, CampApi.TRAVEL_CAMPSITETAG, CampTypeBean.class, false);
    }

    private void processTypeData(CampTypeBean bean) {
        List<CampTypeBean.DataBean> data = bean.getData();
        if (data != null && data.size() > 0) {
            CampTypeBean.DataBean dataBean = new CampTypeBean.DataBean();
            dataBean.setName("全部");
            data.add(0, dataBean);
        }
        campTypeListAdapter.setNewData(data);
    }


    /**
     * 刷新数据
     */
    private void loadDataList() {
        mPage = 1;
        getCampList(mPage);
    }

    private void processData(CampListBean bean) {
        if (mPage == 1) {
            if (bean.getData().getTotalCount() == 0) {
                campAdapter.notifyDataSetChanged();
//                campAdapter.setEmptyView(getEmptyView(rvContent, -1, "还没有营地信息！"));
                return;
            }

            countPage = bean.getData().getTotalPage();
            if (bean.getData().getData() != null) {
                campAdapter.setNewData(bean.getData().getData());
            }
        } else {
            if (bean.getData().getData() != null) {
                campAdapter.addData(bean.getData().getData());
            }
            campAdapter.loadMoreComplete();
        }
    }

    /**
     * 定位权限处理
     */
    @SuppressLint("CheckResult")
    private void permissionProcess() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            new RxPermission(getActivity()).request(
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
            ).subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) throws Exception {
                    if (aBoolean == true) {
                        initGps();
                    }
                }
            });
        } else {
            initGps();
        }
    }

    /**
     * 初始化定位
     */
    public void initGps() {
        locationManager = new LocationManager(getContext());
        locationManager.getLocationDetail(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
                //以下只列举部分获取经纬度相关（常用）的结果信息
                //更多结果信息获取说明，请参照类参考中BDLocation类中的说明

                //获取定位精度，默认值为0.0f
                float radius = location.getRadius();
                //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
                String coorType = location.getCoorType();
                //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
                int errorCode = location.getLocType();
//                setGpsContent("count=:",String.valueOf(count));
//                setGpsContent("latitude:",String.valueOf(location.getLatitude()));
//                setGpsContent("longitude:",String.valueOf(location.getLongitude()));
//                setGpsContent("城市:",location.getCity());
//                setGpsContent("街道:",location.getAddrStr());
//                setGpsContent("当前位置:",location.getLocationDescribe());
                latLatitude = location.getLatitude();
                lonLongitude = location.getLongitude();
                mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
                locationManager.stopLocation();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        GpsManager.getInstance(_mActivity).unbindGpsListener(this);
    }

    @Override
    public void onRefresh() {
        loadDataList();
    }

    @Override
    public void gpsChange(boolean b) {
        if (b) {
            permissionProcess();
        }
    }


    public class AbSpacesItemDecoration extends RecyclerView.ItemDecoration {

        private int left;
        private int right;

        public AbSpacesItemDecoration(int left, int right) {
            this.left = left;
            this.right = right;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int childCount = parent.getChildCount();
            if ((childCount - 1) % 2 == 0) {
                outRect.left = left;
                outRect.right = right;
                outRect.bottom = right;
                outRect.top = right;
            } else {
                outRect.left = right;
                outRect.right = left;
                outRect.bottom = right;
                outRect.top = right;
            }
        }
    }

}
