package com.halo.assistant.fragment.comment;

import android.app.Dialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gh.common.util.CheckLoginUtils;
import com.gh.common.util.DialogUtils;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.common.util.ErrorHelper;
import com.gh.gamecenter.core.utils.KeyboardHeightObserver;
import com.gh.gamecenter.core.utils.KeyboardHeightProvider;
import com.gh.common.util.PostCommentUtils;
import com.gh.gamecenter.common.utils.TextHelper;
import com.gh.gamecenter.CommentDetailActivity;
import com.gh.gamecenter.NewsDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.CommentDetailAdapter;
import com.gh.gamecenter.adapter.OnCommentCallBackListener;
import com.gh.gamecenter.entity.CommentEntity;
import com.gh.gamecenter.entity.MessageEntity;
import com.gh.gamecenter.common.base.fragment.ToolbarFragment;
import com.lightgame.utils.Util_System_Keyboard;

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

import retrofit2.HttpException;

/**
 * Created by CsHeng on 14/12/2017.
 * <p>
 * 评论详情页面-查看对话详情
 */
public class CommentDetailFragment extends ToolbarFragment implements OnCommentCallBackListener, KeyboardHeightObserver {

    private EditText mCommentDetailCommentEt;
    private TextView mCommentSend;
    private View mCommentContentContainer;
    private View mCommentLine;
    private View mShadowView;
    private LinearLayout mAnswerContent;
    private View mPlaceholderView;

    private ScrollView mScrollView;

    private Dialog mSendingDialog;

    private CommentEntity mCommentEntity; // 回复评论的实体 用完马上清空

    private CommentDetailAdapter mAdapter;

    private MessageEntity.Article mArticle;

    private KeyboardHeightProvider mKeyboardHeightProvider = null;
    private int mOffset = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_comment_detail;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setNavigationTitle(getString(R.string.title_comment_detail));
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        RecyclerView recyclerView = view.findViewById(R.id.comment_detail_rv);
        View noDataView = view.findViewById(R.id.reuse_none_data);
        View dataExceptionView = view.findViewById(R.id.reuse_data_exception);
        TextView noDataTv = view.findViewById(R.id.reuseNoneDataTv);
        TextView skipArticleDetail = view.findViewById(R.id.skip_article_detail_btn);
        mCommentDetailCommentEt = view.findViewById(R.id.answer_comment_et);
        mCommentSend = view.findViewById(R.id.answer_comment_send_btn);
        mCommentContentContainer = view.findViewById(R.id.answer_comment_content_container);
        mCommentLine = view.findViewById(R.id.comment_line);
        mShadowView = view.findViewById(R.id.shadowView);
        mAnswerContent = view.findViewById(R.id.answer_content);
        mScrollView = view.findViewById(R.id.scrollView);
        mPlaceholderView = view.findViewById(R.id.placeholderView);

        mCommentSend.setOnClickListener(this);
        mShadowView.setOnTouchListener((v, event) -> {
            if (mCommentContentContainer.getVisibility() == View.VISIBLE) {
                setSoftInput(false);
            }
            return true;
        });

        String commentId = getArguments().getString(EntranceConsts.KEY_COMMENTID);
        mArticle = getArguments().getParcelable(MessageEntity.Article.TAG);

        mCommentDetailCommentEt.addTextChangedListener(watcher);
        mCommentDetailCommentEt.setFilters(new InputFilter[]{TextHelper.getFilter(140, "评论不能多于140字")});
        noDataTv.setText(R.string.content_delete_hint);
        mAdapter = new CommentDetailAdapter(getContext(), commentId, this, noDataView, dataExceptionView, recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(mAdapter);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && !mAdapter.isOver() && !mAdapter.isLoading()) {
                    mAdapter.loadData();
                }
            }
        });

        // 显示原文跳转按钮
        if (mArticle != null) {
            skipArticleDetail.setVisibility(View.VISIBLE);
            skipArticleDetail.setText("资讯：" + mArticle.getTitle());
            skipArticleDetail.setOnClickListener(v -> {
                startActivity(NewsDetailActivity.getIntentById(getContext(), mArticle.getId(), "(消息中心)+(查看对话)"));
            });
        }

        mKeyboardHeightProvider = new KeyboardHeightProvider(requireActivity());
        requireView().post(() -> mKeyboardHeightProvider.start());
    }

    @Override
    public void onResume() {
        super.onResume();
        mKeyboardHeightProvider.setKeyboardHeightObserver(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        mKeyboardHeightProvider.setKeyboardHeightObserver(null);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mKeyboardHeightProvider.close();
    }

    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.toString().trim().length() > 0) {
                mCommentSend.setEnabled(true);
            } else {
                mCommentSend.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    @Override
    public void onCommentCallback(CommentEntity entity) {
        mCommentEntity = entity;
        setSoftInput(true);
    }

    @Override
    public void onClick(View v) {
        final String content = mCommentDetailCommentEt.getText().toString();

        if (content.length() == 0) {
            toast("评论内容不能为空！");
            return;
        }

        mSendingDialog = DialogUtils.showWaitDialog(getContext(), getString(R.string.post_dialog_hint));

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("content", content);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (mCommentEntity != null && mCommentEntity.getId() == null) {
            toast("评论异常 id null");
            mSendingDialog.cancel();
            return;
        }

        PostCommentUtils.addCommentData(getContext(), null, jsonObject, mCommentEntity,
                new PostCommentUtils.PostCommentListener() {
                    @Override
                    public void postSuccess(JSONObject response) {
                        mSendingDialog.dismiss();
                        toast("发表成功");
                        mCommentDetailCommentEt.setText("");

                        setSoftInput(false);

                    }

                    @Override
                    public void postFailed(Throwable e) {
                        mSendingDialog.dismiss();
                        String errorString = null;
                        if (e instanceof HttpException) {
                            try {
                                errorString = ((HttpException) e).response().errorBody().string();
                            } catch (Exception e1) {
                                e1.printStackTrace();
                            }
                        }
                        ErrorHelper.handleError(requireContext(), errorString, false, mCommentSend::performClick, "文章及帖子的评论和回复");
                    }
                });
    }

    //软键盘控制
    private void setSoftInput(boolean isShow) {
        if (isShow) {
            String entrance = "资讯文章详情-评论-写评论";
            if (mCommentEntity == null) {
                entrance = "资讯文章详情-评论-回复";
            }
            CheckLoginUtils.checkLogin(getContext(), entrance, () -> {
                Util_System_Keyboard.showSoftKeyboard(getContext(), mCommentDetailCommentEt);
                mCommentContentContainer.setVisibility(View.VISIBLE);
                mCommentLine.setVisibility(View.VISIBLE);
                mCommentDetailCommentEt.setFocusable(true);
                mCommentDetailCommentEt.setFocusableInTouchMode(true);
                mCommentDetailCommentEt.requestFocus();

                if (mCommentEntity != null && mCommentEntity.getUser() != null) {
                    mCommentDetailCommentEt.setHint(getString(R.string.comment_repty_hint, mCommentEntity.getUser().getName()));
                } else {
                    mCommentDetailCommentEt.setHint(getString(R.string.message_detail_comment_hint));
                }
            });
        } else {
            Util_System_Keyboard.hideSoftKeyboard(getContext(), mCommentDetailCommentEt);

            mCommentContentContainer.setVisibility(View.GONE);
            mCommentLine.setVisibility(View.GONE);
            if (mCommentEntity != null) {
                mCommentEntity = null; // 清空当前评论实体
                mCommentDetailCommentEt.setHint(getString(R.string.message_detail_comment_hint));
                mCommentDetailCommentEt.setText("");
            }
        }

    }

    @Override
    public void onKeyboardHeightChanged(int height, int orientation) {
        popInputLayout(height > 0, height);
    }

    private void popInputLayout(boolean isPopup, int height) {
        mShadowView.setVisibility(isPopup ? View.VISIBLE : View.GONE);
        mCommentLine.setVisibility(isPopup ? View.GONE : View.VISIBLE);
        if (requireActivity() instanceof CommentDetailActivity) {
            View shadowView = ((CommentDetailActivity) requireActivity()).getShadowView();
            shadowView.setVisibility(isPopup ? View.VISIBLE : View.GONE);
            DisplayUtils.setLightStatusBar(requireActivity(), !isPopup && !mIsDarkModeOn);
            shadowView.setOnClickListener(v -> setSoftInput(false));
        }
        mAnswerContent.setOrientation(isPopup ? LinearLayout.VERTICAL : LinearLayout.HORIZONTAL);
        if (isPopup) {
            mAnswerContent.setBackground(ContextCompat.getDrawable(requireActivity(), R.drawable.bg_shape_white_radius_10_top_only));
        } else {
            mAnswerContent.setBackgroundColor(ContextCompat.getColor(requireActivity(), R.color.background_white));
            mOffset = Math.abs(height);
        }
        mPlaceholderView.setVisibility(isPopup ? View.VISIBLE : View.GONE);

        LinearLayout.LayoutParams mScrollViewParams = (LinearLayout.LayoutParams) mScrollView.getLayoutParams();
        mScrollViewParams.width = isPopup ? LinearLayout.LayoutParams.MATCH_PARENT : 0;
        mScrollViewParams.height = isPopup ? DisplayUtils.dip2px(76f) : DisplayUtils.dip2px(28f);
        mScrollViewParams.topMargin = isPopup ? DisplayUtils.dip2px(8f) : 0;
        mScrollView.setLayoutParams(mScrollViewParams);

        RelativeLayout.LayoutParams mLayoutParams = (RelativeLayout.LayoutParams) mCommentContentContainer.getLayoutParams();
        mLayoutParams.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
        mLayoutParams.bottomMargin = isPopup ? height + mOffset : 0;
        mCommentContentContainer.setLayoutParams(mLayoutParams);
    }
}
