package com.gh.gamecenter.collection;

import android.content.Context;
import android.graphics.Paint;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.gh.common.util.NewsUtils;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.viewholder.NewsImage1ViewHolder;
import com.gh.gamecenter.adapter.viewholder.NewsImage2ViewHolder;
import com.gh.gamecenter.adapter.viewholder.NewsImage3ViewHolder;
import com.gh.gamecenter.common.baselist.ListAdapter;
import com.gh.gamecenter.common.callback.OnListClickListener;
import com.gh.gamecenter.common.constant.ItemViewType;
import com.gh.gamecenter.common.retrofit.JSONObjectResponse;
import com.gh.gamecenter.common.utils.DialogHelper;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.common.utils.ImageUtils;
import com.gh.gamecenter.common.view.DrawableView;
import com.gh.gamecenter.common.viewholder.FooterViewHolder;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.core.utils.NumberUtils;
import com.gh.gamecenter.databinding.NewsImage1ItemBinding;
import com.gh.gamecenter.databinding.NewsImage2ItemBinding;
import com.gh.gamecenter.databinding.NewsImage3ItemBinding;
import com.gh.gamecenter.databinding.PopupHistoryOptionBinding;
import com.gh.gamecenter.feature.entity.NewsEntity;
import com.gh.gamecenter.history.ManageOption;
import com.gh.gamecenter.manager.VisitManager;
import com.gh.gamecenter.retrofit.RetrofitManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Locale;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import kotlin.collections.CollectionsKt;

/**
 * Created by khy on 18/07/17.
 */

public class ArticleAdapter extends ListAdapter<NewsEntity> {

    private OnListClickListener mListListener;
    private ArticleViewModel mViewModel;

    private ManageOption mCurrentOption = ManageOption.OPTION_MANAGER;
    private PopupWindow mPopWindow;
    private PopupHistoryOptionBinding mPopupBinding;
    private ArrayList<String> selectItems = new ArrayList<>();

    public ArticleAdapter(Context context, ArticleViewModel viewModel, OnListClickListener listListener) {
        super(context);
        mViewModel = viewModel;
        mListListener = listListener;
    }

    @Override
    protected boolean areItemsTheSame(NewsEntity oldItem, NewsEntity newItem) {
        return !TextUtils.isEmpty(oldItem.getId()) && oldItem.getId().equals(newItem.getId());
    }

    @Override
    protected boolean areContentsTheSame(NewsEntity oldItem, NewsEntity newItem) {
        return oldItem.getViews() == newItem.getViews();
    }

    @Override
    public int getItemViewType(int position) {
        if (position == mEntityList.size()) {
            return ItemViewType.LOADING;
        }
        NewsEntity newsEntity = mEntityList.get(position);

        if (newsEntity.getThumbnail() == null) {
            return ItemViewType.NEWS_IMAGE1;
        }
        if ("4x3".equals(newsEntity.getThumbnail().getType()) && newsEntity.getThumbnail().getUrl().size() == 3) {
            return ItemViewType.NEWS_IMAGE2;
        }
        if ("3x1".equals(newsEntity.getThumbnail().getType())) {
            return ItemViewType.NEWS_IMAGE3;
        }
        return ItemViewType.NEWS_IMAGE1;
    }

    public void changeOption(ManageOption option) {
        mCurrentOption = option;
        if (mCurrentOption == ManageOption.OPTION_MANAGER) {
            if (mPopWindow != null) {
                selectItems.clear();
                mPopWindow.dismiss();
                mPopWindow = null;
            }
        } else {
            if (mPopWindow == null || mPopWindow.isShowing()) {
                showOptionWindow();
            }
        }

        notifyItemRangeChanged(0, mEntityList.size());
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case ItemViewType.NEWS_IMAGE1:
                return new NewsImage1ViewHolder(NewsImage1ItemBinding.inflate(mLayoutInflater, parent, false), new OnListClickListener() {
                    @Override
                    public <T> void onListClick(View view, int position, T data) {
                        onClick(view, position, (NewsEntity) data);
                    }
                });
            case ItemViewType.NEWS_IMAGE2:
                return new NewsImage2ViewHolder(NewsImage2ItemBinding.inflate(mLayoutInflater, parent, false), new OnListClickListener() {
                    @Override
                    public <T> void onListClick(View view, int position, T data) {
                        onClick(view, position, (NewsEntity) data);
                    }
                });
            case ItemViewType.NEWS_IMAGE3:
                return new NewsImage3ViewHolder(NewsImage3ItemBinding.inflate(mLayoutInflater, parent, false), new OnListClickListener() {
                    @Override
                    public <T> void onListClick(View view, int position, T data) {
                        onClick(view, position, (NewsEntity) data);
                    }
                });
            case ItemViewType.LOADING:
                return new FooterViewHolder(mLayoutInflater.inflate(com.gh.gamecenter.common.R.layout.refresh_footerview, parent, false));
            default:
                return null;
        }
    }

    private void onClick(View view, int position, NewsEntity data) {
        if (mCurrentOption == ManageOption.OPTION_MANAGER) {
            mListListener.onListClick(view, position, data);
        } else {
            if (selectItems.contains(data.getId())) {
                selectItems.remove(data.getId());
            } else {
                selectItems.add(data.getId());
            }
            checkSelectItems();
            notifyItemChanged(position);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        switch (getItemViewType(position)) {
            case ItemViewType.NEWS_IMAGE1:
                initNewsImage1ViewHolder((NewsImage1ViewHolder) holder, position);
                addLongClickListenerIfNeed(holder, mEntityList.get(position));
                break;
            case ItemViewType.NEWS_IMAGE2:
                initNewsImage2ViewHolder((NewsImage2ViewHolder) holder, position);
                addLongClickListenerIfNeed(holder, mEntityList.get(position));
                break;
            case ItemViewType.NEWS_IMAGE3:
                initNewsImage3ViewHolder((NewsImage3ViewHolder) holder, position);
                addLongClickListenerIfNeed(holder, mEntityList.get(position));
                break;
            case ItemViewType.LOADING:
                FooterViewHolder footerViewHolder = (FooterViewHolder) holder;
                footerViewHolder.initItemPadding();
                footerViewHolder.initFooterViewHolder(mIsLoading, mIsNetworkError, mIsOver);
                break;
        }
    }

    private void addLongClickListenerIfNeed(RecyclerView.ViewHolder holder, NewsEntity newsEntity) {
        if (ArticleFragment.HISTORY.equals(mViewModel.type)) {
            holder.itemView.setOnLongClickListener(v -> {
                DialogHelper.showCenterDialog(holder.itemView.getContext(),
                        "删除记录",
                        "删除浏览记录将不可恢复，确定删除吗？",
                        "确定",
                        "取消",
                        () -> {
                            mViewModel.removeHistory(newsEntity);
                        },
                        () -> {
                        });
                return false;
            });
        }
    }

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

    private void initNewsImage1ViewHolder(final NewsImage1ViewHolder viewHolder, int position) {

        final NewsEntity newsEntity = mEntityList.get(position);
        viewHolder.setClickData(newsEntity);
        if (newsEntity.getThumbnail() != null && newsEntity.getThumbnail().getUrl() != null) {
            ImageUtils.display(viewHolder.binding.newsImage1Thumb, CollectionsKt.firstOrNull(newsEntity.getThumbnail().getUrl()));
        } else {
            ImageUtils.display(viewHolder.binding.newsImage1Thumb, R.drawable.message_image_placeholder);
        }
        viewHolder.binding.selectIv.setVisibility(mCurrentOption == ManageOption.OPTION_MANAGER ? View.GONE : View.VISIBLE);
        viewHolder.binding.selectIv.setChecked(selectItems.contains(newsEntity.getId()));

        viewHolder.binding.newsImage1Title.setText(newsEntity.getTitle());
        if (newsEntity.getActive()) {
            viewHolder.binding.newsImage1Title.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);
            viewHolder.binding.newsImage1Title.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.title));
        } else {
            viewHolder.binding.newsImage1Title.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            viewHolder.binding.newsImage1Title.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.hint));
        }
        int views = newsEntity.getViews();
        if (views == 0) {
            viewHolder.binding.newsImage1Read.setVisibility(View.GONE);
        } else {
            viewHolder.binding.newsImage1Read.setVisibility(View.VISIBLE);
            viewHolder.binding.newsImage1Read.setText(String.format(Locale.getDefault(), "阅读  %s", NumberUtils.transSimpleCount(views)));
        }
        NewsUtils.setNewsType(viewHolder.binding.newsImage1Type, newsEntity.getType(), newsEntity.getPriority(), position);
    }

    private void initNewsImage2ViewHolder(final NewsImage2ViewHolder viewHolder, int position) {

        final NewsEntity newsEntity = mEntityList.get(position);
        viewHolder.setClickData(newsEntity);
        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        int width = (outMetrics.widthPixels - DisplayUtils.dip2px(mContext, 56)) / 3;
        int height = (int) (width * 3 / 4f);

        LinearLayout.LayoutParams lparams1 = new LinearLayout.LayoutParams(width, height);
        viewHolder.binding.newsImage2Thumb1.setLayoutParams(lparams1);

        LinearLayout.LayoutParams lparams2 = new LinearLayout.LayoutParams(width, height);
        lparams2.leftMargin = DisplayUtils.dip2px(mContext, 8);
        viewHolder.binding.newsImage2Thumb2.setLayoutParams(lparams2);

        LinearLayout.LayoutParams lparams3 = new LinearLayout.LayoutParams(width, height);
        lparams3.leftMargin = DisplayUtils.dip2px(mContext, 8);
        viewHolder.binding.newsImage2Thumb3.setLayoutParams(lparams3);

        viewHolder.binding.selectIv.setVisibility(mCurrentOption == ManageOption.OPTION_MANAGER ? View.GONE : View.VISIBLE);
        viewHolder.binding.selectIv.setChecked(selectItems.contains(newsEntity.getId()));

        viewHolder.binding.newsImage2Title.setText(newsEntity.getTitle());
        if (newsEntity.getActive()) {
            viewHolder.binding.newsImage2Title.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);
            viewHolder.binding.newsImage2Title.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.title));
        } else {
            viewHolder.binding.newsImage2Title.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            viewHolder.binding.newsImage2Title.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.hint));
        }
        if (newsEntity.getThumbnail() != null && newsEntity.getThumbnail().getUrl() != null) {
            ImageUtils.display(viewHolder.binding.newsImage2Thumb1, CollectionsKt.getOrNull(newsEntity.getThumbnail().getUrl(), 0));
            ImageUtils.display(viewHolder.binding.newsImage2Thumb2, CollectionsKt.getOrNull(newsEntity.getThumbnail().getUrl(), 1));
            ImageUtils.display(viewHolder.binding.newsImage2Thumb3, CollectionsKt.getOrNull(newsEntity.getThumbnail().getUrl(), 2));
        }
        int views = newsEntity.getViews();
        if (views == 0) {
            viewHolder.binding.newsImage2Read.setVisibility(View.GONE);
        } else {
            viewHolder.binding.newsImage2Read.setVisibility(View.VISIBLE);
            viewHolder.binding.newsImage2Read.setText(String.format(Locale.getDefault(), "阅读  %s", NumberUtils.transSimpleCount(views)));
        }
        NewsUtils.setNewsType(viewHolder.binding.newsImage2Type, newsEntity.getType(), newsEntity.getPriority(), position);
    }

    private void initNewsImage3ViewHolder(final NewsImage3ViewHolder viewHolder, int position) {

        final NewsEntity newsEntity = mEntityList.get(position);
        viewHolder.setClickData(newsEntity);
        viewHolder.binding.newsImage3Title.setText(newsEntity.getTitle());
        if (newsEntity.getActive()) {
            viewHolder.binding.newsImage3Title.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);
            viewHolder.binding.newsImage3Title.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.title));
        } else {
            viewHolder.binding.newsImage3Title.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            viewHolder.binding.newsImage3Title.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.hint));
        }
        viewHolder.binding.selectIv.setVisibility(mCurrentOption == ManageOption.OPTION_MANAGER ? View.GONE : View.VISIBLE);
        viewHolder.binding.selectIv.setChecked(selectItems.contains(newsEntity.getId()));

        if (newsEntity.getThumbnail() != null && newsEntity.getThumbnail().getUrl() != null) {
            ImageUtils.displayWithAdaptiveHeight(viewHolder.binding.newsImage3Thumb, CollectionsKt.firstOrNull(newsEntity.getThumbnail().getUrl()),
                    mContext.getResources().getDisplayMetrics().widthPixels - DisplayUtils.dip2px(mContext, 40));
        }
        int views = newsEntity.getViews();
        if (views == 0) {
            viewHolder.binding.newsImage3Read.setVisibility(View.GONE);
        } else {
            viewHolder.binding.newsImage3Read.setVisibility(View.VISIBLE);
            viewHolder.binding.newsImage3Read.setText(String.format(Locale.getDefault(), "阅读  %s", NumberUtils.transSimpleCount(views)));
        }
        NewsUtils.setNewsType(viewHolder.binding.newsImage3Type, newsEntity.getType(), newsEntity.getPriority(), position);
    }

    // 统计新闻阅读量
    public void statNewsViews(final NewsEntity newsEntity, final int position) {
        RetrofitManager.getInstance().getApi().postArticleVisit(newsEntity.getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new JSONObjectResponse() {
                    @Override
                    public void onResponse(JSONObject response) {
                        if (response.length() != 0) {
                            try {
                                if ("success".equals(response.getString("status"))) {
                                    newsEntity.setViews(newsEntity.getViews() + 1);

                                    notifyItemChanged(position);

                                    // 更新okhttp缓存数据
                                    VisitManager.updateOkhttpCache(mContext, newsEntity.getId());
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    private void showOptionWindow() {
        mPopupBinding = PopupHistoryOptionBinding.inflate(LayoutInflater.from(mContext));
        mPopupBinding.getRoot().setFocusable(true);
        mPopupBinding.getRoot().setFocusableInTouchMode(true);

        mPopWindow = new PopupWindow(mPopupBinding.getRoot(), LinearLayout.LayoutParams.MATCH_PARENT, DisplayUtils.dip2px(56f));
        mPopWindow.showAtLocation(((AppCompatActivity) mContext).getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
        mPopupBinding.itemDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogHelper.showDialog(mContext,
                        "是否删除" + selectItems.size() + "条记录？",
                        "提示：删除记录将不可恢复",
                        "删除",
                        "取消",
                        () -> {
                            mViewModel.removeHistories(selectItems);
                            selectItems.clear();
                            checkSelectItems();
                        },
                        () -> {
                        },
                        false, "", "");


            }
        });
        mPopupBinding.checkAllCb.setCompoundDrawablesWithIntrinsicBounds(
                DrawableView.getCheckSelectorDrawable(
                        mContext
                ), null, null, null
        );
        mPopupBinding.checkAllCb.setOnClickListener(v -> {
            if (mPopupBinding.checkAllCb.isChecked()) {
                selectItems.clear();
                for (NewsEntity entity : mEntityList) {
                    selectItems.add(entity.getId());
                }
            } else {
                selectItems.clear();
            }
            checkSelectItems();
            notifyItemRangeChanged(0, mEntityList.size());
        });
        checkSelectItems();
    }

    private void checkSelectItems() {
        if (mPopupBinding == null) return;
        mPopupBinding.selectNumTv.setText(selectItems.isEmpty() ? "" : "(" + selectItems.size() + ")");
        mPopupBinding.itemDelete.setBackground(selectItems.isEmpty() ? ExtensionsKt.toDrawable(com.gh.gamecenter.common.R.drawable.bg_shape_f5_radius_999) : ExtensionsKt.toDrawable(com.gh.gamecenter.common.R.drawable.download_button_normal_style));
        mPopupBinding.itemDelete.setTextColor(selectItems.isEmpty() ? ExtensionsKt.toColor(com.gh.gamecenter.common.R.color.text_instance) : ExtensionsKt.toColor(com.gh.gamecenter.common.R.color.white));
        mPopupBinding.itemDelete.setEnabled(!selectItems.isEmpty());
        mPopupBinding.checkAllCb.setChecked(selectItems.size() == mEntityList.size());
    }

}
