package com.tofly.ghrq_route.common.ui.activity;

import android.content.Intent;
import android.os.Bundle;

import androidx.viewpager.widget.ViewPager;

import android.text.format.DateUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.HeaderViewListAdapter;
import android.widget.ListView;

import com.google.android.material.tabs.TabLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.common.ui.adapter.DangerPageAdapter;
import com.tofly.ghrq_route.common.ui.adapter.ReportedAdapter;
import com.tofly.ghrq_route.module.trouble.TroubleTool;
import com.tofly.ghrq_route.module.trouble.controller.TroubleCallBack;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.ghrq_route.common.util.EventBusUtil;

import org.greenrobot.eventbus.Subscribe;

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

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * TODO 2016.08.2  需要刷新才能看见已上报的隐患，改为跳转后获得上报隐患数据并显示
 * Created by zombiexq on 2016/6/28.
 */
public class UiReported extends BaseUi {
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.reported_viewpager)
    ViewPager reportedViewpager;

    private ListView listviewSelected;
    private PullToRefreshListView mPullToRefreshListViewSelected;
    private List<TroubleBean> listTroublesUploaded;
    private ReportedAdapter uploadedTroublesAdapter;
    private List<TroubleBean> listTroublesSaved;
    private ReportedAdapter savedTroublesAdapter;
    private AdapterView.OnItemClickListener mOnItemClickListener;
    private PullToRefreshBase.OnRefreshListener2<ListView> mOnPullRefreshListener;
    private TroubleTool troubleTool;

    private int pageindex = 1;
    private boolean bHasMoreData = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ui_reported);
        ButterKnife.bind(this);

        initView();
        initData();
        initListener();

        EventBusUtil.register(this);
    }

    @Subscribe
    public void onMessageEvent(UiReportedDetail.ReportDetailMessageEvent messageEvent){
        if (messageEvent.message.equals(UiReportedDetail.REPORT_DETAIL_UPLOADED)){
            finish();
        }
    }

    @Subscribe
    public void onMessageEvent(UiReportedClear.ReportClearMessageEvent messageEvent){
        if (messageEvent.message.equals(UiReportedClear.REPORT_CLEAR_UPLOADED)){
            finish();
        }
    }

    private void initView() {
        initTabLayout();
    }

    private void initTabLayout() {
        String[] tabTitle = getResources().getStringArray(R.array.report_tab_title);
        List<String> labelList = Arrays.asList(tabTitle);

        DangerPageAdapter pageAdapter = new DangerPageAdapter(this, labelList);
        reportedViewpager.setAdapter(pageAdapter);
        tabLayout.setupWithViewPager(reportedViewpager);
        for (int i = 0; i < pageAdapter.getCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            if (tab != null)
                tab.setText(tabTitle[i]);
        }
    }

    private void initData() {
        troubleTool = TroubleTool.getInstance();

        int index = reportedViewpager.getCurrentItem();
        DangerPageAdapter pagerAdapter = (DangerPageAdapter) reportedViewpager.getAdapter();
        mPullToRefreshListViewSelected = pagerAdapter.getPullRefreshView(index);
        listviewSelected = mPullToRefreshListViewSelected.getRefreshableView();

        listTroublesUploaded = new ArrayList<>();
        uploadedTroublesAdapter = new ReportedAdapter(this, listTroublesUploaded, false);
        ListView listViewFinished = pagerAdapter.getListView(0);
        listViewFinished.setAdapter(uploadedTroublesAdapter);
        listTroublesSaved = new ArrayList<>();
        savedTroublesAdapter = new ReportedAdapter(this, listTroublesSaved, false);
        ListView listViewSaved = pagerAdapter.getListView(1);
        listViewSaved.setAdapter(savedTroublesAdapter);
    }

    private void initListener() {
        reportedViewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                DangerPageAdapter pagerAdapter = (DangerPageAdapter) reportedViewpager.getAdapter();
                mPullToRefreshListViewSelected = pagerAdapter.getPullRefreshView(position);
                if (position == 1){
                    mPullToRefreshListViewSelected.setMode(PullToRefreshBase.Mode.DISABLED);
                }else {
                    mPullToRefreshListViewSelected.setMode(PullToRefreshBase.Mode.BOTH);
                    mPullToRefreshListViewSelected.setOnRefreshListener(mOnPullRefreshListener);
                }
                listviewSelected = mPullToRefreshListViewSelected.getRefreshableView();
                listviewSelected.setOnItemClickListener(mOnItemClickListener);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mOnItemClickListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TroubleBean troubleBean = getSelectedTrouble(position);
                if (troubleBean != null) {
                    Intent intent = new Intent();
                    intent.setClass(UiReported.this, UiReportedDetail.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("trouble", troubleBean);
                    bundle.putInt("position", position);
                    bundle.putString("title", getString(R.string.reported_detail));
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            }
        };

        if (listviewSelected != null)
            listviewSelected.setOnItemClickListener(mOnItemClickListener);

        mPullToRefreshListViewSelected.setMode(PullToRefreshBase.Mode.BOTH);
        //mPullToRefreshListViewSelected.setRefreshing();
        mOnPullRefreshListener = new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                pullUpRefresh();
            }

            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pullDownRefresh();
            }
        };

        if (mPullToRefreshListViewSelected != null) {
            mPullToRefreshListViewSelected.setOnRefreshListener(mOnPullRefreshListener);

            mPullToRefreshListViewSelected.setRefreshing();
        }
        //pullDownRefresh();
    }

    private void pullDownRefresh(){
        String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
                DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
        mPullToRefreshListViewSelected.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        pageindex = 1;
        bHasMoreData = true;
        getSavedTroubles();
        getUploadTroubles();
    }

    private void pullUpRefresh(){
        if (bHasMoreData){
            String label = getString(R.string.reported_pull_up_hint);
            mPullToRefreshListViewSelected.getLoadingLayoutProxy().setLastUpdatedLabel(label);
            pageindex++;
            getUploadTroubles();
        }
        else {
            String label = getString(R.string.reported_pull_empty_hint);
            mPullToRefreshListViewSelected.getLoadingLayoutProxy().setLastUpdatedLabel(label);
            mPullToRefreshListViewSelected.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mPullToRefreshListViewSelected.onRefreshComplete();
                }
            }, 200);
        }
    }

    private void stopRefresh(){
        mPullToRefreshListViewSelected.postDelayed(new Runnable() {
            @Override
            public void run() {
                mPullToRefreshListViewSelected.onRefreshComplete();
            }
        }, 500);
    }

    /*获取不同状态的Trouble,放在相应的Listview*/
    private void resortTroubles() {
        uploadedTroublesAdapter.setData(listTroublesUploaded);
        savedTroublesAdapter.setData(listTroublesSaved);
    }

    private void getUploadTroubles(){
        troubleTool.getUploadTroubles(this, -1, "", pageindex, new TroubleCallBack(){
            @Override
            public void onGetTroubleList(boolean isSuccess, int errorCode, String errMsg, List<TroubleBean> troubleBeanList, int total) {
                super.onGetTroubleList(isSuccess, errorCode, errMsg, troubleBeanList, total);
                stopRefresh();
                if (isSuccess && troubleBeanList != null){
                    if (pageindex == 1){
                        listTroublesUploaded.clear();
                    }
                    if (troubleBeanList.size() > 0){
                        listTroublesUploaded.addAll(troubleBeanList);
                    }else{
                        bHasMoreData = false;
                    }
                    resortTroubles();
                }else {
                    resortTroubles();
                }
            }
        });
    }

    private void getSavedTroubles(){
        listTroublesSaved = troubleTool.getSavedTroubles();
    }

    /*当前页面所选中的Trouble*/
    private TroubleBean getSelectedTrouble(int position) {
        TroubleBean troubleBean = null;
        int index = reportedViewpager.getCurrentItem();

        DangerPageAdapter pagerAdapter = (DangerPageAdapter) reportedViewpager.getAdapter();
        ListView listView = pagerAdapter.getListView(index);
        if (listView != null) {
            HeaderViewListAdapter headerViewListAdapter = (HeaderViewListAdapter) listView.getAdapter();
            ReportedAdapter adapter = (ReportedAdapter) headerViewListAdapter.getWrappedAdapter();
            troubleBean = (TroubleBean) adapter.getItem(position);
        }

        return troubleBean;
    }

    @Override
    protected void onStop() {
        BaseApp.cancelRequest(getClass().getName());
        super.onStop();
    }

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