package com.yidianling.dynamic.trendsDetail;


import android.support.v7.app.AppCompatActivity;

import com.yidianling.common.tools.LogUtil;
import com.yidianling.dynamic.common.net.DynamicApiUtils;
import com.yidianling.dynamic.model.Command;
import com.yidianling.dynamic.model.CommentBean;
import com.yidianling.dynamic.model.TrendsDetailInfoBean;
import com.yidianling.dynamic.router.DynamicIn;
import com.ydl.ydlcommon.data.http.BaseAPIResponse;
import com.ydl.ydlcommon.data.http.RxUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Jim on 2017/10/28 0028.
 */

public class TrendsDetailInteractor {
    private CompositeDisposable mCompositeSubscription;
    private ITrendsDetailPresenter.OnTrendsDetailDataLoadFinishedListenner callBack;

    public void setCallBack(ITrendsDetailPresenter.OnTrendsDetailDataLoadFinishedListenner callBack) {
        this.callBack = callBack;
    }

    public TrendsDetailInteractor() {
        mCompositeSubscription = new CompositeDisposable();
    }

    public void fetchTrendsDetails(int id) {
        Command.TrendsInfo request = new Command.TrendsInfo(id);
        mCompositeSubscription.add(DynamicApiUtils.fetchTrendsDetailInfo(request)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(resp -> {
                    cacheCommentsData(resp);
                    if (callBack != null) {
                        callBack.onTrendsDetailFetched(resp);
                    }
                }, throwable -> {
                    if (callBack != null) {
                        callBack.onTrendsDetailFetchFailed(throwable);
                    }
                }));
    }

    private static final Integer PAGE_SIZE = 20;
    private List<List<CommentBean>> cacheComments = null;

    private void cacheCommentsData(BaseAPIResponse<TrendsDetailInfoBean> resp) {
        if(resp.data!=null&&resp.data.comments.size()>0) {
            List<CommentBean> comments = resp.data.comments;
            if(cacheComments==null) {
                cacheComments = new ArrayList<>();
            }else {
                cacheComments.clear();
            }

            Integer totalCount = comments.size();

            Integer requestCount = totalCount / PAGE_SIZE;

            for (int i = 0; i <= requestCount; i++) {
                Integer fromIndex = i * PAGE_SIZE;
                int toIndex = Math.min(totalCount, (i + 1) * PAGE_SIZE);
                List<CommentBean> subList = comments.subList(fromIndex, toIndex);
                cacheComments.add(subList);
            }
            callBack.onCommentsListFetched(cacheComments.get(0));
        }
    }


    public void fetchCommentsDatas(int id, int page, int lastId, int direction) {
        Command.TrendsComments request = new Command.TrendsComments(String.valueOf(id), String.valueOf(page), String.valueOf(lastId), String.valueOf(direction));
        mCompositeSubscription.add(DynamicApiUtils.fetchTrendsComments(request)
                .subscribeOn(Schedulers.io())
                .compose(RxUtils.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(listBaseResponse -> {
                    if (callBack != null) {
                        callBack.onCommentsListFetched(listBaseResponse);
                    }
                }, throwable -> {
                    if (callBack != null) {
                        callBack.onCommentsListFetchedFailed(throwable);
                    }
                }));

    }

    public void fetchCommentsDatas(int page) {
        if (callBack != null) {
            List<CommentBean> commentBeans = null;
            if(cacheComments.size() >= page) {
                commentBeans = cacheComments.get(page-1);
            }
            callBack.onCommentsListFetched(commentBeans);
        }
    }

    /**
     * 点赞
     */
    public void doLikeAction(int type, int id) {
        final Command.ZanAction cmd = new Command.ZanAction(String.valueOf(type), String.valueOf(id));
        mCompositeSubscription.add(DynamicApiUtils.zanAction(cmd)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(zanResultBaseResponse -> {
                    if (callBack != null) {
                        callBack.ondoLikeActionFetchedResult(zanResultBaseResponse, type);
                    }
                }, throwable -> {
                    if (callBack != null) {
                        LogUtil.d("do like action error: " + throwable.toString());
                        callBack.showDataLoadErrorView(throwable);
                    }
                }));
    }


    public void focus(String uid) {
        Command.FocusCmd cmd = new Command.FocusCmd(uid, 1 + "");//业务类型：1关注用户，2关注话题
        mCompositeSubscription.add(DynamicApiUtils.focus(cmd)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(resp -> {
                    if (callBack != null) {
                        callBack.onFoucusActionSuccessed(resp);
                    }
                }, throwable -> {
                    if (callBack != null) {
                        callBack.showDataLoadErrorView(throwable);
                    }
                }));
    }

    /**
     * //获取举报的内容列表
     */
    public void fetchReportReasonContent(int answerId, String commentContent) {
        Command.GetReportReason cmd = new Command.GetReportReason();
        mCompositeSubscription.add(DynamicApiUtils.getReportReason(cmd)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(resp -> {
                    if (callBack != null) {
                        callBack.onReportContentFetched(resp, answerId, commentContent);
                    }
                }, throwable -> {
                    callBack.showDataLoadErrorView(throwable);
                }));
    }


    //举报帖子评论
    public void report(int trendId, int type, int reasonId, int answerId, String answerContent) {
        type = 1;//举报帖子和评论都传1
        Command.ReportWorry cmd = new Command.ReportWorry(trendId, reasonId, answerId, answerContent, type);
        mCompositeSubscription.add(DynamicApiUtils.reportWorry(cmd)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(objectBaseResponse -> {
                    if (callBack != null) {
                        callBack.onReportSuccessed(objectBaseResponse);
                    }
                }, throwable -> {
                    callBack.showDataLoadErrorView(throwable);
                }));
    }


    /**
     * //删除帖子或评论
     *
     * @param type 移除类型：1移除评论，2移除动态
     * @param id   评论的id,动态id
     */
    public void delTrendsReply(int type, int id, int position) {
        Command.TrendsReplyDel command = new Command.TrendsReplyDel(type, id);
        mCompositeSubscription.add(DynamicApiUtils.removeTrendsReply(command)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(resp -> {
                    if (callBack != null) {
                        callBack.onDeleteSuccessed(resp, type, position);
                    }
                }, throwable -> {
                    callBack.showDataLoadErrorView(throwable);
                }));

    }

    public void getExpert(AppCompatActivity activity, String expertUid) {
        DynamicIn.INSTANCE.startChat(activity, expertUid);
    }

    public void commitOrReply(int type, String tid, String content, String replyContent, String toName) {
        Command.CommentOrReply cmd = new Command.CommentOrReply(String.valueOf(type), tid, content);
        mCompositeSubscription.add(DynamicApiUtils.commitOrReply(cmd)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(replyBaseResponse -> {
                    if (callBack != null) {
                        callBack.onCommentOrReplySuccessed(replyBaseResponse, type, content, replyContent, toName);
                    }
                }, throwable -> {
                    callBack.showDataLoadErrorView(throwable);
                }));
    }


    public void detachView() {
        mCompositeSubscription.dispose();
    }

}
