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

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
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.base.MainModule;
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.MyTroubleEvent;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.ghrq_route.module.user.UserInfoTool;
import com.tofly.ghrq_route.common.ui.activity.UiMyTroubleList;
import com.tofly.ghrq_route.common.ui.adapter.ListPageAdapter;
import com.tofly.ghrq_route.module.trouble.ui.adapter.TroubleListAdapter;
import com.tofly.ghrq_route.common.util.EventBusUtil;

import org.greenrobot.eventbus.Subscribe;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@SuppressLint("NonConstantResourceId")
public class UiTroubleList extends BaseUi {
    @BindView(R.id.layout_app_bar)
    AppBarLayout appBarLayout;
    @BindView(R.id.toolbar_layout)
    CollapsingToolbarLayout collapsingToolbarLayout;
    @BindView(R.id.layout_trouble_module)
    HorizontalScrollView layoutTroubleModule;
    @BindView(R.id.layout_trouble_upload_module)
    LinearLayout layoutTroubleUpload;
    @BindView(R.id.layout_my_trouble_module)
    LinearLayout layoutMyTrouble;
    @BindView(R.id.layout_trouble_query_module)
    LinearLayout layoutTroubleQuery;
    @BindView(R.id.main_toolbar)
    Toolbar mainToolbar;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.view_pager)
    ViewPager viewPager;

    private List<MainModule.SubModuleBean> mTroubleModules;

    private TroubleTool troubleTool;

    private ListPageAdapter pageAdapter;

    private TroubleListAdapter troubleListAdapter;

    private ARecycleView recyclerView;

    private int mSelectState = TroubleBean.TROUBLE_SELECT_TROUBLE_REPORT;

    private int mSelPosition = 0;

    private int pageindex = 1;

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

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

        initView();

        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不显示
                    layoutTroubleModule.setVisibility(View.VISIBLE);
                    state = CollapsingToolbarLayoutState.EXPANDED;//修改状态标记为展开
                }
            } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                if (state != CollapsingToolbarLayoutState.COLLAPSED) {
                    collapsingToolbarLayout.setTitle("");
                    layoutTroubleModule.setVisibility(View.GONE);
                    state = CollapsingToolbarLayoutState.COLLAPSED;//修改状态标记为折叠
                }
            } else {
                if (state != CollapsingToolbarLayoutState.INTERNEDIATE) {
                    if (state == CollapsingToolbarLayoutState.COLLAPSED) {
                        collapsingToolbarLayout.setTitle("");//设置title不显示
                        layoutTroubleModule.setVisibility(View.VISIBLE);
                    }
                    state = CollapsingToolbarLayoutState.INTERNEDIATE;//修改状态标记为中间
                }
            }
        });
    }

    private void initTabLayout() {
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        mTroubleModules = userInfoTool.getTroubleModules();
        if (mTroubleModules != null) {
            boolean hasTopBtn = false;
            boolean hasListModule = false;
            List<MainModule.SubModuleBean> tabModules = new ArrayList<>();
            for (MainModule.SubModuleBean subModule : mTroubleModules) {
                if (subModule.getSub_type() == MainModule.SUB_TOP_BUTTON_TYPE) {
                    if (subModule.getAclass().equals(UiTroubleReport.class)) {
                        hasTopBtn = true;
                        layoutTroubleUpload.setVisibility(View.VISIBLE);
                    } else if (subModule.getAclass().equals(UiMyTroubleList.class)) {
                        hasTopBtn = true;
                        layoutMyTrouble.setVisibility(View.VISIBLE);
                    } else if (subModule.getAclass().equals(UiTroubleQueryList.class)) {
                        hasTopBtn = true;
                        layoutTroubleQuery.setVisibility(View.VISIBLE);
                    }
                }else if (subModule.getSub_type() == MainModule.SUB_TAP_LIST_TYPE) {
                    hasListModule = true;
                    tabModules.add(subModule);
                }
            }
            layoutTroubleModule.setVisibility(hasTopBtn ? View.VISIBLE : View.GONE);
            if (!hasTopBtn) {
/*                View mAppBarChildAt = appBarLayout.getChildAt(0);
                AppBarLayout.LayoutParams  mAppBarParams = (AppBarLayout.LayoutParams)mAppBarChildAt.getLayoutParams();
                mAppBarParams.setScrollFlags(0);*/
                appBarLayout.setExpanded(false);
            }

            if (hasListModule) {
                if (tabModules.size() > 0) {
                    mSelectState = tabModules.get(0).getSelect_index();
                }

                pageAdapter = new ListPageAdapter(this, tabModules);
                viewPager.setAdapter(pageAdapter);
                tabLayout.setupWithViewPager(viewPager);
                for (int i = 0; i < pageAdapter.getCount(); i++) {
                    MainModule.SubModuleBean subModule = (MainModule.SubModuleBean) pageAdapter.getItem(i);
                    TabLayout.Tab tab = tabLayout.getTabAt(i);
                    if (tab != null)
                        tab.setText(subModule.getTitle());
                }

                initData();
                initListener();
            }
        }
    }

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

        ArrayList<TroubleBean> list = new ArrayList<>();
        troubleListAdapter = new TroubleListAdapter(this, list);

        recyclerView = pageAdapter.getRecycleView(mSelPosition);
        if (recyclerView != null) {
            recyclerView.setAdapter(troubleListAdapter);
            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);
                MainModule.SubModuleBean subModule = (MainModule.SubModuleBean) pageAdapter.getItem(position);
                mSelectState = subModule.getSelect_index();
                if (recyclerView != null) {
                    troubleListAdapter.setData(new ArrayList<>(), mSelectState);
                    recyclerView.setAdapter(troubleListAdapter);
                    recyclerView.setOnRefreshListener(UiTroubleList.this::getOnlineJobList);
                    Handler handler = new Handler();
                    handler.postDelayed(() -> getOnlineJobList(), 100);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

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

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

        if (troubleListAdapter != null) {
            troubleListAdapter.setOnItemClickListener((view, position) -> {
                TroubleBean troubleBean = troubleListAdapter.getItem(position);
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable(TroubleBean.TROUBLE_BEAN_KEY, troubleBean);
                bundle.putSerializable(TroubleBean.TROUBLE_POSITION_KEY, position);
                bundle.putInt(TroubleBean.TROUBLE_LIST_SELECT_TYPE, mSelectState);
                intent.setClass(UiTroubleList.this, UiTroubleDetail.class);
                intent.putExtras(bundle);
                startActivity(intent);
            });
        }
    }

    @OnClick({R.id.layout_trouble_upload_module, R.id.layout_my_trouble_module, R.id.layout_trouble_query_module})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_trouble_upload_module: {
                Intent intent = new Intent();
                intent.setClass(UiTroubleList.this, UiTroubleReport.class);
                startActivity(intent);
            }
            break;
            case R.id.layout_my_trouble_module: {
                Intent intent = new Intent();
                intent.setClass(UiTroubleList.this, UiMyTroubleList.class);
                startActivity(intent);
            }
            break;
            case R.id.layout_trouble_query_module: {
                Intent intent = new Intent();
                intent.setClass(UiTroubleList.this, UiTroubleQueryList.class);
                startActivity(intent);
            }
            break;
        }
    }

    @Subscribe
    public void onMessageEvent(MyTroubleEvent event) {
        if (MyTroubleEvent.TROUBLE_LIST_NEED_REFRESH.equals(event.message)
                || MyTroubleEvent.TROUBLE_UPLOADED.equals(event.message)) {
            getOnlineJobList();
        } else if (MyTroubleEvent.TROUBLE_NEW_TROUBLE.equals(event.message)) {
            String title = "新的隐患";
            String content = "你有一条新的隐患待处理，请查看。";
            showAlertDialog(title, content, (dialog, which) -> getOnlineJobList());
        } else if (MyTroubleEvent.TROUBLE_TROUBLE_HAS_READ.equals(event.message)) {
            if (event.arg0 != null) {
                int position = (int) event.arg0;
                if (troubleListAdapter != null) {
                    troubleListAdapter.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();
        troubleTool.getTroubleListOnline(this, mSelectState, "", pageindex, new TroubleCallBack() {
            @Override
            public void onGetTroubleList(boolean isSuccess, int errorCode, String errMsg, List<TroubleBean> troubleList, int total) {
                super.onGetTroubleList(isSuccess, errorCode, errMsg, troubleList, total);
                stopRefreshing();
                /*加载本地保存的计划*/
                if (pageindex == 1) {
                    recyclerView.setTotal(total);
                    troubleListAdapter.clear();
                }
                if (troubleList != null) {
                    troubleListAdapter.addAll(troubleList);
                }
            }
        });
    }


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

        EventBusUtil.unregister(this);
    }
}
