package com.sjkj.appthreefloor_tsgz.net;

import android.content.Context;
import android.util.Log;

import com.sjkj.appthreefloor_tsgz.bean.FileBean;
import com.sjkj.base_lib.entity.ResponseBean;
import com.sjkj.base_lib.net.RetrofitFactory;
import com.sjkj.base_lib.net.data.exception.BusinessException;
import com.sjkj.base_lib.net.domain.interactor.UseCase;
import com.sjkj.base_lib.net.utils.FileSizeUtil;
import com.sjkj.base_lib.net.utils.LogInterceptor;
import com.sjkj.base_lib.utils.AppTools;
import com.sjkj.base_lib.utils.ToastUtils;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observable;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 上传文件
 */
public class UploadFileRequest extends UseCase {
    private Context context;
    private RetrofitService service;

    private File file;
    private MultipartBody.Part part;

    public void setFile(File file) {
        this.file = file;
        if (this.file.exists()) {
            double filesSize = FileSizeUtil.getFileOrFilesSize(file.getPath(), 3);
            Log.e("UploadFileRequest", filesSize+"MB");
            RequestBody requestBody = RequestBody.create(file, MediaType.parse("file/*"));
            part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        } else {
            ToastUtils.show("文件不存在");
        }
    }

    public UploadFileRequest(Context context) {
        this.context = context;
        service = RetrofitFactory.getRetrofit(AppTools.getBaseUrl(), true).create(RetrofitService.class);
    }

    @Override
    protected Observable buildUseCaseObservable() {
        LogInterceptor.isShowRequestBody = false;
        return service.upload(part)
                .subscribeOn(Schedulers.io())
                .flatMap(new Func1<ResponseBean<FileBean>, Observable<FileBean>>() {
                    @Override
                    public Observable<FileBean> call(ResponseBean<FileBean> responseBean) {
                        LogInterceptor.isShowRequestBody = true;
                        if (!ResponseBean.CODE_SUCCESS.
                                equals(responseBean.getCode())) {
                            return Observable.error(new BusinessException(responseBean.getMsg()));
                        }
                        return Observable.just(responseBean.getData());
                    }
                });
    }

}
