package com.cooleshow.teacher.presenter.minestyle;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.common.im.bean.ContactRoomListBean;
import com.cooleshow.base.constanst.UploadConstants;
import com.cooleshow.base.data.net.BaseResponse;
import com.cooleshow.base.presenter.BasePresenter;
import com.cooleshow.base.rx.BaseObserver;
import com.cooleshow.base.utils.FileUtils;
import com.cooleshow.base.utils.LogUtils;
import com.cooleshow.base.utils.RequestBodyUtil;
import com.cooleshow.base.utils.Utils;
import com.cooleshow.base.utils.helper.upload.UploadHelper;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.api.APIService;
import com.cooleshow.teacher.bean.HomePageSheetMusicListBean;
import com.cooleshow.teacher.bean.TeacherSelfStyleInfoBean;
import com.cooleshow.teacher.bean.TeacherUserInfo;
import com.cooleshow.teacher.bean.request.QueryGroupListEntry;
import com.cooleshow.teacher.contract.MineStylePageContract;
import com.cooleshow.teacher.ui.minestyle.MineStylePageActivity;
import com.cooleshow.usercenter.bean.SetDetailBean;
import com.daya.live_teaching.LiveTeachingApp;
import com.daya.live_teaching.model.FileUploadBean;
import com.daya.live_teaching.repository.ClassRepository;
import com.luck.picture.lib.tools.BitmapUtils;

import java.io.File;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import io.rong.imkit.picture.tools.PictureFileUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 创建日期：2022/5/13 14:17
 *
 * @author Ryan
 * 类说明：
 */
public class MineStylePagePresenter extends BasePresenter<MineStylePageContract.MineStylePageView> implements MineStylePageContract.Presenter {


    @Override
    public void getTeacherSelfStyle() {
        getView().showLoading();
        addSubscribe(create(APIService.class).getTeacherSelfStyle(), new BaseObserver<TeacherSelfStyleInfoBean>(getView()) {
            @Override
            protected void onSuccess(TeacherSelfStyleInfoBean data) {
                if (getView() != null) {
                    getView().getSelfStyleSuccess(data);
                }
            }

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

    public void saveTeacherStyle(String jsonStr) {
        getView().showLoading();
        addSubscribe(create(APIService.class).saveTeacherStyle(RequestBodyUtil.convertToRequestBodyJson(jsonStr)), new BaseObserver<TeacherSelfStyleInfoBean>(getView()) {
            @Override
            protected void onSuccess(TeacherSelfStyleInfoBean data) {
                if (getView() != null) {
                    getView().saveTeacherStyleSuccess(data);
                }
            }

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

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

            }
        });
    }

    private void uploadCover(Activity activity, String videoFilePath, String coverFilePath) {
        TeacherSelfStyleInfoBean.StyleVideoBean styleVideoBean = new TeacherSelfStyleInfoBean.StyleVideoBean();
        UploadHelper uploadHelper = new UploadHelper(activity, UploadConstants.UPLOAD_TYPE_OTHER);
        uploadHelper.uploadFile(new File(coverFilePath));
        uploadHelper.setLoadingTip("封面上传中");
        uploadHelper.setUpLoadCallBack(new UploadHelper.UpLoadCallBack() {
            @Override
            public void onSuccess(String url) {
                if (TextUtils.isEmpty(styleVideoBean.cover)) {
                    //上传完封面再上传视频
                    styleVideoBean.cover = url;
                    uploadHelper.setLoadingTip("视频上传中");
                    uploadHelper.uploadFile(new File(videoFilePath));
                    return;
                }
                if (getView() != null) {
                    styleVideoBean.videoUrl = url;
                    styleVideoBean.type = 0;
                    getView().upLoadVideoSuccess(styleVideoBean);
                }
            }

            @Override
            public void onFailure() {
                if (getView() != null) {
                    getView().upLoadVideoFailure();
                }
            }
        });
    }

    /**
     * 上传视频
     *
     * @param activity
     * @param videoFilePath
     */
    public void uploadVideo(Activity activity, String videoFilePath) {
        TeacherSelfStyleInfoBean.StyleVideoBean styleVideoBean = new TeacherSelfStyleInfoBean.StyleVideoBean();
        UploadHelper uploadHelper = new UploadHelper(activity, UploadConstants.UPLOAD_TYPE_OTHER);
        uploadHelper.uploadFile(new File(videoFilePath));
        uploadHelper.setLoadingTip("视频上传中");
        uploadHelper.setUpLoadCallBack(new UploadHelper.UpLoadCallBack() {
            @Override
            public void onSuccess(String url) {
                if (getView() != null) {
                    styleVideoBean.videoUrl = url;
                    styleVideoBean.type = 0;
                    getView().upLoadVideoSuccess(styleVideoBean);
                }
            }

            @Override
            public void onFailure() {
                if (getView() != null) {
                    getView().upLoadVideoFailure();
                }
            }
        });
    }

    public void uploadCover(Activity activity, String coverFilePath) {
        UploadHelper uploadHelper = new UploadHelper(activity, UploadConstants.UPLOAD_TYPE_OTHER);
        uploadHelper.uploadFile(new File(coverFilePath));
        uploadHelper.setLoadingTip("封面上传中");
        uploadHelper.setUpLoadCallBack(new UploadHelper.UpLoadCallBack() {
            @Override
            public void onSuccess(String url) {
                if (getView() != null) {
                    getView().upLoadVideoCoverSuccess(url);
                }
            }

            @Override
            public void onFailure() {
                if (getView() != null) {
                    getView().upLoadVideoCoverFail();
                }
            }
        });
    }

    public void upLoadImage(Activity activity, String filePath) {
        UploadHelper uploadHelper = new UploadHelper(activity, UploadConstants.UPLOAD_TYPE_OTHER);
        uploadHelper.uploadFile(new File(filePath));
        uploadHelper.setUpLoadCallBack(new UploadHelper.UpLoadCallBack() {
            @Override
            public void onSuccess(String url) {
                if (getView() != null) {
                    getView().upLoadImageSuccess(url);
                }
            }

            @Override
            public void onFailure() {
                if (getView() != null) {
                    getView().upLoadImageFailure();
                }
            }
        });
    }

    public void submitSetDetail(String jsonStr) {
        if (getView() != null) {
            getView().showLoading();
        }
        addSubscribe(create(APIService.class).submitSetDetail(RequestBodyUtil.convertToRequestBodyJson(jsonStr)), new BaseObserver<SetDetailBean>(getView()) {
            @Override
            protected void onSuccess(SetDetailBean data) {
                if (getView() != null) {
                    getView().submitSetDetailSuccess(data);
                }
            }
        });
    }

    /**
     * 获取userInfo
     */
    public void getUserInfoDetail() {
        if (getView() != null) {
            getView().showLoading();
        }
        addSubscribe(create(APIService.class).getTeacherUserInfo(), new BaseObserver<TeacherUserInfo>(getView()) {
            @Override
            protected void onSuccess(TeacherUserInfo data) {
                if (getView() != null) {
                    getView().getUserInfoSuccess(data);
                }
            }
        });
    }

    /**
     * 获取粉丝群
     */
    public void getTeaGroupList() {
        QueryGroupListEntry entry = new QueryGroupListEntry();
        entry.type = "FAN";
        addSubscribe(create(APIService.class).queryTeaGroupList(entry), new BaseObserver<List<ContactRoomListBean>>(getView()) {
            @Override
            protected void onSuccess(List<ContactRoomListBean> list) {
                if (getView() != null) {
                    getView().getFunGroupList(list);
                }
            }
        });
    }


    public void getUploadVideoCover(Activity activity, String videoFilePath) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(@io.reactivex.rxjava3.annotations.NonNull ObservableEmitter<String> emitter) throws Throwable {
                getVideoCover(Utils.getApp(), videoFilePath, emitter);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        uploadCover(activity, videoFilePath, s);
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getVideoCover(Context context, String targetVideoPath, ObservableEmitter<String> emitter) {
        Glide.with(context)
                .setDefaultRequestOptions(
                        new RequestOptions()
                                .frame(0)
                                .centerCrop()
                                .error(com.cooleshow.base.R.drawable.bg_video_placeholder)
                                .placeholder(com.cooleshow.base.R.drawable.bg_video_placeholder)
                ).asBitmap()
                .load(new File(targetVideoPath))
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        if (resource != null) {
                            long currentTime = System.currentTimeMillis();
                            String path = FileUtils.getCacheDir(Utils.getApp(), FileUtils.filesDirectory) + "/videoCover";
                            File parentFile = new File(path);
                            if (!parentFile.exists()) {
                                parentFile.mkdirs();
                            }
                            File file = new File(parentFile, String.valueOf(currentTime) + ".png");
                            PictureFileUtils.saveBitmapFile(resource, file);
                            if (emitter != null) {
                                emitter.onNext(file.getAbsolutePath());
                            }
                        }
                    }
                });
    }
}
