package com.tofly.ghrq_route.module.survey.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
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.survey.SurveyTool;
import com.tofly.ghrq_route.module.survey.controller.SurveyCallBack;
import com.tofly.ghrq_route.module.survey.domain.MySurveyEvent;
import com.tofly.ghrq_route.module.survey.domain.SurveyBean;
import com.tofly.ghrq_route.module.survey.ui.adapter.SurveyAdapter;
import com.tofly.ghrq_route.common.ui.adapter.ListPageAdapter;
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;
import butterknife.OnClick;

@SuppressLint("NonConstantResourceId")
public class UiSurveyList extends BaseUi {
    @BindView(R.id.layout_app_bar)
    AppBarLayout appBarLayout;
    @BindView(R.id.toolbar_layout)
    CollapsingToolbarLayout collapsingToolbarLayout;
    @BindView(R.id.layout_handle_module)
    HorizontalScrollView layoutHandleModule;
    @BindView(R.id.layout_survey_upload_module)
    LinearLayout layoutSurveyUpload;
    @BindView(R.id.main_toolbar)
    Toolbar mainToolbar;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.view_pager)
    ViewPager viewPager;

    private SurveyTool surveyTool;

    private ListPageAdapter pageAdapter;

    private SurveyAdapter surveyAdapter;

    private ARecycleView recyclerView;

    private int mSelectState = 0;

    private int mSelPosition = 0;

    private int pageindex = 1;

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

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

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

        EventBusUtil.register(this);
    }

    private void initView() {
        initTopContent();
        initTabLayout();
    }

    private void initTopContent() {
        // 4.4及以上版本开启
        setTranslucentStatus();
        //setToolbarPadding();

        initAppBar();
    }

    private void initAppBar() {
        appBarLayout.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            if (verticalOffset == 0) {
                if (state != CollapsingToolbarLayoutState.EXPANDED) {
                    collapsingToolbarLayout.setTitle("");//设置title不显示
                    layoutHandleModule.setVisibility(View.VISIBLE);
                    state = CollapsingToolbarLayoutState.EXPANDED;//修改状态标记为展开
                }
            } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                if (state != CollapsingToolbarLayoutState.COLLAPSED) {
                    collapsingToolbarLayout.setTitle("");
                    layoutHandleModule.setVisibility(View.GONE);
                    state = CollapsingToolbarLayoutState.COLLAPSED;//修改状态标记为折叠
                }
            } else {
                if (state != CollapsingToolbarLayoutState.INTERNEDIATE) {
                    if (state == CollapsingToolbarLayoutState.COLLAPSED) {
                        collapsingToolbarLayout.setTitle("");//设置title不显示
                        layoutHandleModule.setVisibility(View.VISIBLE);
                    }
                    state = CollapsingToolbarLayoutState.INTERNEDIATE;//修改状态标记为中间
                }
            }
        });
    }

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

        pageAdapter = new ListPageAdapter(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() {
        surveyTool = SurveyTool.getInstance();

        ArrayList<SurveyBean> list = new ArrayList<>();
        surveyAdapter = new SurveyAdapter(this, list);

        recyclerView = pageAdapter.getRecycleView(mSelPosition);
        if (recyclerView != null) {
            recyclerView.setAdapter(surveyAdapter);
            recyclerView.setOnRefreshListener(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) {
                    surveyAdapter.setData(new ArrayList<>(), mSelectState);
                    recyclerView.setAdapter(surveyAdapter);
                    recyclerView.setOnRefreshListener(UiSurveyList.this::getOnlineJobList);
                    Handler handler = new Handler();
                    handler.postDelayed(() -> getOnlineJobList(), 100);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        recyclerView.setOnRefreshListener(() -> {
            pageindex = 1;
            getOnlineJobList();
        });

        recyclerView.setOnLoadMoreListener(() -> {
            pageindex++;
            getOnlineJobList();
        });

        if (surveyAdapter != null) {
            surveyAdapter.setOnItemClickListener((view, position) -> {
                SurveyBean surveyBean = surveyAdapter.getItem(position);
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable(SurveyBean.SURVEY_DATA_KEY, surveyBean);
                bundle.putSerializable(SurveyBean.SURVEY_POSITION_KEY, position);
                bundle.putInt(SurveyBean.SURVEY_LIST_SELECT_TYPE, mSelectState);
                if (mSelectState == 0) {
                    intent.setClass(UiSurveyList.this, UiSurveyReport.class);
                }
                intent.putExtras(bundle);
                startActivity(intent);
            });
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.menu_plan_detaill, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @OnClick({R.id.layout_survey_upload_module})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_survey_upload_module: {
                Intent intent = new Intent();
                intent.setClass(UiSurveyList.this, UiSurveyReport.class);
                startActivity(intent);
            }
            break;
        }
    }

    @Subscribe
    public void onMessageEvent(MySurveyEvent event) {
        /*if (MySurveyEvent.EMERGENCY_NEW_ASSIGN_EMERGENCY.equals(event.message)) {
            String title = "新的派工";
            String content = "你有一条新的应急派工待处理，请查看。";
            showAlertDialog(title, content, (dialog, which) -> getOnlineJobList());
        } else */
        if (MySurveyEvent.SURVEY_LIST_NEED_REFRESH.equals(event.message)
                || MySurveyEvent.SURVEY_BEFORE_UPLOADED.equals(event.message)) {
            getOnlineJobList();
        }else if (MySurveyEvent.SURVEY_HAS_READ.equals(event.message)) {
            if (event.arg0 != null) {
                int position = (int) event.arg0;
                if (surveyAdapter != null) {
                    surveyAdapter.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();
        surveyTool.getSurveyListOnline(this, mSelectState, -1,"", pageindex, new SurveyCallBack() {
            @Override
            public void onGetDatas(boolean isSuccess, int errorCode, String errMsg, List surveyList, int total) {
                super.onGetDatas(isSuccess, errorCode, errMsg, surveyList, total);
                stopRefreshing();
                /*加载本地保存的计划*/
                if (pageindex == 1) {
                    recyclerView.setTotal(total);
                    surveyAdapter.clear();
                }
                if (surveyList != null) {
                    surveyAdapter.addAll(surveyList);
                }
            }
        });
    }

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

        EventBusUtil.unregister(this);
    }
}
