package com.tofly.ghrq_route.module.emergencyHandle.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.base.MainModule;
import com.tofly.ghrq_route.module.emergencyHandle.EmergencyTool;
import com.tofly.ghrq_route.module.emergencyHandle.controller.EmergencyCallBack;
import com.tofly.ghrq_route.module.emergencyHandle.domain.EmergencyHandleData;
import com.tofly.ghrq_route.module.emergencyHandle.domain.MyEmergencyEvent;
import com.tofly.ghrq_route.module.emergencyHandle.ui.adapter.EmergencyAdapter;
import com.tofly.ghrq_route.module.message.domain.InMessageBean;
import com.tofly.ghrq_route.module.trouble.ui.UiTroubleQueryList;
import com.tofly.ghrq_route.module.user.UserInfoTool;
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.List;

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

@SuppressLint("NonConstantResourceId")
public class UiEmergencyList 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_emerge_upload_module)
    LinearLayout layoutEmergencyUpload;
    @BindView(R.id.layout_emerge_query_module)
    LinearLayout layoutEmergencyQuery;
    @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> mEmergencyModules;

    private EmergencyTool emergencyTool;

    private ListPageAdapter pageAdapter;

    private EmergencyAdapter emergencyAdapter;

    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_emergency_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() {
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        mEmergencyModules = userInfoTool.getEmergencyModules();
        if (mEmergencyModules != null) {
            List<MainModule.SubModuleBean> tabModules = new ArrayList<>();
            for (MainModule.SubModuleBean subModule : mEmergencyModules) {
                if (subModule.getSub_type() == MainModule.SUB_TAP_LIST_TYPE) {
                    tabModules.add(subModule);
                }
            }

            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());
            }

            Intent intent = getIntent();
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                String module = bundle.getString(InMessageBean.MESSAGE_MODULE_KEY);
                if (module != null && !module.isEmpty()) {
                    for (int i = 0; i < pageAdapter.getCount(); i++) {
                        MainModule.SubModuleBean subModule = (MainModule.SubModuleBean) pageAdapter.getItem(i);
                        if (subModule.getCode().equals(module)) {
                            TabLayout.Tab tab = tabLayout.getTabAt(i);
                            mSelectState = subModule.getSelect_index();
                            tabLayout.selectTab(tab, true);
                            mSelPosition = i;
                            break;
                        }
                    }
                }
            }

            boolean hasTopBtn = false;
            for (MainModule.SubModuleBean subModule : mEmergencyModules) {
                if (subModule.getSub_type() == MainModule.SUB_TOP_BUTTON_TYPE) {
                    if (subModule.getAclass().equals(UiTroubleQueryList.class)) {
                        hasTopBtn = true;
                        layoutEmergencyQuery.setVisibility(View.VISIBLE);
                    }
                }
            }
            layoutHandleModule.setVisibility(hasTopBtn ? View.VISIBLE : View.GONE);
        }
    }

    private void initData() {
        emergencyTool = EmergencyTool.getInstance();

        ArrayList<EmergencyHandleData> list = new ArrayList<>();
        emergencyAdapter = new EmergencyAdapter(this, list);

        recyclerView = pageAdapter.getRecycleView(mSelPosition);
        if (recyclerView != null) {
            recyclerView.setAdapter(emergencyAdapter);
            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) {
                    emergencyAdapter.setData(new ArrayList<>(), mSelectState);
                    recyclerView.setAdapter(emergencyAdapter);
                    recyclerView.setOnRefreshListener(UiEmergencyList.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 (emergencyAdapter != null) {
            emergencyAdapter.setOnItemClickListener((view, position) -> {
                EmergencyHandleData emergencyData = emergencyAdapter.getItem(position);
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable(EmergencyHandleData.EMERGENCY_DATA_KEY, emergencyData);
                bundle.putSerializable(EmergencyHandleData.EMERGENCY_POSITION_KEY, position);
                bundle.putInt(EmergencyHandleData.EMERGENCY_LIST_SELECT_TYPE, mSelectState);
                switch (mSelectState) {
                    case 0:
                        intent.setClass(UiEmergencyList.this, UiEmergencyAssignHandle.class);
                        break;
                    case 1:
                        intent.setClass(UiEmergencyList.this, UiEmergencyScheduleAssign.class);
                        break;
                    case 2:
                        intent.setClass(UiEmergencyList.this, UiEmergencyRepairAssign.class);
                        break;
                    case 3:
                        intent.setClass(UiEmergencyList.this, UiEmergencyRepairHandle.class);
                        break;
                }
                intent.putExtras(bundle);
                startActivity(intent);
            });

/*            emergencyAdapter.setOnOverSignClickListener((view, position) -> {
                EmergencyHandleData emergencyData = emergencyAdapter.getItem(position);
                emergencySignOver(emergencyData, position);
            });*/
        }
    }

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

    @OnClick({R.id.layout_emerge_upload_module, R.id.layout_emerge_query_module})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_emerge_upload_module: {
                Intent intent = new Intent();
                intent.setClass(UiEmergencyList.this, UiEmergencyReport.class);
                startActivity(intent);
            }
            break;
            case R.id.layout_emerge_query_module: {
                Intent intent = new Intent();
                intent.setClass(UiEmergencyList.this, UiEmergencyQueryList.class);
                startActivity(intent);
            }
            break;
        }
    }

    @Subscribe
    public void onMessageEvent(MyEmergencyEvent event) {
        if (MyEmergencyEvent.EMERGENCY_ASSIGN_HANDLE_UPLOADED.equals(event.message)
                || MyEmergencyEvent.EMERGENCY_SCHEDULE_ASSIGN_UPLOADED.equals(event.message)
                || MyEmergencyEvent.EMERGENCY_REPAIR_ASSIGN_UPLOADED.equals(event.message)
                || MyEmergencyEvent.EMERGENCY_REPAIR_HANDLE_UPLOADED.equals(event.message)
                || MyEmergencyEvent.EMERGENCY_UPLOADED.equals(event.message)
                || MyEmergencyEvent.EMERGENCY_LIST_NEED_REFRESH.equals(event.message)) {
            getOnlineJobList();
        } else if (MyEmergencyEvent.EMERGENCY_NEW_ASSIGN_EMERGENCY.equals(event.message)) {
            String title = "新的派工";
            String content = "你有一条新的应急派工待处理，请查看。";
            showAlertDialog(title, content, (dialog, which) -> getOnlineJobList());
        } else if (MyEmergencyEvent.EMERGENCY_EMERGENCY_HAS_READ.equals(event.message)) {
            if (event.arg0 != null) {
                int position = (int) event.arg0;
                if (emergencyAdapter != null) {
                    emergencyAdapter.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();
        emergencyTool.getEmergencyListOnline(this, mSelectState, -1,"", pageindex, new EmergencyCallBack() {
            @Override
            public void onGetDatas(boolean isSuccess, int errorCode, String errMsg, List emergencyList, int total) {
                super.onGetDatas(isSuccess, errorCode, errMsg, emergencyList, total);
                stopRefreshing();
                /*加载本地保存的计划*/
                if (pageindex == 1) {
                    recyclerView.setTotal(total);
                    emergencyAdapter.clear();
                }
                if (emergencyList != null) {
                    emergencyAdapter.addAll(emergencyList);
                }
            }
        });
    }

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

        EventBusUtil.unregister(this);
    }
}
