package com.cooleshow.student.presenter.main;

import android.text.TextUtils;
import android.util.Log;

import com.cooleshow.base.constanst.Constants;
import com.cooleshow.base.data.net.BaseResponse;
import com.cooleshow.base.presenter.BasePresenter;
import com.cooleshow.base.rx.BaseObserver;
import com.cooleshow.base.utils.RequestBodyUtil;
import com.cooleshow.student.api.APIService;
import com.cooleshow.student.bean.AppHomeBean;
import com.cooleshow.student.bean.CountOfUnreadBean;
import com.cooleshow.student.bean.HelpCenterContentBean;
import com.cooleshow.student.bean.HomeHotMusicSheetBean;
import com.cooleshow.student.bean.HomeHotNewsBean;
import com.cooleshow.student.bean.HomeLiveAndVideoBean;
import com.cooleshow.student.bean.HomeStyleBean;
import com.cooleshow.student.bean.HotAlbumBean;
import com.cooleshow.student.bean.RecommendTalentListBean;
import com.cooleshow.student.bean.StudentUserInfo;
import com.cooleshow.student.bean.TempLiveTeacherListBean;
import com.cooleshow.student.contract.HomeContract;

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

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

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;

/**
 * 创建日期：2022/5/26 10:09
 *
 * @author Ryan
 * 类说明：
 */
public class HomePresenter extends BasePresenter<HomeContract.HomeView> implements HomeContract.Presenter {
    public void appHome() {
        getView().showLoading();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.putOpt("platform", "android");
            jsonObject.putOpt("version", "1");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        addSubscribe(create(APIService.class).appHome(RequestBodyUtil.convertToRequestBodyJson(jsonObject.toString())), new BaseObserver<AppHomeBean>(getView()) {
            @Override
            protected void onSuccess(AppHomeBean data) {
                if (null != getView()) {
                    getView().appHomeSuccess(data);
                }
            }

        });
    }


    public void userAccountPage() {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.putOpt("platform", "android");
            jsonObject.putOpt("version", "1");
            jsonObject.putOpt("page", 1);
            jsonObject.putOpt("rows", Constants.DEFAULT_DATA_SIZE);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        addSubscribe(create(APIService.class).hotAlbumList(RequestBodyUtil.convertToRequestBodyJson(jsonObject.toString())), new BaseObserver<HotAlbumBean>(getView()) {
            @Override
            protected void onSuccess(HotAlbumBean data) {
                if (getView() != null) {
                    getView().hotAlbumListSuccess(data);
                }
            }
        });
    }

    public void queryLiveAndVideo() {
        addSubscribe(create(APIService.class).queryLiveAndVideo("android", "1"), new BaseObserver<HomeLiveAndVideoBean>(getView()) {
            @Override
            protected void onSuccess(HomeLiveAndVideoBean data) {
                if (getView() != null) {
                    getView().queryLiveAndVideoSuccess(data);
                }
            }

            @Override
            public void onComplete() {
                super.onComplete();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);

            }
        });
    }


    public void helpCenterContentList() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.putOpt("catalogIds", "2");
            jsonObject.putOpt("catalogType", "STUDENT");
            jsonObject.putOpt("page", 1);
            jsonObject.putOpt("status", 1);
            jsonObject.putOpt("rows", Constants.DEFAULT_DATA_SIZE);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        addSubscribe(create(APIService.class).helpCenterContentList(RequestBodyUtil.convertToRequestBodyJson(jsonObject.toString())), new BaseObserver<HelpCenterContentBean>(getView()) {
            @Override
            protected void onSuccess(HelpCenterContentBean data) {
                if (getView() != null) {
                    getView().helpCenterContentListSuccess(data);
                }
            }

            @Override
            public void onComplete() {
                super.onComplete();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);

            }
        });
    }

    public void getStylePage() {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.putOpt("platform", "android");
            jsonObject.putOpt("version", "1");
            jsonObject.putOpt("page", 1);
            jsonObject.putOpt("rows", Constants.DEFAULT_DATA_SIZE);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        addSubscribe(create(APIService.class).getStylePage(RequestBodyUtil.convertToRequestBodyJson(jsonObject.toString())), new BaseObserver<HomeStyleBean>(getView()) {
            @Override
            protected void onSuccess(HomeStyleBean data) {
                if (getView() != null) {
                    getView().getStylePageSuccess(1, data);
                }
            }

            @Override
            public void onComplete() {
                super.onComplete();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);

            }
        });
    }

    /**
     * 获取热门资讯
     *
     * @param page
     */
    public void getHotNewsPage(int page) {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.putOpt("platformType", "STUDENT");
            jsonObject.putOpt("type", "1");
            jsonObject.putOpt("status", "1");
            jsonObject.putOpt("page", page);
            jsonObject.putOpt("rows", Constants.DEFAULT_DATA_SIZE);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        addSubscribe(create(APIService.class).getHotNewsPage(RequestBodyUtil.convertToRequestBodyJson(jsonObject.toString())), new BaseObserver<HomeHotNewsBean>(getView()) {
            @Override
            protected void onSuccess(HomeHotNewsBean data) {
                if (getView() != null) {
                    getView().getHotNewsSuccess(page, data);
                }
            }


            @Override
            public void onError(Throwable e) {
                super.onError(e);
                if (getView() != null) {
                    getView().getHotNewsError(page);
                }
            }
        });
    }


    /**
     * 获取达人风采
     *
     * @param page
     */
    public void getTalentStyle(int page) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.putOpt("platform", "android");
            jsonObject.putOpt("version", "1");
            jsonObject.putOpt("page", page);
            jsonObject.putOpt("rows", Constants.DEFAULT_DATA_SIZE);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Observable<BaseResponse<HomeStyleBean>> observable = create(APIService.class).getStylePage(RequestBodyUtil.convertToRequestBodyJson(jsonObject.toString()));
        Observable<BaseResponse<ArrayList<TempLiveTeacherListBean>>> tempLiveObservable = create(APIService.class).getTempLiveList();
        tempLiveObservable.flatMap(new Function<BaseResponse<ArrayList<TempLiveTeacherListBean>>, ObservableSource<BaseResponse<HomeStyleBean>>>() {
            @Override
            public ObservableSource<BaseResponse<HomeStyleBean>> apply(BaseResponse<ArrayList<TempLiveTeacherListBean>> arrayListBaseResponse) throws Throwable {
                return observable.map(new Function<BaseResponse<HomeStyleBean>, BaseResponse<HomeStyleBean>>() {
                    @Override
                    public BaseResponse<HomeStyleBean> apply(BaseResponse<HomeStyleBean> homeStyleBeanBaseResponse) throws Throwable {
                        Log.i("pq", "匹配直播线程:" + Thread.currentThread().getName());
                        if (arrayListBaseResponse != null && page == 1) {
                            //只有第一页合并添加数据
                            ArrayList<TempLiveTeacherListBean> data = arrayListBaseResponse.getData();
                            if (homeStyleBeanBaseResponse != null && homeStyleBeanBaseResponse.getData() != null) {
                                List<HomeStyleBean.RowsBean> rows = homeStyleBeanBaseResponse.getData().rows;
                                if (rows == null) {
                                    rows = new ArrayList<>();
                                }
                                if (data != null && data.size() > 0) {
                                    for (int i = data.size() - 1; i >= 0; i--) {
                                        TempLiveTeacherListBean tempLiveTeacherListBean = data.get(i);
                                        HomeStyleBean.RowsBean rowsBean = new HomeStyleBean.RowsBean();
                                        rowsBean.liveCoverImg = tempLiveTeacherListBean.liveCoverImg;
                                        rowsBean.liveTitle = tempLiveTeacherListBean.liveTitle;
                                        rowsBean.roomUid = tempLiveTeacherListBean.roomUid;
                                        rowsBean.liveStatus = Constants.ON_LIVING_TAG;
                                        rowsBean.avatar = tempLiveTeacherListBean.avatar;
                                        rowsBean.username = tempLiveTeacherListBean.username;
                                        rows.add(0, rowsBean);
                                    }
                                }
//                                for (int i = 0; i < data.size(); i++) {
//                                    TempLiveTeacherListBean tempLiveTeacherListBean = data.get(i);
//                                    if (homeStyleBeanBaseResponse != null && homeStyleBeanBaseResponse.getData() != null && homeStyleBeanBaseResponse.getData().rows != null && homeStyleBeanBaseResponse.getData().rows.size() > 0) {
//                                        for (int j = 0; j < homeStyleBeanBaseResponse.getData().rows.size(); j++) {
//                                            HomeStyleBean.RowsBean rowsBean = homeStyleBeanBaseResponse.getData().rows.get(j);
//                                            if (TextUtils.equals(tempLiveTeacherListBean.teacherId, String.valueOf(rowsBean.userId))) {
//                                                Log.i("pq", "匹配直播老师id:" + tempLiveTeacherListBean.teacherId);
//                                                rowsBean.liveCoverImg = tempLiveTeacherListBean.liveCoverImg;
//                                                rowsBean.liveTitle = tempLiveTeacherListBean.liveTitle;
//                                                rowsBean.roomUid = tempLiveTeacherListBean.roomUid;
//                                                rowsBean.liveing = Constants.ON_LIVING_TAG;
//                                            }
//                                        }
//                                    }
//                                }
                            } else {
                                Log.i("pq", "直播列表为空");
                            }
                        }
                        return homeStyleBeanBaseResponse;
                    }
                });
            }
        }).

                subscribeOn(Schedulers.newThread())
                .

                        observeOn(AndroidSchedulers.mainThread())
                .

                        subscribe(new Observer<BaseResponse<HomeStyleBean>>() {
                            @Override
                            public void onSubscribe(@NonNull Disposable d) {

                            }

                            @Override
                            public void onNext(@NonNull BaseResponse<HomeStyleBean> homeStyleBeanBaseResponse) {
                                if (getView() != null && homeStyleBeanBaseResponse != null) {
                                    getView().getStylePageSuccess(page, homeStyleBeanBaseResponse.getData());
                                }
                            }

                            @Override
                            public void onError(@NonNull Throwable e) {
                                if (getView() != null) {
                                    getView().onError(e);
                                    getView().hideLoading();
                                }
                            }

                            @Override
                            public void onComplete() {
                                if (getView() != null) {
                                    getView().hideLoading();
                                }
                            }
                        });
        //        addSubscribe(create(APIService.class).getStylePage(RequestBodyUtil.convertToRequestBodyJson(jsonObject.toString())), new BaseObserver<HomeStyleBean>(getView()) {
//            @Override
//            protected void onSuccess(HomeStyleBean data) {
//                if (getView() != null) {
//                    getView().getStylePageSuccess(data);
//                }
//            }
//
//            @Override
//            public void onComplete() {
//                super.onComplete();
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                super.onError(e);
//
//            }
//        });
    }

    public void queryUserInfo() {
        addSubscribe(create(APIService.class).queryUserInfo(), new BaseObserver<StudentUserInfo>(getView()) {
            @Override
            protected void onSuccess(StudentUserInfo data) {
                if (getView() != null) {
                    getView().queryUserInfoSuccess(data);
                }
            }
        });
    }


    public void queryCountOfUnread() {

        addSubscribe(create(APIService.class).queryCountOfUnread(), new BaseObserver<List<CountOfUnreadBean>>(getView()) {
            @Override
            protected void onSuccess(List<CountOfUnreadBean> data) {
                if (getView() != null) {
                    getView().queryCountOfUnreadSuccess(data);
                }
            }
        });
    }


    /**
     * 获取热门曲目
     */
    public void getHotMusicSheetList() {
        if (getView() != null) {
            getView().showLoading();
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.putOpt("myself", false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        addSubscribe(create(APIService.class).getHotMusicSheetList(RequestBodyUtil.convertToRequestBodyJson(jsonObject.toString())), new BaseObserver<HomeHotMusicSheetBean>(getView()) {
            @Override
            protected void onSuccess(HomeHotMusicSheetBean data) {
                if (null != getView()) {
                    getView().getHotMusicSheetListSuccess(data);
                }
            }
        });
    }


    /**
     * 获取推荐达人列表
     */
    public void getRecommendTalentList() {
        addSubscribe(create(APIService.class).getRecommendTalentList(), new BaseObserver<ArrayList<RecommendTalentListBean>>(getView()) {
            @Override
            protected void onSuccess(ArrayList<RecommendTalentListBean> data) {
                if (null != getView()) {
                    getView().getRecommendTalentSuccess(data);
                }
            }
        });
    }

    /**
     * 关注老师
     */
    public void followTeacher(int starStatus, String userId) {
        addSubscribe(create(APIService.class).followTeacher(starStatus, userId), new BaseObserver<Object>(getView()) {
            @Override
            protected void onSuccess(Object data) {
                if (null != getView()) {
                    getView().followTeacherSuccess();
                }
            }
        });
    }
}
