package com.bokecc.livemodule.live.qa.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bokecc.dwlivedemo.R;
import com.bokecc.dwlivedemo.activity.ImageDetailsActivity;
import com.bokecc.livemodule.live.DWLiveCoreHandler;
import com.bokecc.livemodule.utils.DensityUtil;
import com.bokecc.livemodule.view.WarpLinearLayout;
import com.bokecc.sdk.mobile.live.DWLive;
import com.bokecc.sdk.mobile.live.pojo.Answer;
import com.bokecc.sdk.mobile.live.pojo.Question;
import com.bumptech.glide.Glide;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * 问答适配器
 */
public class QaAdapter extends RecyclerView.Adapter<QaAdapter.QaViewHolder> {


    private List<Question> list = new ArrayList<>();
    private List<Question> sourceList = new ArrayList<>();
    private Context mContext;
    private LayoutInflater mInflater;

    private SpannableStringBuilder ss = new SpannableStringBuilder();


    private RecyclerView.RecycledViewPool viewPool;

    private SimpleDateFormat sdf;

    private boolean isOnlyShowSelf = false;

    private String selfId  ="";



    public QaAdapter(Context context,boolean isReplay) {
        this.mContext = context;
        mInflater = LayoutInflater.from(context);
        viewPool = new RecyclerView.RecycledViewPool();
        if (isReplay){
            sdf = new SimpleDateFormat("HH:mm:ss");
        }else {
            sdf = new SimpleDateFormat("HH:mm");
        }
        if (DWLiveCoreHandler.getInstance().getViewer()!=null){
            selfId = DWLiveCoreHandler.getInstance().getViewer().getId();
        }
    }


    @NonNull
    @Override
    public QaAdapter.QaViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView;
        itemView = mInflater.inflate(R.layout.item_qa_question, parent, false);
        return new QaAdapter.QaViewHolder(mContext,itemView);
    }

    @Override
    public void onBindViewHolder(QaAdapter.QaViewHolder holder, int position) {
        Question question = list.get(position);

        holder.rvQaAnswerList.setRecycledViewPool(viewPool);

        holder.showItem(question);


        // 设置提问者名称
        ss.clear();
        ss.append(question.getQuestionUserName());
        ss.setSpan(getQuestionRoleNameColorSpan(question), 0, question.getQuestionUserName().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        holder.questionName.setText(ss);
        // 计算问答时间
        holder.questionTime.setText(sdf.format(new Date(question.getMillsTime())));
        // 设置问题内容
        holder.questionContent.setText(question.getContent());

        // 存在答案显示线
        if (question.getAnswerList() != null && question.getAnswerList().size() > 0) {
            holder.qaSeparateLine.setVisibility(View.VISIBLE);
        } else {
            holder.qaSeparateLine.setVisibility(View.GONE);
        }


        if (isOnlyShowSelf) {
            if (question.getQuestionUserId().equals(selfId)) {
                holder.qaSingleLayout.setVisibility(View.VISIBLE);
            } else {
                holder.qaSingleLayout.setVisibility(View.GONE);
            }
        } else {
            holder.qaSingleLayout.setVisibility(View.VISIBLE);
        }

        holder.llQaImgCon.removeAllViews();


        if (question.getExtra() != null && question.getExtra().getImg() != null) {
            showQaImg(holder, question.getExtra().getImg());
        }

    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    private ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#ff6633"));
    private ForegroundColorSpan foregroundColorSpan2 = new ForegroundColorSpan(Color.parseColor("#79808b"));
    private ForegroundColorSpan getQuestionRoleNameColorSpan(Question question) {
        if (DWLive.getInstance().getViewer() != null && question.getQuestionUserId().equalsIgnoreCase(DWLive.getInstance().getViewer().getId())) {
            return foregroundColorSpan;
        }
        return foregroundColorSpan2;
    }

    private void showQaImg(QaAdapter.QaViewHolder holder, List<Question.ExtraDTO.ImgDTO> imgUrlList) {
        Collections.sort(imgUrlList, new Comparator<Question.ExtraDTO.ImgDTO>() {
            @Override
            public int compare(Question.ExtraDTO.ImgDTO o1, Question.ExtraDTO.ImgDTO o2) {
                return o1.getOrder() - o2.getOrder();
            }
        });

        final List<String> urlList = new ArrayList<>();
        for (int i = 0; i < imgUrlList.size(); i++) {
            Question.ExtraDTO.ImgDTO imgDTO = imgUrlList.get(i);
            if (imgDTO != null) {
                urlList.add(imgDTO.getUrl());
                ImageView imageView = new ImageView(mContext);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                holder.llQaImgCon.addView(imageView);

                ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
                if (imgUrlList.size() == 1) {
                    layoutParams.width = DensityUtil.dp2px(mContext, 180f);
                    layoutParams.height = DensityUtil.dp2px(mContext, 135f);
                } else {
                    layoutParams.width = DensityUtil.dp2px(mContext, 75f);
                    layoutParams.height = DensityUtil.dp2px(mContext, 75f);
                }

                Glide.with(mContext).load(imgDTO.getUrl()).into(imageView);
                final int index = i;
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mContext instanceof Activity) {
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < urlList.size(); i++) {
                                String url = urlList.get(i);

                                if (url != null && !TextUtils.isEmpty(url)) {
                                    sb.append(url);
                                    if (i < urlList.size() - 1) {
                                        sb.append("###");
                                    }
                                }
                            }

                            Intent intent = new Intent(mContext, ImageDetailsActivity.class);
                            intent.putExtra("imageUrl", sb.toString());
                            intent.putExtra("hasDelete", false);
                            intent.putExtra("index", index);
                            ((Activity) mContext).startActivity(intent);
                        }

                    }
                });
            }
        }

    }

    public void setOnlyShowSelf(boolean isSelf) {
        this.isOnlyShowSelf = isSelf;
        setState(isSelf);
    }


    private void setState(boolean isOnlyShowSelf){
        if (isOnlyShowSelf){
            list.clear();

            for (int i = 0; i <sourceList.size(); i++) {
                Question question = sourceList.get(i);
                if (question.getQuestionUserId().equals(selfId)){
                    list.add(question);
                }
            }
            notifyDataSetChanged();
        }else {
            list.clear();
            //未发布的不添加
            for (int i = 0; i < sourceList.size(); i++) {
                Question question = sourceList.get(i);
                if (question.getQuestionUserId().equals(selfId)){
                    list.add(question);
                }else if(question.getIsPublish()==1){
                    list.add(question);
                }
            }
            notifyDataSetChanged();
        }
    }

    public void setList(List<Question> list){
        sourceList.clear();
        sourceList.addAll(list);
        //如果list的size大于3，默认处于收缩状态
        setState(isOnlyShowSelf);
    }


    public static class QaViewHolder extends RecyclerView.ViewHolder {

        RecyclerView rvQaAnswerList;
        WarpLinearLayout llQaImgCon;
        ImageView questionHeadView;
        TextView questionName;
        TextView questionTime;
        TextView questionContent;
        View qaSingleLayout;
        View qaSeparateLine;
        private QaInnerAdapter itemAdapter;
        private LinearLayoutManager linearLayoutManager;


        public void showItem(Question question){
            rvQaAnswerList.setAdapter(itemAdapter);
            if (question.getAnswerList()!=null){
                itemAdapter.setList(question.getAnswerList());
            }else {
                itemAdapter.setList(new ArrayList<Answer>());
            }
        }


        public QaViewHolder(Context context, View itemView) {
            super(itemView);
            questionHeadView = itemView.findViewById(R.id.user_head_view);
            questionName = itemView.findViewById(R.id.tv_question_name);
            questionTime = itemView.findViewById(R.id.tv_question_time);
            questionContent = itemView.findViewById(R.id.tv_question);
            qaSingleLayout = itemView.findViewById(R.id.ll_qa_single_layout);
            qaSeparateLine = itemView.findViewById(R.id.qa_separate_line);
            llQaImgCon = itemView.findViewById(R.id.ll_qa_img_con);
            rvQaAnswerList = itemView.findViewById(R.id.rv_qa_answer_list);
            itemAdapter = new QaInnerAdapter(context);
            linearLayoutManager = new LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false);
            rvQaAnswerList.setLayoutManager(linearLayoutManager);

        }
    }

}
