package com.ycgis.macall.personalcenter.p.request;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

import com.google.gson.JsonObject;
import com.rs.macall.androidx.basemodel.request.OkHttpUtils;
import com.rs.macall.androidx.basemodel.utils.BitMapUtils;
import com.rs.macall.androidx.basemodel.utils.LogUtils;
import com.rs.macall.androidx.basemodel.utils.TypConversion;
import com.ycgis.macall.personalcenter.p.app.RuanseeApplication;
import com.ycgis.macall.personalcenter.p.callback.BaseRequestCallback;
import com.ycgis.macall.personalcenter.p.callback.ImageCallBack;
import com.ycgis.macall.personalcenter.p.request.interceptors.HttpLoggingInterceptor;
import com.ycgis.macall.personalcenter.util.FileUtils;
import com.ycgis.macall.personalcenter.v.activity.applyfo.ApplyForMainActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;
import top.zibin.luban.OnCompressListener;

public class AsyncBitmapLoader {

    /**
     * 内存图片软引用缓冲
     */
    private HashMap<String, SoftReference<Bitmap>> imageCache = null;
    private File files;

    public AsyncBitmapLoader() {
        imageCache = new HashMap<String, SoftReference<Bitmap>>();
    }

  /*  public Bitmap loadBitmap(final Context context, final ZdyText imageView, final String imageURL, final ImageCallBack imageCallBack) {
        //在内存缓存中，则返回Bitmap对象  
        if (imageCache.containsKey(imageURL)) {
            SoftReference<Bitmap> reference = imageCache.get(imageURL);
            Bitmap bitmap = reference.get();
            if (bitmap != null) {
                return bitmap;
            }
        } else {
            *//**
             * 加上一个对本地缓存的查找 
             *//*
            final File cacheDir;
            if (imageURL.startsWith("/storage/emulated")) {
                cacheDir = new File(imageURL);
            } else {
                String bitmapName = imageURL.substring(imageURL.lastIndexOf("/") + 1);
                cacheDir = new File(FileUtils.IMAGE_DIR + bitmapName);
            }
            if (cacheDir.exists()) {
                try {
                    return BitmapFactory.decodeFile(cacheDir.getAbsolutePath());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @SuppressLint("HandlerLeak") final Handler handler = new Handler() {
                *//* (non-Javadoc)
                 * @see android.os.Handler#handleMessage(android.os.Message)
                 *//*
                @Override
                public void handleMessage(final Message msg) {
                    // TODO Auto-generated method stub
                    switch (msg.what) {
                        case -2001:
                            imageCallBack.imageLoadError(imageView, (String) msg.obj);
                            break;
                        case 200:
                            Bitmap bitmap = (Bitmap) msg.obj;
                            String lswn = System.currentTimeMillis() + "";
                            lswn += new Random().nextInt(10) + ".jpg";
                            files = BitMapUtils.saveBitmap(FileUtils.IMAGE_DIR, lswn, bitmap);
                            if (files == null || !files.exists()) {
                                imageCallBack.imageLoadError(imageView, "图片加载失败！");
                                return;
                            }
                            String fileName = imageURL.substring(imageURL.lastIndexOf("/") + 1);
                            ys(context, fileName, this);
                            break;
                        case 1414:
                            Bitmap bitmap1 = (Bitmap) msg.obj;
                            imageCallBack.imageLoad(imageView, bitmap1);
                            imageCache.put(imageURL, new SoftReference<Bitmap>(bitmap1));
                            break;
                        case -2121:
                            imageCallBack.imageLoadError(imageView, (String) msg.obj);
                            break;
                    }
                }
            };

            //如果不在内存缓存中，也不在本地（被jvm回收掉），则开启线程下载图片
            getGetPhtot(AppCache.IMAGE_URL + imageURL, handler);

        }
        return null;
    }
*/
    private void ys(Context context, final String newFileName, final Handler handler) {
        BitMapUtils.lubanCompress(context, files, FileUtils.IMAGE_DIR, new OnCompressListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(File file) {
                if (!files.getName().equals(file.getName()))
                    files.delete();
                boolean is = FileUtils.renameFile(FileUtils.IMAGE_DIR, file.getName(), newFileName);
                if (is) {
                    Bitmap bitmap1 = BitmapFactory.decodeFile(FileUtils.IMAGE_DIR + newFileName);
                    Message message = handler.obtainMessage(1414, bitmap1);
                    handler.sendMessage(message);
                }
            }

            @Override
            public void onError(Throwable e) {
                Message message = handler.obtainMessage(-2121, "图片加载失败！");
                handler.sendMessage(message);
            }
        });
    }

    /**
     * GET 方式请求数据 图片
     */
    public static void getGetPhtot(String urlTal, final Handler handler) {
        URL url = null;
        try {
            url = new URL(urlTal);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Message message = handler.obtainMessage();
            message.what = -2001;
            message.arg2 = 205;
            message.obj = "URL错误";
            handler.sendMessage(message);
            return;
        }
        Request request = new Request.Builder()
                .url(url)
                .build();
        OkHttpUtils.getClient(10, 30, 40,new HttpLoggingInterceptor())
                .newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        System.out.println("加载图片错误：" + e.getMessage());
                        Message message = handler.obtainMessage();
                        message.what = -2001;
                        message.arg2 = 205;
                        message.obj = "加载图片失败：请检查网络连接状况";
                        handler.sendMessage(message);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        int responseCode = response.code();
                        if (responseCode != 200) {
                            System.out.println("加载图片错误：请求码错误");
                            Message message = handler.obtainMessage();
                            message.what = -2001;
                            message.arg2 = 205;
                            message.obj = "加载图片失败,请联系管理员";
                            handler.sendMessage(message);
                            return;
                        }
                        byte[] photoByte = response.body().bytes();
                        Message message = new Message();
                        message.what = 200;
                        message.arg2 = 205;
                        message.obj = BitmapFactory.decodeByteArray(photoByte, 0, photoByte.length);
                        handler.sendMessage(message);
                    }
                });
    }

    public Bitmap loadSeal(String id,String deptCode,ImageView imageView,final ImageCallBack callback) {
        if (imageCache == null){
            imageCache = new HashMap<>();
        }
        SoftReference<Bitmap> bitmapSoftReference = imageCache.get(deptCode);
        if (bitmapSoftReference != null&&bitmapSoftReference.get() != null){
            return bitmapSoftReference.get();
        }
        File file = new File(FileUtils.IMAGE_DIR,deptCode+".png");
        if (file.exists()){
            return BitmapFactory.decodeFile(file.getAbsolutePath());
        }
        Map<String, String> headMap = new HashMap<>(1);
        headMap.put("app-yysq-token", RuanseeApplication.getAppCache().getApply_token());
        ApiModel.request(RetrofitService.getBaseInstance().applyGet(ApplyForMainActivity.BASE_URL + "audit/seal/" + id, headMap, new HashMap<>()), new BaseRequestCallback<JsonObject>() {
            @Override
            public void onRequestFailure(String msg) {
                LogUtils.e(msg);
                callback.imageLoadError(imageView,msg);
            }

            @Override
            public void onRequestSuccess(JsonObject result) {
                LogUtils.w(result.toString());
                try {
                    JSONObject object = new JSONObject(result.toString());
                    int code = TypConversion.getJsonInt(object, "code", 0);
                    if (code == 200){
                        JSONObject data = TypConversion.getJSONObject(object, "data");
                        String seal_img = TypConversion.getJsonStr(data, "seal_img");
                        Bitmap bitmap = BitMapUtils.base64ToBitmap(seal_img);
                        if (bitmap!=null){
                            Bitmap bitmap1 = BitMapUtils.removeWhiteBackground(bitmap);
                            if (imageCache == null){
                                imageCache = new HashMap<>();
                            }
                            imageCache.put(deptCode, new SoftReference<>(bitmap1));
                            BitMapUtils.saveBitmap(FileUtils.IMAGE_DIR,deptCode+".png",bitmap1);
                            callback.imageLoad(imageView,bitmap1);
                        }else {
                         callback.imageLoadError(imageView,"加载失败");
                        }
                    }else {
                        callback.imageLoadError(imageView,"加载失败");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    callback.imageLoadError(imageView,"加载失败");
                }
//                new SoftReference<>()
//                SoftReference<Bitmap> bitmapSoftReference = imageCache.get(deptCode);
//
//
//                if (bitmapSoftReference != null&&bitmapSoftReference.get() != null){
//                    return bitmapSoftReference.get();
//                }
//                File file = new File(FileUtils.IMAGE_DIR,deptCode+".jpg");
//                if (file.exists()){
//                    return BitmapFactory.decodeFile(file.getAbsolutePath());
//                }
            }
        });
        return null;
    }

}
