package com.gh.common.util;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.gh.gamecenter.CommentDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.viewholder.CommentViewHolder;
import com.gh.gamecenter.common.callback.SimpleCallback;
import com.gh.gamecenter.common.retrofit.BiResponse;
import com.gh.gamecenter.common.retrofit.Response;
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.core.utils.DisplayUtils;
import com.gh.gamecenter.core.utils.NumberUtils;
import com.gh.gamecenter.core.utils.ToastUtils;
import com.gh.gamecenter.feature.entity.CommentEntity;
import com.gh.gamecenter.feature.entity.MeEntity;
import com.gh.gamecenter.login.entity.UserInfoEntity;
import com.gh.gamecenter.login.user.UserManager;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.halo.assistant.HaloApp;
import com.lightgame.utils.Utils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

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

/**
 * Created by khy on 2017/3/22.
 */
public class CommentUtils {

    public static void setCommentTime(TextView textView, long time) {
        textView.setText(getCommentTime(time));
    }

    public static String getCommentTime(long timestamp) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
        try {
            long day = timestamp * 1000;
            String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
            format.applyPattern("yyyy");
            String currentYear = format.format(day);
            format.applyPattern("yyyyMMdd");
            long today = format.parse(format.format(new Date())).getTime();
            if (day >= today && day < today + 86400 * 1000) {
                long min = new Date().getTime() / 1000 - day / 1000;
                int hour = (int) (min / (60 * 60));
                if (hour == 0) {
                    if (min < 60) {
                        return "刚刚";
                    } else {
                        return String.format(Locale.getDefault(), "%d分钟前", (int) (min / 60));
                    }
                } else {
                    return String.format(Locale.getDefault(), "%d小时前", hour);
                }
            } else if (day >= today - 86400 * 1000 && day < today) {
                format.applyPattern("HH:mm");
                return "昨天 ";
            } else if (day >= today - 86400 * 1000 * 7 && day < today - 86400 * 1000) {
                format.applyPattern("HH:mm");
                long days = (today - day) / 86400000 + 1;
                return String.format(Locale.getDefault(), "%d天前 ", days);
            } else if (day < today - 86400 * 1000 * 7 && year.equals(currentYear)) {
                format.applyPattern("MM-dd");
                return format.format(day);
            } else {
                format.applyPattern("yyyy-MM-dd");
                return format.format(day);
            }
        } catch (ParseException e) {
            e.printStackTrace();
            format.applyPattern("yyyy-MM-dd");
            return format.format(timestamp * 1000);
        }
    }

    public static void showMorePopupWindow(
            final View anchor,
            final CommentEntity commentEntity,
            final boolean showConversation,
            final String patch,
            final OnCommentDeleteListener onCommentDeleteListener
    ) {
        Context context = anchor.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);
        View contentView = inflater.inflate(com.gh.gamecenter.common.R.layout.layout_popup_container, null);
        PopupWindow popupWindow = new PopupWindow(
                contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);

        LinearLayout container = contentView.findViewById(R.id.container);
        List<String> dialogType = new ArrayList<>();
        dialogType.add("复制");
        dialogType.add("投诉");

        if (commentEntity.getParent() != null && showConversation) {
            dialogType.add("查看对话");
        }

        String commentUserId = commentEntity.getUser().getId();
        String userId = UserManager.getInstance().getUserId();
        MeEntity me = commentEntity.getMe();
        boolean isCommentedByUser = Objects.equals(commentUserId, userId);
        boolean isContentAuthorOrModerator = me != null && (me.isModerator() || me.isContentAuthor());
        if (isCommentedByUser || isContentAuthorOrModerator) {
            dialogType.add("删除");
        }

        for (String s : dialogType) {
            View itemView = inflater.inflate(R.layout.layout_popup_option_item, container, false);
            TextView reportTv = itemView.findViewById(R.id.hint_text);
            reportTv.setText(s);
            container.addView(itemView);

            reportTv.setOnClickListener(v -> {
                popupWindow.dismiss();
                switch (reportTv.getText().toString()) {
                    case "复制":
                        copyText(commentEntity.getContent(), context);
                        break;
                    case "投诉":
                        CheckLoginUtils.checkLogin(context, patch + "-投诉",
                                () -> showReportTypeDialog(commentEntity, context));
                        break;
                    case "查看对话":
                        context.startActivity(CommentDetailActivity.getIntent(context, commentEntity.getId(), null));
                        break;
                    case "删除":
                        DialogHelper.INSTANCE.showDialog(
                                context,
                                "提示",
                                "删除评论后，评论下所有的回复都将被删除",
                                "删除",
                                "取消",
                                () -> {
                                    deleteComment(context, commentEntity, onCommentDeleteListener);
                                    return null;
                                },
                                null,
                                null,
                                null,
                                new DialogHelper.Config("", false, true, true, false, -1)
                        );
                        break;
                }
            });
        }

        ExtensionsKt.showAutoOrientation(popupWindow, anchor, 0, 0);
    }

    private static void showReportTypeDialog(final CommentEntity commentEntity, final Context context) {
        final String[] arrReportType = new String[]{"垃圾广告营销", "恶意攻击谩骂", "淫秽色情信息",
                "违法有害信息", "其它"};
        int widthPixels = context.getResources().getDisplayMetrics().widthPixels;

        final Dialog reportTypeDialog = new Dialog(context);
        LinearLayout container = new LinearLayout(context);
        container.setOrientation(LinearLayout.VERTICAL);
        container.setPadding(0, DisplayUtils.dip2px(context, 12), 0, DisplayUtils.dip2px(context, 12));
        container.setBackgroundColor(ContextCompat.getColor(context, com.gh.gamecenter.common.R.color.ui_surface));

        for (final String s : arrReportType) {
            TextView reportTypeTv = new TextView(context);
            reportTypeTv.setText(s);
            reportTypeTv.setTextSize(17);
            reportTypeTv.setTextColor(ContextCompat.getColor(context, com.gh.gamecenter.common.R.color.title));
            reportTypeTv.setBackgroundResource(com.gh.gamecenter.common.R.drawable.textview_white_style);
            reportTypeTv.setLayoutParams(new LinearLayout.LayoutParams((widthPixels * 9) / 10,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
            reportTypeTv.setPadding(DisplayUtils.dip2px(context, 20), DisplayUtils.dip2px(context, 12),
                    0, DisplayUtils.dip2px(context, 12));
            container.addView(reportTypeTv);

            reportTypeTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("comment_id", commentEntity.getId());
                        jsonObject.put("reason", s);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    PostCommentUtils.addReportData(commentEntity.getId(), jsonObject.toString(),
                            new PostCommentUtils.PostCommentListener() {
                                @Override
                                public void postSuccess(JSONObject response) {
                                    Utils.toast(context, "感谢您的投诉");
                                }

                                @Override
                                public void postFailed(Throwable error) {
                                    Utils.toast(context, "投诉失败，请检查网络设置");
                                }
                            });
                    reportTypeDialog.cancel();
                }
            });
        }

        reportTypeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        reportTypeDialog.setContentView(container);
        reportTypeDialog.show();
    }

    public static void postVote(final Context context, final CommentEntity commentEntity,
                                final TextView commentLikeCountTv, final ImageView commentLikeIv,
                                final OnVoteListener listener) {
        if (commentLikeCountTv.getCurrentTextColor() == ContextCompat.getColor(context, com.gh.gamecenter.common.R.color.text_theme)) {
            ToastUtils.INSTANCE.showToast("已经点过赞啦！");
            return;
        }
        commentEntity.setVote(commentEntity.getVote() + 1);
        commentLikeCountTv.setTextColor(ContextCompat.getColor(context, com.gh.gamecenter.common.R.color.text_theme));
        commentLikeIv.setImageResource(R.drawable.comment_vote_select);
        commentLikeCountTv.setText(NumberUtils.transSimpleCount(commentEntity.getVote()));
        commentLikeCountTv.setVisibility(View.VISIBLE);

        PostCommentUtils.addCommentVote(commentEntity.getId(),
                new PostCommentUtils.PostCommentListener() {
                    @Override
                    public void postSuccess(JSONObject response) {
                        if (listener != null) {
                            listener.onVote();
                        }
                    }

                    @Override
                    public void postFailed(Throwable e) {

                        commentEntity.setVote(commentEntity.getVote() - 1);
                        commentLikeCountTv.setTextColor(ContextCompat.getColor(context, com.gh.gamecenter.common.R.color.hint));
                        commentLikeIv.setImageResource(R.drawable.comment_vote_unselect);
                        commentLikeCountTv.setText(NumberUtils.transSimpleCount(commentEntity.getVote()));
                        if (commentEntity.getVote() == 0) {
                            commentLikeCountTv.setVisibility(View.GONE);
                        } else {
                            commentLikeCountTv.setVisibility(View.VISIBLE);
                        }

                        if (e instanceof HttpException) {
                            HttpException exception = (HttpException) e;
                            if (exception.code() == 403) {
                                try {
                                    String detail = new JSONObject(exception.response().errorBody().string()).getString("detail");
                                    if ("voted".equals(detail)) {
                                        ToastUtils.INSTANCE.showToast("已经点过赞啦！");
                                    }
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }
                                return;
                            }
                        }
                        Utils.toast(context, "网络异常，点赞失败");
                    }
                });
    }

    public static void likeComment(final Context context,
                                   String answerId,
                                   String articleId,
                                   String articleCommunityId,
                                   String videoId,
                                   String questionId,
                                   final CommentEntity commentEntity,
                                   final TextView commentLikeCountTv,
                                   final ImageView commentLikeIv,
                                   final OnVoteListener listener) {

        String entrance = "回答详情-评论-点赞";
        if (TextUtils.isEmpty(articleId)) {
            entrance = "社区文章详情-评论-点赞";
        }
        if (TextUtils.isEmpty(videoId)) {
            entrance = "视频流-评论-点赞";
        }
        CheckLoginUtils.checkLogin(context, entrance, () -> {
            if (commentLikeCountTv.getCurrentTextColor() == ContextCompat.getColor(context, com.gh.gamecenter.common.R.color.text_theme)) {
                ToastUtils.INSTANCE.showToast("已经点过赞啦！");
                return;
            }
            commentEntity.setVote(commentEntity.getVote() + 1);
            commentLikeCountTv.setTextColor(ContextCompat.getColor(context, com.gh.gamecenter.common.R.color.text_theme));
            commentLikeIv.setImageResource(R.drawable.comment_vote_select);
            commentLikeCountTv.setText(NumberUtils.transSimpleCount(commentEntity.getVote()));
            commentLikeCountTv.setVisibility(View.VISIBLE);

            PostCommentUtils.likeComment(answerId, articleId, videoId, questionId, commentEntity.getId(),
                    new PostCommentUtils.PostCommentListener() {
                        @Override
                        public void postSuccess(JSONObject response) {
                            if (listener != null) {
                                listener.onVote();
                            }
                        }

                        @Override
                        public void postFailed(Throwable e) {
                            commentEntity.setVote(commentEntity.getVote() - 1);
                            commentLikeCountTv.setTextColor(ContextCompat.getColor(context, com.gh.gamecenter.common.R.color.hint));
                            commentLikeIv.setImageResource(R.drawable.comment_vote_unselect);
                            commentLikeCountTv.setText(NumberUtils.transSimpleCount(commentEntity.getVote()));
                            if (commentEntity.getVote() == 0) {
                                commentLikeCountTv.setVisibility(View.GONE);
                            } else {
                                commentLikeCountTv.setVisibility(View.VISIBLE);
                            }

                            if (e instanceof HttpException) {
                                HttpException exception = (HttpException) e;
                                if (exception.code() == 403) {
                                    try {
                                        String detail = new JSONObject(exception.response().errorBody().string()).getString("detail");
                                        if ("voted".equals(detail)) {
                                            ToastUtils.INSTANCE.showToast("已经点过赞啦！");
                                        }
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                    }
                                    return;
                                }
                            }
                            Utils.toast(context, "网络异常，点赞失败");
                        }
                    });
        });
    }

    public static void voteVideoComment(final Context context,
                                        String answerId,
                                        String articleId,
                                        String articleCommunityId,
                                        String videoId,
                                        final CommentEntity commentEntity,
                                        final TextView commentLikeCountTv,
                                        final ImageView commentLikeIv,
                                        final OnVoteListener listener) {

        String entrance = "视频流-评论-点赞";
        CheckLoginUtils.checkLogin(context, entrance, () -> {

            PostCommentUtils.likeComment(answerId, articleId, videoId, "", commentEntity.getId(),
                    new PostCommentUtils.PostCommentListener() {
                        @Override
                        public void postSuccess(JSONObject response) {
                            if (listener != null) {
                                listener.onVote();
                            }
                        }

                        @Override
                        public void postFailed(Throwable e) {
                            commentEntity.setVote(commentEntity.getVote() - 1);
                            commentLikeCountTv.setTextColor(ContextCompat.getColor(context, com.gh.gamecenter.common.R.color.hint));
                            commentLikeIv.setImageResource(R.drawable.comment_vote_unselect);
                            commentLikeCountTv.setText(NumberUtils.transSimpleCount(commentEntity.getVote()));
                            if (commentEntity.getVote() == 0) {
                                commentLikeCountTv.setVisibility(View.GONE);
                            } else {
                                commentLikeCountTv.setVisibility(View.VISIBLE);
                            }

                            if (e instanceof HttpException) {
                                HttpException exception = (HttpException) e;
                                if (exception.code() == 403) {
                                    try {
                                        String detail = new JSONObject(exception.response().errorBody().string()).getString("detail");
                                        if ("voted".equals(detail)) {
                                            ToastUtils.INSTANCE.showToast("已经点过赞啦！");
                                        }
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                    }
                                    return;
                                }
                            }
                            Utils.toast(context, "网络异常，点赞失败");
                        }
                    });
        });
    }

    public static void unVoteVideoComment(final Context context,
                                          String videoId,
                                          final CommentEntity commentEntity,
                                          final TextView commentLikeCountTv,
                                          final ImageView commentLikeIv) {
        String entrance = "视频流-评论-取消点赞";
        CheckLoginUtils.checkLogin(context, entrance, () -> {
            RetrofitManager.getInstance().getApi()
                    .unVoteVideoComment(videoId, commentEntity.getId())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Response<ResponseBody>() {
                        @Override
                        public void onResponse(@Nullable ResponseBody response) {
                            super.onResponse(response);
                        }

                        @Override
                        public void onFailure(@Nullable HttpException e) {
                            super.onFailure(e);
                            commentEntity.setVote(commentEntity.getVote() + 1);
                            commentLikeCountTv.setTextColor(ContextCompat.getColor(context, com.gh.gamecenter.common.R.color.text_theme));
                            commentLikeIv.setImageResource(R.drawable.comment_vote_select);
                            commentLikeCountTv.setText(NumberUtils.transSimpleCount(commentEntity.getVote()));
                            commentLikeCountTv.setVisibility(View.VISIBLE);
                            try {
                                if (e != null && e.response().errorBody() != null) {
                                    ErrorHelper.handleError(context, e.response().errorBody().string(), false, null);
                                }
                            } catch (IOException ex) {
                                ex.printStackTrace();
                            }
                        }
                    });

        });
    }

    public static void deleteComment(
            final Context context,
            final CommentEntity commentEntity,
            final OnCommentDeleteListener listener
    ) {
        Dialog dialog = DialogUtils.showWaitDialog(
                context,
                context.getString(R.string.post_dialog_hint)
        );
        RetrofitManager.getInstance().getApi()
                .deleteComment(commentEntity.getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(dialog::cancel)
                .subscribe(new Response<ResponseBody>() {
                    @Override
                    public void onResponse(@Nullable ResponseBody response) {
                        listener.onCommentDelete();
                    }
                });
    }


    // 设置评论item 用户相关的view(点赞/头像/用户名)
    public static void setCommentUserView(Context mContext, CommentViewHolder holder, CommentEntity entity) {
        MeEntity userDataEntity = entity.getMe();
        holder.commentLikeCountTv.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.hint));
        holder.commentLikeIv.setImageResource(R.drawable.comment_vote_unselect);

        if (userDataEntity == null || !userDataEntity.isCommentOwner()) {
            if (holder.replyLine != null) holder.replyLine.setVisibility(View.VISIBLE);
            holder.commentReply.setVisibility(View.VISIBLE);
        } else {
            if (holder.replyLine != null) holder.replyLine.setVisibility(View.GONE);
            holder.commentReply.setVisibility(View.GONE);
        }

        if (entity.getVote() == 0) {
            holder.commentLikeCountTv.setVisibility(View.GONE);
        } else { // 检查是否已点赞
            if (userDataEntity != null && (userDataEntity.isCommentVoted())) {
                holder.commentLikeCountTv.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_theme));
                holder.commentLikeIv.setImageResource(R.drawable.comment_vote_select);
            }
            holder.commentLikeCountTv.setVisibility(View.VISIBLE);
            holder.commentLikeCountTv.setText(NumberUtils.transSimpleCount(entity.getVote()));
        }

        if (entity.getUser().getBadge() != null) {
            holder.userBadgeSdv.setVisibility(View.VISIBLE);
            holder.badgeNameTv.setVisibility(View.VISIBLE);
            ImageUtils.display(holder.userBadgeSdv, entity.getUser().getBadge().getIcon());
            holder.badgeNameTv.setText(entity.getUser().getBadge().getName());
        } else {
            holder.userBadgeSdv.setVisibility(View.GONE);
            holder.badgeNameTv.setVisibility(View.GONE);
        }

        //检查是否是自身评论
        UserInfoEntity userInfo = UserManager.getInstance().getUserInfoEntity();
        if (userDataEntity != null && userDataEntity.isCommentOwner() && userInfo != null) {
            if (entity.getMe() != null && entity.getMe().isContentOwner()) {
                holder.commentAuthorTv.setVisibility(View.VISIBLE);
            } else {
                holder.commentAuthorTv.setVisibility(View.GONE);
            }
            holder.commentUserNameTv.setText(userInfo.getName());
            if (userInfo.getAuth() != null) {
                ImageUtils.display(holder.commentUserBadgeIv, userInfo.getAuth().getIcon());
            } else {
                ImageUtils.display(holder.commentUserBadgeIv, "");
            }
            ImageUtils.display(holder.commentUserIconDv, userInfo.getIcon());
        } else {
            if (entity.getMe() != null && entity.getMe().isContentOwner()) {
                holder.commentAuthorTv.setVisibility(View.VISIBLE);
            } else {
                holder.commentAuthorTv.setVisibility(View.GONE);
            }
            holder.commentUserNameTv.setText(entity.getUser().getName());
            if (entity.getUser().getAuth() != null) {
                ImageUtils.display(holder.commentUserBadgeIv, entity.getUser().getAuth().getIcon());
            } else {
                ImageUtils.display(holder.commentUserBadgeIv, "");
            }
            if (TextUtils.isEmpty(entity.getUser().getIcon())) {
                ImageUtils.display(holder.commentUserIconDv, R.drawable.user_default_icon_comment);
            } else {
                ImageUtils.display(holder.commentUserIconDv, entity.getUser().getIcon());
            }
        }
    }

    @SuppressLint("CheckResult")
    public static void isUserCommentedOnThisGame(String gameId, WeakReference<SimpleCallback<Boolean>> callback) {
        RetrofitManager.getInstance()
                .getApi()
                .isUserCommentedOnThisGame(UserManager.getInstance().getUserId(), gameId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BiResponse<ResponseBody>() {
                    @Override
                    public void onSuccess(ResponseBody data) {
                        SimpleCallback<Boolean> cb = callback.get();
                        if (cb != null) {
                            try {
                                JSONObject object = new JSONObject(data.string());
                                cb.onCallback(object.getBoolean("status"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onFailure(@NotNull Exception exception) {
                        Utils.toast(HaloApp.getInstance().getApplication(), "网络异常");
                    }
                });
    }

    //复制文字
    public static void copyText(String copyContent, Context context) {
        ExtensionsKt.copyTextAndToast(copyContent, "复制成功");
    }


    public interface OnVoteListener {
        void onVote();
    }

    public interface OnCommentDeleteListener {
        void onCommentDelete();
    }
}
