package com.xxrv.video.dialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialogFragment;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.frame.base.url.Constance;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.SPConstance;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseView;
import com.ruiwenliu.wrapper.presenter.WrapperPresenter;
import com.ruiwenliu.wrapper.util.glide.GlideManager;
import com.rv.component.utils.Cookie;
import com.rv.component.utils.DateUtils;
import com.xxrv.video.R;
import com.xxrv.video.api.VideoApi;
import com.xxrv.video.base.BaseRecAdapter;
import com.xxrv.video.base.BaseRecViewHolder;
import com.xxrv.video.bean.circle.Comment;
import com.xxrv.video.bean.circle.CommentBean;
import com.xxrv.video.bean.circle.DiscoveryVideoBean;
import com.xxrv.video.bean.circle.VideoIMTokenBean;
import com.xxrv.video.presenter.VideoPresenter;
import com.xxrv.video.util.ScreenUtil;
import com.yuyife.okgo.OkGoUtil;


import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * 抖音视频评论模块
 */
public class TrillCommDialog extends BottomSheetDialogFragment implements BaseView {
    private OnUpdateCommListener mListener;
    private List<Comment> mCommentData;
    private String mMessageId;

    private String mReplyId;
    private String mReplyName;

    private RecyclerView mListView;
    private CommAvatarAdapter mAdapter;
    private TextView tvTitle;
    private TextView tvTip;
    private int mPagerIndex, mPagerSize = 20;
    private VideoPresenter mPresenter;
    private String content;
    private VideoIMTokenBean ImTokenBean;

    private TrillCommentInputDialog2.OnSendCommentListener mOnSendCommentListener = new TrillCommentInputDialog2.OnSendCommentListener() {

        @Override
        public void sendComment(String str) {
            content = str;
            loadImToken(0);
        }
    };
    private LinearLayoutManager mLayoutManager;
    private boolean more, isLoad;
    private Context mContent;

    public static TrillCommDialog getInstance() {
        TrillCommDialog trillCommDialog = new TrillCommDialog();
        Bundle bundle = new Bundle();
        trillCommDialog.setArguments(bundle);
        return trillCommDialog;
    }

    public void setOnUpdateCommListener(Context context, List<Comment> data, String msgid, OnUpdateCommListener listener) {
        this.mContent = context;
        mCommentData = data;
        if (mCommentData == null) {
            mCommentData = new ArrayList<>();
        }
        mMessageId = msgid;
        mListener = listener;
    }

    private void showInputDialog(String text) {
        // 弹出评论输入框
        TrillCommentInputDialog2 trillCommentInputDialog = new TrillCommentInputDialog2(getActivity(), text, mOnSendCommentListener);
        Window window = trillCommentInputDialog.getWindow();
        if (window != null) {
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); // 软键盘弹起
        }
        trillCommentInputDialog.show();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 给dialog设置主题为透明背景 不然会有默认的白色背景
        setStyle(DialogFragment.STYLE_NO_FRAME, R.style.CustomDialog);

        ParameterizedType type = (ParameterizedType) mContent.getClass().getGenericSuperclass();
        Class<? extends WrapperPresenter> presenterClass = (Class<? extends WrapperPresenter>) type.getActualTypeArguments()[0];
        try {
            this.mPresenter = (VideoPresenter) presenterClass.newInstance();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (java.lang.InstantiationException e) {
            e.printStackTrace();
        }
        mPresenter.attachView(this);
    }

    /*
    不进行onStart内的操作，dialog会显示不全
    网上一大堆解决方法都不靠谱，这样处理就可以了
     */
    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();

        if (dialog != null) {
            View bottomSheet = dialog.findViewById(R.id.design_bottom_sheet);
            // Cannot set MATCH_PARENT, if Settings, dialog can move up
            // bottomSheet.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
            bottomSheet.getLayoutParams().height = ScreenUtil.getScreenHeight(requireContext()) * 2 / 3;
        }
        final View view = getView();
        if (view != null)
            view.post(() -> {
                View parent = (View) view.getParent();
                CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) (parent).getLayoutParams();
                CoordinatorLayout.Behavior behavior = params.getBehavior();
                BottomSheetBehavior mBottomSheetBehavior = (BottomSheetBehavior) behavior;
                int height = ScreenUtil.getScreenHeight(requireContext()) * 2 / 3;
                if (mBottomSheetBehavior != null) {
                    mBottomSheetBehavior.setPeekHeight(height);
                }
                parent.setBackgroundColor(Color.TRANSPARENT);
            });
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.setCanceledOnTouchOutside(true);
        // 设置使软键盘弹出的时候dialog不会被顶起
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams params = dialogWindow.getAttributes();
        dialogWindow.setSoftInputMode(params.SOFT_INPUT_ADJUST_NOTHING);
        // 动画
        dialogWindow.setWindowAnimations(R.style.BottomDialog_Animation);
        return dialog;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 在这里将view的高度设置为精确高度，即可屏蔽向上滑动不占全屏的手势。
        // 如果不设置高度的话 会默认向上滑动时dialog覆盖全屏
        View view = inflater.inflate(R.layout.dialog_trill_comm, container, false);
        // 如不进行该步骤，上面的setPeekHeight好像无效果
        view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                (ScreenUtil.getScreenHeight(requireContext()) * 2 / 3)));
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        tvTitle = view.findViewById(R.id.tv_title);
        tvTip = view.findViewById(R.id.tv_null_tip);
        mListView = view.findViewById(R.id.rv_comm);

        mLayoutManager = new LinearLayoutManager(requireContext());
        mListView.setLayoutManager(mLayoutManager);
        mAdapter = new CommAvatarAdapter(mCommentData);
        mListView.setAdapter(mAdapter);
        if (mCommentData.size() == 0) {
            tvTitle.setVisibility(View.GONE);
            tvTip.setVisibility(View.VISIBLE);
        } else {
            tvTitle.setText(mCommentData.size() + " " + getString(R.string.text_comment_num));
        }

        view.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        view.findViewById(R.id.comment_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mReplyId = "";
                mReplyName = "";
                if (OkGoUtil.getToken() != null) {
                    showInputDialog(null);
                } else {
                    ARouter.getInstance().build(Constance.ACTIVITY_URL_LOGINRV).navigation();
                }
            }
        });

        if (mCommentData.size() >= 20) {
            more = true;
            mPagerIndex = 1;
            addListener();
        }
    }

    private void loadImToken(int type) {
        if (OkGoUtil.getToken() != null) {
            Map<String, Object> headMap = new LinkedHashMap<>();
            headMap.put("Authorization", OkGoUtil.getToken());
            mPresenter.postData(RvFrameConfig.HOST, type, VideoApi.DISCOVERY_IM_LOGIN, VideoIMTokenBean.class, headMap, headMap, false);
        }
    }

    private void addComment() {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", ImTokenBean.getData());
        params.put("messageId", mMessageId);
        if (!TextUtils.isEmpty(mReplyId)) {// 代表回复
            params.put("toUserId", mReplyId);
            params.put("toNickname", mReplyName);
            params.put("toBody", content);
        }
        params.put("body", content);

        mPresenter.getData(RvFrameConfig.HOST, 2, VideoApi.DISCOVERY_COMMENT_ADD, BaseBean.class, params, false);
    }

    private void addListener() {

        mListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int firstVisibleItem, visibleItemCount, totalItemCount;
            private int previousTotal = 0;

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (!more) {
                    // 外界不让加载数据了
                    return;
                }
                visibleItemCount = recyclerView.getChildCount();
                totalItemCount = mLayoutManager.getItemCount();
                firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();

                if (isLoad) {
                    if (totalItemCount > previousTotal) {
                        isLoad = false;
                        previousTotal = totalItemCount;
                    }
                }
                if (!isLoad && (totalItemCount - visibleItemCount) <= firstVisibleItem) {
                    mPagerIndex++;
//                    findCommDataList();
                    loadImToken(3);
                    isLoad = true;
                }
            }
        });
    }

    private void findCommDataList() {

        Log.e("xuan", "findCommDataList: 加载数据" + mPagerIndex);
        isLoad = true;

        Map<String, String> params = new HashMap<>();
        if (ImTokenBean != null && !TextUtils.isEmpty(ImTokenBean.getData())) {
            params.put("access_token", ImTokenBean.getData());
        }
        params.put("pageIndex", String.valueOf(mPagerIndex));
        params.put("pageSize", String.valueOf(mPagerSize));
        params.put("messageId", mMessageId);

        mPresenter.getData(RvFrameConfig.HOST, 1, VideoApi.DISCOVERY_COMMENT_LIST, CommentBean.class, params, false);
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                ImTokenBean = (VideoIMTokenBean) result;
                addComment();
                break;
            case 1:
                setCommentList((CommentBean) result);
                break;
            case 2:
                addCommentData();
                break;
            case 3:
                ImTokenBean = (VideoIMTokenBean) result;
                findCommDataList();
                break;

        }
    }

    private void addCommentData() {
        Comment comment = new Comment();
        comment.setBody(content);
        String usrname = Cookie.getStringValue(getContext(), SPConstance.USER_JSON_NICKANAME, "");
        comment.setNickname(usrname);
        if (!TextUtils.isEmpty(mReplyId)) {
            comment.setToUserId(mReplyId);
            comment.setToNickname(mReplyName);
        }
        comment.setTime(System.currentTimeMillis() / 1000);
        String userid = Cookie.getStringValue(getContext(), SPConstance.USER_JSON_USERID, "");
        comment.setUserId(userid);
        comment.setPicUrl(Cookie.getStringValue(getContext(), SPConstance.USER_JSON_HEADERURL, ""));
        mCommentData.add(comment);
        mListener.updateCommCount();
        if (mCommentData.size() == 1) {// 说明之前没有评论
            tvTitle.setVisibility(View.VISIBLE);
            tvTip.setVisibility(View.GONE);
        }
        tvTitle.setText(mCommentData.size() + " " + getString(R.string.text_comment_num));
        mAdapter.notifyDataSetChanged();
    }

    private void setCommentList(CommentBean result) {
        List<Comment> data = result.getData();
        Log.e("xuan", "onResponse: COMMMMM " + data.size());
        if (data.size() > 0) {
            mCommentData.addAll(data);
            mAdapter.notifyDataSetChanged();
        }

        more = data.size() == 20;
        isLoad = false;
    }

    @Override
    public void onBeforeSuccess() {

    }

    @Override
    public void onShowLoading() {

    }

    @Override
    public void onHideLoading() {

    }

    @Override
    public void onShowError(String errorMsg, int errorType) {
        more = false;
        isLoad = false;
        mReplyId = "";
        mReplyName = "";
    }

    @Override
    public void onErrorToken() {
        mReplyId = "";
        mReplyName = "";
    }

    public interface OnUpdateCommListener {
        void updateCommCount();
    }

    class CommAvatarAdapter extends BaseRecAdapter<Comment, CommAvatarHolder> {
        public CommAvatarAdapter(List<Comment> list) {
            super(list);
        }

        @Override
        public void onHolder(CommAvatarHolder holder, Comment bean, int position) {
            String title = bean.getNickname();
            if (!TextUtils.isEmpty(bean.getToNickname())) {
                title += " " + getString(R.string.replay) + " @" + bean.getToNickname();
            }
            holder.tvName.setText(title);
            holder.tvContent.setText(bean.getBody());
            holder.tvTime.setText(DateUtils.getFriendlyTimeDesc(mContent, bean.getTime()));// 这种转换更人性化一点
            GlideManager.getInstance(mContent).loadCircleImage(bean.getPicUrl(), holder.ivAvatar);
        }

        @Override
        public CommAvatarHolder onCreateHolder() {
            return new CommAvatarHolder(getViewByRes(R.layout.item_trill_comm));
        }
    }

    class CommAvatarHolder extends BaseRecViewHolder {
        public ImageView ivAvatar;
        public LinearLayout mLlWrap;
        public TextView tvName;
        public TextView tvContent;
        public TextView tvTime;

        CommAvatarHolder(View rootView) {
            super(rootView);
            ivAvatar = rootView.findViewById(R.id.iv_avater);
            mLlWrap = rootView.findViewById(R.id.ll_comm);
            tvName = rootView.findViewById(R.id.tv_name);
            tvContent = rootView.findViewById(R.id.tv_content);
            tvTime = rootView.findViewById(R.id.tv_time);

            mLlWrap.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onReply(getAdapterPosition());
                }
            });
        }

        void onReply(int position) {
            Comment comm = mCommentData.get(position);
//            if (comm.getUserId().equals(mLoginUser.getUserId())) {// 不能回复自己
//                return;
//            }

            mReplyId = comm.getUserId();
            mReplyName = comm.getNickname();

            String text = getString(R.string.replay) + " @" + comm.getNickname() + ": ";
            if (OkGoUtil.getToken() != null) {
                showInputDialog(text);
            } else {
                ARouter.getInstance().build(Constance.ACTIVITY_URL_LOGINRV).navigation();
            }
        }
    }
}
