package cn.muchinfo.rma.netManage.utils;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.blankj.utilcode.util.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;

import cn.muchinfo.rma.view.base.BaseActivity;
/**
 * 上传工具类
 */

public class UpLoadUtils {

    public final static String TAG = "UpLoadUtils";
    private int key;
    private File file;
    private String URL;
    private BaseActivity activity;
    StringCallback callback;

    public UpLoadUtils(BaseActivity activity) {
        this.activity = activity;
    }


    /**
     * 上传用户身份证图片
     *
     * @param file
     */
    public void uploadPicture(final File file, StringCallback callback, double maxSize, String URL) {
        //上传用户身份证图片  需要判断 当前拿到的图片的最大大小   是否 小于 3M（服务器暂定）
        this.file = file;
        this.callback = callback;
        this.URL = URL;

        Log.e(TAG, "压缩前" + FileSizeUtil.getAutoFileOrFilesSize(file.getPath()));
        maxSize = 1000;

        if (FileSizeUtil.getFileOrFilesSize(file.getPath(), FileSizeUtil.SIZETYPE_KB) > maxSize) {
            ToastUtils.showLong("图片过大，压缩中...");
//            activity.showProgressDialog(activity, R.string.zip_pic);
            final ZipThread thread = new ZipThread(file.getPath(), file.getPath(), maxSize, false, mHandler);
            thread.start();  //开始
        } else {
            uploadServerRequest(file, URL);
        }
    }

    public Handler mHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
//                    activity.dismissProgressDialog();
                    uploadServerRequest(file, URL);
                    break;
                default:
                    break;
            }

            super.handleMessage(msg);
        }
    };

    /**
     * 向我们服务传递数据
     *
     * @param file
     */
    public void uploadServerRequest(File file, String URL) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("tem.jpg");
        //是否要更变地址名称
        OkHttpUtils.post()
//                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addFile("mFile", stringBuffer.toString(), file)
                .url(URL)
                .build()
                .execute(callback);
    }

}
