package com.gh.gamecenter.libao;

import android.content.Context;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.gh.gamecenter.common.callback.OnRequestCallBackListener;
import com.gh.gamecenter.common.utils.DialogHelper;
import com.gh.common.util.LibaoUtils;
import com.gh.gamecenter.feature.utils.PlatformUtils;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.core.utils.TimeUtils;
import com.gh.gamecenter.common.view.BugFixedPopupWindow;
import com.gh.gamecenter.LibaoDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.common.viewholder.FooterViewHolder;
import com.gh.gamecenter.adapter.viewholder.LibaoNormalViewHolder;
import com.gh.gamecenter.databinding.LibaoItemBinding;
import com.gh.gamecenter.feature.entity.GameEntity;
import com.gh.gamecenter.entity.LibaoEntity;
import com.gh.gamecenter.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.login.user.UserManager;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.lightgame.adapter.BaseRecyclerAdapter;
import com.lightgame.utils.Utils;

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/12.
 */
class Libao3FragmentAdapter extends BaseRecyclerAdapter<RecyclerView.ViewHolder> {

    private OnRequestCallBackListener mCallBackListener;

    private List<LibaoEntity> mLibaoList;

    private String mEntrance;

    private boolean isLoading;
    private boolean isOver;
    private boolean isNetworkError;

    private int mPage;
    private String mFilter = "expires:false";

    Libao3FragmentAdapter(Context context, OnRequestCallBackListener listener, String filter, String entrance) {
        super(context);
        mCallBackListener = listener;
        mEntrance = entrance;
        mLibaoList = new ArrayList<>();
        mPage = 1;
        mFilter = filter;
    }

    void loadData() {
        if (isLoading) return;
        isLoading = true;
        if (TextUtils.isEmpty(UserManager.getInstance().getToken())) {
            mCallBackListener.loadDone(null);
            return;
        }

        if (mPage == 1) {
            mLibaoList.clear();
        }
        RetrofitManager.getInstance()
                .getApi().getCunHaoXiang(UserManager.getInstance().getUserId(), mPage, mFilter)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<List<LibaoEntity>>() {
                    @Override
                    public void onResponse(List<LibaoEntity> response) {
                        super.onResponse(response);
                        for (LibaoEntity entity : response) { // 转译 手动组合userData数据
                            MeEntity userDataEntity = new MeEntity();
                            ArrayList<UserDataLibaoEntity> list = new ArrayList<>();
                            list.add(new UserDataLibaoEntity(entity.getCode(), entity.getStatus(), entity.getTime()));
                            userDataEntity.setUserDataLibaoList(list);
                            entity.setMe(userDataEntity);
                        }

                        mLibaoList.addAll(response);
                        mCallBackListener.loadDone();
                        if (response.size() < 20) {
                            isOver = true;
                        }

                        if (mLibaoList.size() == 0) {
                            mCallBackListener.loadEmpty();
                        } else {
                            mCallBackListener.loadDone();
                        }
                        initData();

                        if (response.size() > 0) {
                            getLibaoStatus(response);
                        }

                        mPage++;
                        isLoading = false;
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        super.onFailure(e);
                        if (mLibaoList.isEmpty()) {
                            mCallBackListener.loadError();
                        } else {
                            isNetworkError = true;
                            notifyItemChanged(getItemCount() - 1);
                        }
                        isLoading = false;
                    }
                });
    }

    private void initData() {
        for (int i = 0; i < mLibaoList.size(); i++) {
            LibaoEntity libaoEntity = mLibaoList.get(i);
            if (!libaoEntity.isActive()) {
                mLibaoList.remove(i);
                i--;
            }
        }

        if (mLibaoList.size() == 0) {
            mCallBackListener.loadEmpty();
        } else {
            mCallBackListener.loadDone();
        }
        notifyDataSetChanged();
    }

    //获取礼包状态
    private void getLibaoStatus(List<LibaoEntity> response) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0, size = response.size(); i < size; i++) {
            builder.append(response.get(i).getId());
            builder.append("-");
        }
        if (builder.length() == 0) return;
        builder.deleteCharAt(builder.length() - 1);
        String ids = builder.toString();

        LibaoUtils.getLibaoStatus(ids, new LibaoUtils.PostLibaoListener() {
            @Override
            public void postSucceed(Object response) {
                List<LibaoStatusEntity> statusList = (List<LibaoStatusEntity>) response;

                LibaoUtils.initLiBaoEntity(statusList, mLibaoList);

                notifyItemRangeChanged(0, getItemCount());
            }

            @Override
            public void postFailed(Throwable error) {

            }
        });
    }

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

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == 0) {
            return new FooterViewHolder(mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false));
        } else {
            View view = mLayoutInflater.inflate(R.layout.libao_item, parent, false);
            return new LibaoNormalViewHolder(LibaoItemBinding.bind(view));
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {

        if (viewHolder instanceof LibaoNormalViewHolder) {
            LibaoNormalViewHolder holder = (LibaoNormalViewHolder) viewHolder;
            final LibaoEntity libaoEntity = mLibaoList.get(position);
            ExtensionsKt.setRootBackgroundColor(holder.binding.getRoot(), R.color.background_white);
            holder.binding.libaoName.setText(libaoEntity.getName());
            holder.binding.libaoGameIcon.displayGameIcon(libaoEntity.getIcon(), libaoEntity.getIconSubscript(), libaoEntity.getGame().getIconFloat());
            if (mFilter.equals("expires:false") && libaoEntity.getExpires() > 0) {
                holder.binding.expiresTime.setVisibility(View.VISIBLE);
                holder.binding.expiresTime.setText(String.format(Locale.CHINA, "%s过期", TimeUtils.getFormatTime(libaoEntity.getExpires(), "MM.dd")));
            } else {
                holder.binding.expiresTime.setVisibility(View.GONE);
            }
            holder.binding.moreIv.setVisibility(View.VISIBLE);
            holder.binding.moreIv.setOnClickListener(v -> showOptionPopupWindow(v, libaoEntity));

            if (TextUtils.isEmpty(libaoEntity.getPlatform())) {
                holder.binding.libaoGameName.setText(libaoEntity.getGame().getName());
            } else {
                holder.binding.libaoGameName.setText(libaoEntity.getGame().getName() + " - " + PlatformUtils.getInstance(mContext)
                        .getPlatformName(libaoEntity.getPlatform()));
            }

            if (libaoEntity.getCode() != null) {
                Spanned content;
                if ("ling".equals(libaoEntity.getStatus()) || "linged".equals(libaoEntity.getStatus())) {
                    libaoEntity.setStatus("linged");
                    String string = mContext.getString(R.string.linged_code, libaoEntity.getCode());
                    content = Html.fromHtml(string);
                } else {
                    libaoEntity.setStatus("taoed");
                    String string = mContext.getString(R.string.taoed_code, libaoEntity.getCode());
                    content = Html.fromHtml(string);
                }
                holder.binding.libaoDes.setText(content);

                holder.binding.libaoBtnStatus.setOnClickListener(v -> {
                    LibaoUtils.copyLink(libaoEntity.getCode(), mContext);
                    if (!TextUtils.isEmpty(libaoEntity.getPackageName()) && LibaoUtils.isAppInstalled(mContext
                            , libaoEntity.getPackageName())) {
                        Spanned msg;
                        if ("ling".equals(libaoEntity.getStatus()) || "linged".equals(libaoEntity.getStatus())) {
                            msg = Html.fromHtml(mContext.getString(R.string.linged_copy_dialog, libaoEntity.getCode()));
                        } else {
                            msg = Html.fromHtml(mContext.getString(R.string.taoed_copy_dialog, libaoEntity.getCode()));
                        }
                        LibaoUtils.lunningAppDialog(mContext, msg, libaoEntity);
                    }
                });
            }

            holder.itemView.setOnClickListener(v -> {
                if (libaoEntity.getLibaoActive() && libaoEntity.getGame().getActive()) {
                    mContext.startActivity(LibaoDetailActivity.getIntent(mContext, libaoEntity, mEntrance + "+(礼包中心:存号箱)"));
                }
            });

            holder.itemView.setOnLongClickListener(v -> {
                showDeleteDialog(libaoEntity);
                return true;
            });

            holder.binding.libaoBtnStatus.setText("复制");
            holder.binding.libaoBtnStatus.setBackgroundResource(R.drawable.button_normal_round_style);

            GameEntity gameEntity = libaoEntity.getGame().toGameEntity();
            GameItemViewHolder.initGameSubtitleAndAdLabel(gameEntity, holder.binding.gameSubtitleTv, null, null, false, null, false, null);
        } else if (viewHolder instanceof FooterViewHolder) {
            initFooterViewHolder((FooterViewHolder) viewHolder);
        }
    }

    private void showOptionPopupWindow(View view, LibaoEntity libaoEntity) {
        View layout = LayoutInflater.from(mContext).inflate(R.layout.layout_popup_container, null);
        BugFixedPopupWindow popupWindow = new BugFixedPopupWindow(
                layout,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );
        LinearLayout container = layout.findViewById(R.id.container);
        View item = LayoutInflater.from(mContext).inflate(R.layout.layout_popup_option_icon_item, container, false);
        container.addView(item, LinearLayout.LayoutParams.WRAP_CONTENT, ExtensionsKt.dip2px(50f));
        ImageView iconView = item.findViewById(R.id.icon);
        TextView hitText = item.findViewById(R.id.hint_text);
        hitText.setText("删除");
        iconView.setImageDrawable(ExtensionsKt.toDrawable(R.drawable.ic_libao_delete));
        item.setOnClickListener(v -> {
            showDeleteDialog(libaoEntity);
            popupWindow.dismiss();
        });
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        ExtensionsKt.showAutoOrientation(popupWindow, view, 0, 0);
    }

    private void showDeleteDialog(LibaoEntity libaoEntity) {
        DialogHelper.showCenterWarningDialog(mContext, "删除礼包", Html.fromHtml(mContext.getString(R.string.libao_delete_dialog))
                , "取消", "确定删除"
                , () -> {
                    LibaoUtils.deleteLibaoCode(libaoEntity.getCode(), new LibaoUtils.PostLibaoListener() {
                        @Override
                        public void postSucceed(Object response) {
                            Utils.toast(mContext, "删除成功");
                            for (LibaoEntity entity : mLibaoList) {
                                if (libaoEntity.getId().equals(entity.getId())) {
                                    entity.setActive(false);
                                    initData();
                                    break;
                                }
                            }
                        }

                        @Override
                        public void postFailed(Throwable error) {

                            if (error instanceof HttpException) {
                                HttpException exception = (HttpException) error;
                                if (exception.code() == 400) {
                                    Utils.toast(mContext, "删除成功code-null");
                                    for (LibaoEntity entity : mLibaoList) {
                                        if (libaoEntity.getId().equals(entity.getId())) {
                                            entity.setActive(false);
                                            initData();
                                            break;
                                        }
                                    }
                                } else {
                                    Utils.toast(mContext, "删除失败，请检查网络状态");
                                }
                            }
                        }
                    });
                    return null;
                }, null);
    }

    private void initFooterViewHolder(FooterViewHolder holder) {
        holder.initItemPadding();
        if (isNetworkError) {
            holder.getLoading().setVisibility(View.GONE);
            holder.getHint().setText(R.string.loading_failed_retry);
            holder.itemView.setClickable(true);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isNetworkError = false;
                    notifyItemChanged(getItemCount() - 1);
                }
            });
        } else if (isOver) {
            holder.getLoading().setVisibility(View.GONE);
            holder.getHint().setText(R.string.load_over_hint);
            holder.itemView.setClickable(false);
        } else {
            holder.getLoading().setVisibility(View.VISIBLE);
            holder.getHint().setText(R.string.loading);
            holder.itemView.setClickable(false);
        }
    }

    @Override
    public int getItemCount() {
        if (mLibaoList.size() == 0) return 0;
        return mLibaoList.size() + 1;
    }

    public boolean isNetworkError() {
        return isNetworkError;
    }

    public boolean isOver() {
        return isOver;
    }

    public boolean isLoading() {
        return isLoading;
    }
}
