package com.xwkj.jcjcgz.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.Gson;
import com.hjq.toast.ToastUtils;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.header.TwoLevelHeader;
import com.scwang.smart.refresh.header.listener.OnTwoLevelListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.RefreshState;
import com.scwang.smart.refresh.layout.simple.SimpleMultiListener;
import com.squareup.picasso.Picasso;
import com.xwkj.jcjcgz.R;
import com.xwkj.jcjcgz.di.component.DaggerRwzxComponent;
import com.xwkj.jcjcgz.mvp.contract.RwzxContract;
import com.xwkj.jcjcgz.mvp.model.api.CommonInterFace;
import com.xwkj.jcjcgz.mvp.model.api.ReqToBus;
import com.xwkj.jcjcgz.mvp.model.entity.ChannelEntity;
import com.xwkj.jcjcgz.mvp.model.entity.TaskEntity;
import com.xwkj.jcjcgz.mvp.presenter.RwzxPresenter;
import com.xwkj.jcjcgz.mvp.ui.activity.MainActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 07/09/2024 14:09
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class RwzxFragment extends BaseFragment<RwzxPresenter> implements RwzxContract.View {

    @BindView(R.id.rwzx_tv_search)
    TextView tvSearch;
    @BindView(R.id.rwzx_layout_task_1)
    View layoutTask1;
    @BindView(R.id.rwzx_layout_task_2)
    View layoutTask2;
    @BindView(R.id.rwzx_layout_task_3)
    View layoutTask3;
    @BindView(R.id.rwzx_tv_task_1)
    TextView tvTask1;
    @BindView(R.id.rwzx_tv_task_2)
    TextView tvTask2;
    @BindView(R.id.rwzx_tv_task_3)
    TextView tvTask3;
    @BindView(R.id.rwzx_tv_task_num_1)
    TextView tvTaskNum1;
    @BindView(R.id.rwzx_tv_task_num_2)
    TextView tvTaskNum2;
    @BindView(R.id.rwzx_tv_task_num_3)
    TextView tvTaskNum3;
    @BindView(R.id.rwzx_iv_task_1)
    ImageView ivTask1;
    @BindView(R.id.rwzx_iv_task_2)
    ImageView ivTask2;
    @BindView(R.id.rwzx_iv_task_3)
    ImageView ivTask3;
    @BindView(R.id.rwzx_iv_triangle_1)
    ImageView ivTriangle1;
    @BindView(R.id.rwzx_iv_triangle_2)
    ImageView ivTriangle2;
    @BindView(R.id.rwzx_iv_triangle_3)
    ImageView ivTriangle3;

    @BindView(R.id.second_floor)
    ImageView secondFloor;
    @BindView(R.id.second_floor_content)
    RelativeLayout secondFloorContent;
    @BindView(R.id.rl_back)
    RelativeLayout rl_back;
    @BindView(R.id.classics)
    ClassicsHeader classics;
    @BindView(R.id.header)
    TwoLevelHeader header;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.rwzx_container)
    View container;
    @BindView(R.id.layout_rwzx)
    View layoutRwzx;
    @BindView(R.id.rwfx_tab)
    TabLayout tabLayout;
    @BindView(R.id.rwfx_vp)
    ViewPager2 viewPager;

    private TaskTypeFragment taskTypeFragment1;
    private TaskTypeFragment taskTypeFragment2;
    private TaskTypeFragment taskTypeFragment3;
    private List<ChannelEntity.Task> tasks;

    public static RwzxFragment newInstance() {
        RwzxFragment fragment = new RwzxFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerRwzxComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_rwzx, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        refreshLayout.setEnableAutoLoadMore(false);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnMultiListener(new SimpleMultiListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                Toast.makeText(getActivity(), "上拉加载", Toast.LENGTH_SHORT).show();
                refreshLayout.finishLoadMore(2000);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                Toast.makeText(getActivity(), "下拉刷新", Toast.LENGTH_SHORT).show();
                refreshLayout.finishRefresh(2000);
            }

            @Override
            public void onStateChanged(@NonNull RefreshLayout refreshLayout, @NonNull RefreshState oldState, @NonNull RefreshState newState) {
                if (oldState == RefreshState.TwoLevel) {
                    secondFloorContent.animate().alpha(0).setDuration(1000);
                }
            }
        });

        View viewById = getActivity().findViewById(R.id.ll_main_tab);
        header.setOnTwoLevelListener(new OnTwoLevelListener() {
            @Override
            public boolean onTwoLevel(@NonNull RefreshLayout refreshLayout) {
                Toast.makeText(getActivity(), "打开二楼", Toast.LENGTH_SHORT).show();
                secondFloorContent.animate().alpha(1).setDuration(2000);
                getActivity().findViewById(R.id.ll_main_tab).setVisibility(View.GONE);
                layoutRwzx.setVisibility(View.GONE);
                return true;
            }
        });
        rl_back.setOnClickListener(v -> {
            header.finishTwoLevel();
            getActivity().findViewById(R.id.ll_main_tab).setVisibility(View.VISIBLE);
            layoutRwzx.setVisibility(View.VISIBLE);
        });
        layoutTask1.performClick();


        // 二楼页面
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(RwfxTaskStatusFragment.newInstance());
        fragments.add(RwfxTaskStatusFragment.newInstance());
        List<String> titles = new ArrayList<>();
        titles.add("已签收");
        titles.add("已反馈");
        FragmentStateAdapter mAdapter = new FragmentStateAdapter(this) {
            @Override
            public int getItemCount() {
                return fragments.size();
            }

            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return fragments.get(position);
            }

        };
        viewPager.setAdapter(mAdapter);
        new TabLayoutMediator(tabLayout, viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText(titles.get(position));
            }
        }).attach();

        Map<String, String> map = new HashMap<>();
        map.put("code", "app_menu");
        mPresenter.getMenu(map);
    }


    @OnClick({R.id.rwzx_layout_task_1, R.id.rwzx_layout_task_2, R.id.rwzx_layout_task_3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rwzx_layout_task_1:
                setTabSelection(0);
                break;
            case R.id.rwzx_layout_task_2:
                setTabSelection(1);
                break;
            case R.id.rwzx_layout_task_3:
                setTabSelection(2);
                break;
        }
    }

    public void setTabSelection(int index) {
        tvTask1.setTextColor(getResources().getColor(R.color.color_666666));
        tvTask2.setTextColor(getResources().getColor(R.color.color_666666));
        tvTask3.setTextColor(getResources().getColor(R.color.color_666666));
        ivTriangle1.setVisibility(View.GONE);
        ivTriangle2.setVisibility(View.GONE);
        ivTriangle3.setVisibility(View.GONE);
        // 开启一个Fragment事务
        FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
        // 先隐藏掉所有的Fragment，
        hideFragments(transaction);
        switch (index) {
            case 0:
                if (taskTypeFragment1 == null) {
                    taskTypeFragment1 = TaskTypeFragment.newInstance(new ArrayList<>());
                    transaction.add(R.id.rwzx_container, taskTypeFragment1);
                } else {
                    transaction.show(taskTypeFragment1);
                }
                tvTask1.setTextColor(getResources().getColor(R.color.color_111111));
                ivTriangle1.setVisibility(View.VISIBLE);
                break;

            case 1:
                if (taskTypeFragment2 == null) {
                    if (tasks != null && tasks.size() > 1) {
                        taskTypeFragment2 = TaskTypeFragment.newInstance(tasks.get(1).getChildren());
                        transaction.add(R.id.rwzx_container, taskTypeFragment2);
                    }
                } else {
                    transaction.show(taskTypeFragment2);
                }
                tvTask2.setTextColor(getResources().getColor(R.color.color_111111));
                ivTriangle2.setVisibility(View.VISIBLE);
                break;
            case 2:
                if (taskTypeFragment3 == null) {
                    if (tasks != null && tasks.size() > 2) {
                        taskTypeFragment3 = TaskTypeFragment.newInstance(tasks.get(2).getChildren());
                        transaction.add(R.id.rwzx_container, taskTypeFragment3);
                    }
                } else {
                    transaction.show(taskTypeFragment3);
                }
                tvTask3.setTextColor(getResources().getColor(R.color.color_111111));
                ivTriangle3.setVisibility(View.VISIBLE);
                break;

        }
        transaction.commit();
    }

    private void hideFragments(FragmentTransaction transaction) {

        if (taskTypeFragment1 != null) {
            transaction.hide(taskTypeFragment1);
        }
        if (taskTypeFragment2 != null) {
            transaction.hide(taskTypeFragment2);
        }

        if (taskTypeFragment3 != null) {
            transaction.hide(taskTypeFragment3);
        }


    }
    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @Override
    public void onSuccess(String result) {
        try {
            ChannelEntity entity = new Gson().fromJson(result, ChannelEntity.class);
            if (entity.getCode() == 200) {
                tasks = entity.getData();
                for (int i = 0; i < tasks.size(); i++) {
                    initFragment(i, tasks.get(i));
                }
                /*FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
                if (taskTypeFragment1 != null) {
                    transaction.add(R.id.rwzx_container, taskTypeFragment1);
                }
                if (taskTypeFragment2 != null) {
                    transaction.add(R.id.rwzx_container, taskTypeFragment2);
                }
                if (taskTypeFragment3 != null) {
                    transaction.add(R.id.rwzx_container, taskTypeFragment3);
                }
                transaction.show(taskTypeFragment1);
                transaction.commit();*/
                layoutTask1.performClick();
            } else {
                ToastUtils.show("获取数据出错，请重试");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initFragment(int i, ChannelEntity.Task task) {
        switch (i) {
            case 0: {
//                taskTypeFragment1 = TaskTypeFragment.newInstance(task.getChildren());
                int num = 0;
                for (ChannelEntity.Task task1: task.getChildren()) {
                    num = num + task1.getNum();
                }
                tvTaskNum1.setText(num + "");
                tvTask1.setText(task.getDictValue());
                Picasso.with(getActivity()).load(task.getRemark()).into(ivTask1);
                taskTypeFragment1.initFragment(task.getChildren());
            }
                break;
            case 1: {
//                taskTypeFragment2 = TaskTypeFragment.newInstance(task.getChildren());
                tvTask2.setText(task.getDictValue());
                Picasso.with(getActivity()).load(task.getRemark()).into(ivTask2);
                int num = 0;
                for (ChannelEntity.Task task1: task.getChildren()) {
                    num = num + task1.getNum();
                }
                tvTaskNum2.setText(num + "");
            }
                break;
            case 2: {
//                taskTypeFragment3 = TaskTypeFragment.newInstance(task.getChildren());
                tvTask3.setText(task.getDictValue());
                Picasso.with(getActivity()).load(task.getRemark()).into(ivTask3);
                int num = 0;
                for (ChannelEntity.Task task1: task.getChildren()) {
                    num = num + task1.getNum();
                }
                tvTaskNum3.setText(num + "");
            }
                break;
            default:
                break;
        }
    }
}
