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

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

import com.google.gson.JsonObject;
import com.rs.macall.androidx.basemodel.utils.BitMapUtils;
import com.rs.macall.androidx.basemodel.utils.LogUtils;
import com.rs.macall.androidx.basemodel.utils.StringUtil;
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.util.FileUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

import okhttp3.ResponseBody;

/**
 * created by:   Macall
 * create time:  2023/11/28 14:21
 * copyright:    @ruansee.com
 * Describe:
 */
public class LoadPhotoImage {
    /**
     * 内存图片软引用缓冲
     */
    private HashMap<String, SoftReference<Bitmap>> imageCache = null;

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

    public Bitmap loadPhotoImage(String id, ImageView view, ImageCallBack callBack) {
        //在内存缓存中，则返回Bitmap对象
        if (imageCache.containsKey(id)) {
            SoftReference<Bitmap> reference = imageCache.get(id);
            Bitmap bitmap = reference.get();
            if (bitmap != null) {
                return bitmap;
            }
        } else {
            File cacheDir = new File(FileUtils.IMAGE_DIR + id);
            if (cacheDir.exists()) {
                try {
                    return BitmapFactory.decodeFile(cacheDir.getAbsolutePath());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        Map<String, String> param = new HashMap<>();
        param.put("id", id);
        param.put("token", RuanseeApplication.getAppCache().getToken());
        param.put("clientType", "MOBILE");
        param.put("imsi1", StringUtil.get(RuanseeApplication.getAppCache().getImsi(),""));
        param.put("deviceFlags",StringUtil.get( RuanseeApplication.getAppCache().getImei(),""));
        param.put("sysCode", RuanseeApplication.getAppCache().getSysmCode());
        ApiModel.request(RetrofitService.getBaseInstance().loadPhoto("http://20.90.2.2/UniAuth/api/sso/v1/download", param),
                new BaseRequestCallback<ResponseBody>() {
                    @Override
                    public void onRequestFailure(String msg) {
                        LogUtils.e(msg);
                        if (callBack != null) {
                            callBack.imageLoadError(view, msg);
                        }
                    }

                    @Override
                    public void onRequestSuccess(ResponseBody result) {
                        InputStream is = null;
                        byte[] buf = new byte[2048];
                        int len = 0;
                        FileOutputStream fos = null;
                        // 储存下载文件的目录
                        String savePath = FileUtils.IMAGE_DIR;
                        try {
                            is = result.byteStream();
//                            long total = result.contentLength();
                            String nameFromUrl = (String) getPayloads().get(0);
//                            if (StringUtil.isNullOrEmpty(nameFromUrl)){
//                                nameFromUrl = getNameFromUrl(url);
//                            }
                            File file = new File(savePath, nameFromUrl);
                            fos = new FileOutputStream(file);
//                            long sum = 0;
                            while ((len = is.read(buf)) != -1) {
                                fos.write(buf, 0, len);
//                                sum += len;
//                                int progress = (int) (sum * 1.0f / total * 100);
                                // 下载中
//                                listener.onDownloading(progress);
                            }
                            fos.flush();
                            if (callBack != null) {
                                callBack.imageLoad(view,BitmapFactory.decodeFile(file.getAbsolutePath()));
                            }
                            // 下载完成
//                            listener.onDownloadSuccess(file);
                        } catch (Exception e) {
                            e.printStackTrace();
                            if (callBack != null) {
                                callBack.imageLoadError(view, e.getMessage());
                            }
                        } finally {
                            try {
                                if (is != null)
                                    is.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            try {
                                if (fos != null)
                                    fos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }.addPayload(id));

        return null;
    }


}
