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

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

import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.lcp.arecyclerview.widget.ARecycleView;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.module.job.JobTool;
import com.tofly.ghrq_route.module.job.controller.JobCallBack;
import com.tofly.ghrq_route.module.job.domain.JobBean;
import com.tofly.ghrq_route.module.job.domain.MyJobEvent;
import com.tofly.ghrq_route.common.ui.adapter.JobListAdapter;
import com.tofly.ghrq_route.common.ui.adapter.JobListPageAdapter;
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;


public class UiJobList extends BaseUi {
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.view_pager)
    ViewPager viewPager;

    private int mSelectState = 0;

    private ARecycleView recyclerView;

    private JobListPageAdapter pageAdapter;

    private JobListAdapter jobListAdapter;

    private JobTool jobTool;
    private List<String> labelList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.ui_job_list);
        ButterKnife.bind(this);

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

        EventBusUtil.register(this);
    }

    private void initView() {
        initTabLayout();
    }

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

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

    private void initData() {
        jobTool = JobTool.getInstance();

        ArrayList<JobBean> list = new ArrayList<>();
        jobListAdapter = new JobListAdapter(this, list);

        //getOnlineJobList();
        recyclerView = pageAdapter.getRecycleView(mSelectState);
        if (recyclerView != null) {
            recyclerView.setAdapter(jobListAdapter);
            recyclerView.setOnRefreshListener(UiJobList.this::getOnlineJobList);
            getOnlineJobList();
        }
    }

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

            }

            @Override
            public void onPageSelected(int position) {
                recyclerView = pageAdapter.getRecycleView(position);
                mSelectState = position;
                if (recyclerView != null) {
                    jobListAdapter.clear();
                    recyclerView.setAdapter(jobListAdapter);
                    recyclerView.setOnRefreshListener(UiJobList.this::getOnlineJobList);
                    Handler handler = new Handler();
                    handler.postDelayed(() -> getOnlineJobList(), 100);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });



/*        recyclerView.setOnLoadMoreListener(new ARecycleView.OnLoadMoreListener() {
            @Override
            public void loadMore() {
                pageindex++;
                getLocalPlanList();
            }
        });*/

        if (jobListAdapter != null) {
            jobListAdapter.setOnItemClickListener((view, position) -> {
                JobBean jobBean = jobListAdapter.getItem(position);
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable(JobBean.JOB_BEAN_KEY, jobBean);
                bundle.putSerializable(JobBean.JOB_POSITION_KEY, position);
                intent.setClass(UiJobList.this, UiJobDetail.class);
                intent.putExtras(bundle);
                startActivity(intent);
            });
        }
    }

    @Subscribe
    public void onMessageEvent(MyJobEvent event) {
        if (MyJobEvent.MY_JOB_LIST_NEED_REFRESH.equals(event.message)) {
            getOnlineJobList();
        } else if (MyJobEvent.MY_JOB_LIST_NEW_JOB.equals(event.message)) {
            String title = "我的工单";
            String content = "你有一条新的工单，请查看。";
            showAlertDialog(title, content, (dialog, which) -> getOnlineJobList());
        } else if (MyJobEvent.MY_JOB_LIST_JOB_HAS_READ.equals(event.message)) {
            if (event.arg0 != null) {
                int position = (int) event.arg0;
                if (jobListAdapter != null) {
                    jobListAdapter.notifyItemChanged(position);
                }
            }
        }
    }

    private void startRefreshing() {
        recyclerView.setRefreshing(true);
    }

    private void stopRefreshing() {
        Handler handler = new Handler();
        handler.postDelayed(() -> {
            recyclerView.setRefreshing(false);
            recyclerView.hideMoreProgress();
        }, 500);
    }

    private void getOnlineJobList() {
        startRefreshing();
        jobTool.getJobListOnline(this, new JobCallBack() {
            @Override
            public void onGetJobList(boolean isSuccess, int errorCode, String errMsg, List<JobBean> jobList, int total) {
                super.onGetJobList(isSuccess, errorCode, errMsg, jobList, total);
                stopRefreshing();
                /*加载本地保存的计划*/
                getLocalJobList();
            }
        });
    }

    private void getLocalJobList() {
        int job_state = mSelectState;
        jobTool.getJobListOffline(this, job_state, new JobCallBack() {
            @Override
            public void onGetJobList(boolean isSuccess, int errorCode, String errMsg, List<JobBean> jobList, int total) {
                super.onGetJobList(isSuccess, errorCode, errMsg, jobList, total);
                if (isSuccess) {
                    recyclerView.setTotal(total);
                    jobListAdapter.clear();
                    if (jobList != null) {
                        jobListAdapter.setData(jobList, mSelectState);
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBusUtil.unregister(this);
    }
}
