package com.rv.im.util;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;
import com.rv.component.utils.CacheEnum;
import com.rv.component.utils.RvCache;
import com.rv.im.AppConfig;
import com.rv.im.bean.UploadFileResult;
import com.rv.im.db.table.ChatMessage;
import com.rv.im.enums.MessageTypeEnum;
import com.rv.im.log.LogUtil;

import org.apache.http.Header;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

public class UploadEngine {

    private static Map<String, RequestHandle> requestHandleMap = new HashMap<>();

    public static void uploadImFile(Context context, String accessToken, final String loginUserId, final String toUserId, final ChatMessage message, final ImFileUploadResponse response) {
        RequestParams params = new RequestParams();
        params.put("access_token", accessToken);
        params.put("userId", loginUserId);
        try {
            params.put("file1", new File(message.getFilePath()));
        } catch (FileNotFoundException e) {
            LogUtil.e("文件<" + message.getFilePath() + ">找不到，" + e.toString());
        }
        params.put("validTime", "7");
        AsyncHttpClient client = new AsyncHttpClient(true, 0, 0);
        AppConfig config = (AppConfig) RvCache.getInstance().get(CacheEnum.IM_CONFIG);
        if (config == null || TextUtils.isEmpty(config.UPLOAD_URL)) return;
        RequestHandle requestHandle = client.post(config.UPLOAD_URL, params, new AsyncHttpResponseHandler() {

            @Override
            public void onProgress(int bytesWritten, int totalSize) {
                super.onProgress(bytesWritten, totalSize);
                if (bytesWritten == totalSize) {
                    message.setUpLoadStatus(2);
                    message.setUploadSchedule(100);
                    response.onUpProgress(toUserId, message);
                } else {
                    if (totalSize != 0) {
                        message.setUpLoadStatus(1);
                        int progress = bytesWritten * 100 / totalSize;
                        message.setUploadSchedule(progress);
                        response.onUpProgress(toUserId, message);
                    }
                }
            }

            @Override
            public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {// 数据发送成功，并且有返回值<不是上传成功。。。>
                requestHandleMap.remove(message.getPackId());
                String url = null;
                if (arg0 == 200) {
                    UploadFileResult result = null;
                    try {
                        String res = new String(arg2);
                        LogUtil.d("上传文件<" + message.getFilePath() + ">返回：" + res);
                        result = new Gson().fromJson(res, UploadFileResult.class);
                    } catch (Exception e) {
                        LogUtil.d("上传文件响应解析失败，" + e.toString());
                    }
                    if (result.getFailure() == 1) {//上传失败
                        if (response != null) {
                            message.setUpLoadStatus(3);
                            response.onFailure(toUserId, message);
                        }
                        LogUtil.d("上传文件失败，");
                        return;
                    }
                    //上传成功
                    if (result.getResultCode() != 1 || result.getData() == null
                            || result.getSuccess() != result.getTotal()) {

                    } else {
                        UploadFileResult.Data data = result.getData();
                        if (message.getMessageType() == MessageTypeEnum.PIC.getType()) {
                            url = getImagesUrl(data);
                        } else if (message.getMessageType() == MessageTypeEnum.VOICE.getType()) {
                            url = getAudiosUrl(data);
                        } else if (message.getMessageType() == MessageTypeEnum.FILE.getType()) {
                            if (TextUtils.isEmpty(url = getFilesUrl(data)))//如果获取到的文件名为空，就获取其他的
                                if (TextUtils.isEmpty(url = getAudiosUrl(data)))
                                    if (TextUtils.isEmpty(url = getImagesUrl(data)))
                                        if (TextUtils.isEmpty(url = getVideosUrl(data)))
                                            url = getOthersUrl(data);
                        }
                    }
                }

                if (TextUtils.isEmpty(url)) {//返回成功，但是却获取不到对应的URL，服务器返回值异常<概率极小>
                    if (response != null) {
                        message.setUpLoadStatus(3);
                        response.onFailure(toUserId, message);
                    }
                } else {
                    // 记录本机上传，用于快速读取，
                    if (response != null) {
                        message.setContent(url);
                        message.setUpLoadStatus(2);
                        response.onSuccess(toUserId, message);
                    }
                }
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
                requestHandleMap.remove(message.getPackId());
                LogUtil.i("上传文件<" + message.getFilePath() + ">失败，" + arg3);
                message.setUpLoadStatus(3);
                if (response != null) {
                    response.onFailure(toUserId, message);
                }
            }
        });
        requestHandleMap.put(message.getPackId(), requestHandle);
    }

    public static void cancel(String msgId) {

//        EventBus.getDefault().post(new EventUploadCancel(msgId));

        RequestHandle requestHandle = requestHandleMap.get(msgId);
        if (requestHandle != null) {
            requestHandle.cancel(true);
        }
    }

    private static String getOthersUrl(UploadFileResult.Data data) {
        if (data.getOthers() != null && data.getOthers().size() > 0) {
            return data.getOthers().get(0).getOriginalUrl();
        } else {
            return "";
        }
    }

    private static String getImagesUrl(UploadFileResult.Data data) {
        if (data.getImages() != null && data.getImages().size() > 0) {
            return data.getImages().get(0).getOriginalUrl();
        } else {
            return "";
        }
    }

    private static String getVideosUrl(UploadFileResult.Data data) {
        if (data.getVideos() != null && data.getVideos().size() > 0) {
            return data.getVideos().get(0).getOriginalUrl();
        } else {
            return "";
        }
    }

    private static String getAudiosUrl(UploadFileResult.Data data) {
        if (data.getAudios() != null && data.getAudios().size() > 0) {
            return data.getAudios().get(0).getOriginalUrl();
        } else {
            return "";
        }
    }

    private static String getFilesUrl(UploadFileResult.Data data) {
        if (data.getFiles() != null && data.getFiles().size() > 0) {
            return data.getFiles().get(0).getOriginalUrl();
        } else {
            return "";
        }
    }


    public interface ImFileUploadResponse {
        void onSuccess(String toUserId, ChatMessage message);

        void onFailure(String toUserId, ChatMessage message);

        void onUpProgress(String toUserId, ChatMessage message);
    }


}
