package com.gh.gamecenter.message;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gh.gamecenter.common.callback.OnListClickListener;
import com.gh.gamecenter.common.constant.Constants;
import com.gh.gamecenter.common.constant.ItemViewType;
import com.gh.common.util.CommentUtils;
import com.gh.gamecenter.common.utils.DialogHelper;
import com.gh.common.util.DirectUtils;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.common.utils.ImageUtils;
import com.gh.gamecenter.core.utils.MtaHelper;
import com.gh.gamecenter.GameDetailActivity;
import com.gh.gamecenter.ImageViewerActivity;
import com.gh.gamecenter.NewsDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.common.viewholder.FooterViewHolder;
import com.gh.gamecenter.common.baselist.ListAdapter;
import com.gh.gamecenter.databinding.MessageKefuItemBinding;
import com.gh.gamecenter.common.entity.LinkEntity;
import com.gh.gamecenter.entity.MessageKeFuEntity;
import com.gh.gamecenter.entity.MessageLinkEntity;
import com.gh.gamecenter.gamedetail.rating.RatingReplyActivity;
import com.gh.gamecenter.login.user.UserManager;
import com.gh.gamecenter.qa.questions.newdetail.NewQuestionDetailActivity;
import com.gh.gamecenter.subject.SubjectActivity;
import com.gh.gamecenter.video.detail.VideoDetailContainerViewModel;
import com.google.android.flexbox.FlexboxLayout;
import com.lightgame.utils.Utils;

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

/**
 * Created by khy on 2017/4/10.
 * 消息-客服适配器
 */
public class KeFuFragmentAdapter extends ListAdapter<MessageKeFuEntity> {

    private OnListClickListener mClickListener;

    private KeFuViewModel mListViewModel;

    private String mEntrance;

    private int mImageSize;

    public KeFuFragmentAdapter(Context context, OnListClickListener listener, KeFuViewModel listViewModel, String entrance) {
        super(context);
        mListViewModel = listViewModel;
        mClickListener = listener;
        mEntrance = entrance;

        mImageSize = (mContext.getResources().getDisplayMetrics().widthPixels - DisplayUtils.dip2px(36)) / 3;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == ItemViewType.ITEM_FOOTER) {
            View view = mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false);
            return new FooterViewHolder(view);
        } else {
            return new KeFuViewHolder(MessageKefuItemBinding.inflate(mLayoutInflater, parent, false), mClickListener);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof KeFuViewHolder) {
            MessageKeFuEntity keFuEntity = mEntityList.get(position);
            KeFuViewHolder viewHolder = (KeFuViewHolder) holder;
            initKeFuViewHolder(viewHolder, keFuEntity);
        } else if (holder instanceof FooterViewHolder) {
            ((FooterViewHolder) holder).initFooterViewHolder(mIsLoading, mIsNetworkError, mIsOver);
            ((FooterViewHolder) holder).initItemPadding();
        }

    }

    @Override
    public int getItemViewType(int position) {
        if (position == getItemCount() - 1) {
            return ItemViewType.ITEM_FOOTER;
        } else {
            return ItemViewType.ITEM_BODY;
        }
    }

    @Override
    public int getItemCount() {
        return mEntityList == null || mEntityList.isEmpty() ? 0 : mEntityList.size() + FOOTER_ITEM_COUNT;
    }

    private void initKeFuViewHolder(KeFuViewHolder viewHolder, final MessageKeFuEntity keFuEntity) {
        viewHolder.binding.messageKaifuItem.setBackground(ContextCompat.getDrawable(mContext, R.drawable.reuse_listview_item_style));
        viewHolder.binding.messageKefuSuggestion.setBackgroundColor(ContextCompat.getColor(mContext, R.color.background));
        viewHolder.binding.messageKefuSuggestion.setTextColor(ContextCompat.getColor(mContext, R.color.title));
        viewHolder.binding.messageKefuName.setTextColor(ContextCompat.getColor(mContext, R.color.text_black));
        viewHolder.binding.messageKefuContent.setTextColor(ContextCompat.getColor(mContext, R.color.title));
        viewHolder.binding.messageKefuTime.setTextColor(ContextCompat.getColor(mContext, R.color.hint));
        viewHolder.binding.copyTv.setTextColor(ContextCompat.getColor(mContext, R.color.text_subtitle));

        boolean shouldShouldUserId = keFuEntity.getShowUserId() != null && keFuEntity.getShowUserId();

        List<String> images = keFuEntity.getImages();
        if (images != null && !images.isEmpty()) {
            viewHolder.binding.messageKefuImagesContainer.removeAllViews();
            viewHolder.binding.messageKefuImagesContainer.setVisibility(View.VISIBLE);
            for (int i = 0; i < images.size(); i++) {
                String image = images.get(i);
                SimpleDraweeView draweeView = new SimpleDraweeView(mContext);
                int padding = DisplayUtils.dip2px(2);
                draweeView.setPadding(padding, padding, padding, padding);
                FlexboxLayout.LayoutParams params = new FlexboxLayout.LayoutParams(mImageSize, mImageSize);
                draweeView.setLayoutParams(params);
                draweeView.setImageURI(image);
                int finalI = i;
                draweeView.setOnClickListener(v -> {
                    Intent intent = ImageViewerActivity.getIntent(mContext,
                            (ArrayList<String>) images,
                            finalI,
                            "(消息中心-系统)");
                    mContext.startActivity(intent);
                    MtaHelper.onEvent("消息中心", "系统_二级列表", "点击图片");
                });

                GenericDraweeHierarchy hierarchy = draweeView.getHierarchy();
                RoundingParams roundingParams = RoundingParams.fromCornersRadius(18f);
                hierarchy.setRoundingParams(roundingParams);
                hierarchy.setPlaceholderImage(R.drawable.occupy);
                viewHolder.binding.messageKefuImagesContainer.addView(draweeView);
            }
            viewHolder.binding.messageKefuImagesContainer.requestLayout();
        } else {
            viewHolder.binding.messageKefuImagesContainer.setVisibility(View.GONE);
        }

        ExtensionsKt.goneIf(viewHolder.binding.copyIdContainer, !shouldShouldUserId);
        if (shouldShouldUserId) {
            viewHolder.binding.copyIdContainer.setOnClickListener(view -> ExtensionsKt.copyTextAndToast(UserManager.getInstance().getUserId(), "已复制"));
        }

        viewHolder.binding.messageKefuContent.setText(Html.fromHtml(keFuEntity.getMessage()));

        viewHolder.binding.messageKefuContent.setOnSpannableClickListener(spannableText -> ExtensionsKt.copyTextAndToast(spannableText, "已复制：" + spannableText));

        viewHolder.setClickData(keFuEntity);
        if (!TextUtils.isEmpty(keFuEntity.getSuggestion())) {
            viewHolder.binding.messageKefuSuggestion.setVisibility(View.VISIBLE);
            viewHolder.binding.messageKefuSuggestion.setText(keFuEntity.getSuggestion());
        } else {
            viewHolder.binding.messageKefuSuggestion.setVisibility(View.GONE);
        }

        List<LinkEntity> newLinks = keFuEntity.getNewLinks();
        if (newLinks != null && !newLinks.isEmpty()) {
            viewHolder.binding.messageSkipList.setVisibility(View.VISIBLE);
            viewHolder.binding.messageSkipList.removeAllViews();
            for (LinkEntity linkEntity : newLinks) {
                if (TextUtils.isEmpty(linkEntity.getText()) && TextUtils.isEmpty(linkEntity.getTitle()))
                    continue;
                TextView textView = getLinkChildView(viewHolder, !TextUtils.isEmpty(linkEntity.getTitle()) ? linkEntity.getTitle() : linkEntity.getText());
                textView.setOnClickListener(v -> {
                    if (!keFuEntity.isRead()) {
                        mListViewModel.postMessageRead(keFuEntity.getId());
                        notifyDataSetChanged();
                    }
                    linkNewSkip(linkEntity);
                });
            }
        } else {
            List<MessageLinkEntity> links = keFuEntity.getLinks();
            if (links != null && !links.isEmpty()) {
                viewHolder.binding.messageSkipList.setVisibility(View.VISIBLE);
                viewHolder.binding.messageSkipList.removeAllViews();
                for (MessageLinkEntity link : links) {
                    if (TextUtils.isEmpty(link.getQq()) &&
                            TextUtils.isEmpty(link.getId()) &&
                            TextUtils.isEmpty(link.getUrl()) &&
                            !"7moor".equals(link.getType()) &&
                            !"个人主页".equals(link.getType())) continue;
                    TextView textView = getLinkChildView(viewHolder, link.getDocument());
                    textView.setOnClickListener(v -> {
                        if (!keFuEntity.isRead()) {
                            mListViewModel.postMessageRead(keFuEntity.getId());
                            notifyDataSetChanged();
                        }
                        linkSkip(link);
                    });
                }
            } else {
                viewHolder.binding.messageSkipList.setVisibility(View.GONE);
            }
        }

        MessageKeFuEntity.ServiceEntity serviceEntity = keFuEntity.getServiceEntity();
        viewHolder.binding.messageKefuName.setText(R.string.kefu_default_name);
        if (serviceEntity != null) {
            String name = serviceEntity.getName();
            if (!TextUtils.isEmpty(name)) {
                viewHolder.binding.messageKefuName.setText(name);
            }
            ImageUtils.displayIcon(viewHolder.binding.messageKefuIcon, serviceEntity.getIcon());
        } else {
            ImageUtils.display(viewHolder.binding.messageKefuIcon, R.drawable.message_kefu_icon);
        }

        if (keFuEntity.getServiceEntity() != null && keFuEntity.getServiceEntity().getAuth() != null) {
            ImageUtils.display(viewHolder.binding.messageUserBadge, keFuEntity.getServiceEntity().getAuth().getIcon());
            viewHolder.binding.messageUserBadge.setVisibility(View.VISIBLE);
        } else {
            viewHolder.binding.messageUserBadge.setVisibility(View.GONE);
        }

        CommentUtils.setCommentTime(viewHolder.binding.messageKefuTime, keFuEntity.getTime());

        if (!TextUtils.isEmpty(keFuEntity.getSuggestion())) {
            StringBuffer suggest = new StringBuffer();
            suggest.append("反馈原文：");
            suggest.append(keFuEntity.getSuggestion());
            viewHolder.binding.messageKefuSuggestion.setVisibility(View.VISIBLE);
            viewHolder.binding.messageKefuSuggestion.setText(suggest);
        } else {
            viewHolder.binding.messageKefuSuggestion.setVisibility(View.GONE);
        }

        if (keFuEntity.isRead()) {
            viewHolder.binding.messageKefuUnread.setVisibility(View.GONE);
        } else {
            viewHolder.binding.messageKefuUnread.setVisibility(View.VISIBLE);
        }

        viewHolder.binding.messageKefuIcon.setOnClickListener(v -> {
            if (serviceEntity != null) {
                MtaHelper.onEvent("消息中心", "系统_二级列表", "点击头像");
                DirectUtils.directToHomeActivity(mContext, serviceEntity.getId(), mEntrance, "消息中心-系统");
            }
        });
        viewHolder.binding.messageKefuName.setOnClickListener(v -> {
            if (serviceEntity != null) {
                MtaHelper.onEvent("消息中心", "系统_二级列表", "点击名字");
                DirectUtils.directToHomeActivity(mContext, serviceEntity.getId(), mEntrance, "消息中心-系统");
            }
        });

        viewHolder.binding.getRoot().setOnLongClickListener(v -> {
            DialogHelper.showDialog(mContext,
                    "删除消息",
                    "消息删除将不可恢复，确定删除吗？",
                    "确定", "取消", () -> {
                        mListViewModel.deleteMessage(keFuEntity.getId());
                    }, () -> {
                    },
                    true, "消息中心", "系统列表-删除");
            return false;
        });
    }

    private TextView getLinkChildView(KeFuViewHolder viewHolder, String text) {
        TextView textView = new TextView(mContext);
        textView.setTextColor(mContext.getResources().getColor(R.color.theme_font));
        textView.setTextSize(12F);
        textView.setText(text);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT
                , ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(0, DisplayUtils.dip2px(8F), 0, 0);
        viewHolder.binding.messageSkipList.addView(textView, params);
        return textView;
    }

    private void linkSkip(MessageLinkEntity data) {
        String type = data.getType();
        if (TextUtils.isEmpty(type)) {
            Utils.toast(mContext, "数据请求失败");
            return;
        }
        MtaHelper.onEvent("消息中心", "系统_二级列表", "点击链接");


        switch (type) {
            case "游戏":
                if (!TextUtils.isEmpty(data.getId())) {
                    GameDetailActivity.startGameDetailActivity(mContext, data.getId(), "", null);
                }
                break;
            case "QQ号":
                if (!TextUtils.isEmpty(data.getQq())) {
                    DirectUtils.directToQqConversation(mContext, data.getQq());
                }
                break;
            case "web":
                if (!TextUtils.isEmpty(data.getUrl())) {
                    DirectUtils.directToWebView(mContext, data.getUrl(), "(消息-公告)");
                }
                break;
            case "QQ群":
                if (!TextUtils.isEmpty(data.getKey())) {
                    DirectUtils.directToQqGroup(mContext, data.getKey());
                }
                break;
            case "新闻":
                if (!TextUtils.isEmpty(data.getId())) {
                    Intent intent2 = new Intent(mContext, NewsDetailActivity.class);
                    intent2.putExtra(EntranceConsts.KEY_ENTRANCE, "(消息-公告)");
                    intent2.putExtra(EntranceConsts.KEY_NEWSID, data.getId());
                    mContext.startActivity(intent2);
                }
                break;
            case "专题":
                if (!TextUtils.isEmpty(data.getId())) {
                    SubjectActivity.startSubjectActivity(mContext, data.getId()
                            , null, false, "(消息-客服)");
                }
                break;
            case "7moor":
                if (mContext instanceof Activity) {
                    // 去掉七陌支持，跳转到企点
                    // ImManager.startChatActivity((Activity) mContext, null, null);
                    DirectUtils.directToWebView(mContext, Constants.TENCENT_QIDIAN_ADDRESS, mEntrance);
                }
                break;
            case "问题":
                if (!TextUtils.isEmpty(data.getId())) {
                    mContext.startActivity(NewQuestionDetailActivity.getIntent(mContext, data.getId(), mEntrance, "(消息-客服)"));
                }
                break;
            case "回答":
                if (!TextUtils.isEmpty(data.getId())) {
                    DirectUtils.directToAnswerDetail(mContext, data.getId(), mEntrance, "(消息-客服)");
                }
                break;
            case "社区文章":
                if (!TextUtils.isEmpty(data.getId()) && data.getCommunity() != null) {
                    DirectUtils.directToCommunityArticle(mContext, data.getId(), data.getCommunity().getId(), mEntrance, "(消息-客服)");
                }
                break;
            case "社区专题":
                if (!TextUtils.isEmpty(data.getId()) && data.getCommunity() != null) {
                    DirectUtils.directToCommunityColumn(mContext, data.getCommunity(), data.getId(), mEntrance, "(消息-客服)");
                }
                break;
            case "视频":
                if (!TextUtils.isEmpty(data.getId())) {
                    DirectUtils.directToVideoDetail(mContext, data.getId(), VideoDetailContainerViewModel.Location.SINGLE_VIDEO.getValue(), false, "", mEntrance, "系统_二级列表", "");
                }
                break;
            case "安利墙评论":
                if (!TextUtils.isEmpty(data.getId())) {
                    MtaHelper.onEvent("安利墙", "进入", "消息中心");
                    DirectUtils.directToAmway(mContext, data.getId(), mEntrance, "(消息-客服)");
                }
                break;
            case "个人主页":
                DirectUtils.directToHomeActivity(mContext, UserManager.getInstance().getUserId(), mEntrance, "(消息-客服)");
                break;
            case "游戏详情评论":
                if (!TextUtils.isEmpty(data.getId())) {
                    GameDetailActivity.startGameDetailActivity(mContext, data.getId(), "", -1, true, false, false, false, null);
                }
                break;
            case "订单中心":
                DirectUtils.directToOrderCenter(mContext);
                break;
            case "订单详情":
                if (!TextUtils.isEmpty(data.getId())) {
                    DirectUtils.directToOrderDetail(mContext, data.getId());
                }
                break;
            case "光能记录":
            case "光能记录获取":
                DirectUtils.directToEnergyRecord(mContext);
                break;
            case "光能记录使用":
                DirectUtils.directToEnergyRecord(mContext, 1);
                break;
            case "抽奖中心":
                DirectUtils.directToLotteryParadisePage(mContext);
                break;
            case "我的奖品":
                DirectUtils.directToMyPrizePage(mContext);
                break;
            case "兑换商品":
                DirectUtils.directToExchangeCommodityPage(mContext);
                break;
            case "中奖订单详情":
                if (!TextUtils.isEmpty(data.getId()) && !TextUtils.isEmpty(data.getActivityId())) {
                    DirectUtils.directToWinOrderDetail(mContext, data.getId(), data.getActivityId());
                }
                break;
            default:
                LinkEntity entity = new LinkEntity();
                entity.setType(data.getType());
                if (TextUtils.isEmpty(data.getId())) {
                    entity.setLink(data.getId());
                }
                if (TextUtils.isEmpty(data.getUrl())) {
                    entity.setLink(data.getUrl());
                }
                if (TextUtils.isEmpty(data.getDocument())) {
                    entity.setText(data.getDocument());
                }
                entity.setCommunity(data.getCommunity());
                DirectUtils.directToLinkPage(mContext, entity, mEntrance, "(消息-客服)");
                break;
        }
    }

    private void linkNewSkip(LinkEntity data) {
        String type = data.getType();
        if (TextUtils.isEmpty(type)) {
            Utils.toast(mContext, "数据请求失败");
            return;
        }
        MtaHelper.onEvent("消息中心", "系统_二级列表", "点击链接");

        switch (type) {
            case "home":
                DirectUtils.directToHomeActivity(mContext, UserManager.getInstance().getUserId(), mEntrance, "(消息-客服)");
                break;
            case "7moor":
            case "qidian":
                DirectUtils.directToWebView(mContext, Constants.TENCENT_QIDIAN_ADDRESS, mEntrance);
                break;
            case "order_center":
                DirectUtils.directToOrderCenter(mContext);
                break;
            case "order_detail":
                if (!TextUtils.isEmpty(data.getLink())) {
                    DirectUtils.directToOrderDetail(mContext, data.getLink());
                }
                break;
            case "energy_record":
            case "energy_record_get":
                DirectUtils.directToEnergyRecord(mContext);
                break;
            case "energy_record_cost":
                DirectUtils.directToEnergyRecord(mContext, 1);
                break;
            case "raffle_center":
                DirectUtils.directToLotteryParadisePage(mContext);
                break;
            case "raffle_prize":
                DirectUtils.directToMyPrizePage(mContext);
                break;
            case "exchange_commodity":
                DirectUtils.directToExchangeCommodityPage(mContext);
                break;
            case "win_order_detail":
                if (!TextUtils.isEmpty(data.getLink()) && !TextUtils.isEmpty(data.getActivityId())) {
                    DirectUtils.directToWinOrderDetail(mContext, data.getLink(), data.getActivityId());
                }
                break;
            case "game_comment_detail":
                mContext.startActivity(RatingReplyActivity.getIntent(mContext, data.getGameId(), data.getLink(), "消息中心-系统消息", ""));
                break;
            default:
                DirectUtils.directToLinkPage(mContext, data, mEntrance, "(消息-客服)");
                break;
        }
    }

}
