package com.ifavine.pay.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;


import com.ifavine.pay.common.AppContext;
import com.ifavine.pay.common.Constants;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@SuppressLint("SimpleDateFormat")
/**
 *
 *使用之前必须初始化调用init();
 * @author(qiuyw)
 * @date 2015-6-24
 *
 */
public class AppFileUtil {
    public static String ROOT_PATH = null;

    public static void init(Context context) {
        // Log.i("aaaaa", context.getFilesDir().getAbsolutePath());
        // Log.i("aaaaa", context.getCacheDir().getAbsolutePath());
        // Log.i("aaaaa", context.getExternalCacheDir().getAbsolutePath());
        // Log.i("aaaaa", Environment.getDataDirectory().getAbsolutePath());
        // Log.i("aaaaa", Environment.getDownloadCacheDirectory()
        // .getAbsolutePath());
        // Log.i("aaaaa", Environment.getRootDirtory().getAbsolutePath());
        // Log.i("aaaaa", Environment.getExternalStorageDirectory()
        // .getAbsolutePath());
        // SD 卡可用
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            ROOT_PATH = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + File.separator;
        } else {
            // 使用手机内部存储
            ROOT_PATH = context.getFilesDir().getAbsolutePath()
                    + File.separator;
        }
    }

    /**
     * 获取文件夹大小
     *
     * @param f
     * @return
     * @throws Exception
     */

    public static long getFileDirSize(File f) {
        if (!f.exists()) {
            return 0;
        }
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileDirSize(flist[i]);
            } else {
                size = size + flist[i].length();
            }
        }
        return size;
    }

    public static String formatFileSize(long fileS) {// 转换文件大小
        if (fileS <= 0) {
            return "0MB";
        }
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    public static long getListFileNums(File f) {// 递归求取目录文件个数
        long size = 0;
        File flist[] = f.listFiles();
        size = flist.length;
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getListFileNums(flist[i]);
                size--;
            }
        }
        return size;
    }

    /**
     * 获取文件大小
     *
     * @param f
     * @return
     * @throws Exception
     */

    public static long getFileSizes(File f) {
        try {
            long s = 0;
            if (f.exists()) {
                FileInputStream fis = null;
                fis = new FileInputStream(f);
                s = fis.available();
                fis.close();
                Log.i("aaaaa", "getFileSizes:" + s);
            }
            return s;
        } catch (Exception e) {
            Log.i("aaaaa", "getFileSizes Exception");
            return -1;
        }
    }

    /**
     * @param appFileName xxx.apk
     */
    public static File createFile(String appFileName, File dir) {

        // 创建文件夹及文件
        File fileDir = new File(dir.getAbsolutePath());
        if (!fileDir.exists()) {
            try {
                // 按照指定的路径创建文件夹
                fileDir.mkdirs();
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        File myFile = new File(dir, appFileName);
        if (myFile.exists()) {
            myFile.delete();
        }
        if (!myFile.exists()) {
            try {
                // 在指定的文件夹中创建文件
                myFile.createNewFile();
            } catch (Exception e) {
            }
        }
        return myFile;

    }

    public static void compressPathImage(String fromFile, String toFile,
                                         int width, int height, int quality) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Config.RGB_565;
        try {
            InputStream i = new FileInputStream(new File(fromFile));
            Bitmap bitmap = BitmapFactory.decodeStream(i, null, options);
            saveCompressImage(bitmap, toFile, width, height, quality);
        } catch (Exception e) {

            e.printStackTrace();
        }

    }

    public static void saveCompressImage(Bitmap bitmap, String outFile,
                                         int width, int height, int quality) {
        try {
            int bitmapWidth = bitmap.getWidth();
            int bitmapHeight = bitmap.getHeight();
            // 缩放图片的尺寸
            float scaleWidth = (float) width / bitmapWidth;
            // float scaleHeight = (float) height / bitmapHeight;
            Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleWidth);
            // 产生缩放后的Bitmap对象
            Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                    bitmapWidth, bitmapHeight, matrix, false);
            // save file
            File myCaptureFile = new File(outFile);
            FileOutputStream out = new FileOutputStream(myCaptureFile);
            if (resizeBitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)) {
                out.flush();
                out.close();
            }
            if (!bitmap.isRecycled()) {
                bitmap.recycle();// 记得释放资源，否则会内存溢出
            }
            if (!resizeBitmap.isRecycled()) {
                resizeBitmap.recycle();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void saveCompressImageAndCropBitmap(Bitmap bitmap,
                                                      String outFile, int width, int height, int quality) {
        try {
            int bitmapWidth = bitmap.getWidth();
            int bitmapHeight = bitmap.getHeight();
            // 缩放图片的尺寸
            float scaleWidth = (float) width / bitmapWidth;
            // float scaleHeight = (float) height / bitmapHeight;
            Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleWidth);

            float scan = 0.1f;
            // 根据实际图片宽度定制图片大小
            if (bitmapHeight > 700) {
                scan = 0.1f;
            } else {
                scan = 0.18f;
                quality = 100;
            }
            // 产生缩放后的Bitmap对象
            int xp = (int) (bitmapWidth * scan);
            int yp = BaseUtil.Dp2Px(AppContext.getInstance(), 10);
            // 宽度处理
            int reWidth = (int) (bitmapWidth * (1.0f - 2.0f * scan));
            if (reWidth + xp >= bitmapWidth) {
                reWidth = bitmapWidth - xp;
            }
            // 高度度处理
            int reHeight = bitmapHeight * 13 / 20;
            if (reHeight + yp >= bitmapHeight) {
                reHeight = bitmapHeight - yp;
            }
            Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, xp, yp, reWidth,
                    reHeight);
            // save file
            File myCaptureFile = new File(outFile);
            FileOutputStream out = new FileOutputStream(myCaptureFile);
            if (resizeBitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)) {
                out.flush();
                out.close();
            }
            if (!bitmap.isRecycled()) {
                bitmap.recycle();// 记得释放资源，否则会内存溢出
            }
            if (!resizeBitmap.isRecycled()) {
                resizeBitmap.recycle();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 获取根目录
     *
     * @return
     */
    public static String getRootDir() {
        TLog.log("aaaaa", "ROOT_PATH:" + ROOT_PATH);
        if (ROOT_PATH != null) {
            return ROOT_PATH;
        }
        return Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator;
    }

    /**
     * 目录是否已存在
     *
     * @param path
     * @return
     */
    public static boolean existsDir(String path) {
        return new File(getRootDir() + path).exists();
    }

    /**
     * sdcard是否挂载
     *
     * @return
     */
    public static boolean isAvaiableSDCard() {
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 保存图片到Sdcard
     *
     * @param data
     * @param path
     * @param default [width:500,height:500,quality:60]
     */
    public static void saveNewPhoto(Bitmap data, String path) {
        saveNewPhoto(data, path, 0, 0);
    }

    public static File createFile(String dir, String filename) {
        try {
            File dirFile = new File(dir);
            if (!dirFile.exists())
                dirFile.mkdirs();
            File file = new File(dir, filename);
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            return file;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 保存图片到Sdcard
     *
     * @param data
     * @param path
     * @param width    -1:不剪裁 0：默认宽（500）
     * @param height   -1:不剪裁 0：默认高（500）
     * @param qualitys
     */
    public static void saveNewPhoto(Bitmap data, String path, int width,
                                    int height, int... qualitys) {
        // 把文件写入sd卡中
        FileOutputStream fileOutputStream = null;
        BufferedOutputStream bos = null;
        try {
            fileOutputStream = new FileOutputStream(path);
            bos = new BufferedOutputStream(fileOutputStream);
            if (data == null) {
                return;
            }
            // 如果需要改变大小(默认的是宽500×高500),如改成宽600×高800
            Bitmap newBM = Bitmap.createScaledBitmap(data, width == 0 ? 500
                    : width == -1 ? data.getWidth() : width, height == 0 ? 500
                    : height == -1 ? data.getHeight() : height, false);

            if (path.endsWith("png")) {
                if (qualitys != null && qualitys.length > 0) {
                    newBM.compress(Bitmap.CompressFormat.PNG,
                            qualitys[0] == 0 ? 60 : qualitys[0] == -1 ? 100
                                    : qualitys[0], bos);// 把数据写入文件
                } else {
                    newBM.compress(Bitmap.CompressFormat.PNG, 60, bos);// 把数据写入文件
                }
            } else {
                if (qualitys != null && qualitys.length > 0) {
                    newBM.compress(Bitmap.CompressFormat.JPEG,
                            qualitys[0] == 0 ? 60 : qualitys[0] == -1 ? 100
                                    : qualitys[0], bos);// 把数据写入文件
                } else {
                    newBM.compress(Bitmap.CompressFormat.JPEG, 60, bos);// 把数据写入文件
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            AppFileUtil.deleteTempFile(path);
        } finally {
            try {
                if (bos != null) {
                    bos.flush();
                    bos.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String readTextFile(String path, String charset) {
        byte[] data = readFile(path);
        if (data != null) {
            try {
                return new String(data, charset);
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

    public static byte[] readFile(String path) {
        try {
            File file = new File(path);
            if (file.exists()) {
                FileInputStream fis = new FileInputStream(file);
                return readStream(fis);
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过Bitmap剪裁
     *
     * @param activity    页面上下文
     * @param data        图片对象
     * @param outputX     尺寸
     * @param outputY     尺寸
     * @param requestCode 请求码
     */
    public static void doCropPhoto(Activity activity, Bitmap data, int outputX,
                                   int outputY, int requestCode) {
        Intent intent = getCropImageIntent(data, outputX, outputY, 1);
        activity.startActivityForResult(intent, requestCode);
    }

    /**
     * 通过Uri剪裁
     *
     * @param activity    页面上下文
     * @param uri         图片Uri
     * @param outputX     尺寸
     * @param outputY     尺寸
     * @param requestCode 请求码
     */
    public static void doCropPhoto(Activity activity, Uri uri, int outputX,
                                   int outputY, int requestCode) {
        Intent intent = getCropImageIntent(uri, outputX, outputY, 0);
        activity.startActivityForResult(intent, requestCode);
    }

    /**
     * 获取intent剪裁对象
     *
     * @param obj     bitmap uri
     * @param outputX 裁剪尺寸
     * @param outputY 裁剪尺寸
     * @param type    类型 0：Uri 1：Bitmap
     * @return
     */
    private static Intent getCropImageIntent(Object obj, int outputX,
                                             int outputY, int type) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        switch (type) {
            case 0: // URI
                intent.setDataAndType((Uri) obj, "image/*");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, (Uri) obj);
                intent.putExtra("return-data", false);
                break;
            case 1: // Bitmap
                intent.setType("image/*");
                intent.putExtra("data", (Bitmap) obj);
                intent.putExtra("return-data", true);
                break;
            default:
                break;
        }
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        return intent;
    }

    /**
     * 字节流转Bitmap
     *
     * @param bytes
     * @param opts
     * @return
     */
    public static Bitmap getPicFromBytes(byte[] bytes,
                                         BitmapFactory.Options opts) {
        if (bytes != null)
            if (opts != null)
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
                        opts);
            else
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        return null;
    }

    public static void write2File(String dir, String filename, String content,
                                  boolean isAppend) {
        OutputStream os = null;
        try {
            File file = createFile(dir, filename);
            os = new FileOutputStream(file, isAppend);
            os.write(content.getBytes());
            os.flush();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (os != null)
                    os.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static void write2File(String dir, String filename, InputStream is,
                                  boolean isAppend) {
        OutputStream os = null;
        try {
            File file = createFile(dir, filename);
            os = new FileOutputStream(file, isAppend);
            byte[] buffer = new byte[1024 * 10];
            int length = -1;
            while ((length = is.read(buffer)) != -1) {
                os.write(buffer, 0, length);
            }
            os.flush();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (os != null)
                    os.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 读取字节流
     *
     * @param inStream
     * @return
     * @throws Exception
     */

    /**
     * 获取图片名称【以系统时间为准】
     *
     * @return
     */
    public static String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }

    /**
     * 解析Uri，生成Bitmap
     *
     * @param context
     * @param uri
     * @return
     */
    public static Bitmap decodeUriAsBitmap(Context context, Uri uri) {
        Bitmap bitmap = null;
        try {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(uri.getPath(), options);
            options.inJustDecodeBounds = false;
            bitmap = BitmapFactory.decodeStream(context.getContentResolver()
                    .openInputStream(uri), null, options);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    /**
     * 压缩bitmap图片
     *
     * @param path
     * @param size 宽或高
     * @return
     * @throws IOException
     */
    public static Bitmap compressImageSize(String path, int size)
            throws IOException {

        FileInputStream input = new FileInputStream(path);

        // 取得图片
        BitmapFactory.Options options = new BitmapFactory.Options();
        // 这个参数代表，不为bitmap分配内存空间，只记录一些该图片的信息（例如图片大小），内存优化
        options.inJustDecodeBounds = true;
        // 通过创建图片的方式，取得options的内容（这里就是利用了java的地址传递来赋值）
        BitmapFactory.decodeStream(input, null, options);
        // 关闭流
        input.close();

        // 生成压缩的图片
        int i = 0;
        Bitmap bitmap = null;
        while (true) {
            // 这一步是根据要设置的大小，使宽和高都能满足
            if ((options.outWidth >> i <= size)
                    && (options.outHeight >> i <= size)) {
                // 重新取得流，注意：这里一定要再次加载，不能二次使用之前的流！
                input = new FileInputStream(path);
                // 这个参数表示 新生成的图片为原始图片的几分之一。
                options.inSampleSize = (int) Math.pow(2.0D, i);
                // 这里之前设置为了true，所以要改为false，否则就创建不出图片
                options.inJustDecodeBounds = false;

                bitmap = BitmapFactory.decodeStream(input, null, options);
                break;
            }
            i += 1;
        }
        return bitmap;
    }

    /**
     * 计算图片的缩放值
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // Calculate ratios of height and width to requested height and
            // width
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);

            // Choose the smallest ratio as inSampleSize value, this will
            // guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }

        return inSampleSize;
    }

    /**
     * 根据路径获得突破并压缩返回bitmap用于显示
     *
     * @param imagesrc
     * @return
     */
    public static Bitmap getSmallBitmap(String filePath, int reqWidth,
                                        int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(filePath, options);
    }

    /**
     * 根据路径获得突破并压缩返回bitmap用于显示
     *
     * @param imagesrc
     * @return
     */
    public static Bitmap getSmallBitmap(Resources res, int resourcesId,
                                        int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resourcesId, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeResource(res, resourcesId, options);
    }

    /**
     * 压缩图片
     *
     * @param bitmap
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static Bitmap getSmallBitmap(Bitmap bitmap, int reqWidth,
                                        int reqHeight) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        // 计算缩放比例
        float scaleWidth = ((float) reqWidth) / width;
        float scaleHeight = ((float) reqHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        return bitmap;
    }

    /**
     * BitMap 转 Drawable
     *
     * @param res
     * @param resourcesId
     * @param newWidth    -1:不压缩宽度
     * @param newHeight   -1 不压缩高度
     * @return
     */
    public static Drawable convertToDrawable(Resources res, int resourcesId,
                                             int newWidth, int newHeight) {
        Bitmap bitMap = getSmallBitmap(res, resourcesId, newWidth, newHeight);
        bitMap = getSmallBitmap(bitMap, newWidth == -1 ? bitMap.getWidth()
                : newWidth, newHeight == -1 ? bitMap.getHeight() : newHeight);
        @SuppressWarnings("deprecation")
        BitmapDrawable drawable = new BitmapDrawable(bitMap);
        return drawable;
    }

    /**
     * BitMap 转 Drawable
     *
     * @param bitMap
     * @param newWidth
     * @param newHeight
     * @return
     */
    public static Drawable convertToDrawable(Bitmap bitMap, int newWidth,
                                             int newHeight) {
        bitMap = getSmallBitmap(bitMap, newWidth, newHeight);
        @SuppressWarnings("deprecation")
        BitmapDrawable drawable = new BitmapDrawable(bitMap);
        return drawable;
    }

    /**
     * 根据路径删除图片
     *
     * @param path
     */
    public static void deleteTempFile(String path) {
        try {
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param file
     */
    public static void deleteDirs(File file) {
        if (file.isFile()) {
            file.delete();
            return;
        }

        if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length == 0) {
                file.delete();
                return;
            }

            for (int i = 0; i < childFiles.length; i++) {
                deleteDirs(childFiles[i]);
            }
            file.delete();
        }
    }

    /**
     * 添加到图库
     */
    public static void galleryAddPic(Context context, String path) {
        Intent mediaScanIntent = new Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(path);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        context.sendBroadcast(mediaScanIntent);
    }

    /**
     * 保存图片路径
     */
    public static File getCacheImagePath() {
        File file = new File(getRootDir() + Constants.IMAGE_DOWNLOAD
                + File.separator);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    /**
     * 临时保存图片路径
     */
    public static File getCacheImageTempPath() {
        File file = new File(getRootDir() + Constants.IMAGE_TEMP
                + File.separator);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    /**
     * 获取相册目录
     *
     * @return
     */
    public static File getAlbumDir() {
        File dir = new File(getRootDir() + "DCIM/");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir;
    }

    /**
     * 获取图片的保存路径（以系统时间命名图片）
     */
    public static String getSaveImageFile() {
        return getCacheImagePath() + File.separator + getPhotoFileName();
    }

    /**
     * 获取临时图片的保存路径（以系统时间命名图片）
     */
    public static String getSaveImageTempFile() {
        return getCacheImageTempPath() + File.separator + getPhotoFileName();
    }

    /**
     * 获取图片的保存路径（自己命名）
     *
     * @param imageName
     * @return
     */
    public static String getImageForNamePath(String imageName) {
        return getCacheImagePath() + File.separator + imageName + ".png";
    }

    public static byte[] readStream(InputStream is) {
        if (is != null) {
            try {
                int len = is.available();
                byte[] buffer = new byte[len];
                is.read(buffer);
                return buffer;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static String readStream(InputStream is, String charset) {
        if (is != null) {
            try {
                StringBuilder sb = new StringBuilder();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is, charset));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                is.close();
                return sb.toString();
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /** */
    /**
     * 文件重命名
     *
     * @param oldname 原来的文件名,带路径
     * @param newname 新文件名，带路径
     */
    public static boolean renameFile(String oldname, String newname) {
        if (!BaseUtil.isNull(newname) && !BaseUtil.isNull(oldname)
                && !oldname.equals(newname)) {// 新的文件名和以前文件名不同时,才有必要进行重命名
            File oldfile = new File(oldname);
            File newfile = new File(newname);
            if (!oldfile.exists()) {
                return false;// 重命名文件不存在
            }
            if (newfile.exists())// 若在该目录下已经有一个文件和新文件名相同，则不允许重命名
                return false;
            else {
                oldfile.renameTo(newfile);
                return true;
            }
        } else {
            return false;
        }
    }

    /**
     * 读取assets 文件数据
     *
     * @param fileName
     * @param context
     * @return
     */
    public static String getStringFromAssetsFile(String fileName,
                                                 Context context) {
        try {
            InputStream inputStream = context.getAssets().open(fileName);
            return readTextFile(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String readTextFile(InputStream inputStream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte buf[] = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
            return null;
        }
        return outputStream.toString();
    }

    /**
     * 读取raw 文件
     *
     * @return
     */
    public static String getFromRaw(Context context, int resourcesId) {
        try {
            InputStreamReader inputReader = new InputStreamReader(context
                    .getResources().openRawResource(resourcesId));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            String Result = "";
            while ((line = bufReader.readLine()) != null)
                Result += line;
            return Result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Bitmap getPathBitmap(String path) {
        try {
            FileInputStream fis = new FileInputStream(path);
            Bitmap bitmap = BitmapFactory.decodeStream(fis);
            return bitmap;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
