package com.ycgis.macall.personalcenter.v.activity.travel;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import androidx.appcompat.widget.PopupMenu;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.JsonObject;

import com.rs.macall.androidx.basemodel.base.BaseViewBindActivity;
import com.rs.macall.androidx.basemodel.callback.CustomClickListener;
import com.rs.macall.androidx.basemodel.callback.SimpleListClickListener;
import com.rs.macall.androidx.basemodel.decoration.MyDividerItemDecoration;
import com.rs.macall.androidx.basemodel.utils.LogUtils;
import com.rs.macall.androidx.basemodel.utils.StringUtil;
import com.rs.macall.androidx.basemodel.utils.ToastUtil;
import com.rs.macall.androidx.basemodel.utils.TypConversion;

import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.databinding.ActivityTravelAssistantBinding;
import com.ycgis.macall.personalcenter.m.adapterbean.TravelCityBean;
import com.ycgis.macall.personalcenter.p.app.RuanseeApplication;
import com.ycgis.macall.personalcenter.p.callback.BaseRequestCallback;
import com.ycgis.macall.personalcenter.p.request.ApiModel;
import com.ycgis.macall.personalcenter.p.request.RetrofitService;
import com.ycgis.macall.personalcenter.v.adapter.TravelAssistantAdapter;
import com.ycgis.macall.personalcenter.v.adapter.TravelSearchListAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

/**
 *
 * 差旅助手
 */
public class TravelAssistantActivity extends BaseViewBindActivity<ActivityTravelAssistantBinding> {
    private TravelAssistantAdapter historyAdapter, popularAdapter;
    private TravelSearchListAdapter searchAdapter;
    private int level = 2;

    @Override
    protected ActivityTravelAssistantBinding getViewBinding() {
        return ActivityTravelAssistantBinding.inflate(getLayoutInflater());
    }

    @Override
    protected boolean isImmersiveStatusBar() {
        return true;
    }

    @Override
    protected void init() {
        GridLayoutManager manager1 = new GridLayoutManager(getContext(), 4);
        GridLayoutManager manager2 = new GridLayoutManager(getContext(), 4);
        viewBinding.travelRvHistory.setLayoutManager(manager1);
        viewBinding.travelRvPopular.setLayoutManager(manager2);
        viewBinding.travelRvApplist.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        MyDividerItemDecoration myDividerItemDecoration = new MyDividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL);
        myDividerItemDecoration.setBottom(true);
        viewBinding.travelRvApplist.addItemDecoration(myDividerItemDecoration);
    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {

    }

    @Override
    protected void start() {
        viewBinding.travelTitle.contentTitle.setText("差旅助手");
        viewBinding.travelTitle.leftImage.setImageDrawable(getDrawable(R.drawable.back_cliener));
        viewBinding.travelTitle.titleleft.setOnClickListener(v -> finish());
        viewBinding.travelTitle.rightText.setText("一般人员▼");
        viewBinding.trvaelSearch.editQuery.setHint("搜索城市 如：北京/bj/beijing");
        viewBinding.trvaelSearch.editQuery.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        viewBinding.trvaelSearch.btnClean.setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                viewBinding.trvaelSearch.editQuery.setText("");
                goneView(viewBinding.travelRvApplist);
            }
        });
        viewBinding.travelTitle.rightText.setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                popup(v);
            }
        });
        viewBinding.trvaelSearch.editQuery.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String searchWord = getEditText(viewBinding.trvaelSearch.editQuery);
                baseShowDialog("正在搜索,请稍后...");
                searchApp(searchWord);
                return true;
            }
            return false;
        });
        viewBinding.trvaelSearch.editQuery.addTextChangedListener(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) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s == null || StringUtil.isNullOrEmpty(s.toString())) {
                    goneView(viewBinding.trvaelSearch.btnClean);
                    return;
                }
                visibleView(viewBinding.trvaelSearch.btnClean);
            }
        });
        baseShowDialog("正在获取数据,请稍后...");
        getDataS();
    }
    //083432  范
    private TravelCityBean getErrorBean(int type, String msg) {
        TravelCityBean bean = new TravelCityBean();
        bean.setBaseType(type);
        bean.setBaseMessage(msg);
        return bean;
    }

    public void popup(View view) {
        PopupMenu popupMenu = new PopupMenu(this, view, Gravity.RIGHT);
        popupMenu.inflate(R.menu.travel_assistant_level);
        popupMenu.show();
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                viewBinding.travelTitle.rightText.setText(item.getTitle()+"▼");
                level = item.getItemId() == R.id.menu_travel_level2?1:2;
                return false;
            }
        });
    }

    private void searchApp(String searchWord) {
        ApiModel.request(RetrofitService.getBaseInstance().getSearchCity(searchWord), new BaseRequestCallback<JsonObject>() {
            @Override
            public void onRequestFailure(String msg) {
                LogUtils.e(TAG, msg);
                baseDismissDialog();
                ToastUtil.centered(getContext(), msg);
            }

            @Override
            public void onRequestSuccess(JsonObject result) {
                //{"code":20041,"data":["北京"],"msg":""}
                LogUtils.w(TAG, result.toString());
                baseDismissDialog();
                List<TravelCityBean> dataList = new ArrayList<>();
                try {
                    JSONObject object = new JSONObject(result.toString());
                    int code = TypConversion.getJsonInt(object, "code", -1);
                    if (code == 20041) {
                        JSONArray data = TypConversion.getJSONArray(object, "data");
                        for (int i = 0; i < data.length(); i++) {
                            String string = data.getString(i);
                            TravelCityBean bean = new TravelCityBean();
                            bean.setBaseType(1);
                            bean.setName(string);
                            dataList.add(bean);
                        }
                        if (dataList.isEmpty()) {
                            TravelCityBean errorBean = getErrorBean(0, "未搜索到该城市，请使用城市全称或全拼进行搜索。");
                            dataList.add(errorBean);
                        }
                        initSearchList(dataList);
                    } else {
                        TravelCityBean errorBean = getErrorBean(-1, TypConversion.getJsonStr(object, "msg"));
                        dataList.add(errorBean);
                        initSearchList(dataList);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    TravelCityBean errorBean = getErrorBean(-1, e.getMessage());
                    dataList.add(errorBean);
                    initSearchList(dataList);
                }
            }
        });

    }

    private void initSearchList(List<TravelCityBean> dataList) {
        visibleView(viewBinding.travelRvApplist);
        if (searchAdapter == null) {
            searchAdapter = new TravelSearchListAdapter(getContext(), dataList);
            viewBinding.travelRvApplist.setAdapter(searchAdapter);
            searchAdapter.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    TravelCityBean dataItem = searchAdapter.getDataItem(pointer);
                    if (dataItem.getBaseType() == 1) {
                        goneView(viewBinding.travelRvApplist);
                        handlerFootData(dataItem);
                    }
                }
            });
        } else {
            searchAdapter.upData(dataList);
        }
    }

    private void getDataS() {
        ApiModel.request("getCity",
                RetrofitService.getBaseInstance().getPopularCity(RuanseeApplication.getUserData().getUserCode()),
                new BaseRequestCallback<JsonObject>() {
                    @Override
                    public void onRequestFailure(String msg) {
                        baseDismissDialog();
                        LogUtils.e(TAG, msg);
                        List<TravelCityBean> dataList = new ArrayList<>();
                        dataList.add(getErrorBean(-1, msg));
                        initPopularData(dataList);
                        initHistoryData(dataList);
                    }


                    @Override
                    public void onRequestSuccess(JsonObject result) {
                        baseDismissDialog();
                        LogUtils.w(TAG, result.toString());
                        try {
                            JSONObject object = new JSONObject(result.toString());
                            int code = TypConversion.getJsonInt(object, "code", -200);
                            if (code == 20041) {
                                JSONObject data = TypConversion.getJSONObject(object, "data");
                                if (data == null) {
                                    return;
                                }
                                JSONArray footCity = TypConversion.getJSONArray(data, "footCity");
                                List<TravelCityBean> footCityList = new ArrayList<>();
                                if (footCity == null) {
                                    footCityList.add(getErrorBean(0, "暂无足迹数据"));
                                } else {
                                    for (int i = 0; i < footCity.length(); i++) {
                                        String string = footCity.getString(i);
                                        if (string == null) continue;
                                        TravelCityBean bean = new TravelCityBean();
                                        bean.setBaseType(1);
                                        bean.setName(string);
                                        footCityList.add(bean);
                                    }
                                }
                                initHistoryData(footCityList);
                                JSONArray popularCity = TypConversion.getJSONArray(data, "popularCity");
                                List<TravelCityBean> popularCityList = new ArrayList<>();
                                if (popularCity == null) {
                                    popularCityList.add(getErrorBean(0, "暂无热门城市推荐"));
                                } else {
                                    for (int i = 0; i < popularCity.length(); i++) {
                                        String string = popularCity.getString(i);
                                        if (string == null) continue;
                                        TravelCityBean bean = new TravelCityBean();
                                        bean.setBaseType(1);
                                        bean.setName(string);
                                        popularCityList.add(bean);
                                    }
                                }
                                initPopularData(popularCityList);
                            } else {
                                List<TravelCityBean> dataList = new ArrayList<>();
                                dataList.add(getErrorBean(-1, TypConversion.getJsonStr(object, "msg")));
                                initPopularData(dataList);
                                initHistoryData(dataList);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            List<TravelCityBean> dataList = new ArrayList<>();
                            dataList.add(getErrorBean(-1, e.getMessage()));
                            initPopularData(dataList);
                            initHistoryData(dataList);
                        }
                    }
                });
    }

    private void initPopularData(List<TravelCityBean> dataList) {
        if (popularAdapter == null) {
            popularAdapter = new TravelAssistantAdapter(getContext(), dataList);
            viewBinding.travelRvPopular.setAdapter(popularAdapter);
            popularAdapter.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    TravelCityBean dataItem = popularAdapter.getDataItem(pointer);
                    if (dataItem.getBaseType() == 1) {
                        handlerFootData(dataItem);
                    }
                }
            });
        } else {
            popularAdapter.upData(dataList);
        }
    }

    private void initHistoryData(List<TravelCityBean> dataList) {
        if (historyAdapter == null) {
            historyAdapter = new TravelAssistantAdapter(getContext(), dataList);
            viewBinding.travelRvHistory.setAdapter(historyAdapter);
            historyAdapter.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    TravelCityBean dataItem = historyAdapter.getDataItem(pointer);
                    if (dataItem.getBaseType() == 1) {
                        handlerFootData(dataItem);
                    }
                }
            });
        } else {
            historyAdapter.upData(dataList);
        }
    }

    private void handlerFootData(TravelCityBean bean) {
        Intent intent = new Intent(getContext(), TravelDetailsActivity.class);
        intent.putExtra("cityName", bean.getName());
        intent.putExtra("level", String.valueOf(level));
        startActivity(intent);
        if (historyAdapter == null) return;
        List<TravelCityBean> data = historyAdapter.getData();
        if (data == null) return;

        int index = -1;
        for (int i = 0; i < data.size(); i++) {
            TravelCityBean beans = data.get(i);
            if (beans.getName().endsWith(bean.getName())) {
                index = i;
                break;
            }
        }
        if (index > -1) {
            historyAdapter.removeItem(index);
        } else {
            if (historyAdapter.getItemCount() >= 12) {
                historyAdapter.removeItem(data.size() - 1);
            }
        }
        historyAdapter.addItem(0, bean);


    }
}