package com.yidianling.im.session.viewholder;

import android.view.View;
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.CustomAttachLingxiAnswerQuestion;
import com.yidianling.im.session.extension.CustomAttachLingxiWhichQuestion;
import com.yidianling.im.session.viewholder.adapter.AdapterLingxiMultipleChoice;
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 AdapterLingxiMultipleChoice.OnMultiplelItemClickListener {
    private RecyclerView recycleviewMultipleChoice;
    private TextView confirm_multiple_choice;
    private TextView multiple_choice_title;

    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 isOthers;
    //回答试卷接口
    private String examId;
    private String questionPaperId;
    private String questionId;
    private String singleOrMultipletype;
    private ArrayList<AnswersItem> answersItems = new ArrayList<>();
    Map<String, Object> mapMessageFromCustom;
    Map map1 = new HashMap();
    private ArrayList<String> multipleAnswers = new ArrayList<>();
    private ArrayList<String> answersItemsMap = new ArrayList<>();

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

    @Override
    protected int getContentResId() {
        customAttachLingxiWhichQuestion = ((CustomAttachLingxiWhichQuestion) message.getAttachment());
        singleOrMultipletype = customAttachLingxiWhichQuestion.type;
        if (customAttachLingxiWhichQuestion.type != null) {
            return R.layout.im_nim_lingxi_multiple_choice;
        } else {
            return R.layout.im_nim_lingxi_multiple_choice;
        }
    }

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

    @Override
    protected void bindContentView() {
        avatarRight.setVisibility(View.INVISIBLE);
        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;
        }
        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) {
            singleOrMultipletype = customAttachLingxiWhichQuestion.type;
            UpdateFromLocal();
            initMultipleChoice();
        }

        //进入消息列表时候，保存当type为56的时候的，将ID作为key保存
        NIMClient.getService(MsgService.class).queryMessageList(message.getSessionId(), SessionTypeEnum.P2P, 0, 100).setCallback(new RequestCallback<List<IMMessage>>() {
            @Override
            public void onSuccess(List<IMMessage> param) {
                if (param != null && param.size() > 0) {

                    for (IMMessage msg : param) {
                        MsgAttachment attachment = msg.getAttachment();
                        if (attachment instanceof CustomAttachLingxiAnswerQuestion) {
                            CustomAttachLingxiAnswerQuestion customattachlingxianswerquestion = (CustomAttachLingxiAnswerQuestion) attachment;
                            map1.put(customattachlingxianswerquestion.questionId + customattachlingxianswerquestion.examId, true);
                            mapMessageFromCustom = map1;
                            UpdateFromLocalExtention();
                        }
                    }
                }
            }

            @Override
            public void onFailed(int code) {
                LogUtil.e("获取消息onFailed：" + code);
            }

            @Override
            public void onException(Throwable exception) {
                LogUtil.e("获取消息exception：" + exception.getLocalizedMessage());
            }
        });

    }

    private void UpdateFromLocal() {
        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) {
                        //不可点击
                        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().equals(multipleAnswers.get(j))) {
                                questionList.get(i).setSelected(true);
                            }
                        }
                    }
                    if (multipleAnswers.size()>0){
                        confirm_multiple_choice.setEnabled(true);
                        confirm_multiple_choice.setText(String.format("确定(%d)", multipleAnswers.size()));
                        confirm_multiple_choice.setBackground(context.getResources().getDrawable(R.drawable.im_background_18dp_1da1f2));
                    }else{
                        confirm_multiple_choice.setEnabled(false);
                        confirm_multiple_choice.setText("确定");
                        confirm_multiple_choice.setBackground(context.getDrawable(R.drawable.im_background_18dp_ebebeb));
                    }
                }

            } else {
                //可点击
                if (!singleOrMultipletype.contains("radio")){
                    confirm_multiple_choice.setEnabled(false);
                    confirm_multiple_choice.setText("确定");
                    confirm_multiple_choice.setBackground(context.getDrawable(R.drawable.im_background_18dp_ebebeb));
                }
            }
        } catch (Exception e) {
            LogUtil.e("aaaaa" + e.getLocalizedMessage());
        }
    }

    private void UpdateFromLocalExtention() {
        try {
            Map<String, Object> mapMessage = new HashMap<>();
            if (mapMessageFromCustom != null) {
                mapMessage = mapMessageFromCustom;
            }
            if (mapMessage != null) {
                Object questionPaperId = mapMessage.get(customAttachLingxiWhichQuestion.id + customAttachLingxiWhichQuestion.examId);
                if (questionPaperId != null) {
                    boolean b = (boolean) questionPaperId;
                    if (b) {
                        //隐藏回答的信息
                        recycleviewMultipleChoice.setVisibility(View.GONE);
                        confirm_multiple_choice.setVisibility(View.GONE);
                    } else {
                        recycleviewMultipleChoice.setVisibility(View.VISIBLE);
                        confirm_multiple_choice.setVisibility(View.VISIBLE);
                    }
                } else {
                    if (singleOrMultipletype.contains("radio")) {
                        recycleviewMultipleChoice.setVisibility(View.VISIBLE);
                    } else {
                        recycleviewMultipleChoice.setVisibility(View.VISIBLE);
                        confirm_multiple_choice.setVisibility(View.VISIBLE);
                    }
                }
            }
        } catch (Exception e) {
            LogUtil.e(e.getLocalizedMessage());
        }

    }

    private void initMultipleChoice() {
        if (singleOrMultipletype.contains("radio")) {
            confirm_multiple_choice.setVisibility(View.GONE);
        } else {
            confirm_multiple_choice.setVisibility(View.VISIBLE);
        }
        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 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 (singleOrMultipletype.contains("radio")) {
            /*
             * 单选题：分其他选项和非其他选项
             * 其他选项，唤起输入框
             * 点击非其他选项直接发送答案
             * */
            for (int i = 0; i < questionList.size(); i++) {
                if (questionList.get(i).isSelected()) {
                    if (i == position) {
                        if (questionList.get(i).getName().contains("其他")) {
                            questionList.get(i).setSelected(false);
                            selectedStr.remove(questionList.get(i).getName());
                            break;
                        }
                    }
                } 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);
            }
            adapterLingxiMultipleChoice.setTagData(questionList);
            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) {
                //请求接口发送所选题目
                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));
            }
        } else {
            //多选发送消息
            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);
                confirm_multiple_choice.setBackground(context.getResources().getDrawable(R.drawable.im_background_18dp_1da1f2));
            } else {
                confirm_multiple_choice.setEnabled(false);
                confirm_multiple_choice.setText("确定");
                confirm_multiple_choice.setBackground(context.getDrawable(R.drawable.im_background_18dp_ebebeb));
            }
            stringBuffer.delete(3, 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);
            answersItemsMap.clear();
            for (int i = 0; i < answersItems.size(); i++) {
                if (!answersItemsMap.contains(answersItems.get(i).getName())) {
                    answersItemsMap.add(i, answersItems.get(i).getName());
                }
            }
            updateLocalMsg(null, answersItemsMap);
        }
    }

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