package com.rv.tourism;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

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.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ruiwenliu.wrapper.SPConstance;
import com.frame.base.url.Constance;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseFragment;
import com.ruiwenliu.wrapper.inter.ImInitListenter;
import com.ruiwenliu.wrapper.util.GpsManager;
import com.ruiwenliu.wrapper.util.LocationManager;
import com.ruiwenliu.wrapper.util.glide.GlideManager;
import com.ruiwenliu.wrapper.util.permission.RxPermission;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshLayout;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshView;
import com.rv.component.utils.Cookie;
import com.rv.component.utils.LocationRecord;
import com.rv.tourism.adapter.AllPopularAdapter;
import com.rv.tourism.adapter.PopularBrigadeAdapter;
import com.rv.tourism.adapter.TourAroundAdapter;
import com.rv.tourism.api.TourismApi;
import com.rv.tourism.bean.BeanPopularBrigade;
import com.rv.tourism.bean.BeanPopularBrigadeAll;
import com.rv.tourism.bean.BeanTourAround;
import com.rv.tourism.bean.BeanTourismBanner;
import com.rv.tourism.other.PopularTourListActivity;

import com.rv.tourism.presenter.TourismPresenter;
import com.yuyife.banner.Banner;
import com.yuyife.banner.BannerConfig;
import com.yuyife.banner.listener.OnBannerListener;
import com.yuyife.banner.loader.ImageLoader;
import com.yuyife.okgo.OkGoUtil;

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

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;


/**
 * 旅游
 */

public class TourismFragment extends BaseFragment<TourismPresenter> implements SimpleRefreshLayout.OnSimpleRefreshListener, GpsManager.GpsChangeListener {
    //BaseQuickAdapter.RequestLoadMoreListener,
    @BindView(R2.id.travel_city_text)
    TextView travelCityText;
    @BindView(R2.id.search_input)
    TextView searchInput;
    @BindView(R2.id.travel_banner)
    Banner travelBanner;
    @BindView(R2.id.rv_popular_brigade)
    RecyclerView rvPopularBrigade;
    @BindView(R2.id.rv_tour_around)
    RecyclerView rvTourAround;
    @BindView(R2.id.rv_popular_more)
    RecyclerView rvPopularMore;
    @BindView(R2.id.travel_hot_more_close)
    ImageView travelHotMoreClose;
    @BindView(R2.id.ll_layout_popular_more)
    LinearLayout llLayoutPopularMore;
    @BindView(R2.id.refresh)
    SimpleRefreshLayout mSimpleRefreshLayout;
    @BindView(R2.id.travel_server_image)
    ImageView ImgTravelServer;


    private ArrayList<String> images = new ArrayList<>();    //图片(默认采用网络地址)
    private List<String> titles = new ArrayList<>();         //图片标题
    private List<BeanTourismBanner.DataBean> banners = new ArrayList<>();
    private final int TYPE_REQUEST_CITY = 106;//城市列表

    private PopularBrigadeAdapter mPopularBrigadeAdapter;
    private TourAroundAdapter mTourAroundAdapter;
    private AllPopularAdapter mAllPopularAdapter;
    private int mPage;
    private int countPage;
    private int mTourismCityId;// 头城市ID
    private double latLatitude = 0;
    private double lonLongitude = 0;
    private LatLng mLatLng;//当前城市经纬度
    private LocationManager locationManager;
    private GeoCoder geoCoder;

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

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

    @Override
    protected void initView(Bundle savedInstanceState) {
        GpsManager.getInstance(_mActivity).bindGpsListener(this);
        mSimpleRefreshLayout.setHeaderView(new SimpleRefreshView(_mActivity));
        mSimpleRefreshLayout.setOnSimpleRefreshListener(this);
        setBanner();
        permissionProcess();
        //热门游
        mPopularBrigadeAdapter = new PopularBrigadeAdapter();
        rvPopularBrigade.setLayoutManager(new LinearLayoutManager(_mActivity, LinearLayoutManager.HORIZONTAL, false));
//        rvPopularBrigade.addItemDecoration(new AbSpacesItemDecoration(20,10));// 分割线。
        rvPopularBrigade.setNestedScrollingEnabled(false);
        rvPopularBrigade.setAdapter(mPopularBrigadeAdapter);

        //全部热门旅游
        mAllPopularAdapter = new AllPopularAdapter();
        rvPopularMore.setLayoutManager(new GridLayoutManager(_mActivity, 3));
        rvPopularMore.addItemDecoration(new AbSpacesItemDecoration2(20, 10));// 分割线。
//        rvPopularMore.setNestedScrollingEnabled(false);
        rvPopularMore.setAdapter(mAllPopularAdapter);

        //周边游
        mTourAroundAdapter = new TourAroundAdapter();
        rvTourAround.setLayoutManager(new LinearLayoutManager(_mActivity, LinearLayoutManager.VERTICAL, false));
        rvTourAround.setAdapter(mTourAroundAdapter);

        mPopularBrigadeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                BeanPopularBrigade.DataBean dataBean = (BeanPopularBrigade.DataBean) adapter.getItem(position);
                startActivity(PopularTourListActivity.getIntent(_mActivity, dataBean.getName(), dataBean.getId()));
            }
        });

        mAllPopularAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                BeanPopularBrigadeAll.DataBeanX.DataBean item = (BeanPopularBrigadeAll.DataBeanX.DataBean) adapter.getItem(position);
                startActivity(PopularTourListActivity.getIntent(_mActivity, item.getName(), item.getId()));
                llLayoutPopularMore.setVisibility(View.GONE);
            }
        });

        mTourAroundAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                BeanTourAround.DataBeanX.DataBean dataBean = (BeanTourAround.DataBeanX.DataBean) adapter.getItem(position);
                ARouter.getInstance()
                        .build(Constance.ACTIVITY_URL_TRAVELDETAILS)
                        .withString("id", dataBean.getId())
                        .withString("name", dataBean.getName())
                        .withString("content", dataBean.getContent())
                        .withString("url", dataBean.getCover())
                        .withString("posterBackground", dataBean.getPosterBackground())
                        .withDouble("price", Double.valueOf(dataBean.getPrice()))
                        .navigation();
            }
        });

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

    @Override
    protected void loadData(Bundle savedInstanceState) {
        loadBannerData();
        loadPopularBrigadeData();
        loadPopularBrigadeAllData();
        loadTourAroundData();
    }


    @OnClick({R2.id.travel_city_layout, R2.id.ll_item_search, R2.id.travel_server_image, R2.id.ll_item_popular_brigade_many,
            R2.id.travel_hot_more_close, R2.id.iv_popular_brigade_many})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.travel_city_layout) {
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_CITYLIST)
                    .withInt("mCityType", 1)
                    .withString("mNowCity", travelCityText.getText().toString())
                    .withInt("mCityId", mTourismCityId)
                    .navigation(getActivity(), TYPE_REQUEST_CITY);

        } else if (id == R.id.ll_item_search) {
            //搜索
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_TRAVELSEARCH)
                    .withDouble("latLatitude", 0)
                    .withDouble("lonLongitude", 0)
                    .navigation();
        } else if (id == R.id.travel_server_image) {
            if (isLogin()) {
                if (_mActivity instanceof ImInitListenter && !((ImInitListenter) _mActivity).isBindService()) {
                    showToast("Im初始化中...");
                    return;
                }
                ComponentName name = new ComponentName(getActivity(), "com.rv.im.CustomerListActivity");
                Intent intent = new Intent();
                intent.putExtra("login_user_id", Cookie.getStringValue(getContext(), SPConstance.USER_JSON_IMUSERID));
                intent.setComponent(name);
                startActivity(intent);
            }
        } else if (id == R.id.ll_item_popular_brigade_many || id == R.id.iv_popular_brigade_many) {
            //查看热门更多
            llLayoutPopularMore.setVisibility(View.VISIBLE);
        } else if (id == R.id.travel_hot_more_close) {
            llLayoutPopularMore.setVisibility(View.GONE);
        }
    }

    /**
     * 判断是否登录
     *
     * @return
     */
    private boolean isLogin() {
        if (TextUtils.isEmpty(OkGoUtil.getToken())) {
            ARouter.getInstance().build(Constance.ACTIVITY_URL_LOGINRV).navigation();
            return false;
        }
        return true;
    }


    /**
     * 获取周边游
     */
    private void loadTourAroundData() {
        if (latLatitude == 0 && lonLongitude == 0) return;
        mPage = 1;
        getLoadTourAroundData(mPage);
    }

    private void getLoadTourAroundData(int page) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("tagId", "");
        map.put("query", "");
        map.put("page", page);
        map.put("limit", "10");
        map.put("latitude", latLatitude);
        map.put("longitude", lonLongitude);
        mPresenter.getData(2, TourismApi.QUERY_RIM_LIST, BeanTourAround.class, map, false);
    }

    /**
     * 获取热门
     */
    private void loadPopularBrigadeData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("hot", "1");
        map.put("page", "1");
        map.put("limit", "50");
        mPresenter.getData(1, TourismApi.QUERY_HOT_LIST, BeanPopularBrigade.class, map, false);
    }

    /**
     * 获取全部
     */
    private void loadPopularBrigadeAllData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("hot", "0");
        map.put("page", "1");
        map.put("limit", "50");
        mPresenter.getData(3, TourismApi.QUERY_HOT_LIST, BeanPopularBrigadeAll.class, map, false);
    }

    /**
     * 获取轮播图
     */
    private void loadBannerData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("type", "1");
        mPresenter.getData(0, TourismApi.QUERY_BANNER_MAIN, BeanTourismBanner.class, map, false);
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        mSimpleRefreshLayout.onRefreshComplete();
        switch (requestType) {
            case 0:
                bannerData((BeanTourismBanner) result);
                break;
            case 1:
                popularBrigade((BeanPopularBrigade) result);
                break;
            case 2:
                tourAround((BeanTourAround) result);
                break;
            case 3:
                popularBrigadeAll((BeanPopularBrigadeAll) result);
                break;
//            case 4:
//                BeanTourDetail beanTourDetail = (BeanTourDetail) result;
//                if (beanTourDetail.getData() != null) {
//                    perfectTourDetail(beanTourDetail.getData());
//                }
//                break;
        }
    }

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

    /******
     * 完善banner信息
     * @param data
     */
    private void perfectTourDetail(BeanTourAround.DataBeanX.DataBean data) {
        if (banners != null) {
            for (BeanTourismBanner.DataBean bean : banners) {
                if (bean.getId() != null && bean.getId().equals(data.getId())) {
                    bean.setName(data.getName());
                    bean.setPrice(data.getPrice());
                    bean.setContent(data.getContent());
                    break;
                }
            }
        }

    }

    private void popularBrigadeAll(BeanPopularBrigadeAll data) {
        mAllPopularAdapter.getData().clear();
        mAllPopularAdapter.addData(data.getData().getData());
    }

    private void tourAround(BeanTourAround bean) {
        if (mPage == 1) {
            if (bean.getData().getTotalCount() == 0) {
//                mTourAroundAdapter.setEmptyView(getEmptyView(recyclerView, -1, mActivity.getString(R.string.rv_driving_data_null)));
                mTourAroundAdapter.notifyDataSetChanged();
                return;
            }

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


    private void popularBrigade(BeanPopularBrigade result) {
        mPopularBrigadeAdapter.getData().clear();
        mPopularBrigadeAdapter.addData(result.getData());
    }

    private void bannerData(BeanTourismBanner data) {
        if (data != null) {
            titles.clear();
            images.clear();
            banners.clear();
            banners.addAll(data.getData());
            for (int i = 0; i < data.getData().size(); i++) {
                images.add(data.getData().get(i).getCover());
                titles.add("");
//                getBannerDetail(data.getData().get(i));
            }
        }
        setBanner();
    }

//    private void getBannerDetail(BeanTourismBanner.DataBean bean) {
//        bean.setId(mPresenter.getIdFromUrl(bean.getUrl()));
//        mPresenter.getData(4, String.format(TourismApi.TOUR_DETAIL, bean.getId()), BeanTourDetail.class, false);
//    }


    /**
     * 设置轮番图
     */
    private void setBanner() {
        travelBanner.isAutoPlay(true)
                .setBannerTitles(titles)
                .setImages(images)
                .setDelayTime(3000)
                .setImageLoader(new ImageLoader() {
                    @Override
                    public void displayImage(Context context, Object path, ImageView imageView) {

                        GlideManager.getInstance(context).loadImage(String.valueOf(path), imageView);
                    }
                })
                .setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(int position) {
                        BeanTourismBanner.DataBean dataBean = banners.get(position);
                        mPresenter.toTarget(getActivity(), dataBean.getUrl(), dataBean.getTitle());
                    }
                })
                .start();

        travelBanner.updateBannerStyle(BannerConfig.CIRCLE_INDICATOR);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (geoCoder != null) {
            geoCoder.destroy();
        }
        if (locationManager != null) {
            locationManager.stopLocation();
            locationManager.onDestroy();
        }
    }

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


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            int type = data.getIntExtra("type", 1);
            String requestData = data.getStringExtra("location");
            switch (requestCode) {
                case TYPE_REQUEST_CITY://城市列表
                    if (type == 1) {
                        travelCityText.setText("");
                        mTourismCityId = data.getIntExtra("id", 0);
                    }
                    setRequestData(type, requestData, 0, 0);
                    break;
            }
        }
    }

    private void setRequestData(int type, String data, double lat, double lon) {
        switch (type) {
            case 1:
                travelCityText.setText(data);
                geoCoder.geocode(new GeoCodeOption()
                        .city(data)
                        .address(data));
                break;
        }
    }

    @Override
    public void onRefresh() {
        loadBannerData();
        loadPopularBrigadeData();
        loadTourAroundData();
        loadPopularBrigadeAllData();
    }

    @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;
            }
        }
    }


    public class AbSpacesItemDecoration2 extends RecyclerView.ItemDecoration {

        private int left;
        private int right;

        public AbSpacesItemDecoration2(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 % 3 == 1) {
                outRect.left = left;
                outRect.right = right;
                outRect.bottom = right;
                outRect.top = right;
            } else if (childCount % 3 == 2) {
                outRect.left = right;
                outRect.right = right;
                outRect.bottom = right;
                outRect.top = right;
            } else if (childCount % 3 == 0) {
                outRect.left = right;
                outRect.right = left;
                outRect.bottom = right;
                outRect.top = right;
            }
        }
    }

    /**
     * 定位权限处理
     */
    @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) {
                    if (aBoolean == true) {
                        initGps();
                        initCity();
                    }
                }
            });
        } else {
            initGps();
            initCity();
        }
    }

    private void initCity() {
        geoCoder = GeoCoder.newInstance();
        geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    //没有检索到结果
                } else {
                    latLatitude = LocationRecord.getOrSavelatLatitude(getContext(), 161, result.getLocation().latitude);
                    lonLongitude = LocationRecord.getOrSaveLonLongitude(getContext(), 161, result.getLocation().longitude);

                    mTourAroundAdapter.getData().clear();
                    mTourAroundAdapter.notifyDataSetChanged();
                    loadTourAroundData();
                }
                //获取地理编码结果
            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    //没有找到检索结果
                } else {
                    latLatitude = LocationRecord.getOrSavelatLatitude(getContext(), 161, result.getLocation().latitude);
                    lonLongitude = LocationRecord.getOrSaveLonLongitude(getContext(), 161, result.getLocation().longitude);
                    mTourAroundAdapter.getData().clear();
                    mTourAroundAdapter.notifyDataSetChanged();
                    loadTourAroundData();
                }
            }
        });
    }

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

    /**
     * 初始化定位
     */
    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();  //62
                latLatitude = LocationRecord.getOrSavelatLatitude(getContext(), errorCode, location.getLatitude());
                lonLongitude = LocationRecord.getOrSaveLonLongitude(getContext(), errorCode, location.getLongitude());

                mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
                loadTourAroundData();
                if (!TextUtils.isEmpty(location.getCity()))
                    travelCityText.setText(location.getCity());
                locationManager.stopLocation();
            }
        });
    }
}
