package com.bonait.bnframework.common.image.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Debug;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.os.Process;

import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.HBL.NetworkUtils;
import com.bonait.bnframework.MainApplication;
import com.bonait.bnframework.R;
import com.bonait.bnframework.business.OrderServer;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.glide.transform.FitXYRoundRadiusTransform;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 三级缓存之本地缓存
 */
public class LocalCacheUtils {

    private static final String CACHE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/hblchayingdb/WebImage";

    //region 私有单例
    private static volatile LocalCacheUtils _instance;

    public static LocalCacheUtils Get() {
        if (_instance == null)
            _instance = new LocalCacheUtils();
        return _instance;
    }

    private LocalCacheUtils() {
    }
    //endregion

    /**
     * 设置Image图片
     *
     * @param ivPic
     * @param name
     * @param url
     * @return
     */
    public boolean SetBitmapFile(ImageView ivPic, String name,String url) {
        File file = new File(CACHE_PATH, name);
        String imgUrl = null;
        if(url!=null && url.startsWith("http")){
            if(NetworkUtils.isNetworkConnected(MainApplication.getContext())){
                imgUrl = url;
            }
        }
        if (null != file && file.exists()) {
            try {
                LogUtils.d("加载图片");
                Glide.with(ivPic.getContext()).load(imgUrl==null?file:imgUrl)
                        //.override(width, height)
//                        .thumbnail(0.1f) // 加载原始图片的10%作为缩略图
                        .fitCenter() // 缩放图片以适应ImageView的尺寸
//                        .override(150, 75) // 设置目标图片的宽度和高度
                        .placeholder(R.mipmap.loading3)
//                        .error(R.mipmap.loadingerror)
                        .skipMemoryCache(true) // 禁用内存缓存
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .apply(new RequestOptions().transform(new FitXYRoundRadiusTransform(10)))
                        //.diskCacheStrategy(DiskCacheStrategy.ALL) // 缓存所有版本的图片
                        .into(ivPic);
                System.out.println("从本地获取图片啦.....");
                return true;
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            } catch (IllegalArgumentException ex) {
                System.out.println("界面已经销毁.....");
            }
        }
        return false;
    }
    /**
     * 判断活动窗体是否正在显示
     *
     * @param context
     * @return
     */
    public boolean isActivityVisible(Context context) {
        if (context instanceof Activity) {
            Activity activity = (Activity) context;
            return !activity.isFinishing() && !activity.isDestroyed();
        }
        return false;
    }

    /**
     * 从网络获取图片后,保存至本地缓存
     *
     * @param url
     * @param bitmap
     */
    public String setBitmapToLocal(String url, Bitmap bitmap) {
        try {

            String fileName = url.substring(url.lastIndexOf('/') + 1);
            ;//MD5Encoder.encode(url);;//AES.Encrypt(url);//;MD5Encoder.encode(url);//把图片的url当做文件名,并进行MD5加密
            File file = new File(CACHE_PATH, fileName);
            //通过得到文件的父文件,判断父文件是否存在
            File parentFile = file.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }

            if (!file.exists())//文件不存在
            {
                //把图片保存至本地
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, new FileOutputStream(file));
            }

            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private RandomAccessFile procStatFile;
    private RandomAccessFile appStatFile;
    private Long lastCpuTime;
    private Long lastAppCpuTime;
    /**
     * 运行内存
     */
    public void RunCPUOrMemory()
    {
//        int cpu = (int)sampleCPU();
//        int mem = (int)sampleMemory();
//        Log.e("实时内存消耗", ": CPU: " + cpu + "%" + ", Memory: " + mem + "MB");
        releaseMemory();
    }

    /**
     * 释放内存
     */
    public static void releaseMemory() {
        System.runFinalization();
        Runtime.getRuntime().gc();
        Runtime.getRuntime().runFinalization();
        System.gc();
    }
    /**
     * 读取CPU
     * @return
     */
    private double sampleCPU() {
        long cpuTime;
        long appTime;
        double sampleValue = 0.0D;
        try {
            if (procStatFile == null || appStatFile == null) {
                procStatFile = new RandomAccessFile("/proc/stat", "r");
                appStatFile = new RandomAccessFile("/proc/" + Process.myPid() + "/stat", "r");
            } else {
                procStatFile.seek(0L);
                appStatFile.seek(0L);
            }
            String procStatString = procStatFile.readLine();
            String appStatString = appStatFile.readLine();
            String procStats[] = procStatString.split(" ");
            String appStats[] = appStatString.split(" ");
            cpuTime = Long.parseLong(procStats[2]) + Long.parseLong(procStats[3])
                    + Long.parseLong(procStats[4]) + Long.parseLong(procStats[5])
                    + Long.parseLong(procStats[6]) + Long.parseLong(procStats[7])
                    + Long.parseLong(procStats[8]);
            appTime = Long.parseLong(appStats[13]) + Long.parseLong(appStats[14]);
            if (lastCpuTime == null && lastAppCpuTime == null) {
                lastCpuTime = cpuTime;
                lastAppCpuTime = appTime;
                return sampleValue;
            }
            sampleValue = ((double) (appTime - lastAppCpuTime) / (double) (cpuTime - lastCpuTime)) * 100D;
            lastCpuTime = cpuTime;
            lastAppCpuTime = appTime;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sampleValue;
    }
    /**
     * 读取内存消耗
     * @return
     */
    private double sampleMemory() {
        double mem = 0.0D;
        try {
            // 统计进程的内存信息 totalPss
            ActivityManager activityManager = (ActivityManager) ConfigName.getInstance().dishesCon.getSystemService(Context.ACTIVITY_SERVICE);
            final Debug.MemoryInfo[] memInfo = activityManager.getProcessMemoryInfo(new int[]{Process.myPid()});
            if (memInfo.length > 0) {
                // TotalPss = dalvikPss + nativePss + otherPss, in KB
                final int totalPss = memInfo[0].getTotalPss();
                if (totalPss >= 0) {
                    // Mem in MB
                    mem = totalPss / 1024.0D;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mem;
    }

}