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

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.frame.base.url.Constance;
import com.google.gson.Gson;
import com.ruiwenliu.wrapper.base.BaseBean;

import com.ruiwenliu.wrapper.util.LocationManager;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.utils.LogUtil;
import com.rv.home.R;
import com.rv.home.R2;
import com.rv.home.rv.module.basic.BaseStatusActivity;
import com.rv.home.rv.module.basic.bean.MultiItemBean;
import com.rv.home.rv.module.basic.presenter.CommonPresenter;
import com.rv.home.rv.module.ui.main.home.adapter.CityListAdapter;
import com.rv.home.rv.module.ui.main.home.bean.CityHeadBean;
import com.rv.home.rv.module.ui.main.home.bean.CityPickerBean;
import com.rv.home.rv.module.ui.main.home.bean.HotCityBean;
import com.rv.home.rv.module.ui.main.home.bean.HotCityListBean;
import com.rv.home.rv.module.ui.main.home.bean.ListsBean;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

@Route(path = Constance.ACTIVITY_URL_CITYLIST)
public class CityListActivity extends BaseStatusActivity<CommonPresenter> {

    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.edt_search)
    EditText edtSearch;
    @Autowired
    int mCityType;
    @Autowired
    String mNowCity;
    @Autowired
    int mCityId;
    private Disposable mDisposable = null;
    private CityListAdapter cityListAdapter;
    private LocationManager locationManager;

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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle(mActivity.getString(R.string.rv_city_list));
        titleView.setImageResource(R.id.iv_title_left, R.drawable.rv_common_icon_back_white);
        cityListAdapter = new CityListAdapter(new ArrayList<MultiItemBean>(), listener, mNowCity);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 6));
        recyclerView.setAdapter(cityListAdapter);
        cityListAdapter.setSpanSizeLookup(new BaseQuickAdapter.SpanSizeLookup() {
            @Override
            public int getSpanSize(GridLayoutManager gridLayoutManager, int position) {
                return cityListAdapter.getData().get(position).getSpanSize();
            }
        });
        recyclerView.setBackgroundColor(ContextCompat.getColor(this, R.color.colorLine));
        cityListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MultiItemBean bean = cityListAdapter.getItem(position);
                if (bean instanceof ListsBean) {
                    ListsBean cityBean = (ListsBean) bean;
                    sendData(cityBean.getName(), cityBean.getId());

                } else if (bean instanceof HotCityBean) {
                    HotCityBean hotCityBean = (HotCityBean) bean;
                    if (hotCityBean.hotCityId == 0) {
                        filterData(hotCityBean.hotCityName, cityListAdapter.getData());
                        return;
                    }
                    sendData(hotCityBean.hotCityName, hotCityBean.hotCityId);
                }
            }
        });
        setData(null);
        edtSearch.addTextChangedListener(watcher);
    }

    private void setData(String searchCity) {
        List<MultiItemBean> list = getListData(searchCity);
        cityListAdapter.setNewData(list);
    }

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

    @Override
    public void onShowResult(int requestType, BaseBean result) {

    }

    private List<HotCityBean> getHotCitys() {
        List<HotCityBean> lists = new ArrayList<>();
        lists.add(new HotCityBean("北京市", 110100));
        lists.add(new HotCityBean("上海市", 310100));
        lists.add(new HotCityBean("东莞市", 441900));
        lists.add(new HotCityBean("深圳市", 440300));
        lists.add(new HotCityBean("广州市", 440100));
        lists.add(new HotCityBean("杭州市", 330100));
        lists.add(new HotCityBean("南昌市", 360100));
        lists.add(new HotCityBean("西安市", 610100));
        return lists;
    }

    private List<MultiItemBean> getListData(String searchCity) {
        List<MultiItemBean> list = new ArrayList<>();
        list.add(new HotCityListBean(getHotCitys()));
        String json = getJson(this, "city.json");
        CityPickerBean bean = new Gson().fromJson(json, CityPickerBean.class);
        for (CityPickerBean.CityBean cityBean : bean.getCity()) {
            if (TextUtils.isEmpty(searchCity)) {
                list.add(new CityHeadBean(cityBean.getTitle()));
            }
            for (ListsBean lsBean : cityBean.getLists()) {
                if (!TextUtils.isEmpty(searchCity)) {
                    if (lsBean.getName().contains(searchCity)) {
                        list.add(lsBean);
                    }
                } else {
                    list.add(lsBean);
                }
            }
        }
        return list;
    }

    /**
     * 读取本地文件的方法
     *
     * @param context
     * @param fileName
     * @return
     */
    private String getJson(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    /**
     * 传送数据
     */
    private void sendData(String name, int id) {
        getIntent().putExtra("location", name);
        getIntent().putExtra("id", id);
        getIntent().putExtra("type", mCityType);

        setResult(RESULT_OK, getIntent());
        finish();
    }

    @Override
    public void onDestroy() {
        if (mDisposable != null) {
            mDisposable.dispose();
            mDisposable = null;
        }

        if (locationManager != null) {
            locationManager.onDestroy();
        }
        super.onDestroy();
    }

    public void filterData(final String city, final List<MultiItemBean> list) {

        mDisposable = Flowable.fromIterable(list).doOnNext(new Consumer<MultiItemBean>() {
            @Override
            public void accept(MultiItemBean multiItemBean) throws Exception {

            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<MultiItemBean>() {
            @Override
            public void accept(MultiItemBean multiItemBean) throws Exception {
                if (multiItemBean instanceof ListsBean) {
                    ListsBean bean = (ListsBean) multiItemBean;
                    if (bean.getName().equals(city)) {
                        sendData(city, bean.getId());
                    }
                }
            }
        });
    }

    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            LogUtil.d("CharSequence==", s.toString());
            setData(s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    private CityListAdapter.GridClickListener listener = new CityListAdapter.GridClickListener() {
        @Override
        public void click(HotCityBean hotCityBean) {
            sendData(hotCityBean.hotCityName, hotCityBean.hotCityId);
        }

        @Override
        public void reRelocation() {
            createLoadingDialog().show();
            if (locationManager == null) {
                locationManager = new LocationManager(getApplicationContext());
            }
            locationManager.getLocationDetail(new BDAbstractLocationListener() {
                @Override
                public void onReceiveLocation(BDLocation location) {
                    createLoadingDialog().dismiss();
                    mNowCity = location.getCity();
                    cityListAdapter.setCurrentCity(mNowCity);
                    locationManager.stopLocation();
                }
            });
        }
    };
}


