package com.sjkj.appthreefloor_tsgz.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sjkj.appthreefloor_tsgz.R;
import com.sjkj.appthreefloor_tsgz.activity.EventDetailsActivity;
import com.sjkj.appthreefloor_tsgz.adapter.EventCenterAdapter;
import com.sjkj.appthreefloor_tsgz.app.App;
import com.sjkj.appthreefloor_tsgz.bean.EventBean;
import com.sjkj.appthreefloor_tsgz.bean.EventCenterListBean;
import com.sjkj.appthreefloor_tsgz.databinding.FragmentEventBinding;
import com.sjkj.appthreefloor_tsgz.fragment.viewModel.EventFargmentViewModel;
import com.sjkj.appthreefloor_tsgz.header.MyClassicsHeader;
import com.sjkj.appthreefloor_tsgz.net.EventListRequest;
import com.sjkj.base_lib.adapter.BaseRecAdapter;
import com.sjkj.base_lib.entity.Params;
import com.sjkj.base_lib.net.domain.interactor.ProcessErrorSubscriber;
import com.sjkj.base_lib.utils.Constants;
import com.sjkj.base_lib.view.BaseFragment;
import com.sjkj.base_lib.weight.LoadingDialog;

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

public class EventFragment extends BaseFragment /*implements View.OnClickListener */ {
    private FragmentEventBinding binding;
    private EventFargmentViewModel viewModel;
    private String[] eventStatusNames = new String[]{"待签收", "处理中", "已完成", "归档"};
    private String[] eventStatusValues = new String[]{"20", "30", "40", "50"};
    private int currentPage = 1;
    private EventCenterAdapter adapter;
    public EventListRequest eventListRequest = new EventListRequest(App.getInstance());
    private List<EventBean> eventItemList = new ArrayList<>();

    static {
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.color_transparent00, R.color.color_transparent00);//全局设置主题颜色
                return new MyClassicsHeader(context).setAccentColor(context.getResources().getColor(R.color.white));
            }
        });
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_event;
    }


    @Override
    public View initBinding(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        binding = (FragmentEventBinding) getViewDataBing(inflater, container);
        viewModel = new ViewModelProvider(getActivity(), new ViewModelProvider.NewInstanceFactory()).get(EventFargmentViewModel.class);
        binding.setViewModel(viewModel);
        binding.setLifecycleOwner(this);
        return binding.getRoot();
    }

    @Override
    public void initView() {
        ImmersionBar.with(this).titleBar(binding.toolbar)
                .init();

        ViewGroup.LayoutParams params = binding.toolbar.getLayoutParams();
        params.height = ImmersionBar.getStatusBarHeight(this);
        binding.toolbar.setLayoutParams(params);
        initTab();
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(RecyclerView.VERTICAL);
        binding.recyclerView.setLayoutManager(manager);
        adapter = new EventCenterAdapter(getActivity());
        adapter.setItemClick(new BaseRecAdapter.OnItemClick<EventBean>() {
            @Override
            public void onItemClick(EventBean bean, int position) {
                Intent intent = new Intent(getActivity(), EventDetailsActivity.class);
                intent.putExtra("id", bean.getId());
                intent.putExtra("eventCode", bean.getEventCode());
                startActivityForResult(intent, 1000);
            }
        });
        binding.recyclerView.setAdapter(adapter);
        binding.smartRefreshLayout.setPrimaryColors(getResources().getColor(R.color.colorPrimary));
        binding.smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                requestListRefresh();
            }
        });
        binding.smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                requestListLoadMore();
            }
        });
        // binding.recyclerView.addItemDecoration(new DividerItem(getActivity()));

        binding.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (!recyclerView.canScrollVertically(1)) { // 检查是否可以垂直向下滚动更多内容
                    // 执行相关操作，例如加载更多数据等
                    //binding.emptyView.setVisibility(View.VISIBLE);
                    // 动态设置边距
                    ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) binding.recyclerView.getLayoutParams(); // 创建MarginLayoutParams对象
                    params.setMargins(0, 0, 0, 240); // 设置左、上、右、下的margin值

                    binding.recyclerView.setLayoutParams(params);

                    FrameLayout.LayoutParams frameParams = (FrameLayout.LayoutParams) binding.ivAdd.getLayoutParams();
                 // 设置margin
                    frameParams.leftMargin = 0; // 左边距
                    frameParams.topMargin = 0; // 上边距
                    frameParams.rightMargin = 45; // 右边距
                    frameParams.bottomMargin = 240; // 下边距

                    binding.ivAdd.setLayoutParams(frameParams);
                }
            }
        });

    }


    private void initTab() {
        for (int i = 0; i < eventStatusNames.length; i++) {
            binding.tabLayout.addTab(binding.tabLayout.newTab().setText(eventStatusNames[i]).setTag(eventStatusValues[i]));
        }
    }

    private void requestListRefresh() {

        currentPage = 1;
        Params params = new Params();
        params.put("pageSize", Constants.ITEM_NUMBERS);
        params.put("pageNum", currentPage);
        params.put("reasonable", false);
        params.put("status", viewModel.eventStatusValue.get());
//        params.put("eventType", viewModel.eventTypeValue.get());
//        params.put("satrtTime", viewModel.satrtTime.get());
//        params.put("endTime", viewModel.endTime.get());
        if (!TextUtils.isEmpty(viewModel.keyword.get())) {
            params.put("eventName", viewModel.keyword.get());
        }
        eventListRequest.setParams(params);
        eventListRequest.execute(new ProcessErrorSubscriber<EventCenterListBean>() {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
                finishRefreshOrLoadMore(binding.smartRefreshLayout);
                hideLoadingDialog(LoadingDialog.LOADING_FAILED);
            }

            @Override
            public void onNext(EventCenterListBean bean) {
                super.onNext(bean);
                finishRefreshOrLoadMore(binding.smartRefreshLayout);

                eventItemList.clear();

                if (bean != null && bean.getRows().size() > 0) {
                    Gson gson = new Gson();

                    for (int i = 0; i < bean.getRows().size(); i++) {
                        EventCenterListBean.EventCenter eventCenter = gson.fromJson(bean.getRows().get(i).getEventJson(), EventCenterListBean.EventCenter.class);
                        String id = eventCenter.getId();
                        String title = eventCenter.getEventName();
                        String content = eventCenter.getRemark();
                        String time = eventCenter.getCreateTime();
                        String type = eventCenter.getEventType();
                        String eventSource = eventCenter.getEventSource();
                        String eventCode = bean.getRows().get(i).getId();


                        EventBean eventBean = new EventBean(id, title, content, time, type, "", "", "", "", eventCode, eventSource);
                        eventItemList.add(eventBean);

                    }

                }
                /*else {
                   ToastUtils.show("暂无数据");
                }*/
                adapter.refreshList(eventItemList);
            }
        });

    }

    private void requestListLoadMore() {
        showLoadingDialog();
        Params params = new Params();
        params.put("pageSize", Constants.ITEM_NUMBERS);
        params.put("pageNum", currentPage + 1);
        params.put("reasonable", false);
        params.put("status", viewModel.eventStatusValue.get());
        //   params.put("eventType", viewModel.eventTypeValue.get());
//        params.put("satrtTime", viewModel.satrtTime.get());
//        params.put("endTime", viewModel.endTime.get());
        if (!TextUtils.isEmpty(viewModel.keyword.get())) {
            params.put("eventName", viewModel.keyword.get());
        }
        eventListRequest.setParams(params);
        eventListRequest.execute(new ProcessErrorSubscriber<EventCenterListBean>() {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
                finishRefreshOrLoadMore(binding.smartRefreshLayout);
                hideLoadingDialog(LoadingDialog.LOADING_FAILED);
            }

            @Override
            public void onNext(EventCenterListBean bean) {
                super.onNext(bean);
                finishRefreshOrLoadMore(binding.smartRefreshLayout);
                hideLoadingDialog(LoadingDialog.LOADING_SUCCESS);
                if (bean != null) {
                    //  if (AppTools.ceil(bean.getTotal()) > currentPage) {

                    if (bean != null && bean.getRows().size() > 0) {
                        Gson gson = new Gson();

                        for (int i = 0; i < bean.getRows().size(); i++) {
                            EventCenterListBean.EventCenter eventCenter = gson.fromJson(bean.getRows().get(i).getEventJson(), EventCenterListBean.EventCenter.class);
                            String id = eventCenter.getId();
                            String title = eventCenter.getEventName();
                            String content = eventCenter.getRemark();
                            String time = eventCenter.getCreateTime();
                            String type = eventCenter.getEventType();
                            String eventSource = eventCenter.getEventSource();
                            String eventCode = eventCenter.getId();


                            EventBean eventBean = new EventBean(id, title, content, time, type, "", "", "", "", eventCode, eventSource);
                            eventItemList.add(eventBean);

                        }

                    }
                    adapter.refreshList(eventItemList);

                }


            }
        });
    }

    @Override
    public void initListener() {
        binding.ivSerch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("ZHR21111", "搜索");
                // startActivityForResult(new Intent(getActivity(), NewEventActivity.class), 1000);
            }
        });
        binding.llChongzhi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewModel.keyword.set("");
                viewModel.eventTypeValue.set("");
                viewModel.satrtTime.set("");
                viewModel.endTime.set("");
                binding.inputEt.setHint(getResources().getString(R.string.input_content));


                binding.tvSerch.setText("条件筛选");
                binding.tvSerch.setTextColor(getResources().getColor(R.color.black));
                binding.llSerch.setBackground(getResources().getDrawable(R.drawable.shape_background_white_5));
                binding.ivS.setBackground(getResources().getDrawable(R.drawable.icon_arrow_right));


                binding.tvStartTime.setText("时间筛选");
                binding.tvStartTime.setTextColor(getResources().getColor(R.color.black));
                binding.llTime.setBackground(getResources().getDrawable(R.drawable.shape_background_white_5));
                binding.ivT.setBackground(getResources().getDrawable(R.drawable.icon_arrow_right));
                requestListRefresh();
            }
        });
        binding.llSerch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //startActivityForResult(new Intent(getActivity(), EventCenterSerchActivity.class).putExtra("parentId",getIntent().getStringExtra("parentId")), 2000);
            }
        });
        binding.llTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // startActivityForResult(new Intent(getActivity(), EventCenterSerchTimeActivity.class).putExtra("starttime", viewModel.satrtTime.get()).putExtra("endtime", viewModel.endTime.get()), 3000);
            }
        });
//        setTitleListener(new BaseActivity.TitleListener() {
//            @Override
//            public void onRightClick() {
//                startActivityForResult(new Intent(getActivity(), NewEventActivity.class), 1000);
//            }
//
//            @Override
//            public void onBackClick() {
//
//            }
//        });
        binding.inputEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                viewModel.keyword.set(s.toString().trim());
            }
        });
        binding.searchTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestListRefresh();
            }
        });
        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewModel.eventStatus.set(tab.getText().toString());
                viewModel.eventStatusValue.set(tab.getTag().toString());
                requestListRefresh();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    @Override
    public void loadData() {
//        viewModel.eventStatus.set(eventStatusNames[0]);
//        viewModel.eventStatusValue.set(eventStatusValues[0]);
        viewModel.satrtTime.set("2011-05-26");
        viewModel.endTime.set("2026-05-26");
        viewModel.eventStatusValue.set("20");
        requestListRefresh();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1000&&resultCode==1000){
            requestListRefresh();
        }
    }
}
