package com.example.leudaemialikeme.Fragment;

import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.leudaemialikeme.Activity.BaseActivity;
import com.example.leudaemialikeme.Adapter.BlogAdapter;
import com.example.leudaemialikeme.Adapter.QuestionAdapter;
import com.example.leudaemialikeme.Model.Blog;
import com.example.leudaemialikeme.Model.Question;
import com.example.leudaemialikeme.R;
import com.example.leudaemialikeme.Utils.OkHttpUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class InvitationChannelFragment extends Fragment {
    private static final String ARG_CATEGORY_TITLE = "category_title";
    private static final String ARG_CATEGORY_TITLE_NUM = "category_title_num";
    public static List<List<Blog>> resourceList = new ArrayList<>();
    private List<Question> allQuestion = new ArrayList<>();
    private List<Blog> allBlog = new ArrayList<>();
    private String invitationCategoryTitle = "Default";
    private int invitationCategoryTitleNum = 0;
    private TextView mTitleField;
    static List<Blog> blogList = new ArrayList<>();
    private List<Blog> blogLists = new ArrayList<>();
    private List<Blog> expBlog = new ArrayList<>();
    private List<Blog> badBlog = new ArrayList<>();
    private List<Blog> recBlog = new ArrayList<>();
    //    static BlogAdapter allAdapter=new BlogAdapter();
    private QuestionAdapter questionAdapter = new QuestionAdapter();
    private BlogAdapter expAdapter = new BlogAdapter();
    private BlogAdapter badAdapter = new BlogAdapter();
    private BlogAdapter recAdapter = new BlogAdapter();
    private RecyclerView allRecyclerView;
    private RecyclerView questionRecyclerView;
    private RecyclerView expRecyclerView;
    private RecyclerView recRecyclerView;
    private RecyclerView badRecyclerView;
    private boolean isPause = false;

    private final String[] channelList = {"全部", "经验"
            , "康复", "扫雷", "问答"};

    //    int temp=0;
    public InvitationChannelFragment() {
        // Required empty public constructor
    }

    public static InvitationChannelFragment newInstance(String invitationCategoryTitle, int pos) {
        InvitationChannelFragment fragment = new InvitationChannelFragment();
        Bundle args = new Bundle();
        args.putString(ARG_CATEGORY_TITLE, invitationCategoryTitle);
        args.putInt(ARG_CATEGORY_TITLE_NUM, pos);
        fragment.setArguments(args);
//        blogList=getBlogList();
//        resourceList=getResourceList();
//        Log.e("newInstance","newInstance");
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            invitationCategoryTitle = (String) getArguments().getString(ARG_CATEGORY_TITLE);
            invitationCategoryTitleNum = getArguments().getInt(ARG_CATEGORY_TITLE_NUM);
//            Log.e("onCreate","onCreate");
        } catch (java.lang.NullPointerException e) {
            System.out.println("TesFragment getArg error!");
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view;
        view = inflater.inflate(R.layout.recyclerview, container, false);
//        initAllBlog();// 所有blog组
//        initAllBlogList();  //第一栏:全部项
        questionAdapter = new QuestionAdapter();
        questionAdapter.setQuestionList(allQuestion);
        expAdapter = new BlogAdapter();
        expAdapter.setRecnewsList(expBlog);
        badAdapter = new BlogAdapter();
        badAdapter.setRecnewsList(badBlog);
        recAdapter = new BlogAdapter();
        recAdapter.setRecnewsList(recBlog);

        if (invitationCategoryTitleNum == 0) {
            view = inflater.inflate(R.layout.recyclerview, container, false);
            allRecyclerView = (RecyclerView) view.findViewById(R.id.list_community);
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            allRecyclerView.setLayoutManager(layoutManager);
            BlogAdapter allAdapter = new BlogAdapter(allBlog);
            allRecyclerView.setAdapter(allAdapter);
//            initAllBlogList();
            Map<String, String[]> paramMap = new HashMap<String, String[]>();
            paramMap.put("channelList", new String[]{"全部"});
            getAllBlogListRequest(paramMap);
//            allAdapter.notifyDataSetChanged();
        } else if (invitationCategoryTitleNum == 4) {
            questionRecyclerView = (RecyclerView) view.findViewById(R.id.list_community);
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            questionRecyclerView.setLayoutManager(layoutManager);
            questionRecyclerView.setAdapter(questionAdapter);
//            Map<String, String[]> paramMap = new HashMap<>();
//            paramMap.put("channelList", new String[]{"问答"});
            getQuestionListRequest();

//            Log.e("应该为4：问答", String.valueOf(invitationCategoryTitleNum));

        } else if (invitationCategoryTitleNum == 2) {
            recRecyclerView = (RecyclerView) view.findViewById(R.id.list_community);
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            recRecyclerView.setLayoutManager(layoutManager);
            recRecyclerView.setAdapter(recAdapter);
            Map<String, String[]> paramMap = new HashMap<String, String[]>();
            paramMap.put("channelList", new String[]{"康复"});
            getRecInvitationRequest(paramMap);
//            Log.e("应该为2：康复", String.valueOf(invitationCategoryTitleNum));
//            Log.e("应该为2：康复数据",String.valueOf(recBlog));
        } else if (invitationCategoryTitleNum == 3) {
            badRecyclerView = (RecyclerView) view.findViewById(R.id.list_community);
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            badRecyclerView.setLayoutManager(layoutManager);
            badRecyclerView.setAdapter(badAdapter);
            Map<String, String[]> paramMap = new HashMap<String, String[]>();
            paramMap.put("channelList", new String[]{"扫雷"});
            getBadListRequest(paramMap);
//            Log.e("应该为3：扫雷", String.valueOf(invitationCategoryTitleNum));
        } else if (invitationCategoryTitleNum == 1) {
            expRecyclerView = (RecyclerView) view.findViewById(R.id.list_community);
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            expRecyclerView.setLayoutManager(layoutManager);
            expRecyclerView.setAdapter(expAdapter);
            Map<String, String[]> paramMap = new HashMap<String, String[]>();
            paramMap.put("channelList", new String[]{"经验"});
            getExpListRequest(paramMap);
        }

//        temp=temp+1;
        return view;
    }

    private void initAllBlogList() {
        Map<String, String[]> paramMap = new HashMap<String, String[]>();
        paramMap.put("channelList", new String[]{"全部"});
        getAllBlogListRequest(paramMap);
        getQuestionListRequest();
    }

    private void getQuestionListRequest() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url2 = BaseActivity.SERVER_URL + "/question-servlet?action=get-allQuestion";
                    OkHttpUtil.asyPost(url2, null, new Callback() {

                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String jsonStr = response.body().string();
                            getQuestionResponse(jsonStr);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void getExpListRequest(final Map paramMap) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = BaseActivity.SERVER_URL + "/blog-servlet?action=get-invitation";
                    OkHttpUtil.asyPost(url, paramMap, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String jsonStr = response.body().string();
                            getExpInvitationResponse(jsonStr);
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private void getBadListRequest(final Map paramMap) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = BaseActivity.SERVER_URL + "/blog-servlet?action=get-invitation";
                    OkHttpUtil.asyPost(url, paramMap, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String jsonStr = response.body().string();
                            getBadInvitationResponse(jsonStr);
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void getAllBlogListRequest(final Map paramMap) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = BaseActivity.SERVER_URL + "/blog-servlet?action=get-invitation";
                    OkHttpUtil.asyPost(url, paramMap, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String jsonStr = response.body().string();
                            getAllBlogListResponse(jsonStr);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void getAllBlogListResponse(final String jsonStr) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Gson gson = new Gson();
                Type listType = new TypeToken<List<List<Blog>>>() {
                }.getType();
//                Log.e("AllBlogList:jsonStr",jsonStr);
                List<Blog> lists = gson.fromJson(jsonStr, listType);
//                List<Blog> allBlogList=new ArrayList<>();
                lists = (List<Blog>) lists.get(0);
                allBlog = lists;
//                Log.e("allBlog的数据",String.valueOf(lists));
                BlogAdapter allAdapter = new BlogAdapter(allBlog);
                allRecyclerView.setAdapter(allAdapter);
//
//                if(allAdapter==null)
//                    Log.e("allAdapter","allAdapter is null");
//                if(allRecyclerView==null)
//                    Log.e("allRecyclerView1","allRecyclerView1 is null");
//                allRecyclerView= (RecyclerView) (getActivity().getLayoutInflater().inflate(R.layout.recyclerview, null)).findViewById(R.id.list_community);
//                if(allRecyclerView==null)
//                    Log.e("allRecyclerView2","allRecyclerView2 is null");
//                allRecyclerView.setAdapter(allAdapter);
////                InvitationChannelFragment.allBlog=allBlogList;

            }
        });
    }

    private void initAllBlog() {
        Map<String, String[]> paramMap_bad = new HashMap<String, String[]>();
        Map<String, String[]> paramMap_rec = new HashMap<String, String[]>();
        Map<String, String[]> paramMap_exp = new HashMap<String, String[]>();
        Map<String, String[]> paramMap_all = new HashMap<String, String[]>();
        Map<String, String[]> paramMap = new HashMap<String, String[]>();

//        paramMap.put("channelList",java.util.Arrays.copyOf(channelList,1));
        paramMap_rec.put("channelList", new String[]{"康复"});
        paramMap_bad.put("channelList", new String[]{"扫雷"});
        paramMap_exp.put("channelList", new String[]{"经验"});

        getExpListRequest(paramMap_exp);
        getBadListRequest(paramMap_bad);
        getRecInvitationRequest(paramMap_rec);
    }

    private void getRecInvitationRequest(final Map paramMap) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = BaseActivity.SERVER_URL + "/blog-servlet?action=get-invitation";
                    OkHttpUtil.asyPost(url, paramMap, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String jsonStr = response.body().string();
                            getRecInvitationResponse(jsonStr);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void getInvitationRequest(final Map paramMap, final Map paramMap_bad,
                                      final Map paramMap_rec, final Map paramMap_exp) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url1 = BaseActivity.SERVER_URL + "/blog-servlet?action=get-invitation";
                    String url2 = BaseActivity.SERVER_URL + "/question-servlet?action=get-allQuestion";
//                    String jsonStr1= OkHttpUtil.synPost(url1, paramMap);换为异步
//                    String jsonStr2= OkHttpUtil.synPost(url2, null);换为异步
//                    String jsonStr_rec= OkHttpUtil.synPost(url1, paramMap_rec);
//                    String jsonStr_bad= OkHttpUtil.synPost(url1, paramMap_bad);
//                    String jsonStr_exp= OkHttpUtil.synPost(url1, paramMap_exp);
//                    Log.e("getInvitationRequest","getInvitationRequest");
//                    getInvitationResponse(jsonStr1);
//                    getQuestionResponse(jsonStr2);
//                    getRecInvitationResponse(jsonStr_rec);
//                    getBadInvitationResponse(jsonStr_bad);
//                    getExpInvitationResponse(jsonStr_exp);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void getBadInvitationResponse(final String jsonStr) {
        getActivity().runOnUiThread(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void run() {
//                Log.e("jsonStr",jsonStr);
                Gson gson = new Gson(); // 使用 gson 库解析 JSON 数据
//                 创建一个 TypeToken 的匿名子类对象，并调用对象的 getType()方法
                Type listType = new TypeToken<List<List<Blog>>>() {
                }.getType();
//                Log.e("jsonStr",jsonStr);
                List<List<Blog>> lists = gson.fromJson(jsonStr, listType);

                List<Blog> badBlogList = new ArrayList<>();
                badBlogList = (List<Blog>) lists.get(0);
                badBlog = badBlogList;
                BlogAdapter badAdapter = new BlogAdapter();
                badAdapter.setRecnewsList(badBlog);
                badRecyclerView.setAdapter(badAdapter);
//                Log.e("badBlog",String.valueOf(badBlogList));

            }
        });
    }

    private void getRecInvitationResponse(final String jsonStr) {
        getActivity().runOnUiThread(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void run() {
//                Log.e("jsonStr",jsonStr);
                Gson gson = new Gson(); // 使用 gson 库解析 JSON 数据
//                 创建一个 TypeToken 的匿名子类对象，并调用对象的 getType()方法
                Type listType = new TypeToken<List<List<Blog>>>() {
                }.getType();
//                Log.e("jsonStr",jsonStr);
                List<List<Blog>> lists = gson.fromJson(jsonStr, listType);

                List<Blog> recBlogList = new ArrayList<>();
                recBlogList = (List<Blog>) lists.get(0);
                recBlog = recBlogList;
                BlogAdapter recAdapter = new BlogAdapter();
                recAdapter.setRecnewsList(recBlog);
                recRecyclerView.setAdapter(recAdapter);
//                Log.e("recBlog的数据",String.valueOf(recBlogList));
            }
        });
    }

    private void getExpInvitationResponse(final String jsonStr) {
        getActivity().runOnUiThread(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void run() {
                Log.e("jsonStr", jsonStr);
                Gson gson = new Gson(); // 使用 gson 库解析 JSON 数据
//                 创建一个 TypeToken 的匿名子类对象，并调用对象的 getType()方法
                Type listType = new TypeToken<List<List<Blog>>>() {
                }.getType();
//                Log.e("jsonStr",jsonStr);
                List<List<Blog>> lists = gson.fromJson(jsonStr, listType);

                List<Blog> expBlogList = new ArrayList<>();
                expBlogList = (List<Blog>) lists.get(0);
                expBlog = expBlogList;
//                Log.e("expBlog的数据",String.valueOf(expBlogList));
                BlogAdapter expAdapter = new BlogAdapter();
                expAdapter.setRecnewsList(expBlog);
                expRecyclerView.setAdapter(expAdapter);
            }
        });
    }

    private void getQuestionResponse(final String jsonStr) {
        getActivity().runOnUiThread(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void run() {
                Gson gson = new Gson(); // 使用 gson 库解析 JSON 数据
//                 创建一个 TypeToken 的匿名子类对象，并调用对象的 getType()方法
//                Log.e("questionListStr",jsonStr);
                Type listType = new TypeToken<List<Question>>() {
                }.getType();
                List<Question> questionList = gson.fromJson(jsonStr, listType);
                allQuestion = questionList;
                QuestionAdapter questionAdapter = new QuestionAdapter();
                questionAdapter.setQuestionList(allQuestion);
                questionRecyclerView.setAdapter(questionAdapter);
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        isPause = true; //记录页面已经被暂停
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isPause) { //判断是否暂停
            isPause = false;
            if (invitationCategoryTitleNum == 0) {
                Map<String, String[]> paramMap = new HashMap<String, String[]>();
                paramMap.put("channelList", new String[]{"全部"});
                getAllBlogListRequest(paramMap);
                BlogAdapter allAdapter = new BlogAdapter(allBlog);
                allRecyclerView.setAdapter(allAdapter);
            }else if(invitationCategoryTitleNum == 4) {
                getQuestionListRequest();
                QuestionAdapter questionAdapter = new QuestionAdapter(allQuestion, getContext());
                questionRecyclerView.setAdapter(questionAdapter);
            }else if(invitationCategoryTitleNum == 2) {
                Map<String, String[]> paramMap = new HashMap<String, String[]>();
                paramMap = new HashMap<String, String[]>();
                paramMap.put("channelList", new String[]{"康复"});
                getRecInvitationRequest(paramMap);
                BlogAdapter recAdapter = new BlogAdapter(recBlog);
                recRecyclerView.setAdapter(recAdapter);
            }else if(invitationCategoryTitleNum == 3) {
                Map<String, String[]> paramMap = new HashMap<String, String[]>();
                paramMap = new HashMap<String, String[]>();
                paramMap.put("channelList", new String[]{"扫雷"});
                getBadListRequest(paramMap);
                BlogAdapter badAdapter = new BlogAdapter(badBlog);
                badRecyclerView.setAdapter(badAdapter);
            }else if(invitationCategoryTitleNum == 1) {
                Map<String, String[]> paramMap = new HashMap<String, String[]>();
                paramMap = new HashMap<String, String[]>();
                paramMap.put("channelList", new String[]{"经验"});
                getExpListRequest(paramMap);
                BlogAdapter expAdapter = new BlogAdapter(expBlog);
                expRecyclerView.setAdapter(expAdapter);
            }

        }

    }

}

