package com.yidianling.im.session.viewholder;

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.MultipleSelectedEvent;
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 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 String examId;
    private String questionPaperId;
    private String questionId;
    private ArrayList<AnswersItem> answersItems=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;
//                return R.layout.im_nim_lingxi_multiple_choice;
                 case "check"://请问是发生了什么事情导致的呢？（多选）
                     return R.layout.im_nim_lingxi_multiple_choice;
                 case "3"://您是先生还是女生
                     return R.layout.im_nim_lingxi_men_female;
                 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);

    }

    @Override
    protected void bindContentView() {
        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();
        which_question_title.setText(customAttachLingxiWhichQuestion.name);
        for (int i=0;i<questionList.size();i++){
            questionList.get(i).setSelected(false);
            if (questionList.get(i).getName().length()>5){
                isSingleChoice=true;
                break;
            }
        }
        if (customAttachLingxiWhichQuestion.type!=null){
            switch (customAttachLingxiWhichQuestion.type){
                case "radio"://您想要咨询下列哪类的问题？（单选）
                    if (questionList!=null&&questionList.size()!=0){
                        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);
                    }
                    break;
                case "check"://请问是发生了什么事情导致的呢？（多选）
                    //        //请问是发生了什么事情导致的呢？（多选）
                    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);
                    break;
                case "3"://您是先生还是女生
                    break;
                default:
                    break;
            }
        }

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

                if (obj != null) {
                    boolean b = (boolean) obj;
                    Integer posi=(Integer) position;
                    if (b) {
                        //不可点击
                        isClickable=false;
                        questionList.get(posi).setSelected(true);
                    }
                }  else {
                    //可点击
                }

            } else {
            //可点击

            }
        } catch (Exception e) {
        }


    }

    @Override
    public void onItemClick(@NotNull QuestionItemBean itemBean, int position) {
        if (isClickable){
            for (int i=0;i<questionList.size();i++){
                questionList.get(i).setSelected(i==position);
            }
            adapterLingxiWhichQuestion.setTagData(questionList,isSingleChoice);
            isClickable=false;
            answersItems.add(new AnswersItem(questionList.get(position).getId(),
                    questionList.get(position).getName(),"其他",questionList.get(position).getRelates()));
            //请求接口发送所选题目
            answerLingxiQuestion(examId,questionPaperId, ImIn.INSTANCE.getUserInfo().getUid().toString(),questionId,answersItems);
            //更新本地消息
            updateLocalMsg(position);

        }
    }

    /*
     * 用户回答问题接口
     * */
    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),message.getFromAccount(),"56",uid));
        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) {
        //多选发送消息
        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());
                }
            }else{
                if (i==position){
                    questionList.get(i).setSelected(true);
                    selectedStr.add(questionList.get(i).getName());
                }
            }
        }
        confirm_multiple_choice.setText(selectedStr.size());
        stringBuffer.delete(2,stringBuffer.length());
        for (int i=0;i<selectedStr.size();i++){
            stringBuffer.append("#").append(selectedStr.get(i));
        }
        EventBus.getDefault().post(new MultipleSelectedEvent(stringBuffer.toString()));
        adapterLingxiMultipleChoice.setTagData(questionList);
    }
    private void updateLocalMsg(Integer position) {
        //更新本地消息
        Map<String, Object> map = message.getLocalExtension();
        if (map == null) {
            map = new HashMap();
        }
        map.put("isSure", true);
        map.put("position", position);

        message.setLocalExtension(map);
        NIMClient.getService(MsgService.class).updateIMMessage(message);
        //同时更新历史同订单未确认的消息状态
        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 CustomAttachLingxiWhichQuestion) {
                                Map map1 = msg.getLocalExtension();
                                if (map1 == null) {
                                    map1 = new HashMap();
                                    map1.put("isExpired", true);
                                    map1.put("position", position);
                                    msg.setLocalExtension(map1);
                                    NIMClient.getService(MsgService.class).updateIMMessage(msg);
                                    //通知ui刷新
                                    getMsgAdapter().updateItemAtLocalExtension(msg);
                                }
                        }
                    }
                }
            }

            @Override
            public void onFailed(int code) {

            }

            @Override
            public void onException(Throwable exception) {

            }
        });
    }

}
