package com.sheep.gamegroup.view.fragment;

import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lqr.emoji.EmotionKeyboard;
import com.lqr.emoji.EmotionLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.sheep.gamegroup.model.api.ApiService;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.UserCommentDetail;
import com.sheep.gamegroup.model.entity.UserCommentReply;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.ApiJSONUtil;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.KeyEventUtil;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.RefreshUtil;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.util.viewHelper.UserCommentHelper;
import com.sheep.gamegroup.view.adapter.AdpUserCommentReply;
import com.sheep.gamegroup.view.dialog.DialogSuccessUtil;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;

import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by realicing on 2018/11/2.
 * realicing@sina.com
 * 用户评论详情界面
 */
public class FgtUserCommentDetail extends BaseListFragment3<UserCommentReply> implements Action1<UserCommentReply> {

    @Override
    public int getLayoutId() {
        return R.layout.net_empty_smart_refresh_rv_exp;
    }

    @BindView(R.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    @BindView(R.id.rlContent)
    RelativeLayout rlContent;
    @BindView(R.id.elEmotion)
    EmotionLayout elEmotion;

    private TextView input_comment_reply;
    //输入框
    private EditText input_comment_input;
    private ImageView input_comment_exp;

    //表情键盘协调工具
    private EmotionKeyboard mEmotionKeyboard;

    @Override
    public void initView() {
        TitleBarUtils.getInstance()
                .setShowOrHide(getActivity(), true)
                .setTitle(getActivity(), "评论详情")
                .setTitleFinish(getActivity());
        smartRefreshLayout = refresh;
        refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMoreData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshData();
            }
        });
        RefreshUtil.newInstance().publicParameterLoadMore(refresh, activity);

        //头部view
        initHeaderView();

        //尾部，在无数据时显示
        footerView = LayoutInflater.from(SheepApp.getInstance()).inflate(R.layout.footer_user_comment_detail, null);
        //底部可发表评论
        LayoutInflater.from(SheepApp.getInstance()).inflate(R.layout.include_input_comment_exp, bottom);
        input_comment_reply = bottom.findViewById(R.id.input_comment_reply);
        input_comment_input = bottom.findViewById(R.id.input_comment_input);
        input_comment_exp = bottom.findViewById(R.id.input_comment_exp);
        input_comment_reply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                call(getUserCommentReply());
            }
        });
        bottom.findViewById(R.id.input_comment_commit).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                String content = input_comment_input.getText().toString();
                commitContent(content);
            }
        });
        //初始化 表情键盘协调工具
        initEmotionKeyboard();
        initSticker();

    }

    //用户评论一个用户对游戏的评论
    private void commitContent(String content) {
        if (TestUtil.isDev()) G.showToast("评论内容：" + content);
        if (content.isEmpty()) {
            G.showToast("评论内容不能为空");
            return;
        }
        // 发表评论
        Observable<BaseMessage> observable = userCommentReply == null ? ApiJSONUtil.postGameUserUserComment(user_comment_id, content) : ApiJSONUtil.postGameUserReplyComment(userCommentReply.getId(), content);
        if(userCommentReply != null){//只能回复一次，所以需要让回复输入框上面的回复xx消失
            call(userCommentReply);
        }
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        input_comment_input.setText("");
                        DialogSuccessUtil.showSuccess("发表成功", new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialogInterface) {
                                refreshData();
                            }
                        });
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage);
                    }
                });
    }

    //    ------------------------------start header------------------------------------
    private UserCommentHelper headerViewHelper;

    private LinearLayout user_comment_detail_game_ll;
    private View user_comment_detail_line1;
    private View user_comment_detail_line2;
    private TextView total_count_tv;

    //初始化headerView
    private void initHeaderView() {
        headerViewHelper = new UserCommentHelper(R.layout.header_user_comment_detail);
        total_count_tv = headerViewHelper.getRootView().findViewById(R.id.total_count_tv);
        user_comment_detail_game_ll = headerViewHelper.getRootView().findViewById(R.id.user_comment_detail_game_ll);
        user_comment_detail_line1 = headerViewHelper.getRootView().findViewById(R.id.user_comment_detail_line1);
        user_comment_detail_line2 = headerViewHelper.getRootView().findViewById(R.id.user_comment_detail_line2);
        headerViewHelper.getUser_comment_detail_user_publish_score().setVisibility(View.GONE);
        user_comment_detail_game_ll.setVisibility(View.GONE);
        user_comment_detail_line1.setVisibility(View.GONE);
        user_comment_detail_line2.setVisibility(View.GONE);
        if (total_count_tv != null) {
            ViewUtil.setText(total_count_tv, getString(R.string.total_x_comment, ViewUtil.BLOCK));
        }
    }

    //    ------------------------------end header------------------------------------

    private View footerView;

    private int user_comment_id;

    public void setUser_comment_id(int user_comment_id) {
        this.user_comment_id = user_comment_id;
    }

    @Override
    public boolean useSelfEmpty() {
        return false;
    }

    private AdpUserCommentReply adapter;

    @Override
    protected RecyclerView.Adapter getAdapter() {
        //用户评论的回复列表
        adapter = new AdpUserCommentReply(list);
        adapter.addHeaderView(headerViewHelper.getRootView());
        adapter.setAction1(this);
        return adapter;
    }

    @Override
    protected String getKey(int page, int per_page) {
        return String.format(Locale.CHINA, "app/game_user/user_comment_detail?page_no=%d&page_size=%d&user_comment_id=%d", page, per_page, user_comment_id);
    }

    @Override
    protected Observable<BaseMessage> getApi(ApiService apiService) {
        return apiService.getGameUserUserCommentDetail(page, per_page, user_comment_id);
    }

    @Override
    protected List<UserCommentReply> resolveData(BaseMessage baseMessage, int page) {
        final UserCommentDetail userCommentDetail = baseMessage.getData(UserCommentDetail.class);
        if (page == 1 && userCommentDetail != null) {//第一页才有下面的数据
            adapter.setUserComment(userCommentDetail.getUser_comment());
            headerViewHelper.loadHeaderViewData(userCommentDetail.getUser_comment());
            if (!userCommentDetail.getUser_comment().isArticleUserComment()) {
                headerViewHelper.getUser_comment_detail_user_publish_score().setVisibility(View.VISIBLE);
                user_comment_detail_game_ll.setVisibility(View.VISIBLE);
                user_comment_detail_line1.setVisibility(View.VISIBLE);
                user_comment_detail_line2.setVisibility(View.VISIBLE);
                user_comment_detail_game_ll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //点击游戏
                        if (userCommentDetail.getUser_comment() != null)
                            Jump2View.getInstance().goPlayGameDetail(activity, userCommentDetail.getUser_comment().getApp_id());
                        else
                            G.showToast(R.string.loading_data);
                    }
                });
            }
            ViewUtil.setText(total_count_tv, getString(R.string.total_x_comment, String.valueOf(userCommentDetail.getUser_comment_reply().getTotal())));
        }
        if (userCommentDetail != null && userCommentDetail.getUser_comment_reply() != null && userCommentDetail.getUser_comment_reply().getReply_list() != null)
            return userCommentDetail.getUser_comment_reply().getReply_list();
        return ListUtil.emptyList();
    }

    @Override
    protected Class<UserCommentReply> getTClass() {
        return UserCommentReply.class;
    }


    @Override
    protected void updateEmptyView() {
        if (adapter != null) {
            if (list.isEmpty()) {
                if (footerView.getParent() == null)//未添加尾部view
                    adapter.addFooterView(footerView);
            } else {
                if (footerView.getParent() != null)//已经添加尾部view
                    adapter.removeFooterView(footerView);
            }
        }
    }

    private void initSticker() {
        elEmotion.attachEditText(input_comment_input);
    }

    //初始化 表情键盘协调工具
    private void initEmotionKeyboard() {
        mEmotionKeyboard = EmotionKeyboard.with(activity);
        mEmotionKeyboard.bindToContent(rlContent);
        mEmotionKeyboard.bindToEmotionButton(input_comment_exp);
        mEmotionKeyboard.bindToEditText(input_comment_input);
        mEmotionKeyboard.setEmotionLayout(elEmotion);
    }

    //返回处理
    public boolean onBackPressed() {
        if (mEmotionKeyboard != null) {
            return mEmotionKeyboard.interceptBackPress(true);
        }
        return false;
    }

    private UserCommentReply userCommentReply;

    public UserCommentReply getUserCommentReply() {
        return userCommentReply;
    }

    //当前用户在自己的评论详情 点击别人的评论中的图标进行回复
    @Override
    public void call(UserCommentReply userCommentReply) {
        if(this.userCommentReply == userCommentReply){
            this.userCommentReply = null;
            ViewUtil.setVisibility(input_comment_reply, false);
        } else {
            this.userCommentReply = userCommentReply;
            ViewUtil.setText(input_comment_reply, String.format(Locale.CHINA, "回复：%s", userCommentReply.getNickname()));
            ViewUtil.setVisibility(input_comment_reply, true);
        }
    }
}
