package jk.cloud.app.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

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

import butterknife.BindView;
import io.github.yavski.fabspeeddial.FabSpeedDial;
import io.github.yavski.fabspeeddial.SimpleMenuListenerAdapter;
import jk.cloud.app.R;
import jk.cloud.app.model.Refresh;
import jk.cloud.app.model.domain.Opportunity;
import jk.cloud.app.presenter.OpportunityContract;
import jk.cloud.app.presenter.OpportunityPresenter;
import jk.cloud.app.util.WrapContentLinearLayoutManager;
import jk.cloud.app.view.adapter.OpportunityAdapter;

/**
 * 报备商机列表
 */
public class OpportunityListActivity extends SwipeBackAppCompatActivity
        implements OpportunityContract.View {

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.txtNoData)
    TextView txtNoData;
    @BindView(R.id.fab_speed)
    FabSpeedDial fabSpeed;

    private OpportunityContract.Presenter presenter;
    private OpportunityAdapter adapter;
    private List<Opportunity> mList = new ArrayList<>();
    private HashMap<String, String> paraMap = new HashMap<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);//注册事件
        }
    }

    @Override
    protected int getPageLayoutID() {
        return R.layout.fragment_page_opportunity;
    }

    @Override
    protected void initData() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            paraMap.put("companyId", bundle.getString("CompanyId"));
            if (mToolbar != null) {
                setSupportActionBar(mToolbar);
                ActionBar mActionBar = getSupportActionBar();
                if (mActionBar != null) {
                    mActionBar.setDisplayHomeAsUpEnabled(true);
                    mActionBar.setTitle("商机报备 -> " + bundle.getString("CompanyShortName"));
                }
            }
        }
        new OpportunityPresenter(this);
        presenter.getData(1, SIZE, paraMap);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        showLoading();
        adapter = new OpportunityAdapter(OpportunityListActivity.this, mList);
        linearLayoutManager = new WrapContentLinearLayoutManager(OpportunityListActivity.this, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setAdapter(adapter);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        mSwipeRefreshLayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48, getResources().getDisplayMetrics()));
        mSwipeRefreshLayout.setRefreshing(true);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && (lastVisibleItem + 1 == adapter.getItemCount()) && hasMore) {
                    mSwipeRefreshLayout.setRefreshing(true);
                    presenter.getData(mOffset, SIZE, paraMap);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager())
                        .findLastVisibleItemPosition();
            }
        });

        mSwipeRefreshLayout.setOnRefreshListener(() -> {
            refresh = true;
            paraMap.remove("keyWord");
            presenter.getData(1, SIZE, paraMap);
        });
    }

    private static final int ACTION_NEW = 0;
    private static final int ACTION_SEARCH = 1;

    @Override
    protected void initViewListener() {
        super.initViewListener();
        fabSpeed.setMenuListener(new SimpleMenuListenerAdapter() {

            @Override
            public boolean onMenuItemSelected(MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.action_new:
                        startActivityForResult(new Intent(OpportunityListActivity.this,
                                NewOpportunityActivity.class), ACTION_NEW);
                        break;
                    case R.id.action_search:
                        startActivityForResult(new Intent(OpportunityListActivity.this,
                                SearchActivity.class), ACTION_SEARCH);
                        break;
                }
                return super.onMenuItemSelected(menuItem);
            }
        });
    }

    private SearchView mSearchView;

    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        /*简单查询*/
        final MenuItem item = menu.findItem(R.id.action_search);
        mSearchView = (SearchView) MenuItemCompat.getActionView(item);

        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                paraMap.put("keyWord", query);
                showLoading();
                refresh = true;
                presenter.getData(1, SIZE, paraMap);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

                return false;
            }
        });
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case ACTION_NEW:/*新增*/
                showLoading();
                refresh = true;
                presenter.getData(1, SIZE, paraMap);
                break;
            case ACTION_SEARCH:/*高级查询*/
                if (data != null) {
                    String ParameterJson = data.getStringExtra("ParameterJson");
                    if (!TextUtils.isEmpty(ParameterJson)) {
                        paraMap.put("ParameterJson", data.getStringExtra("ParameterJson"));
                        showLoading();
                        refresh = true;
                        presenter.getData(1, SIZE, paraMap);
                    }
                }
                break;
            default:
        }
    }

    private static final int REFRESH = 200;

    @Subscribe
    public void onEvent(Refresh event) {
        if (event.status == REFRESH) {
            showLoading();
            //获取当前项的页码,用于更新被选中的纪录
            int offset = 1;
            int position = adapter.position() + 1;
            if (position < SIZE) {
                offset = 1;
            } else if (position % SIZE == 0) {
                offset = position / SIZE;
            } else {
                offset = ((int) Math.ceil(position / SIZE)) + 1;
            }
            presenter.getData(offset, SIZE, paraMap);
        }
    }

    @Override
    public void setPresenter(OpportunityContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void setData(List<Opportunity> dataList) {
        dismissLoading();
        if (adapter.position() == 0) {
            if (refresh) {
                refresh = false;
                mOffset = 1;
                mList.clear();
                adapter.notifyDataSetChanged();
            }
            if (dataList.size() < 1 && hasMore) {
                hasMore = false;
                Snackbar.make(mToolbar, "没有更多数据了", Snackbar.LENGTH_LONG).show();
            } else {
                hasMore = true;
                int pos = mList.size() - 1;
                mList.addAll(dataList);
                adapter.notifyItemRangeChanged(pos, dataList.size());
                mOffset++;
            }
            if (adapter.getItemCount() == 0) {
                txtNoData.setVisibility(View.VISIBLE);
            } else {
                txtNoData.setVisibility(View.GONE);
            }
            Log.i(TAG, "setData1: " + adapter.position());
        } else {
            /*只是局部刷新*/
            Opportunity opportunity = mList.get(adapter.position());
            String reportid = opportunity.getReportid();
            for (int i = 0; i < dataList.size(); i++) {
                if (reportid.contains(dataList.get(i).getReportid())) {
                    mList.set(adapter.position(), dataList.get(i));
                }
            }
            adapter.notifyItemChanged(adapter.position());
        }
    }

    @Override
    public void setError(String msg) {
        dismissLoading();
        if (refresh) {
            refresh = false;
            Toast.makeText(this, "刷新失败", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "获取数据失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void showLoading() {
        mSwipeRefreshLayout.setRefreshing(true);
    }

    @Override
    public void dismissLoading() {
        mSwipeRefreshLayout.setRefreshing(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}