package com.yidianling.dynamic.trendsHome.content;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.collection.SparseArrayCompat;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.ydl.webview.H5Params;
import com.ydl.webview.NewH5Activity;
import com.ydl.ydl_image.config.SimpleImageOpConfiger;
import com.ydl.ydl_image.manager.YDLImageCacheManager;
import com.ydl.ydl_image.module.GlideApp;
import com.ydl.ydlcommon.modular.ModularServiceManager;
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.consultant.api.IConsultantService;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.common.view.ImageInfo;
import com.yidianling.dynamic.common.view.NineGridView;
import com.yidianling.dynamic.common.view.NineGridViewClickAdapter;
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 TrendsCotentListAdapter 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 TrendsCotentListAdapter(Context context, List<TrendsListBean.Trend> datas) {
        mContext = context;
        mDatas = datas;
        footerState = FOOTRE_STATE_LOAD_MORE;
    }

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

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

    public int getFooterState() {
        return 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_content_list, parent, 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.d("onBindeViewHolder");
        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);

        if (trend.isAssistantGuide==1) {
            holder.setVisibility(R.id.iv_assistant_guide_image, View.VISIBLE);
            holder.setVisibility(R.id.nine_grid, View.GONE);
            holder.setVisibility(R.id.item_trend_zan_rel, View.GONE);
            ImageView guideImage = holder.getView(R.id.iv_assistant_guide_image);

            GlideApp.with(mContext).load( trend.assistantGuideImg).into(guideImage);
        } else {
            holder.setVisibility(R.id.iv_assistant_guide_image, View.GONE);
            holder.setVisibility(R.id.nine_grid, View.VISIBLE);
            holder.setVisibility(R.id.item_trend_zan_rel, 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) {
        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);
            } 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)) {

        } else {

        }
        holder.setVisibility(R.id.item_trend_title_tv, TextUtils.isEmpty(trend.title) ? View.GONE : View.VISIBLE);

        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, trend.zanCount + "")
                .setText(R.id.text_talk_num, trend.commentsCount + "")
                .setText(R.id.text_trend, "#" + trend.topicTitle + "#")
                .setImageResource(R.id.item_trend_zan_iv, trend.isZan == 1 ? R.drawable.dynamic_icon_warm_sel : R.drawable.dynamic_icon_warm_nor)
                .setImageResource(R.id.item_trend_user_gender_iv, trend.gender.equals("2") ? R.drawable.dynamic_new_female : R.drawable.dynamic_new_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_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);
                        Bundle bundle = new Bundle();
                        bundle.putString("user_id", uid);
                        intent.putExtra("bundle", bundle);
                        mContext.startActivity(intent);
                    }
                })
                .setOnClickListener(R.id.ll_trend_content, v -> {
                    if (onItemClickListener != null) {
                        if (trend.isAssistantGuide ==0) {
                            onItemClickListener.onItemClick(Integer.valueOf(trend.id), Integer.valueOf(trend.commentsCount), position);
                        } else {
//                            ToastUtil.toastShort("跳转到导医入口页面");
                             ModularServiceManager.INSTANCE.provide(IConsultantService.class).jumpConsultAssistant((Activity) mContext,3);

                        }
                    }
                });
    }

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

    //文本包含图片
    private void showTypeContainPic(int position, BaseViewHolder holder, TrendsListBean.Trend trend) {
        NineGridView.setImageLoader(new GlideImageLoader());
        NineGridView nineGridView = holder.getView(R.id.nine_grid);
        List<ImageInfo> imageInfos = new ArrayList<>();
        if (trend.isAd == 1) {
            ImageInfo imageInfo = new ImageInfo();
            imageInfo.setThumbnailUrl(trend.adImg);
            imageInfo.imageLinkUrl = trend.url;
            imageInfo.mShareData = trend.share;
            imageInfos.add(imageInfo);
        } else {
            if (null != trend && null != trend.smallAttach) {
                for (int i = 0; i < trend.smallAttach.size(); i++) {
                    ImageInfo imageInfo = new ImageInfo();
                    imageInfo.setThumbnailUrl(trend.smallAttach.get(i));
                    if (null != trend.bigAttach && trend.bigAttach.size() > i) {
                        imageInfo.setBigImageUrl(trend.bigAttach.get(i));
                    }
                    imageInfos.add(imageInfo);
                }
            }
        }

        nineGridView.setAdapter(new NineGridViewClickAdapter(mContext, imageInfos));
        setBasicInfo(position, holder, trend)
                .setVisibility(R.id.nine_grid, View.VISIBLE) //显示图片布局
                .setVisibility(R.id.item_trend_ad_rel, View.GONE);       //隐藏广告
    }


    /**
     * Glide 加载
     */
    private class GlideImageLoader implements NineGridView.ImageLoader {
        @Override
        public void onDisplayImage(Context context, ImageView imageView, String url) {
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            SimpleImageOpConfiger sp = new SimpleImageOpConfiger();
            sp.errorPic = R.drawable.dynamic_ic_default_color;
            sp.isCacheOnDisk = false;
            YDLImageCacheManager.showImage(context, url, imageView, sp);
        }

        @Override
        public Bitmap getCacheImage(String url) {
            return null;
        }
    }


    //显示广告
    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.nine_grid, 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));
                            }
                        }
                    }
                });
    }


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

}
