package com.gh.gamecenter.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.text.HtmlCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;

import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gh.common.util.DirectUtils;
import com.gh.common.util.LibaoUtils;
import com.gh.gamecenter.GameDetailActivity;
import com.gh.gamecenter.ImageViewerActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.viewholder.LibaoDetailContentViewHolder;
import com.gh.gamecenter.adapter.viewholder.LibaoDetailTopViewHolder;
import com.gh.gamecenter.common.callback.OnRequestCallBackListener;
import com.gh.gamecenter.common.entity.SimpleGameEntity;
import com.gh.gamecenter.common.entity.SuggestType;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.common.utils.ImageUtils;
import com.gh.gamecenter.common.utils.PicassoImageGetter;
import com.gh.gamecenter.common.viewholder.FooterViewHolder;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.core.utils.ExtraTagHandler;
import com.gh.gamecenter.core.utils.SpanBuilder;
import com.gh.gamecenter.core.utils.StringUtils;
import com.gh.gamecenter.databinding.LibaodetailItemContentBinding;
import com.gh.gamecenter.databinding.LibaodetailItemTopBinding;
import com.gh.gamecenter.entity.LibaoDetailEntity;
import com.gh.gamecenter.feature.entity.GameEntity;
import com.gh.gamecenter.feature.entity.LibaoEntity;
import com.gh.gamecenter.feature.entity.LibaoStatusEntity;
import com.gh.gamecenter.feature.entity.MeEntity;
import com.gh.gamecenter.feature.entity.UserDataLibaoEntity;
import com.gh.gamecenter.feature.game.GameItemViewHolder;
import com.gh.gamecenter.feature.utils.PlatformUtils;
import com.gh.gamecenter.feature.view.DownloadButton;
import com.gh.gamecenter.help.HelpAndFeedbackBridge;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.lightgame.adapter.BaseRecyclerAdapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.HttpException;

/**
 * Created by khy on 2016/12/13.
 */
public class LibaoDetailAdapter extends BaseRecyclerAdapter<ViewHolder> {

    public static final int LIBAO_MAX_LINES = 3;
    private OnRequestCallBackListener mOnRequestCallBackListener;
    private OnCodeScrollListener mOnCodeScrollListener;

    private DownloadButton mDownloadPb;

    private LibaoEntity mLibaoEntity;
    private LibaoDetailEntity mLibaoDetailEntity;
    private GameEntity mGameEntity;

    private String mEntrance;
    private final int TYPE_FOOTER = 100;
    public LibaoDetailTopViewHolder libaoDetailTopViewHolder;
    private ArrayList<View> mImageViewList = new ArrayList<>();

    public LibaoDetailAdapter(Context context, OnRequestCallBackListener onRequestCallBackListener,
                              OnCodeScrollListener onCodeScrollListener, LibaoEntity libaoEntity,
                              DownloadButton downloadPb, String entrance) {
        super(context);
        mOnRequestCallBackListener = onRequestCallBackListener;
        mOnCodeScrollListener = onCodeScrollListener;
        mLibaoEntity = libaoEntity;
        mDownloadPb = downloadPb;
        mEntrance = entrance;
    }

    public void setGameEntity(GameEntity gameEntity) {
        mGameEntity = gameEntity;
    }

    public GameEntity getGameEntity() {
        return mGameEntity;
    }

    public void addLibaoDetail(Context context, boolean isExistGameData) {
        RetrofitManager.getInstance().getApi().getLibaoDetail(mLibaoEntity.getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<LibaoDetailEntity>() {
                    @Override
                    public void onResponse(LibaoDetailEntity response) {
                        mLibaoDetailEntity = response;
                        if (isExistGameData) {
                            MeEntity userData = response.getMe();
                            if (mLibaoEntity.isActive()) { // 以active判断礼包入口 true 为存号箱入口
                                // 合并userData数据
                                mLibaoEntity.setMe(userData);
                            }
                            mOnRequestCallBackListener.loadDone(); // 回调 检查领取状态(是否可以重复领取/重复淘号)
                            notifyDataSetChanged();
                        } else {
                            mOnRequestCallBackListener.loadEmpty();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        if (e != null && e.code() == 404) {
                            mOnRequestCallBackListener.loadNotFound();
                        } else {
                            mOnRequestCallBackListener.loadError();
                        }
                    }
                });
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        switch (viewType) {
            case 0:
                libaoDetailTopViewHolder = new LibaoDetailTopViewHolder(LibaodetailItemTopBinding.inflate(mLayoutInflater, parent, false));
                return libaoDetailTopViewHolder;
            case TYPE_FOOTER:
                view = mLayoutInflater.inflate(com.gh.gamecenter.common.R.layout.refresh_footerview, parent, false);
                return new FooterViewHolder(view);
            default:
                return new LibaoDetailContentViewHolder(LibaodetailItemContentBinding.inflate(mLayoutInflater, parent, false));
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof LibaoDetailTopViewHolder) {
            initLibaoDetailTop((LibaoDetailTopViewHolder) holder);
        } else if (holder instanceof LibaoDetailContentViewHolder) {
            initLibaoDetailContent((LibaoDetailContentViewHolder) holder, position);
        } else if (holder instanceof FooterViewHolder) {
            FooterViewHolder viewHolder = (FooterViewHolder) holder;
            viewHolder.initItemPadding();
            viewHolder.getLoading().setVisibility(View.GONE);


            SpannableStringBuilder builder = new SpanBuilder("此礼包有问题？点击反馈")
                    .click(mContext, 7, 11, com.gh.gamecenter.common.R.color.text_theme, false, () -> {
                        HelpAndFeedbackBridge.startSuggestionActivity(mContext,
                                SuggestType.GAME, "libao",
                                StringUtils.buildString(mLibaoEntity.getName(), "有问题："), new SimpleGameEntity(mLibaoEntity.getGame().getId(), mLibaoEntity.getGame().getName(), mLibaoEntity.getGame().getIcon(), ""));
                        return null;
                    })
                    .build();
            viewHolder.getHint().setText(builder);
            viewHolder.getHint().setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_secondary));
            viewHolder.getHint().setMovementMethod(new LinkMovementMethod());
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (position == getItemCount() - 1) {
            return TYPE_FOOTER;
        }
        return position;
    }

    @Override
    public int getItemCount() {
        if (mLibaoDetailEntity != null && mLibaoEntity != null) return 3; // top + content + bottom
        return 0;
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initLibaoDetailTop(LibaoDetailTopViewHolder holder) {

        if (TextUtils.isEmpty(mLibaoEntity.getDes())) { // 由动态进来的数据不存咋des字段
            mLibaoEntity.setDes(mLibaoDetailEntity.getDes());
        }

        holder.itemView.setOnClickListener(v -> {
            if (mGameEntity != null) {
                GameDetailActivity.startGameDetailActivity(mContext, mGameEntity, mEntrance, null);
            }
        });

        ExtensionsKt.setRootBackgroundColor(holder.binding.getRoot(), com.gh.gamecenter.common.R.color.ui_surface);
        if (mLibaoEntity.getGame() != null) {
            holder.binding.libaodetailGameIcon.displayGameIcon(mLibaoEntity.getGame().getIcon(), mLibaoEntity.getGame().getIconSubscript(), mLibaoEntity.getGame().getIconFloat());
            GameEntity gameEntity = mLibaoEntity.getGame().toGameEntity();
            GameItemViewHolder.initGameSubtitleAndAdLabel(gameEntity, holder.binding.gameSubtitleTv, null, null, false, null, false, null);
        } else {
            holder.binding.libaodetailGameIcon.displayGameIcon(mLibaoEntity.getIcon(), null, null);
        }
        holder.binding.libaodetailName.setText(mLibaoEntity.getName());
        if (TextUtils.isEmpty(mLibaoEntity.getPlatform())) {
            holder.binding.libaodetailGameName.setText(mLibaoEntity.getGame().getName());
        } else {
            holder.binding.libaodetailGameName.setText((mLibaoEntity.getGame().getName() + " - " +
                    PlatformUtils.getInstance(mContext).getPlatformName(mLibaoEntity.getPlatform())));
        }

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setStackFromEnd(true);
        holder.binding.libaodetailLibaocodeRv.setLayoutManager(linearLayoutManager);

        float availablePercent = ((float) mLibaoEntity.getAvailable() / (float) mLibaoEntity.getTotal()) * 100;
        int count;
        if (availablePercent >= 1) {
            count = (int) availablePercent;
        } else if (availablePercent == 0) {
            count = 0;
        } else {
            count = 1;
        }
        Spanned content = null;
        String status = mLibaoEntity.getBeforeStatus();
        if ("coming".equals(status) || "finish".equals(status) || TextUtils.isEmpty(status)) {
            content = Html.fromHtml("剩余：--");
        } else if ("ling".equals(status) || "linged".equals(status)) {
            content = Html.fromHtml(StringUtils.buildString("剩余：", "<font color=\"#1383EB\">", count + "%", "</font>"));
        } else if ("tao".equals(status) || "taoed".equals(status)) {
            content = Html.fromHtml(StringUtils.buildString("剩余：", String.valueOf(count), "%"));
        } else if ("used_up".equals(status)) {
            content = Html.fromHtml("剩余：0%  ");
        }

        //已领取或已淘号
        if (mLibaoEntity.getMe() != null && mLibaoEntity.getMe().getUserDataLibaoList() != null
                && mLibaoEntity.getMe().getUserDataLibaoList().size() > 0) {
            List<UserDataLibaoEntity> userDataLibaoList = mLibaoEntity.getMe().getUserDataLibaoList();
            LibaoUtils.initLibaoBtn(mContext, holder.binding.libaodetailCopyBtn, mLibaoEntity,
                    mLibaoDetailEntity.getInstallRequired(), this, false,
                    StringUtils.buildString(mEntrance, "+(礼包详情[", mLibaoEntity.getName(), "])"), "礼包详情", null);
            if (mLibaoEntity.getUniversal()) {
                holder.binding.libaodetailDes.setVisibility(View.GONE);
            } else {
                holder.binding.libaodetailDes.setVisibility(View.VISIBLE);
                holder.binding.libaodetailDes.setText(content);
            }

            holder.binding.libaodetailLibaocodeRv.setVisibility(View.VISIBLE);
            holder.binding.line.setVisibility(View.VISIBLE);
            holder.binding.libaodetailLibaocodeRv.setAdapter(new LiBaoCodeAdapter(mContext, userDataLibaoList));
            ViewGroup.LayoutParams params = holder.binding.libaodetailLibaocodeRv.getLayoutParams();
            if (userDataLibaoList.size() <= LIBAO_MAX_LINES) {
                params.height = userDataLibaoList.size() * DisplayUtils.dip2px(mContext, 40);
            } else {
                params.height = LIBAO_MAX_LINES * DisplayUtils.dip2px(mContext, 40);
            }
            holder.binding.libaodetailLibaocodeRv.setLayoutParams(params);

            holder.binding.libaodetailLibaocodeRv.setOnTouchListener((v, event) -> {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    mOnCodeScrollListener.isScroll(false);
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    mOnCodeScrollListener.isScroll(true);
                }
                return false;
            });
            return;
        }

        if (mLibaoEntity.getUniversal()) {
            holder.binding.libaodetailDes.setVisibility(View.GONE);
        } else {
            holder.binding.libaodetailDes.setVisibility(View.VISIBLE);
            holder.binding.libaodetailDes.setText(content);
        }

        if (mLibaoEntity.getStatus() != null && mLibaoDetailEntity != null) {
            LibaoUtils.initLibaoBtn(mContext, holder.binding.libaodetailCopyBtn, mLibaoEntity,
                    mLibaoDetailEntity.getInstallRequired(), this, false,
                    StringUtils.buildString(mEntrance, "+(礼包详情[", mLibaoEntity.getName(), "])"), "礼包详情", null);
        }

        // 判断按钮状态是否为空(礼包详情进入)，重新获取
        if (TextUtils.isEmpty(status)) {
            LibaoUtils.getLibaoStatus(mLibaoEntity.getId(), new LibaoUtils.PostLibaoListener() {
                @Override
                public void postSucceed(Object response) {
                    List<LibaoStatusEntity> statusList = (List<LibaoStatusEntity>) response;
                    if (statusList.size() != 0) {
                        mLibaoEntity.setStatus(statusList.get(0).getStatus());
                        mLibaoEntity.setAvailable(statusList.get(0).getAvailable());
                        mLibaoEntity.setTotal(statusList.get(0).getTotal());
                        notifyItemChanged(0);
                    }
                }

                @Override
                public void postFailed(Throwable error) {

                }
            });
        }
    }

    private void initLibaoDetailContent(LibaoDetailContentViewHolder holder, int position) {

        if (mLibaoEntity.getContent() != null) {
            holder.binding.libaodetailContentLl.setVisibility(View.VISIBLE);
            holder.binding.libaodetailContent.setText(Html.fromHtml(mLibaoEntity.getContent()));
        }
        if (mLibaoEntity.getMaterials().isEmpty()) {
            holder.binding.horizontalScrollView.setVisibility(View.GONE);
        } else {
            holder.binding.horizontalScrollView.setVisibility(View.VISIBLE);
            holder.binding.imagesContainer.removeAllViews();
            mImageViewList.clear();
            for (int i = 0; i < mLibaoEntity.getMaterials().size(); i++) {
                String imageUrl = mLibaoEntity.getMaterials().get(i).getImg();
                SimpleDraweeView imageView = new SimpleDraweeView(mContext);
                RoundingParams roundingParams = new RoundingParams();
                roundingParams.setCornersRadius(DisplayUtils.dip2px(4F));
                roundingParams.setOverlayColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.ui_surface));
                imageView.setHierarchy(new GenericDraweeHierarchyBuilder(mContext.getResources())
                        .setFadeDuration(500)
                        .setRoundingParams(roundingParams)
                        .setPlaceholderImage(com.gh.gamecenter.common.R.drawable.occupy, ScalingUtils.ScaleType.FIT_XY)
                        .build());
                ImageUtils.display(imageView, imageUrl);
                final int index = i;
                imageView.setOnClickListener(v -> {
                    Intent intent = ImageViewerActivity.getIntent(mContext, mLibaoEntity.getMaterialImgList(), index, mImageViewList, mEntrance);
                    mContext.startActivity(intent);
                });
                mImageViewList.add(imageView);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(DisplayUtils.dip2px(24F), DisplayUtils.dip2px(24F));
                layoutParams.setMargins(DisplayUtils.dip2px(i == 0 ? 8F : 16F), 0, 0, 0);
                holder.binding.imagesContainer.addView(imageView, layoutParams);
            }
        }
        if (mLibaoDetailEntity != null) {
            holder.binding.libaodetailTimeLl.setVisibility(View.VISIBLE);

            initLibaoDetailCondition(holder);

            if (mLibaoDetailEntity.getTime() != null) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm", Locale.CHINA);
                String start = format.format((mLibaoDetailEntity.getTime().getStart() * 1000));
                
                long libaoLingEndTime = mLibaoDetailEntity.getTime().getEnd();
                String end = libaoLingEndTime == 0
                        ? mContext.getString(R.string.libao_ling_time_infinitely) // 礼包领取结束时间为空则表示礼包长期有效
                        : format.format((mLibaoDetailEntity.getTime().getEnd() * 1000));

                holder.binding.libaodetailTimeStart.setText(StringUtils.buildString("开始时间：", start));
                holder.binding.libaodetailTimeEnd.setText(StringUtils.buildString("截止时间：", end));
            }
            String des = mLibaoDetailEntity.getNewDes();
            if (des == null) {
                des = mLibaoDetailEntity.getDes();
            }
            if (des != null && position == getItemCount() - 2) {
                holder.binding.libaodetailDesLl.setVisibility(View.VISIBLE);
                CharSequence spanned = HtmlCompat.fromHtml(des, HtmlCompat.FROM_HTML_MODE_COMPACT,
                        new PicassoImageGetter(holder.binding.libaodetailDes), new ExtraTagHandler());
                ExtensionsKt.setTextWithInterceptingInternalUrl(holder.binding.libaodetailDes, spanned);
            }
        }
    }

    private void initLibaoDetailCondition(LibaoDetailContentViewHolder holder) {
        if (mLibaoDetailEntity.getInstallRequired()) {
            Spanned content;
            if (TextUtils.isEmpty(mLibaoEntity.getPlatform())) {
                content = Html.fromHtml(mContext.getString(R.string.libao_install_hint, mLibaoEntity.getGame().getName()));
            } else {
                content = Html.fromHtml(mContext.getString(R.string.libao_install_hint_platform, mLibaoEntity.getGame().getName(),
                        PlatformUtils.getInstance(mContext).getPlatformName(mLibaoEntity.getPlatform())));
            }
            holder.binding.libaodetailCondition.setVisibility(View.VISIBLE);
            holder.binding.libaodetailCondition.setText(content);
        } else if (ExtensionsKt.toResString(R.string.libao_activity_grant).equals(mLibaoEntity.getReceiveLimit())) {
            holder.binding.libaodetailCondition.setVisibility(View.VISIBLE);
            String url = mLibaoEntity.getActivityLink().getUrl();
            if (TextUtils.isEmpty(url)) {
                holder.binding.libaodetailCondition.setText("领取条件：通过活动获得");
            } else {
                SpannableStringBuilder content = new SpannableStringBuilder("领取条件：通过活动获得，查看详情");
                content.setSpan(new ClickableSpan() {

                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setColor(ExtensionsKt.toColor(com.gh.gamecenter.common.R.color.text_theme, mContext));
                        ds.setUnderlineText(false);
                    }

                    @Override
                    public void onClick(@NonNull View widget) {
                        DirectUtils.directToWebView(mContext, url, "礼包详情-领取条件-查看活动详情");
                    }
                }, 12, content.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                holder.binding.libaodetailCondition.setText(content);
                holder.binding.libaodetailCondition.setMovementMethod(new LinkMovementMethod());
                ExtensionsKt.setDrawableEnd(holder.binding.libaodetailCondition, com.gh.gamecenter.common.R.drawable.ic_libao_activity_arrow, null, null);
                holder.binding.libaodetailCondition.setCompoundDrawablePadding(DisplayUtils.dip2px(4F));
            }
        } else if (mLibaoDetailEntity.getReceiveCondition() != null) {
            holder.binding.libaodetailCondition.setVisibility(View.VISIBLE);
            holder.binding.libaodetailConditionDescTv.setVisibility(View.VISIBLE);
            holder.binding.libaodetailCondition.setText("领取条件：");
            holder.binding.libaodetailConditionDescTv.setText(
                    getConditionDescText(
                            mGameEntity.getName(),
                            mLibaoDetailEntity.getReceiveCondition().getStar(),
                            mLibaoDetailEntity.getReceiveCondition().getWords()
                    )
            );
        }
    }

    /**
     * 根据评分和字数限制生成文案。
     *
     * @param gameName  游戏名称
     * @param star      评分选项 (-1: 无限制, 5: 5星好评, 4: 4星及以上, 3: 3星及以上, 2: 2星及以上, 1: 1星及以上)
     * @param words     字数限制 (-1: 无限制,  n: 字数不少于n)
     * @return 生成的文案
     */
    private String getConditionDescText(String gameName, int star, int words) {
        StringBuilder text = new StringBuilder();

        text.append("发表《").append(gameName).append("》");

        if (words == -1) {
            text.append("的游戏评价");
        } else {
            text.append("不少于").append(words).append("字的游戏评价");
        }

        if (star != -1) {
            text.append("并给予");
            switch (star) {
                case 5:
                    text.append("5星好评");
                    break;
                case 4:
                    text.append("4星及以上评分");
                    break;
                case 3:
                    text.append("3星及以上评分");
                    break;
                case 2:
                    text.append("2星及以上评分");
                    break;
                case 1:
                    text.append("1星及以上评分");
                    break;
                default:
                    //throw new IllegalArgumentException("Invalid star value: " + star);  // 或者返回一个默认值，比如空字符串或错误消息
                    return ""; // or return a default string or throw an exception.
            }
        }

        return text.toString();
    }

    public LibaoEntity getLibaoEntity() {
        return mLibaoEntity;
    }

    public void setLibaoEntity(LibaoEntity libaoEntity) {
        mLibaoEntity = libaoEntity;
    }

    public LibaoDetailEntity getLibaoDetailEntity() {
        return mLibaoDetailEntity;
    }

    public void initLibaoCode(UserDataLibaoEntity userDataLibaoEntity) {
        boolean isLibaoDataDuplicated = false;

        MeEntity userData = mLibaoEntity.getMe();
        if (userData == null) {
            userData = new MeEntity();
            mLibaoEntity.setMe(userData);
        }

        List<UserDataLibaoEntity> userDataLibaoList = userData.getUserDataLibaoList();
        if (userDataLibaoList == null) {
            userDataLibaoList = new ArrayList<>();
            userData.setUserDataLibaoList(userDataLibaoList);
        } else {
            for (UserDataLibaoEntity entity : userDataLibaoList) {
                if (entity.getCode() != null
                        && entity.getCode().equals(userDataLibaoEntity.getCode())) {
                    isLibaoDataDuplicated = true;
                }
            }
        }

        if (!isLibaoDataDuplicated) {
            userDataLibaoList.add(userDataLibaoEntity);
            notifyItemChanged(0);
        }

        mOnRequestCallBackListener.loadDone(userDataLibaoEntity);
    }

    // 点击立即安装打开下载页面，如果只有一个包 直接下载
    public void openDownload(String platform) {
        mDownloadPb.setTag(platform);
        mDownloadPb.performClick();
    }

    public interface OnCodeScrollListener {
        void isScroll(boolean isScroll);
    }
}
