package com.casic.dcms.utils.retrofit;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.casic.dcms.base.BaseApplication;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.CaseCheckBean;
import com.casic.dcms.bean.CaseCheckedBean;
import com.casic.dcms.bean.CaseDetailBean;
import com.casic.dcms.bean.CaseHandleBean;
import com.casic.dcms.bean.CaseHandledBean;
import com.casic.dcms.bean.CaseLargeClassBean;
import com.casic.dcms.bean.CaseListResultBean;
import com.casic.dcms.bean.CaseNextNodeBean;
import com.casic.dcms.bean.CaseProcessBean;
import com.casic.dcms.bean.CaseSmallClassBean;
import com.casic.dcms.bean.CaseStatusBean;
import com.casic.dcms.bean.CaseVerifiedBean;
import com.casic.dcms.bean.CaseVerifyBean;
import com.casic.dcms.bean.CommonSentenceBean;
import com.casic.dcms.bean.DeptTreeBean;
import com.casic.dcms.bean.EventSourceBean;
import com.casic.dcms.bean.HighEventBean;
import com.casic.dcms.bean.HomePageBean;
import com.casic.dcms.bean.LoginResultBean;
import com.casic.dcms.bean.NewVersionBean;
import com.casic.dcms.bean.OnlinePersonBean;
import com.casic.dcms.bean.OvertimeCaseBean;
import com.casic.dcms.bean.PhoneBookBean;
import com.casic.dcms.bean.PublicKeyBean;
import com.casic.dcms.bean.UrgentCaseBean;
import com.casic.dcms.bean.UserBean;
import com.casic.dcms.utils.AuthenticationHelper;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.HttpConfig;
import com.casic.dcms.utils.OtherUtils;
import com.casic.dcms.utils.SaveKeyValues;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.TimeOrDateUtil;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;

public class RetrofitServiceManager {
    private static final String TAG = "RetrofitServiceManager";

    private static Retrofit createRetrofit() {
        String ip = (String) SaveKeyValues.getValue(Constant.IP_KEY, "http://111.198.10.15:11409");
//        String ip = (String) SaveKeyValues.getValue(Constant.IP_KEY, "http://223.82.47.232:11401");
        return new Retrofit.Builder()
                .baseUrl(ip)
                .addConverterFactory(GsonConverterFactory.create())//Gson转换器
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(createOKHttpClient())//log拦截器
                .build();
    }

    private static OkHttpClient createOKHttpClient() {
        //日志显示级别
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(@NotNull String message) {
                Log.d(TAG, "log: " + message);
            }
        });
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .readTimeout(HttpConfig.HTTP_TIMEOUT, TimeUnit.SECONDS)
                .connectTimeout(HttpConfig.HTTP_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(HttpConfig.HTTP_TIMEOUT, TimeUnit.SECONDS);
        return builder.addInterceptor(interceptor).build();
    }

    /**
     * 验证PublicKey
     */
    public static Observable<PublicKeyBean> authenticate() {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainPublicKey();
    }

    /**
     * 登录并获取Token
     */
    public static Observable<LoginResultBean> getTokenData(String username, String key) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.login(username, key);
    }

    /**
     * 获取用户信息
     */
    public static Observable<UserBean> getUserData() {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainUser(AuthenticationHelper.getToken());
    }

    /**
     * 大类列表查询
     */
    public static Observable<CaseLargeClassBean> getCaseLargeClass(String eorc) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainLargeClass(AuthenticationHelper.getToken(), eorc);
    }

    /**
     * 大类列表查询
     */
    public static Observable<CaseSmallClassBean> getCaseSmallClass(String eorc, String typeId) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainLargeClass(AuthenticationHelper.getToken(), eorc, typeId);
    }

    /**
     * 提交案卷
     */
    public static Observable<ActionResultBean> getSubmitCaseResult(String isNeedVerify, String isNeedRevisit,
                                                                   String longitude, String latitude,
                                                                   String source, String caseLevel,
                                                                   String eorc, String casetypeCode,
                                                                   String casetypeDetailCode, String areaCode,
                                                                   String streetCode, String communityCode,
                                                                   String gridId, String description,
                                                                   String fieldintro, String fileIdVerify,
                                                                   String audioIdVerify, String videoIdVerify,
                                                                   int bzhours, int bzminis) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.submitCase(AuthenticationHelper.getToken(), isNeedVerify, isNeedRevisit, longitude, latitude,
                source, caseLevel, eorc, casetypeCode, casetypeDetailCode, areaCode, streetCode, communityCode,
                gridId, description, fieldintro, fileIdVerify, audioIdVerify, videoIdVerify, bzhours, bzminis);
    }

    /**
     * 退出登录
     */
    public static Observable<ActionResultBean> getLoginOutResult() {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.loginOut(AuthenticationHelper.getToken());
    }

    /**
     * 修改密码
     */
    public static Observable<ActionResultBean> getChangePasswordResult(String oldPwd, String newPwd) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.changePassword(AuthenticationHelper.getToken(), oldPwd, newPwd);
    }

    /**
     * 获取部门树
     */
    public static Observable<DeptTreeBean> getDeptTreeResult(String pid) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainDeptTree(AuthenticationHelper.getToken(), pid);
    }

    /**
     * 获取通讯录
     */
    public static Observable<PhoneBookBean> getPhoneBookResult(String deptid) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainPhoneBook(AuthenticationHelper.getToken(), deptid);
    }

    /**
     * 获取高发问题
     */
    public static Observable<HighEventBean> getHighEventResult(String begTime, String endTime) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainHighEvent(AuthenticationHelper.getToken(), begTime, endTime);
    }

    /**
     * 获取问题来源
     */
    public static Observable<EventSourceBean> getEventSourceResult(String begTime, String endTime) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainEventSource(AuthenticationHelper.getToken(), begTime, endTime);
    }

    /**
     * 获取案件状态
     */
    public static Observable<CaseStatusBean> getCaseStatusResult() {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainCaseStatus(AuthenticationHelper.getToken());
    }

    /**
     * 根据时间查询案卷列表
     */
    public static Observable<CaseListResultBean> getCaseListResult(String casetypeCode, String casetypeDetailCode,
                                                                   String caseState, String registerTimeBegin,
                                                                   String registerTimeEnd, String eorc, int offset) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainCaseList(AuthenticationHelper.getToken(), casetypeCode, casetypeDetailCode, caseState,
                registerTimeBegin, registerTimeEnd, eorc, 15, offset);
    }

    /**
     * 获取案件详情
     */
    public static Observable<CaseDetailBean> getCaseDetailResult(String id) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainCaseDetail(AuthenticationHelper.getToken(), id);
    }

    /**
     * 获取案件流转记录
     */
    public static Observable<CaseProcessBean> getCaseProcessResult(String processId) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainCaseProcess(AuthenticationHelper.getToken(), processId);
    }

    /**
     * 更新版本
     */
    public static Observable<NewVersionBean> getVersionResult() {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainVersion(AuthenticationHelper.getToken());
    }

    /**
     * 获取核实待办案卷
     */
    public static Observable<CaseVerifyBean> getCaseVerifyListResult(int limit, int offset) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainCaseVerifyList(AuthenticationHelper.getToken(), limit, offset);
    }

    /**
     * 获取核实已办案卷
     */
    public static Observable<CaseVerifiedBean> getCaseVerifiedListResult(int offset) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainCaseVerifiedList(AuthenticationHelper.getToken(), 15, offset);
    }

    /**
     * 获取核查待办案卷
     */
    public static Observable<CaseCheckBean> getCaseCheckListResult(int limit, int offset) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainCaseCheckList(AuthenticationHelper.getToken(), limit, offset);
    }

    /**
     * 获取核查已办案卷
     */
    public static Observable<CaseCheckedBean> getCaseCheckedListResult(int offset) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainCaseCheckedList(AuthenticationHelper.getToken(), 15, offset);
    }

    /**
     * 上传案卷图片
     * <p>
     * 系统路径static拼接图片返回路径
     * http://xx.com/static/2019-10/8050891248624f2bbefedcb196ce89cb.jpeg
     */
    public static Observable<ActionResultBean> getImageUploadResult(File image) {
        //改为上传带水印的图片
        Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath());
        String path = OtherUtils.drawTextToRightBottom(BaseApplication.getInstance(), bitmap,
                StringHelper.getUserAccount(),
                TimeOrDateUtil.rTimestampToDate(System.currentTimeMillis()),
                TimeOrDateUtil.timestampToTime(System.currentTimeMillis()));

        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), new File(path));
        MultipartBody.Part imagePart = MultipartBody.Part.createFormData("file", image.getName(), requestBody);
        return service.uploadImage(AuthenticationHelper.getToken(), imagePart);
    }

    /**
     * 上传案卷音频
     */
    public static Observable<ActionResultBean> getAudioUploadResult(File audio) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        RequestBody requestBody = RequestBody.create(MediaType.parse("audio/m4a"), audio);
        MultipartBody.Part imagePart = MultipartBody.Part.createFormData("file", audio.getName(), requestBody);
        return service.uploadAudio(AuthenticationHelper.getToken(), imagePart);
    }

    /**
     * 上传案卷视频
     */
    public static Observable<ActionResultBean> getVideoUploadResult(File video) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        RequestBody requestBody = RequestBody.create(MediaType.parse("video/mp4"), video);
        MultipartBody.Part imagePart = MultipartBody.Part.createFormData("file", video.getName(), requestBody);
        return service.uploadVideo(AuthenticationHelper.getToken(), imagePart);
    }

    /**
     * 五包上报
     */
    public static Observable<ActionResultBean> getSubmitShopCaseResult(String isNeedVerify, String isNeedRevisit,
                                                                       String longitude, String latitude,
                                                                       String source, String caseLevel,
                                                                       String areaCode, String streetCode,
                                                                       String communityCode, String gridId,
                                                                       String description, String fieldintro,
                                                                       String fileIdVerify, int bzhours,
                                                                       int bzminis, String shopId,
                                                                       String shopkeeperName, String shopPhone) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.submitShopCase(AuthenticationHelper.getToken(), isNeedVerify, isNeedRevisit, longitude,
                latitude, source, caseLevel, areaCode, streetCode, communityCode, gridId, description,
                fieldintro, fileIdVerify, bzhours, bzminis, shopId, shopkeeperName, shopPhone);
    }

    /**
     * 案卷处理分页查询
     */
    public static Observable<CaseHandleBean> getCaseHandleListResult(String isOvertime, String isEmergent,
                                                                     int limit, int offset) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainHandleCase(AuthenticationHelper.getToken(), isOvertime, isEmergent, limit, offset);
    }

    /**
     * 处理已办分页查询
     */
    public static Observable<CaseHandledBean> getCaseHandledListResult(int offset) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainHandledCase(AuthenticationHelper.getToken(), 15, offset);
    }

    /**
     * 紧急案件分页查询
     */
    public static Observable<UrgentCaseBean> getUrgentCaseListResult(String isSupervise, int offset) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainUrgentCase(AuthenticationHelper.getToken(), isSupervise, 15, offset);
    }

    /**
     * 超时案件分页查询
     */
    public static Observable<OvertimeCaseBean> getOvertimeCaseListResult(String isSupervise, int offset) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainOvertimeCase(AuthenticationHelper.getToken(), isSupervise, 15, offset);
    }

    /**
     * 在线人员查询
     */
    public static Observable<OnlinePersonBean> getOnlinePersonResult(String deptid, String roleTips, String isOnLine) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainOnlinePerson(AuthenticationHelper.getToken(), deptid, roleTips, isOnLine);
    }

    /**
     * 设备定位信息上传
     */
    public static Observable<ActionResultBean> getPositionUploadResult(String imei, String positionLat, String positionLng) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.uploadDevicePosition(AuthenticationHelper.getToken(), imei, positionLat, positionLng);
    }

    /**
     * 获取流转下级节点
     *
     * @param caseState 字典值
     */
    public static Observable<CaseNextNodeBean> getProcessNextNodeResult(String caseState) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainProcessNextNode(AuthenticationHelper.getToken(), caseState);
    }

    /**
     * 获取常见语句
     */
    public static Observable<CommonSentenceBean> getCommonSentenceResult() {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainCommonSentence(AuthenticationHelper.getToken());
    }

    /**
     * 案卷处理
     * <p>
     * 案卷核实-仅添加核实意见/核实情况/核实图片
     */
    public static Observable<ActionResultBean> getHandleCaseResult(String processId, String bizId,
                                                                   String currState, String changeState,
                                                                   String remarks, String fileId) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.handleCase(AuthenticationHelper.getToken(), processId, bizId, currState, changeState, remarks, fileId);
    }

    /**
     * 案卷处理
     * <p>
     * 超时案卷
     */
    public static Observable<ActionResultBean> getHandleCaseResult(String processId, String bizId,
                                                                   String currState, String changeState,
                                                                   String remarks, String fileId,
                                                                   String approvalResult) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.handleCase(AuthenticationHelper.getToken(), processId, bizId, currState, changeState, remarks,
                fileId, approvalResult);
    }

    /**
     * 案卷处理
     * <p>
     * 案卷核实-热线电话和微信公众号提交的数据，需要补全信息
     * 案卷核查
     */
    public static Observable<ActionResultBean> getHandleCaseResult(String processId, String bizId,
                                                                   String currState, String changeState,
                                                                   String remarks, String fileId,
                                                                   String eorc, String casetypeCode,
                                                                   String casetypeDetailCode, String lng,
                                                                   String lat, String caseLevel,
                                                                   String areaCode, String streetCode,
                                                                   String communityCode, String gridId,
                                                                   String fieldintro) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.handleCase(AuthenticationHelper.getToken(), processId, bizId, currState, changeState,
                remarks, fileId, eorc, casetypeCode, casetypeDetailCode, lng, lat, caseLevel, areaCode,
                streetCode, communityCode, gridId, fieldintro);
    }

    /**
     * 紧急要件-超时督办
     */
    public static Observable<ActionResultBean> getUpdateSuperviseResult(String id, String superviseRemarks) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.updateSuperviseRemarks(AuthenticationHelper.getToken(), id, superviseRemarks);
    }

    /**
     * 获取首页九宫格数据
     */
    public static Observable<HomePageBean> getHomePageResult(String resourceType) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.obtainHomePage(AuthenticationHelper.getToken(), resourceType);
    }

    /**
     * 个推推送cid注册
     */
    public static Observable<ActionResultBean> getRegisterResult(String clientId) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.registerPush(AuthenticationHelper.getToken(), clientId);
    }

    /**
     * 公厕打扫签到
     */
    public static Observable<ActionResultBean> getCleanToiletResult(String toiletId, String userId,
                                                                    String lng, String lat,
                                                                    String cleanTime, String photo,
                                                                    String workContent) {
        Retrofit retrofit = createRetrofit();
        RetrofitService service = retrofit.create(RetrofitService.class);
        return service.cleanToilet(AuthenticationHelper.getToken(), toiletId, userId, lng, lat, cleanTime,
                photo, workContent);
    }
}
