package com.yidianling.dynamic.trendList.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.collection.SparseArrayCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.ydl.webview.H5Params;
import com.ydl.webview.NewH5Activity;
import com.ydl.ydlcommon.utils.MoonUtil;
import com.ydl.ydlcommon.utils.StringUtils;
import com.ydl.ydlcommon.view.BaseViewHolder;
import com.yidianling.common.tools.LogUtil;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.members.MembersActivity;
import com.yidianling.dynamic.model.TrendsListBean;
import com.yidianling.dynamic.router.DynamicIn;

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

/**
 * Created by Jim on 2017/9/22 0022.
 */

public class TrendsListAdapter extends RecyclerView.Adapter<BaseViewHolder> {

    private static final int BASE_ITEM_TYPE_HEADER = 100000;
    private static final int BASE_ITEM_TYPE_FOOTER = 200000;

    public final static int TYPE_PURE_TEXT = 1;
    public final static int TYPE_PURE_PIC = 2;
    public final static int TYPE_TEXT_MERGE_PIC = 3;
    public final static int TYPE_PURE_URL = 4;
    public final static int FOOTER_STATE_NO_DATA = 1000 + BASE_ITEM_TYPE_FOOTER;
    public final static int FOOTER_STATE_ERROR = 1001 + BASE_ITEM_TYPE_FOOTER;
    public final static int FOOTRE_STATE_LOAD_MORE = 1002 + BASE_ITEM_TYPE_FOOTER;
    public final static int FOOTRE_STATE_INIT = 1003 + BASE_ITEM_TYPE_FOOTER;

    private int footerState;
    private List<TrendsListBean.Trend> mDatas;
    private Context mContext;
    private SparseArrayCompat<View> mHeaderViews;
    private SparseArrayCompat<View> mFootViews;
    private OnItemClickListener onItemClickListener;


    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onItemLikeClick(View view, int position, List<TrendsListBean.Trend> mDatas);

        void onItemClick(int id, int commentCount, int position);

        void onItemCommentClick(int id, int commentCount, int position);

//        void onItemHeadClick(int )
    }

    public TrendsListAdapter(Context context, List<TrendsListBean.Trend> datas) {
        mContext = context;
        mDatas = datas;
        footerState = FOOTRE_STATE_INIT;
    }

    public void setDatas(List<TrendsListBean.Trend> datas) {
        mDatas = datas;
    }

    public void setDatas(List<TrendsListBean.Trend> datas, int footerState) {
        mDatas = datas;
        this.footerState = footerState;
    }

    public void addDatas(List<TrendsListBean.Trend> datas, int footerState) {
        this.footerState = footerState;
        if (mDatas == null) {
            mDatas = new ArrayList<>();
        }
        mDatas.addAll(datas);
        notifyItemRangeChanged(mDatas.size() + getHeadersCount() - datas.size() - 1, datas.size());
    }

    public void addDatas(List<TrendsListBean.Trend> datas) {
        if (mDatas == null) {
            mDatas = new ArrayList<>();
        }
        mDatas.addAll(datas);
        notifyItemRangeChanged(mDatas.size() - datas.size() - 1, datas.size());
    }

    public List<TrendsListBean.Trend> getDatas() {
        return mDatas;
    }


    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (mHeaderViews != null && mHeaderViews.get(viewType) != null) {
            return new BaseViewHolder(mHeaderViews.get(viewType), mContext, viewType);
        }
        if (mFootViews != null && mFootViews.get(viewType) != null) {
            return new BaseViewHolder(mFootViews.get(viewType), mContext, viewType);
        }
        View view = LayoutInflater.from(mContext).inflate(R.layout.dynamic_item_trends_list, parent, false);
        ((RecyclerView) view.findViewById(R.id.item_trend_img_rcv)).setNestedScrollingEnabled(false);
        return new BaseViewHolder(view, mContext, viewType);
    }

    public void addHeaderView(View v) {
        if (mHeaderViews == null) {
            mHeaderViews = new SparseArrayCompat<>();
        }
        mHeaderViews.put(mHeaderViews.size() + BASE_ITEM_TYPE_HEADER, v);
    }

    public void addFooterView(View v) {
        if (mFootViews == null) {
            mFootViews = new SparseArrayCompat<>();
        }
        mFootViews.put(mFootViews.size() + BASE_ITEM_TYPE_FOOTER, v);
    }

    public int getHeadersCount() {
        if (mHeaderViews != null) {
            return mHeaderViews.size();
        }
        return 0;
    }

    public int getFootersCount() {
        if (mFootViews != null) {
            return mFootViews.size();
        }
        return 0;
    }

    private boolean isHeaderView(int position) {
        return position < getHeadersCount();
    }

    private boolean isFooterView(int position) {
        return position >= getHeadersCount() + mDatas.size();
    }


    @Override
    public int getItemViewType(int position) {
        if (isHeaderView(position)) {
            return mHeaderViews.keyAt(position);
        } else if (isFooterView(position)) {
            return mFootViews.keyAt(position - mDatas.size() - getHeadersCount());
        }
        return super.getItemViewType(position);
    }

    @Override
    public void onBindViewHolder(BaseViewHolder holder, int position) {
        LogUtil.i("run in onBindViewHolder " + position);
        holder.updatePosition(position);
        if (isHeaderView(position)) {
            return;
        }
        if (isFooterView(position)) {
            switch (footerState) {
                case FOOTER_STATE_ERROR:
                    holder.setVisibility(R.id.text_con, View.VISIBLE)
                            .setVisibility(R.id.pb, View.GONE)
                            .setText(R.id.text_con, "数据加载失败");
                    break;
                case FOOTER_STATE_NO_DATA:
                    holder.setText(R.id.text_con, mContext.getString(R.string.dynamic_no_more_data_hint))
                            .setVisibility(R.id.text_con, View.VISIBLE)
                            .setVisibility(R.id.pb, View.GONE);
                    break;
                case FOOTRE_STATE_LOAD_MORE:
                    holder.setText(R.id.text_con, mContext.getString(R.string.dynamic_loading_hint))
                            .setVisibility(R.id.pb, View.VISIBLE)
                            .setVisibility(R.id.text_con, View.VISIBLE);
                    break;
                case FOOTRE_STATE_INIT:
                    holder.setVisibility(R.id.text_con, View.GONE)
                            .setVisibility(R.id.pb, View.GONE);
                    break;
            }
            return;
        }
        TrendsListBean.Trend trend = mDatas.get(position - getHeadersCount());
        if (trend.isAd == 1) {
            trend.multitextType = TYPE_TEXT_MERGE_PIC;
            trend.smallAttach = new ArrayList<>();
            trend.smallAttach.add(trend.adImg);
        }
        //如果是广告，隐藏占赞和评论图标
        holder.setVisibility(R.id.item_trend_discuss_iv, trend.isAd == 1 ? View.GONE : View.VISIBLE);
        holder.setVisibility(R.id.text_talk_num, trend.isAd == 1 ? View.GONE : View.VISIBLE);
        holder.setVisibility(R.id.text_zan_num, trend.isAd == 1 ? View.GONE : View.VISIBLE);
        holder.setVisibility(R.id.item_trend_zan_iv, trend.isAd == 1 ? View.GONE : View.VISIBLE);
        holder.setVisibility(R.id.text_trend, trend.isAd == 1 ? View.GONE : View.VISIBLE);
        holder.setVisibility(R.id.item_trend_souce_tv, trend.isAd == 1 ? View.GONE : View.VISIBLE);
        int type = trend.multitextType;
        switch (type) {
            case TYPE_PURE_TEXT:
                showPureTextType(position, holder, trend);
                break;
            case TYPE_PURE_PIC:
                showTypeContainPic(position, holder, trend);
                break;
            case TYPE_TEXT_MERGE_PIC:
                showTypeContainPic(position, holder, trend);
                break;
            case TYPE_PURE_URL:
                showUrlType(position, holder, trend);
                break;
            default:
                break;
        }
    }

    private BaseViewHolder setBasicInfo(final int position, BaseViewHolder holder, final TrendsListBean.Trend trend) {
        LogUtil.d("content: " + trend.content);
        String trendContent = trend.content;
        if (!TextUtils.isEmpty(trendContent)) {     //动态内容处理
            holder.setVisibility(R.id.item_trend_content_tv, View.VISIBLE);
            if (trendContent.length() > 140) {
                trendContent = StringUtils.CustomEmojiSub(trendContent);    //处理表情没显示完全的情况
                MoonUtil.SetTrendContent(mContext, holder.getView(R.id.item_trend_content_tv), trendContent, "", "...查看全部", ImageSpan.ALIGN_BOTTOM);
                LogUtil.d("get Trend content: " + trendContent);
            } else {
                MoonUtil.SetTrendContent(mContext, holder.getView(R.id.item_trend_content_tv), trendContent, "", "", ImageSpan.ALIGN_BOTTOM);
            }
        } else {
            holder.setVisibility(R.id.item_trend_content_tv, View.GONE);
        }
        if (TextUtils.isEmpty(trend.title)){
            holder.setVisibility(R.id.item_trend_title_tv, View.GONE);
        }

        if (trend.comments!=null){
            showCommentsPart(holder, trend);

        }
        LogUtil.d("head: " + trend.avatar + " pos：" + position);
        LogUtil.d("time: " + trend.timeStr + " source: " + trend.from);
        return holder.setHeadImageWithUrl(R.id.item_trend_user_head_iv, trend.avatar)       //头像
                .setText(R.id.item_trend_user_name_tv, trend.name)
                .setText(R.id.item_trend_time_tv, trend.timeStr)    //发布时间
                .setText(R.id.item_trend_souce_tv, "-" + trend.from) //来源
                .setText(R.id.item_trend_title_tv, trend.title)  //标题
                .setText(R.id.item_trend_readed_tv, "阅读 " + trend.visitCount)  //阅读量
                .setText(R.id.text_zan_num, String.valueOf(trend.zanCount))
                .setText(R.id.text_talk_num, trend.commentsCount == 0 ? "评论" : trend.commentsCount + "")
                .setText(R.id.text_trend, "#" + trend.topicTitle + "#")
                .setImageResource(R.id.item_trend_zan_iv, trend.isZan == 1 ? R.drawable.dynamic_newsfeed_like_sel : R.drawable.dynamic_newsfeed_like)
                .setImageResource(R.id.item_trend_user_gender_iv, "2".equals(trend.gender) ? R.drawable.dynamic_female : R.drawable.dynamic_male)
                .setOnClickListener(R.id.item_trend_zan_iv, v -> {
                    if (onItemClickListener != null) {
                        onItemClickListener.onItemLikeClick(holder.getView(R.id.item_trend_zan_rel), position - getHeadersCount(), mDatas);
                    }
                })
                .setOnClickListener(R.id.item_trend_discuss_iv, v -> {
                    if (onItemClickListener != null) {
                        onItemClickListener.onItemCommentClick(Integer.valueOf(trend.id), Integer.valueOf(trend.commentsCount), position);
                    }
                })
                .setOnClickListener(R.id.item_trend_rel, v -> {
                    if (onItemClickListener != null) {
                        onItemClickListener.onItemClick(Integer.valueOf(trend.id), Integer.valueOf(trend.commentsCount), position);
                    }
                })
                .setOnClickListener(R.id.item_trend_user_head_iv, v -> {
                    String uid = trend.uid;
                    if (!uid.equals("0")) {
                        LogUtil.d("start memberActivity uid: " + uid);
                        Intent intent = new Intent();
                        intent.setClass(mContext, MembersActivity.class);
//                            intent.putExtra("user_id", uid);
                        Bundle bundle = new Bundle();
                        bundle.putString("user_id", uid);
                        intent.putExtra("bundle", bundle);
                        mContext.startActivity(intent);
//                            MembersActivity.start(mContext,uid);
                    }
                });
    }

    //显示純文本
    private void showPureTextType(int position, BaseViewHolder holder, TrendsListBean.Trend trend) {
        setBasicInfo(position, holder, trend)
                .setVisibility(R.id.item_trend_img_rel, View.GONE)
                .setVisibility(R.id.item_trend_ad_rel, View.GONE);
    }

    //文本包含图片
    @SuppressLint("ClickableViewAccessibility")
    private void showTypeContainPic(int position, BaseViewHolder holder, TrendsListBean.Trend trend) {
        ItemImageAdapter adapter = new ItemImageAdapter(mContext, trend);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, ItemImageAdapter.spanCount);
        gridLayoutManager.setSpanSizeLookup(new ItemImageAdapter.ItemImagSpanSizeLookup(trend));
        setBasicInfo(position, holder, trend)
                .setVisibility(R.id.item_trend_img_rel, View.VISIBLE) //显示图片布局
                .setVisibility(R.id.item_trend_ad_rel, View.GONE)       //隐藏广告
                .setOnTouchListener(R.id.item_trend_img_rcv, (v, event) -> {
                    if (event.getAction()==MotionEvent.ACTION_UP){
                        if (onItemClickListener != null) {
                            onItemClickListener.onItemClick(Integer.valueOf(trend.id), Integer.valueOf(trend.commentsCount), position);
                        }
                    }
                    return false;
                })
                .setVisibility(R.id.item_trend_img_num_tv, (null != trend && null != trend.smallAttach && trend.smallAttach.size() > 3) ? View.VISIBLE : View.GONE) //张数显示可见
                .setLayoutManager(R.id.item_trend_img_rcv, gridLayoutManager)   //设置recyclerview显示图片
                .setRcvAdapter(R.id.item_trend_img_rcv, adapter)
                .setText(R.id.item_trend_img_num_tv, "共" + ((null == trend || null == trend.smallAttach) ? 0 : trend.smallAttach.size()) + "张");    //张数超过则显示图片数量
    }


    //显示广告
    private void showUrlType(int position, BaseViewHolder holder, TrendsListBean.Trend trend) {
        setBasicInfo(position, holder, trend)
                .setVisibility(R.id.item_trend_ad_rel, View.VISIBLE)
                .setVisibility(R.id.item_trend_img_rel, View.GONE)
                .setVisibility(R.id.iv_fm,(null != trend && null != trend.ext && trend.ext.url.contains("fm/detail")) ? View.VISIBLE : View.GONE)
                .setImageWithUrl(R.id.item_trend_ad_iv, (null == trend || null == trend.ext) ? "" : trend.ext.cover)
                .setText(R.id.item_trend_ad_tv, (null == trend || null == trend.ext) ? "" : trend.ext.title)
                .setOnClickListener(R.id.item_trend_ad_rel, v -> {
                    if (null != trend && null != trend.ext && !TextUtils.isEmpty(trend.ext.url)){
                        Map<String, String> map = StringUtils.IsHttpReturn(trend.ext.url);
                        String jumpType = map.get("jump_type");
                        if ("url".equals(jumpType)) {
                            String realUrl = map.get("url");
                            String urlPage = map.get("url_page");
                            if ("experts_search".equals(urlPage)) {
                                mContext.startActivity(DynamicIn.INSTANCE.expertSearchIntent((Activity) mContext, 0, 0, false));
                            } else if ("test_detail".equals(urlPage)) {
                                String[] strs = realUrl.split("/");
                                String containsId = strs[strs.length - 1];
                                try {
                                    int id = Integer.parseInt(containsId.replaceAll("[^0-9]*", ""));
//                                    mContext.startActivity(DynamicIn.INSTANCE.testDetailIntent((Activity) mContext, id));
                                    DynamicIn.INSTANCE.testDetailH5(id);
                                } catch (NumberFormatException e) {
                                    e.printStackTrace();
                                }
                            } else if ("test_result".equals(urlPage)) {
                                String[] strs = realUrl.split("/");
                                strs = strs[strs.length - 1].split("&");
                                String containsId = strs[0];
                                try {
                                    int id = Integer.parseInt(containsId.replaceAll("[^0-9]*", ""));
//                                    mContext.startActivity(DynamicIn.INSTANCE.testResultIntent((Activity) mContext, id));
                                    DynamicIn.INSTANCE.testResultH5(id);
                                } catch (NumberFormatException e) {
                                    e.printStackTrace();
                                }
                            } else if ("test".equals(urlPage)) {
                                String[] strs = realUrl.split("/");
                                strs = strs[strs.length - 1].split("&");
                                String containsId = strs[0];
                                try {
                                    int id = Integer.parseInt(containsId.replaceAll("[^0-9]*", ""));
//                                    mContext.startActivity(DynamicIn.INSTANCE.testDetailIntent((Activity) mContext, id));
                                    DynamicIn.INSTANCE.testDetailH5(id);
                                } catch (NumberFormatException e) {
                                    e.printStackTrace();
                                }
                            } else if (realUrl.contains("fm/detail")){
                                //因为ios已经做了，就是这么判断的，所以后续改吧
                                String id = realUrl.substring(realUrl.lastIndexOf("/") + 1);
                                if (!TextUtils.isEmpty(id)){
                                    mContext.startActivity(DynamicIn.INSTANCE.fmDetailIntent((Activity) mContext,Integer.valueOf(id)));
                                }
                            }else {
                                H5Params h5Params = new H5Params(realUrl, null);
                                NewH5Activity.start(mContext, h5Params);
                            }
                        } else if ("native".equals(jumpType)) {
                            String nativePage = map.get("native_page");
                            if ("listen".equals(nativePage)) {
                                mContext.startActivity(DynamicIn.INSTANCE.phoneCallIntent((Activity) mContext));
                            } else if ("fm".equals(nativePage)) {
                                String fmId = map.get("id");
                                int fm_idi = Integer.valueOf(fmId);
                                mContext.startActivity(DynamicIn.INSTANCE.fmDetailIntent((Activity) mContext, fm_idi));
                            }
                        }
                    }
                });
    }

    //显示评论部分
    private void showCommentsPart(BaseViewHolder holder, TrendsListBean.Trend trend) {
        LogUtil.d("comment size: " + trend.comments.size());
        boolean isShowCommentsPart = trend.comments.size() > 0;
        if (!isShowCommentsPart) {
            holder.setVisibility(R.id.item_trend_discuss_rel, View.GONE);
            return;
        }
        boolean isShowCommentsNum = Integer.valueOf(trend.commentsCount) > trend.comments.size() || Integer.valueOf(trend.commentsCount) > 3;
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        ItemCommentsAdapter adapter = new ItemCommentsAdapter(mContext, trend.comments);
        adapter.setOnItemClickLister((view, position) -> {
            if (TrendsListAdapter.this.onItemClickListener != null) {
                TrendsListAdapter.this.onItemClickListener.onItemClick(Integer.valueOf(trend.id), Integer.valueOf(trend.commentsCount), holder.getLayoutPosition());
            }
        });
        holder.setVisibility(R.id.item_trend_discuss_rel, View.VISIBLE)
                .setVisibility(R.id.item_trend_discuss_num_tv, isShowCommentsNum ? View.VISIBLE : View.GONE)
                .setLayoutManager(R.id.item_trend_discuss_rcv, layoutManager)
                .setRcvAdapter(R.id.item_trend_discuss_rcv, adapter)
                .setText(R.id.item_trend_discuss_num_tv, isShowCommentsNum ? "全部" + trend.commentsCount + "条评论" : null)
                .setOnClickListener(R.id.item_trend_discuss_num_tv, v -> {
                    if (onItemClickListener != null) {
                        TrendsListAdapter.this.onItemClickListener.onItemClick(Integer.valueOf(trend.id), Integer.valueOf(trend.commentsCount), holder.getLayoutPosition());
                    }
                });
    }


    @Override
    public int getItemCount() {
        return mDatas != null && mDatas.size() > 0 ? mDatas.size() + getHeadersCount() + getFootersCount() : getHeadersCount() + getFootersCount();
    }

}
