package com.bokecc.room.ui.view.widget;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckedTextView;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bokecc.room.ui.R;
import com.bokecc.room.ui.view.adapter.QuestionListAdapter;
import com.bokecc.sskt.base.CCAtlasClient;
import com.bokecc.sskt.base.bean.CCQuestionAnswerBean;
import com.bokecc.sskt.base.bean.CCQuestionBean;
import com.bokecc.sskt.base.common.network.CCRequestCallback;
import com.bokecc.sskt.base.common.util.DensityUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;


/**
 * 问答组件
 */
public class CCQuestionView extends FrameLayout {
    public static final int showAllQuestion = 0;
    public static final int showMineQuestion = 1;

    private CheckedTextView tv_show_type;
    private TextView tvQuestionTitle;
    private RecyclerView rvQuestionList;
    private ArrayList<CCQuestionBean> studentAllQuestionBeans = new ArrayList<>();
    private ArrayList<CCQuestionBean> allQuestionBeans = new ArrayList<>();
    private ArrayList<CCQuestionBean> mineQuestionBeans = new ArrayList<>();
    private QuestionListAdapter adapter;
    private CCQuestionAnswerView answerView;
    private CCQuestionAskView askView;
    private ToggleButton toggle_button_allow_question;
    private View ll_toggle_button;

    private int showType = showAllQuestion;
    private InputMethodManager manager = ((InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE));


    public CCQuestionView(Context context) {
        super(context);
        initView(context);
    }

    public CCQuestionView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public CCQuestionView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(final Context context) {
        View questionView = View.inflate(context, R.layout.cc_question_view_layout, null);
        addView(questionView);

        questionView.findViewById(R.id.parent).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                setVisibility(GONE);
            }
        });

        toggle_button_allow_question = questionView.findViewById(R.id.toggle_button_allow_question);
        ll_toggle_button = findViewById(R.id.ll_allow_question);
        toggle_button_allow_question.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, final boolean b) {
                if (!toggle_button_allow_question.isPressed()) {
                    return;
                }

                CCAtlasClient.getInstance().sendAllowQuestion(b ? 1 : 0, new CCRequestCallback<Object>() {
                    @Override
                    public void onSuccess(Object response) {
                    }

                    @Override
                    public void onFailure(int errorCode, String errorMsg) {
                        Toast.makeText(getContext(), errorMsg, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

        tvQuestionTitle = questionView.findViewById(R.id.tv_question_title);
        tv_show_type = questionView.findViewById(R.id.tv_show_type);
        tv_show_type.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (showType == showAllQuestion) {
                    tv_show_type.setChecked(true);
                    showType = showMineQuestion;
//                    tv_show_type.setText("看全部");
                } else {
                    tv_show_type.setChecked(false);
                    showType = showAllQuestion;
                    tv_show_type.setText("只看自己");
                }
                setShowQuestionType();
            }
        });

        rvQuestionList = questionView.findViewById(R.id.rv_question_list_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(context, LinearLayout.VERTICAL, false);
        rvQuestionList.setLayoutManager(layoutManager);

        adapter = new QuestionListAdapter(context, new QuestionListAdapter.QuestionListClickListener() {
            @Override
            public void clickAnswer(int position, final CCQuestionBean questionBean) {
                if (CCAtlasClient.getInstance().isRoomLive()) {
                    answerView.setVisibility(VISIBLE);
                    answerView.initData(questionBean, new CCQuestionAnswerView.OnClickTeacherAnswerViewListener() {
                        @Override
                        public void clickSendAnswer(String content, boolean isPrivate) {
                            if (manager != null) {
                                manager.hideSoftInputFromWindow(CCQuestionView.this.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                            }
                            if (!isPrivate) {
                                allQuestionBeans.get(allQuestionBeans.indexOf(questionBean)).setPublish(1);
                                adapter.notifyItemChanged(allQuestionBeans.indexOf(questionBean));
                            }
                            CCAtlasClient.getInstance().sendQuestionAnswer(questionBean.getId(), content, isPrivate ? 1 : 0, CCAtlasClient.getInstance().getUserIdInPusher()
                                    , CCAtlasClient.getInstance().getUserName(), questionBean.getQuestionUser().getId());
                        }
                    });
                } else {
                    Toast.makeText(context, "开启直播前无法操作问答！", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void clickPublic(int position, CCQuestionBean questionBean) {
                if (CCAtlasClient.getInstance().isRoomLive()) {
                    CCAtlasClient.getInstance().sendQuestionPublic(questionBean.getId());
                } else {
                    Toast.makeText(context, "开启直播前无法操作问答！", Toast.LENGTH_SHORT).show();
                }
            }
        });
        adapter.bindDatas(studentAllQuestionBeans);
        rvQuestionList.setAdapter(adapter);

        answerView = questionView.findViewById(R.id.answer_view);
        askView = questionView.findViewById(R.id.ask_view);

//        getAllQuestionData();
    }

    public void getAllQuestionData() {
        CCAtlasClient.getInstance().getAllQuestionListData(new CCRequestCallback<ArrayList<CCQuestionBean>>() {
            @Override
            public void onSuccess(ArrayList<CCQuestionBean> response) {
//                showQuestionBeans.clear();
//                showQuestionBeans.addAll(response);
                allQuestionBeans.clear();
                allQuestionBeans.addAll(response);
                studentAllQuestionBeans.clear();
                mineQuestionBeans.clear();

                for (int i = 0; i < allQuestionBeans.size(); i++) {
                    if (allQuestionBeans.get(i).getPublish() == 1
                            || allQuestionBeans.get(i).getQuestionUser().getId().equals(CCAtlasClient.getInstance().getUserIdInPusher())) {
                        studentAllQuestionBeans.add(0, allQuestionBeans.get(i));
                        askQuestionTimeSort(studentAllQuestionBeans);
                    }
                    if (allQuestionBeans.get(i).getQuestionUser().getId().equals(CCAtlasClient.getInstance().getUserIdInPusher())) {
                        mineQuestionBeans.add(0, allQuestionBeans.get(i));
                        askQuestionTimeSort(mineQuestionBeans);
                    }
                }


                setShowQuestionType();
            }

            @Override
            public void onFailure(int errorCode, String errorMsg) {
                Log.e("getAllQuestionListData", "errorMsg = " + errorMsg + "errorCode = " + errorCode);
            }
        });
    }

    @Override
    public void setVisibility(int visibility) {
        super.setVisibility(visibility);
        if (visibility == VISIBLE) {
            if (CCAtlasClient.getInstance().getRole() == CCAtlasClient.TALKER
                    || CCAtlasClient.getInstance().getRole() == CCAtlasClient.AUDITOR) {
                tv_show_type.setVisibility(VISIBLE);
                ll_toggle_button.setVisibility(GONE);
            } else {
                tv_show_type.setVisibility(GONE);
                ll_toggle_button.setVisibility(VISIBLE);
            }
            if (allQuestionBeans == null || allQuestionBeans.size() == 0) {
                getAllQuestionData();
            }
            if (CCAtlasClient.getInstance().getRole() == CCAtlasClient.TALKER
                    || CCAtlasClient.getInstance().getRole() == CCAtlasClient.ASSISTANT) {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) rvQuestionList.getLayoutParams();
                params.bottomMargin = DensityUtil.dp2px(getContext(), 85);
                askView.showAskView(new CCQuestionAskView.OnClickTeacherAskViewListener() {
                    @Override
                    public void clickSendAsk(String content) {
                        if (manager != null) {
                            manager.hideSoftInputFromWindow(CCQuestionView.this.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                        }
                        if (CCAtlasClient.getInstance().isRoomLive()) {
                            CCAtlasClient.getInstance().sendQuestion(CCAtlasClient.getInstance().getUserIdInPusher()
                                    , CCAtlasClient.getInstance().getUserName(), content);
                        } else {
                            Toast.makeText(CCQuestionView.this.getContext(), "开启直播前无法操作问答！", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            } else {
                askView.setVisibility(GONE);
            }
        }
    }

    public void releaseData() {
        if (allQuestionBeans != null) {
            allQuestionBeans.clear();
        }
        if (mineQuestionBeans != null) {
            mineQuestionBeans.clear();
        }
        if (studentAllQuestionBeans != null) {
            studentAllQuestionBeans.clear();
        }
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }

    public void enableAskQuestion(boolean isEnable) {
        if (askView != null && askView.getVisibility() == VISIBLE) {
            askView.enableAskQuestion(isEnable);
        }
    }

    public void setAskQuestionData(CCQuestionBean questionData) {
        allQuestionBeans.add(0, questionData);

        if (CCAtlasClient.getInstance().getRole() == CCAtlasClient.TALKER
                || CCAtlasClient.getInstance().getRole() == CCAtlasClient.AUDITOR) {
            if (questionData.getPublish() == 1
                    || questionData.getQuestionUser().getId().equals(CCAtlasClient.getInstance().getUserIdInPusher())) {
                studentAllQuestionBeans.add(0, questionData);
                askQuestionTimeSort(studentAllQuestionBeans);
                adapter.notifyDataSetChanged();
            }

            if ((questionData.getQuestionUser().getId().equals(CCAtlasClient.getInstance().getUserIdInPusher()))) {
                mineQuestionBeans.add(0, questionData);
                askQuestionTimeSort(mineQuestionBeans);
                adapter.notifyDataSetChanged();
            }
//            adapter.notifyItemChanged(0);

        } else if (CCAtlasClient.getInstance().getRole() == CCAtlasClient.PRESENTER
                || CCAtlasClient.getInstance().getRole() == CCAtlasClient.ASSISTANT) {
//            adapter.notifyItemChanged(0);
            adapter.notifyDataSetChanged();
        }
    }

    public void setAnswerQuestionData(CCQuestionAnswerBean questionAnswerData) {
        for (int i = 0; i < allQuestionBeans.size(); i++) {
            if (allQuestionBeans.get(i).getId().equals(questionAnswerData.getQuestionId())) {
                if (CCAtlasClient.PRESENTER == CCAtlasClient.getInstance().getRole() ||
                        CCAtlasClient.ASSISTANT == CCAtlasClient.getInstance().getRole()) {
                    allQuestionBeans.get(i).getAnswerBeans().add(questionAnswerData);
//                    adapter.notifyItemChanged(i);
                    adapter.notifyDataSetChanged();
                    break;

                } else if (CCAtlasClient.TALKER == CCAtlasClient.getInstance().getRole()
                        || CCAtlasClient.AUDITOR == CCAtlasClient.getInstance().getRole() ) {
                    if (mineQuestionBeans.contains(allQuestionBeans.get(i))) {
                        mineQuestionBeans.get(mineQuestionBeans.indexOf(allQuestionBeans.get(i)))
                                .getAnswerBeans().add(questionAnswerData);
                    } else if (studentAllQuestionBeans.contains(allQuestionBeans.get(i))) {
                        studentAllQuestionBeans.get(studentAllQuestionBeans.indexOf(allQuestionBeans.get(i)))
                                .getAnswerBeans().add(questionAnswerData);
                    }

                    if (questionAnswerData.getIsPrivate() == 0) {
                        publishQuestionWhenAnswerPublic(allQuestionBeans.get(i),questionAnswerData);
                    }

//                    if (showType == showMineQuestion) {
//                        adapter.notifyItemChanged(mineQuestionBeans.indexOf(allQuestionBeans.get(i)));
//                    } else {
//                        adapter.notifyItemChanged(studentAllQuestionBeans.indexOf(allQuestionBeans.get(i)));
//                    }
                    adapter.notifyDataSetChanged();
                    break;

                }
            }
        }
    }

    public void setQuestionPublic(String questionId) {
        for (int i = 0; i < allQuestionBeans.size(); i++) {

            if (CCAtlasClient.TALKER == CCAtlasClient.getInstance().getRole()
                    || CCAtlasClient.AUDITOR == CCAtlasClient.getInstance().getRole() ) {
                if (allQuestionBeans.get(i).getId().equals(questionId)) {
                    allQuestionBeans.get(i).setPublish(1);
                    if (studentAllQuestionBeans.contains(allQuestionBeans.get(i))) {
                        if (showType == showAllQuestion) {
                            int index = studentAllQuestionBeans.indexOf(allQuestionBeans.get(i));
                            studentAllQuestionBeans.get(index).setPublish(1);
//                            adapter.notifyItemChanged(index);
                        } else {
                            int index = mineQuestionBeans.indexOf(allQuestionBeans.get(i));
                            mineQuestionBeans.get(index).setPublish(1);
//                            adapter.notifyItemChanged(index);
                        }
//                        adapter.notifyDataSetChanged();
                    } else {
                        studentAllQuestionBeans.add(0, allQuestionBeans.get(i));
                        askQuestionTimeSort(studentAllQuestionBeans);
//                            adapter.notifyItemChanged(0);
                    }
                    adapter.notifyDataSetChanged();
                }
            } else if (CCAtlasClient.PRESENTER == CCAtlasClient.getInstance().getRole()
                || CCAtlasClient.ASSISTANT == CCAtlasClient.getInstance().getRole()) {
                if (allQuestionBeans.get(i).getId().equals(questionId)) {
                    allQuestionBeans.get(i).setPublish(1);//0 是不公开，1是公开
                    adapter.notifyItemChanged(i);
                }
            }
        }
    }

    public void setShowQuestionType() {
        if (CCAtlasClient.getInstance().getRole() == CCAtlasClient.TALKER
                || CCAtlasClient.getInstance().getRole() == CCAtlasClient.AUDITOR) {
            if (showType == showAllQuestion) {
                adapter.bindDatas(studentAllQuestionBeans);
            } else {
                adapter.bindDatas(mineQuestionBeans);
            }
        } else if (CCAtlasClient.getInstance().getRole() == CCAtlasClient.PRESENTER
                || CCAtlasClient.getInstance().getRole() == CCAtlasClient.ASSISTANT) {
            adapter.bindDatas(allQuestionBeans);
        }

        adapter.notifyDataSetChanged();
    }

    private void publishQuestionWhenAnswerPublic(CCQuestionBean questionBean,CCQuestionAnswerBean questionAnswerData) {
        if (studentAllQuestionBeans.contains(questionBean)) {
            studentAllQuestionBeans.get(studentAllQuestionBeans.indexOf(questionBean)).setPublish(1);
        } else {
            studentAllQuestionBeans.add(0, allQuestionBeans.get(allQuestionBeans.indexOf(questionBean)));
            studentAllQuestionBeans.get(0).getAnswerBeans().add(questionAnswerData);
            askQuestionTimeSort(studentAllQuestionBeans);
            if (unreadQuestionListener != null){
                unreadQuestionListener.onUnreadQuestion();
            }
        }
    }

    private OnUnreadQuestionListener unreadQuestionListener;
    public void setOnUnreadQuestionListener(OnUnreadQuestionListener unreadQuestionListener){
        this.unreadQuestionListener = unreadQuestionListener;
    }

    public interface OnUnreadQuestionListener{
        void onUnreadQuestion();
    }

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public void askQuestionTimeSort(ArrayList<CCQuestionBean> questionBeans){
        Collections.sort(questionBeans, new Comparator<CCQuestionBean>() {
            @Override
            public int compare(CCQuestionBean questionBean, CCQuestionBean t1) {
                try {
                    long questionBeanTime1 = format.parse(questionBean.getTime()).getTime();
                    long questionBeanTime2 = format.parse(t1.getTime()).getTime();
                    if (questionBeanTime1 < questionBeanTime2) {
                        return 1;
                    } else if (questionBeanTime1 > questionBeanTime2) {
                        return -1;
                    } else {
                        return 0;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
    }
}
