package com.sheep.gamegroup.util.upfile;


import android.graphics.Bitmap;

import com.nanchen.compresshelper.CompressHelper;
import com.sheep.gamegroup.model.api.ICallBack;
import com.sheep.gamegroup.model.util.ExceptionHandle;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.service.ListenerShotService;
import com.sheep.jiuyan.samllsheep.utils.FileUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.io.File;
import java.util.ArrayList;
import java.util.Locale;

import go.kfzssafe.Kfzssafe;
import okhttp3.Call;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by howie on 2017/5/11.
 */

public class UpFileUtils {
    //    private static String URL_RN_UP_IMAGE = "http://shopapi.bandaimi.com/v1/upload_pic/avatar";
    private static String URL_RN_UP_IMAGE = "http://static.kuaifazs.com/sdkkitfile.php";

    //上传图片
    public static void upImage(File file, final UpFileListener upFileListener) {
        OkHttpUtils.post()//
                .addFile("uploadfile", "1.png", file)//
                .url(URL_RN_UP_IMAGE)
                .build()//
                .execute(new Callback() {
                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                        upFileListener.Progress(String.valueOf(Math.round(progress * 100)), -1);
                    }

                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        ResponseBody body = response.body();
                        return body == null ? response : body.string();
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        upFileListener.Failure(e.toString());
                    }

                    @Override
                    public void onResponse(Object response, int id) {
                        upFileListener.Success(response.toString(), -1);
                    }
                });

    }

    public static void upImages(ArrayList<String> photos, final UpFileListener upFileListener, ICallBack<Boolean> action1) {
        upImages(photos, upFileListener, action1, 0);
    }
    public static void upImages(final ArrayList<String> photos, final UpFileListener upFileListener, final ICallBack<Boolean> action1, final int index) {
        int size = photos.size();
        if (index < size) {
            File file;
            if ((file = new File(photos.get(index))).exists()) {
                File newFile = null;
                boolean convertFile = false;
                boolean needDecodeImage = action1 != null;
                if(ListenerShotService.IS_RECORD_PATH) {
                    try {
                        //是否需要转换图片：不启用上传所有图片时，或者记录到图片时需要转换
                        needDecodeImage = action1 != null && (!DataUtil.IS_USE_ALL_IMAGE || action1.call(ICallBack.IS_RECORD, file.getAbsolutePath()));
                        if(needDecodeImage) {
                            if (!Kfzssafe.isPng(file.getAbsolutePath())) {//非png图片才转换
                                String toFilePath = String.format(Locale.CHINA, "%s%s_%d.png", file.getParent(), File.separator, System.currentTimeMillis());
                                FileUtil.convertImage(file.getAbsolutePath(), toFilePath, Bitmap.CompressFormat.PNG);
                                file = new File(toFilePath);
                                convertFile = true;
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    newFile = new CompressHelper.Builder(SheepApp.getInstance())
                            .setMaxWidth(1080)  // 默认最大宽度为720
                            .setMaxHeight(1080) // 默认最大高度为960
                            .setQuality(80)    // 默认压缩质量为80
                            .setCompressFormat(Bitmap.CompressFormat.PNG) // 设置默认压缩为png格式
                            .build().compressToFile(file);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if(newFile == null || !newFile.exists()){
                    newFile = file;
                } else {
                    if(convertFile) {//如果转换了图片，就需要删除掉转换的图片
                        if(file.delete()){
                            file = null;
                        }
                    }
                }
                try {
                    if(needDecodeImage)
                        action1.call(ICallBack.DECODE_PNG, newFile.getAbsolutePath(), size, index);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                OkHttpUtils.post()
                        .addFile("uploadfile", "1.png", newFile)//
                        .url(URL_RN_UP_IMAGE)
                        .build()//
                        .execute(new Callback() {
                            @Override
                            public void inProgress(float progress, long total, int id) {
                                super.inProgress(progress, total, id);
                                upFileListener.Progress(String.valueOf(Math.round(progress * 100)), index);
                            }

                            @Override
                            public Object parseNetworkResponse(Response response, int id) throws Exception {
                                ResponseBody body = response.body();
                                return body == null ? response : body.string();
                            }

                            @Override
                            public void onError(Call call, Exception e, int id) {
                                //访问获得对应的Exception
                                ExceptionHandle.ResponeThrowable throwable = ExceptionHandle.handleException(e);
                                upFileListener.Failure(throwable.message+"");
                            }

                            @Override
                            public void onResponse(Object response, int id) {
                                upFileListener.Success(response.toString(), index);
                                upImages(photos, upFileListener, action1,index + 1);
                            }
                        });
            }else {//文件不存在就不用上传
                upImages(photos, upFileListener, action1,index + 1);
            }
        } else
            upFileListener.Success("全部上传完成", -1);

    }
}
