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.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
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.rv.home.R;
import com.rv.home.R2;
import com.rv.home.rv.module.basic.BaseStatusActivity;
import com.ruiwenliu.wrapper.weight.SideLetterBar;
import com.ruiwenliu.wrapper.weight.TitleView;
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.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.tv_letter_overlay)
    TextView tvLetterOverlay;
    @BindView(R2.id.side_letter_bar)
    SideLetterBar sideLetterBar;

    @Autowired
    int mCityType;
    @Autowired
    String mNowCity;
    @Autowired
    int mCityId;
    //    private Map<String,String> mapSave;
    private Disposable mDisposable = null;

//    public static Intent getIntent(Context context, int type, String city, int id) {
//        return new Intent(context, CityListActivity.class).putExtra("type", type).putExtra("location", city).putExtra("id", id);
//    }

    @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));
//        String  jsonCity= UtilsManager.getInstance(mActivity).getSPStringCode("city_json", "city");
//        if(!TextUtils.isEmpty(jsonCity)){
//            Log.d("===tag===",jsonCity);
//        }
//        mCityType = intent.getIntExtra("type", 1);
//        mNowCity = intent.getStringExtra("location");
//        mCityId = intent.getIntExtra("id", 1);
        final List<MultiItemBean> list = getListData(mNowCity);
        List<MultiItemBean> lists = new ArrayList<>();
        final CityListAdapter cityListAdapter = new CityListAdapter(lists);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 6));
        recyclerView.setAdapter(cityListAdapter);
        recyclerView.setBackgroundColor(ContextCompat.getColor(this, R.color.colorLine));
        /**
         * 设置每个Item的横排显示数量
         *  注意：======对应GridLayoutManager设置
         */
        cityListAdapter.setSpanSizeLookup(new BaseQuickAdapter.SpanSizeLookup() {
            @Override
            public int getSpanSize(GridLayoutManager gridLayoutManager, int position) {
                return list.get(position).getSpanSize();
            }
        });
        cityListAdapter.setNewData(list);
        sideLetterBar.setOverlay(tvLetterOverlay);
        sideLetterBar.setOnLetterChangedListener(new SideLetterBar.OnLetterChangedListener() {
            @Override
            public void onLetterChanged(String letter) {
                int position = cityListAdapter.getSelectIndex(letter);
                if (position == -1) {
                    return;
                }
                recyclerView.scrollToPosition(position);

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

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

    }

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

    }

    private List<MultiItemBean> getListData(String now_city) {
        List<MultiItemBean> list = new ArrayList<>();
        if (!TextUtils.isEmpty(now_city)) {
            list.add(new HotCityBean(now_city, mCityId));
            list.add(new CityHeadBean("当前城市/已访问城市"));
        }
        list.add(new CityHeadBean("热门城市"));
        list.add(new HotCityBean("北京市", 110100));
        list.add(new HotCityBean("上海市", 310100));
        list.add(new HotCityBean("东莞市", 441900));
        list.add(new HotCityBean("深圳市", 440300));
        list.add(new HotCityBean("广州市", 440100));
        list.add(new HotCityBean("杭州市", 330100));
        list.add(new HotCityBean("南昌市", 360100));
        list.add(new HotCityBean("西安市", 610100));
        String json = getJson(this, "city.json");
        CityPickerBean bean = new Gson().fromJson(json, CityPickerBean.class);

        for (CityPickerBean.CityBean cityBean : bean.getCity()) {
            list.add(new CityHeadBean(cityBean.getTitle()));
            for (ListsBean lsBean : cityBean.getLists()) {
                list.add(lsBean);
            }
        }


        return list;
    }


    /**
     * 获取拼音的首字母（大写）
     *
     * @param pinyin
     * @return
     */
    public String getFirstLetter(final String pinyin) {
        if (TextUtils.isEmpty(pinyin)) return "";
        String c = pinyin.substring(0, 1);
        Pattern pattern = Pattern.compile("^[A-Za-z]+$");
        if (pattern.matcher(c).matches()) {
            return c.toUpperCase();
        }
        return "";
    }

    /**
     * 读取本地文件的方法
     *
     * @param context
     * @param fileName
     * @return
     */
    public 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) {
//        if(mapSave==null){
//            mapSave=new LinkedHashMap<>();
//        }
//        mapSave.put(name,name);
        getIntent().putExtra("location", name);
        getIntent().putExtra("id", id);
        getIntent().putExtra("type", mCityType);

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

    @Override
    public void onDestroy() {
//        if(mapSave!=null){
//            UtilsManager.getInstance(mActivity).setSharePreferencesSave("city_json").putString("city", JSON.toJSONString(mapSave)).commit();
//            UtilsManager.getInstance(mActivity).setShNull();
//        }
        if (mDisposable != null) {
            mDisposable.dispose();
            mDisposable = null;
        }
        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());
                    }
                }
            }
        });
    }


}


