package com.yidianling.im.session.viewholder;

import android.os.Build;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.yidianling.common.tools.LogUtil;
import com.yidianling.im.R;
import com.yidianling.im.event.MultipleAnswerBean;
import com.yidianling.im.event.MultipleSelectedEvent;
import com.yidianling.im.event.OthersState;
import com.yidianling.im.http.ImRetrofitApi;
import com.yidianling.im.router.ImIn;
import com.yidianling.im.session.extension.CustomAttachLingxiWhichQuestion;
import com.yidianling.im.session.viewholder.adapter.AdapterLingxiMultipleChoice;
import com.yidianling.im.session.viewholder.adapter.AdapterLingxiWhichQuestion;
import com.yidianling.im.session.viewholder.bean.AnswerBean;
import com.yidianling.im.session.viewholder.bean.AnswersItem;
import com.yidianling.im.session.viewholder.bean.LingxiAnswerBean;
import com.yidianling.im.session.viewholder.bean.QuestionItemBean;
import com.yidianling.nimbase.common.ui.recyclerview.adapter.BaseMultiItemFetchLoadAdapter;
import com.yidianling.uikit.business.session.viewholder.MsgViewHolderBase;

import org.jetbrains.annotations.NotNull;

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

import de.greenrobot.event.EventBus;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class MsgViewHolderLingxiWhichQuestion extends MsgViewHolderBase implements AdapterLingxiWhichQuestion.OnQuestionlItemClickListener, AdapterLingxiMultipleChoice.OnMultiplelItemClickListener  {
    private RecyclerView recycleviewWhichQuestion;
    private RecyclerView recycleviewMultipleChoice;
    private TextView confirm_multiple_choice;
    private TextView which_question_title;
    private TextView multiple_choice_title;

    private AdapterLingxiWhichQuestion adapterLingxiWhichQuestion;
    private AdapterLingxiMultipleChoice adapterLingxiMultipleChoice;

    ArrayList<QuestionItemBean> questionList = new ArrayList<QuestionItemBean>();
    Boolean isSingleChoice = false;
    CustomAttachLingxiWhichQuestion customAttachLingxiWhichQuestion;
    private StringBuffer stringBuffer = new StringBuffer("已选:");
    ArrayList<String> selectedStr = new ArrayList<String>();
    private Boolean isClickable = true;
    private Boolean isOthers;
    //回答试卷接口
    private String examId;
    private String questionPaperId;
    private String questionId;
    private ArrayList<AnswersItem> answersItems = new ArrayList<>();
    private ArrayList<String> multipleAnswers=new ArrayList<>();

    public MsgViewHolderLingxiWhichQuestion(BaseMultiItemFetchLoadAdapter adapter) {
        super(adapter);
    }

    @Override
    protected int getContentResId() {
        customAttachLingxiWhichQuestion = ((CustomAttachLingxiWhichQuestion) message.getAttachment());
        if (customAttachLingxiWhichQuestion.type != null) {
            switch (customAttachLingxiWhichQuestion.type) {
                case "radio"://您想要咨询下列哪类的问题？（单选）
                    return R.layout.im_nim_lingxi_which_question;
                case "check"://请问是发生了什么事情导致的呢？（多选）
                    return R.layout.im_nim_lingxi_multiple_choice;
                default:
                    return R.layout.im_nim_lingxi_which_question;
            }
        } else {
            return R.layout.im_nim_lingxi_which_question;
        }

    }

    @Override
    protected void inflateContentView() {
        recycleviewWhichQuestion = findViewById(R.id.which_question_rv);
        recycleviewMultipleChoice = findViewById(R.id.multiple_question_rv);
        confirm_multiple_choice = findViewById(R.id.confirm_multiple_choice);
        which_question_title = findViewById(R.id.which_question_title);
        multiple_choice_title = findViewById(R.id.multiple_choice_title);

    }

    @Override
    protected void bindContentView() {
        ImIn.INSTANCE.setImMessage(message);
        customAttachLingxiWhichQuestion = ((CustomAttachLingxiWhichQuestion) message.getAttachment());
        examId = customAttachLingxiWhichQuestion.examId;
        questionPaperId = customAttachLingxiWhichQuestion.questionPaperId;
        questionId = customAttachLingxiWhichQuestion.id;

        //您想要咨询下列哪类的问题？（单选）
        if (customAttachLingxiWhichQuestion.options != null) {
            questionList = (ArrayList<QuestionItemBean>) customAttachLingxiWhichQuestion.options;
        }
        adapterLingxiWhichQuestion = new AdapterLingxiWhichQuestion();
        for (int i = 0; i < questionList.size(); i++) {
            questionList.get(i).setSelected(false);
            if (questionList.get(i).getName().length() > 5) {
                isSingleChoice = true;
            }
        }
        if (customAttachLingxiWhichQuestion.type != null) {
            switch (customAttachLingxiWhichQuestion.type) {
                case "radio"://您想要咨询下列哪类的问题？（单选）
                    if (questionList != null && questionList.size() != 0) {
                        initSingleChoice();
                    }
                    break;
                case "check"://请问是发生了什么事情导致的呢？（多选）
                    initMultipleChoice();
                    break;
                default:
                    break;
            }
        }
        UpdateFromLocalExtention();
    }

    private void UpdateFromLocalExtention() {
        try {
            Map<String, Object> map = message.getLocalExtension();
            if (map != null) {
                Object obj = map.get("isSure");
                Object position = map.get("position");
                Object multiple = map.get("multiple");

                if (obj != null) {
                    boolean b = (boolean) obj;
                    Integer posi = (Integer) position;
                    if (b) {
                        //不可点击
                        isClickable = false;
                        if (posi!=null){
                            questionList.get(posi).setSelected(true);
                        }
                    }
                } else {
                    //可点击
                }
                if (multiple!=null){
                    multipleAnswers= (ArrayList<String>) multiple;
                    for (int i=0;i<questionList.size();i++){
                        for (int j=0;j<multipleAnswers.size();j++){
                            if (questionList.get(i).getName().contains(multipleAnswers.get(j))){
                                questionList.get(i).setSelected(true);
                            }
                        }
                    }
                    if (isClickable){
                        confirm_multiple_choice.setEnabled(true);
                        confirm_multiple_choice.setBackground(context.getResources().getDrawable(R.drawable.im_background_18dp_ebebeb));
                    }else{
                        confirm_multiple_choice.setEnabled(false);
                        confirm_multiple_choice.setBackground(context.getResources().getDrawable(R.drawable.im_background_18dp_1da1f2));
                        confirm_multiple_choice.setText("确定("+multipleAnswers.size()+")");
                    }
                }

            } else {
                //可点击

            }
        } catch (Exception e) {
            LogUtil.e("aaaaa"+e.getLocalizedMessage());
        }

    }

    private void initMultipleChoice() {

        confirm_multiple_choice.setOnClickListener(view -> {
            //请求接口发送所选题目，通过发通知到YDLMessageFragment统一回答问题。
            EventBus.getDefault().post(new MultipleSelectedEvent(null, null,
                    new MultipleAnswerBean(examId, questionPaperId, ImIn.INSTANCE.getUserInfo().getUid(),
                            questionId, answersItems,message.getFromAccount()),false,false));
        });
        multiple_choice_title.setText(customAttachLingxiWhichQuestion.name);
        adapterLingxiMultipleChoice = new AdapterLingxiMultipleChoice();
        adapterLingxiMultipleChoice.setTagData(questionList);
        adapterLingxiMultipleChoice.setItemListener(this);
        GridLayoutManager multipleChoiceManager = new GridLayoutManager(context, 2);
        //当list中字段大于6个显示单行，否则显示双行
        multipleChoiceManager.setSpanCount(isSingleChoice ? 1 : 2);
        multipleChoiceManager.setOrientation(GridLayoutManager.VERTICAL);
        recycleviewMultipleChoice.setLayoutManager(multipleChoiceManager);
        recycleviewMultipleChoice.setAdapter(adapterLingxiMultipleChoice);
    }

    private void initSingleChoice() {
        which_question_title.setText(customAttachLingxiWhichQuestion.name);
        adapterLingxiWhichQuestion.setTagData(questionList, isSingleChoice);
        adapterLingxiWhichQuestion.setItemListener(this);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 2);
        //当list中字段大于6个显示单行，否则显示双行
        gridLayoutManager.setSpanCount(isSingleChoice ? 1 : 2);
        gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
        recycleviewWhichQuestion.setLayoutManager(gridLayoutManager);
        recycleviewWhichQuestion.setAdapter(adapterLingxiWhichQuestion);
    }

    @Override
    public void onItemClick(@NotNull QuestionItemBean itemBean, int position) {
        if (isClickable) {
            for (int i = 0; i < questionList.size(); i++) {
                if (questionList.get(i).isSelected()) {
                    if (i == position) {
                        if (questionList.get(i).getName().contains("其他")){
                            isClickable = true;
                            questionList.get(i).setSelected(false);
                            selectedStr.remove(questionList.get(i).getName());
                        }
                    }
                } else {
                    if (i == position) {
                        questionList.get(i).setSelected(true);
                        selectedStr.add(questionList.get(i).getName());
                    }else{
                        questionList.get(i).setSelected(false);
                        if (questionList.get(i).getName().contains("其他")){
                            selectedStr.remove(questionList.get(i).getName());
                        }
                    }
                }
                questionList.get(i).setSelected(i == position);
            }
            adapterLingxiWhichQuestion.setTagData(questionList, isSingleChoice);
            for (int i = 0; i < questionList.size(); i++) {
               if (questionList.get(i).isSelected()){
                   answersItems.clear();
                   answersItems.add(new AnswersItem(questionList.get(position).getId(),
                           questionList.get(position).getName(), "", questionList.get(position).getRelates()));
                   break;
               }
            }


            stringBuffer.delete(2, stringBuffer.length());
            for (int i = 0; i < selectedStr.size(); i++) {
                stringBuffer.append("#").append(selectedStr.get(i));
            }
            isOthers = questionList.get(position).getName().contains("其他");
            if (!isOthers){
                isClickable = false;
                //请求接口发送所选题目
                answerLingxiQuestion(examId, questionPaperId, ImIn.INSTANCE.getUserInfo().getUid().toString(), questionId, answersItems);
                //更新本地消息
                updateLocalMsg(position,null);
                //发通知取消隐藏输入框表情等符号
                EventBus.getDefault().post(new MultipleSelectedEvent(stringBuffer.toString(), new OthersState(isOthers, questionList.get(position).isSelected()), new MultipleAnswerBean(examId, questionPaperId, ImIn.INSTANCE.getUserInfo().getUid(),
                        questionId, answersItems,message.getFromAccount()),false,true));
            }else{
                EventBus.getDefault().post(new MultipleSelectedEvent(stringBuffer.toString(), new OthersState(isOthers, questionList.get(position).isSelected()), new MultipleAnswerBean(examId, questionPaperId, ImIn.INSTANCE.getUserInfo().getUid(),
                        questionId, answersItems,message.getFromAccount()),false,false));
            }
        }
    }

    /*
     * 用户回答问题接口
     * */
    private void answerLingxiQuestion(String examID, String questionPaperId, String uid, String questionId, ArrayList<AnswersItem> answersItems) {
        String str = new Gson().toJson(new LingxiAnswerBean(new AnswerBean(examID, questionPaperId, uid, questionId, answersItems), uid, "56", message.getFromAccount()));
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), str);
        Disposable subscribe = ImRetrofitApi.Companion.getImRetrofitApi().lingxiAnswerQuestion(body)
                .compose(RxUtils.INSTANCE.resultJavaData())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(it -> {
                            LogUtil.e("answerQuestion" + it.toString());
                        }, throwable ->
                                LogUtil.e(throwable.getMessage())
                );
    }


    @Override
    public void onMultipleItemClick(@NotNull QuestionItemBean string, int position) {
        if (isClickable){
            //多选发送消息
            for (int i = 0; i < questionList.size(); i++) {
                if (questionList.get(i).isSelected()) {
                    if (i == position) {
                        questionList.get(i).setSelected(false);
                        selectedStr.remove(questionList.get(i).getName());
                        for (int j=0;j<answersItems.size();j++){
                            if (questionList.get(i).getName()==answersItems.get(j).getName()){
                                answersItems.remove(j);
                                break;
                            }
                        }

                    }
                } else {
                    if (i == position) {
                        questionList.get(i).setSelected(true);
                        selectedStr.add(questionList.get(i).getName());
                        answersItems.add(new AnswersItem(questionList.get(position).getId(),
                                questionList.get(position).getName(), "", questionList.get(position).getRelates()));
                    }
                }
            }
            confirm_multiple_choice.setText(String.format("确定(%d)", selectedStr.size()));
            if (selectedStr.size() > 0) {
                confirm_multiple_choice.setEnabled(true);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    confirm_multiple_choice.setBackground(context.getResources().getDrawable(R.drawable.im_background_18dp_1da1f2));
                }
            } else {
                confirm_multiple_choice.setEnabled(false);
                confirm_multiple_choice.setText("确定");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    confirm_multiple_choice.setBackground(context.getDrawable(R.drawable.im_background_18dp_ebebeb));
                }
            }
            stringBuffer.delete(2, stringBuffer.length());
            for (int i = 0; i < selectedStr.size(); i++) {
                stringBuffer.append("#").append(selectedStr.get(i));
            }
            isOthers = questionList.get(position).getName().contains("其他");
            EventBus.getDefault().post(new MultipleSelectedEvent(stringBuffer.toString(), new OthersState(isOthers, questionList.get(position).isSelected()), new MultipleAnswerBean(examId, questionPaperId, ImIn.INSTANCE.getUserInfo().getUid(),
                    questionId, answersItems,message.getFromAccount()),false,false));
            adapterLingxiMultipleChoice.setTagData(questionList);
        }
    }

    private void updateLocalMsg(Integer position,ArrayList<String> selectedPosition) {
        //更新本地消息
        Map<String, Object> map = message.getLocalExtension();
        if (map == null) {
            map = new HashMap();
        }
        map.put("isSure", true);
        if (position!=null){
            map.put("position", position);
        }
        if (selectedPosition!=null){
            map.put("multiple", selectedPosition);
        }
        message.setLocalExtension(map);
        NIMClient.getService(MsgService.class).updateIMMessage(message);
        //通知ui刷新
        getMsgAdapter().updateItemAtLocalExtension(message);
    }
}
