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

import android.annotation.SuppressLint;
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.rs.macall.androidx.basemodel.request.OkHttpUtils;
import com.rs.macall.androidx.basemodel.request.RequestCode;
import com.rs.macall.androidx.basemodel.utils.BitMapUtils;
import com.ycgis.macall.personalcenter.p.callback.ImageCallBack;
import com.ycgis.macall.personalcenter.p.request.AsyncBitmapLoader;
import com.ycgis.macall.personalcenter.util.AppTools;
import com.ycgis.macall.personalcenter.util.FileUtils;

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 java.util.Random;

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

/**
 * created by:   Macall
 * create time:  2023/11/16 9:45
 * copyright:    @ruansee.com
 * Describe:
 */
public class LoadAppCenterImage {

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

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

    public Bitmap loadBitmapText(final Context context, final ImageView imageView, final String imageName, final ImageCallBack imageCallBack) {
        //在内存缓存中，则返回Bitmap对象
        if (imageCache.containsKey(imageName)) {
            SoftReference<Bitmap> reference = imageCache.get(imageName);
            Bitmap bitmap = reference.get();
            if (bitmap != null) {
                return bitmap;
            }
        } else {
            File cacheDir = new File(FileUtils.IMAGE_DIR + imageName);
            if (cacheDir.exists()) {
                try {
                    return BitmapFactory.decodeFile(cacheDir.getAbsolutePath());
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }

            @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 RequestCode.REQUEST_OK:
                            Bitmap bitmap = (Bitmap) msg.obj;
                            String wei = imageName.substring(imageName.lastIndexOf("."));
                            String lswn = System.currentTimeMillis() + "" + new Random().nextInt(10) + wei;
                            File 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, files, imageName, this);
                            break;
                        case 1414:
                            Bitmap bitmap1 = (Bitmap) msg.obj;
                            imageCallBack.imageLoad(imageView, bitmap1);
                            imageCache.put(imageName, new SoftReference<Bitmap>(bitmap1));
                            break;
                        case -2121:
                            imageCallBack.imageLoadError(imageView, (String) msg.obj);
                            break;
                    }
                }
            };

            Map<String, String> param = new HashMap<>();
            param.put("devCode", "442eab382e6a49649e3402115bd8837f");
            param.put("appId", AppTools.getPackageName(context));
            param.put("fileId", imageName);
            //如果不在内存缓存中，也不在本地（被jvm回收掉），则开启线程下载图片
            postGetPhoto("http://20.90.1.128:7310/api/v1/appInfo/downloadImg", param, handler);
//            BaseRequest.postRequestPhotoText("http://20.90.1.128:7310/api/v1/appInfo/downloadImg", param, handler);
        }
        return null;
    }

    private void ys(Context context, File files, 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);
            }
        });
    }

    private static FormBody getRequestParam(Map<String, String> map) {
        FormBody.Builder formBody = new FormBody.Builder();
        if (map == null || map.isEmpty()) return formBody.build();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getValue() == null) {
                formBody.add(entry.getKey(), "");
            } else {
                formBody.add(entry.getKey(), entry.getValue());
            }
        }
        return formBody.build();
    }

    /**
     * GET 方式请求数据 图片
     */
    public static void postGetPhoto(String urlTal, Map<String, String> param, 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;
        }
        FormBody requestParam = getRequestParam(param);
        Request.Builder builder = new Request.Builder()
                .url(url);
        if (requestParam != null) {
            builder.post(requestParam);
        }
        Request request = builder.build();
        OkHttpUtils.getUploadPhotoClient(10, 30, 40)
                .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);
                    }
                });
    }
}
