package com.rv.home.rv.module.ui.main.home;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
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.frame.base.url.Constance;
import com.frame.rv.config.RvFrameConfig;
import com.google.gson.Gson;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.inter.OnViewHolder;
import com.ruiwenliu.wrapper.util.UtilsManager;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.rv.component.utils.DisplayUtil;
import com.rv.home.R;
import com.rv.home.R2;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshLayout;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshView;
import com.rv.home.rv.module.ApiConfig;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.rv.home.rv.module.ui.main.home.adapter.SelectShopAdapter;
import com.rv.home.rv.module.ui.main.home.bean.CityPickerBean;
import com.rv.home.rv.module.ui.main.home.bean.ListsBean;
import com.rv.home.rv.module.ui.main.home.bean.ShopListBean;

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

import butterknife.BindView;

/**
 * Created :Auser
 * Date: 2019/5/18.
 * Desc:门店选择
 */
@Route(path = Constance.ACTIVITY_URL_SELECTSHOP)
public class SelectShopActivity extends BaseStatusActivity<CommonPresenter> implements BaseQuickAdapter.RequestLoadMoreListener, SimpleRefreshLayout.OnSimpleRefreshListener {

    private final int TYPE_REQUEST_CITY = 10001;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.refresh)
    SimpleRefreshLayout mSimpleRefreshLayout;
    @BindView(R2.id.ll_search)
    LinearLayout llSearch;
    @BindView(R2.id.tv_current_city)
    TextView tvCurrentCity;
    private SelectShopAdapter mAdapter;

    private int mCityId;
    @Autowired()
    int shopType;
    @Autowired()
    double mLat;
    @Autowired()
    double mLon;
    @Autowired()
    String cityName;

    private int mPage;
    private int countPage;

    private GeoCoder geoCoder;
    private double latLatitude;
    private double lonLongitude;


    @Override
    protected int setLayout() {
        return R.layout.rv_act_shop_select;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        if (shopType == 1) {
            titleView.setTitle("选择取车公司");
        } else if (shopType == 2) {
            titleView.setTitle("选择还车公司");
        }
        titleView.setImageResource(R.id.iv_title_left, R.drawable.rv_common_icon_back_dark);
        Drawable drawable = getResources().getDrawable(R.drawable.icon_position);
        drawable.setBounds(0, 0, DisplayUtil.dip2px(this, 12), DisplayUtil.dip2px(this, 15));
        tvCurrentCity.setCompoundDrawables(drawable, null, null, null);
        tvCurrentCity.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(cityName)) {
            tvCurrentCity.setText(cityName);
        }
        getCityId();
        mAdapter = new SelectShopAdapter();
        mAdapter.setOnLoadMoreListener(this, recyclerView);
        mAdapter.setPosition(mLat, mLon);
        mSimpleRefreshLayout.setHeaderView(new SimpleRefreshView(this));
        mSimpleRefreshLayout.setOnSimpleRefreshListener(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        recyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent();
                intent.putExtra("location", cityName);
                intent.putExtra("type", shopType);
                intent.putExtra("id", mAdapter.getItem(position).getAddrCity());
                intent.putExtra("company", mAdapter.getItem(position).getName());
                intent.putExtra("company_id", mAdapter.getItem(position).getId());
                intent.putExtra("address", mAdapter.getItem(position).getAddrDetail());
                intent.putExtra("latitude", latLatitude);
                intent.putExtra("longitude", lonLongitude);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        llSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到城市选择界面
                ARouter.getInstance()
                        .build(Constance.ACTIVITY_URL_CITYLIST)
                        .withInt("mCityType", 2)
                        .withString("mNowCity", cityName)
                        .navigation(SelectShopActivity.this, TYPE_REQUEST_CITY);
            }
        });
        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 = result.getLocation().latitude;
                    lonLongitude = result.getLocation().longitude;
                }
                //获取地理编码结果
            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    //没有找到检索结果
                } else {
                    latLatitude = result.getLocation().latitude;
                    lonLongitude = result.getLocation().longitude;
                }
            }
        });
    }


    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        onRefresh();
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        if (requestType == 0) {
            ShopListBean bean = (ShopListBean) result;
            if (mPage == 1) {
                mSimpleRefreshLayout.onRefreshComplete();
                if (bean != null && bean.getData() != null && bean.getData().getData() != null && bean.getData().getData().size() > 0) {
                    processData((ShopListBean) result);
                } else {
                    mAdapter.getData().clear();
                    mAdapter.setEmptyView(getEmptyView(recyclerView, -1, "暂无分公司，请换个城市试试！"));
                    mAdapter.notifyDataSetChanged();
                    mAdapter.loadMoreComplete();
                }
            } else {
                mAdapter.addData(bean.getData().getData());
                mAdapter.loadMoreComplete();
            }

        }
    }

    /**
     * 获取通用空布局
     *
     * @param mRecyclerView
     * @param imageId
     * @param empty
     * @return
     */
    protected View getEmptyView(RecyclerView mRecyclerView, final int imageId, final String empty) {
        return getHelperView(mRecyclerView, R.layout.select_shop_empty, new OnViewHolder() {
            @Override
            public void helper(ViewHolder helper) {
                if (imageId != -1) {
                    helper.setImageResource(com.ruiwenliu.wrapper.R.id.iv_flag, imageId);
                }
                helper.setText(com.ruiwenliu.wrapper.R.id.tv_tip, empty);


            }
        });
    }

    @Override
    public void onRefresh() {
        mPage = 1;
        getShopList(mPage);
    }

    @Override
    public void onLoadMoreRequested() {

        if (mPage > countPage) {
            mAdapter.loadMoreEnd();
        } else {
            mPage++;
            getShopList(mPage);
        }
    }

    /**
     * 获取门店列表
     */
    private void getShopList(int page) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("page", page);
        map.put("limit", 10);
        if (mCityId == 0) {
            mCityId = 441900;
        }
        map.put("addrCity", mCityId);
//        if (mLat > 0) {
//            map.put("lat", mLat);
//            map.put("lon", mLon);
//        }
        mPresenter.getData(RvFrameConfig.VEHICLE_POST, 0, ApiConfig.HTTP_URL_SHOP_LIST, ShopListBean.class, map, page == 1 ? true : false);
    }

    /******
     * 获取城市id
     */
    private void getCityId() {
        if (TextUtils.isEmpty(cityName)) return;
        String json = UtilsManager.getInstance().getJson(this, "city.json");
        CityPickerBean bean = new Gson().fromJson(json, CityPickerBean.class);
        for (CityPickerBean.CityBean cityBean : bean.getCity()) {
            for (ListsBean lsBean : cityBean.getLists()) {
                if (cityName.equals(lsBean.getName())) {
                    mCityId = lsBean.getId();
                    return;
                }
            }
        }
    }

    private void processData(ShopListBean bean) {
        countPage = bean.getData().getTotalPage();
        mAdapter.setNewData(bean.getData().getData());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TYPE_REQUEST_CITY && data != null) {
            cityName = data.getStringExtra("location");
            geoCoder.geocode(new GeoCodeOption()
                    .city(cityName)
                    .address(cityName));
            mCityId = data.getIntExtra("id", 0);
            if (!TextUtils.isEmpty(cityName)) {
                tvCurrentCity.setText(cityName);
            }
//            getIntent().putExtra("type", mCityType);
            mPage = 1;
            getShopList(mPage);
        }
    }

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