package com.efounder.chat.utils;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.webkit.MimeTypeMap;

import com.efounder.constant.EnvironmentVariable;
import com.utilcode.util.UriUtils;

import java.io.File;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;

/**
 * Created by zhangshunyun on 2017/6/21.
 */

public class FileUtil {
    public static String USERDIR = Environment.getExternalStorageDirectory().getPath() +
            "/" + EnvironmentVariable.getProperty(KEY_SETTING_APPID) + "/" + EnvironmentVariable.getProperty(CHAT_USER_ID) + "/";
    public static String dir1 = USERDIR + "chat/";
    public static String filePath = dir1 + "chatfile/";
    //加密文件保存以及下载目录
    public static String encryptFilePath = dir1 + ".encryptFile/";
    //暂时没用到
    public static String decryptFilePath = dir1 + ".decryptFile/";
    //解密文件临时目录
    public static String decryptTemp = dir1+ ".tempDir/";
    public static String FILE_CLOUD_BASE_URL = "https://panserver.solarsource.cn/panserver/";
    public static String File_PROPERTY_BASE_URL = "http://panserver.solarsource.cn:9692/panserver/v2/files/dir/";
    public static String dir2 = "v2/files/dir/";
    public static String dir3 = "/query";

    static {
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        File file1 = new File(encryptFilePath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        File file2 = new File(decryptFilePath);
        if (!file2.exists()) {
            file2.mkdir();
        }
    }

    /**
     * 打开文件路径
     *
     * @param path
     * @return
     */
    public static Intent openAssignFolder(String path) {
        File file = new File(path);
        File parentFile = new File(file.getParent());
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(UriUtils.getUriForFile(parentFile), "*/*");
        return intent;
    }

    /***
     * 通过文件路径 打开程序列表
     *
     * @param filePath
     * @return
     */
    public static Intent openFile(String filePath) {

        File file = new File(filePath);
        if (!file.exists()) return null;
        /* 取得扩展名 */
        String end = file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length()).toLowerCase();
        /* 依扩展名的类型决定MimeType */
        if (end.equalsIgnoreCase("m4a") || end.equalsIgnoreCase("cd") || end.equalsIgnoreCase("mp3") || end.equalsIgnoreCase("asf") || end.equalsIgnoreCase("wma") || end.equalsIgnoreCase("mid") ||
                end.equalsIgnoreCase("mp3pro") || end.equalsIgnoreCase("xmf") || end.equalsIgnoreCase("ogg") || end.equalsIgnoreCase("wav") || end.equalsIgnoreCase("rm") || end.equalsIgnoreCase("real") || end.equalsIgnoreCase("ape") || end.equalsIgnoreCase("module") || end.equalsIgnoreCase("midi") || end.equalsIgnoreCase("vqf")) {
            return getAudioFileIntent(filePath);
        } else if (end.equalsIgnoreCase("avi") || end.equalsIgnoreCase("wmv") || end.equalsIgnoreCase("rmvb") || end.equalsIgnoreCase("flash") || end.equalsIgnoreCase("mpg") || end.equalsIgnoreCase("dat") || end.equalsIgnoreCase("3gp") || end.equalsIgnoreCase("mp4")) {
            return getVideoFileIntent(filePath);
        } else if (end.equalsIgnoreCase("jpg") || end.equalsIgnoreCase("gif") || end.equalsIgnoreCase("png") ||
                end.equalsIgnoreCase("jpeg") || end.equalsIgnoreCase("bmp") || end.equalsIgnoreCase("webp")) {
            return getImageFileIntent(filePath);
        } else if (end.equalsIgnoreCase("apk")) {
            return getApkFileIntent(filePath);
        } else if (end.equalsIgnoreCase("ppt") || end.equalsIgnoreCase("pot") || end.equalsIgnoreCase("pps") || end.equalsIgnoreCase("pptx") || end.equalsIgnoreCase("pptm") || end.equalsIgnoreCase("potx") || end.equalsIgnoreCase("potm") || end.equalsIgnoreCase("ppsx") || end.equalsIgnoreCase("ppsm")) {
            return getPptFileIntent(filePath);
        } else if (end.equalsIgnoreCase("xls") || end.equalsIgnoreCase("xlsx") || end.equalsIgnoreCase("xlsb") || end.equalsIgnoreCase("xlsm") || end.equalsIgnoreCase("xlst")) {
            return getExcelFileIntent(filePath);
        } else if (end.equalsIgnoreCase("doc") || end.equalsIgnoreCase("docx") || end.equalsIgnoreCase("dot") || end.equalsIgnoreCase("dotx") || end.equalsIgnoreCase("docm") || end.equalsIgnoreCase("dotm")) {
            return getWordFileIntent(filePath);
        } else if (end.equalsIgnoreCase("pdf")) {
            return getPdfFileIntent(filePath);
        } else if (end.equalsIgnoreCase("chm")) {
            return getChmFileIntent(filePath);
        } else if (end.equalsIgnoreCase("txt")) {
            return getTextFileIntent(filePath, false);
        } else if (end.equalsIgnoreCase("html")) {
            return getHtmlFileIntent(filePath);
        } else {
            return getAllIntent(filePath);
        }
    }

    //Android获取一个用于打开文件的intent
    public static Intent getAllIntent(String param) {

        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        Uri uri = UriUtils.getUriForFile(new File(param));
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(uri, "*/*");
        return intent;
    }

    //Android获取一个用于打开APK文件的intent
    public static Intent getApkFileIntent(String param) {

        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri uri = UriUtils.getUriForFile(new File(param));
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        return intent;
    }

    //Android获取一个用于打开VIDEO文件的intent
    public static Intent getVideoFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("oneshot", 0);
        intent.putExtra("configchange", 0);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri uri = UriUtils.getUriForFile(new File(param));
        intent.setDataAndType(uri, "video/*");
        return intent;
    }

    //Android获取一个用于打开AUDIO文件的intent
    public static Intent getAudioFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.putExtra("oneshot", 0);
        intent.putExtra("configchange", 0);
        Uri uri = UriUtils.getUriForFile(new File(param));
        intent.setDataAndType(uri, "audio/*");
        return intent;
    }

    //Android获取一个用于打开Html文件的intent
    public static Intent getHtmlFileIntent(String param) {

        Uri uri = Uri.parse(param).buildUpon().encodedAuthority("com.android.htmlfileprovider").scheme("content").encodedPath(param).build();
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(uri, "text/html");
        return intent;
    }

    //Android获取一个用于打开图片文件的intent
    public static Intent getImageFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri uri = UriUtils.getUriForFile(new File(param));
        intent.setDataAndType(uri, "image/*");
        return intent;
    }

    //Android获取一个用于打开PPT文件的intent
    public static Intent getPptFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri uri = UriUtils.getUriForFile(new File(param));
        intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
        return intent;
    }

    //Android获取一个用于打开Excel文件的intent
    public static Intent getExcelFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri uri = UriUtils.getUriForFile(new File(param));
        intent.setDataAndType(uri, "application/vnd.ms-excel");
        return intent;
    }

    //Android获取一个用于打开Word文件的intent
    public static Intent getWordFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri uri = UriUtils.getUriForFile(new File(param));
        intent.setDataAndType(uri, "application/msword");
        return intent;
    }

    //Android获取一个用于打开CHM文件的intent
    public static Intent getChmFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri uri = UriUtils.getUriForFile(new File(param));
        intent.setDataAndType(uri, "application/x-chm");
        return intent;
    }

    //Android获取一个用于打开文本文件的intent
    public static Intent getTextFileIntent(String param, boolean paramBoolean) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        if (paramBoolean) {
            Uri uri1 = Uri.parse(param);
            intent.setDataAndType(uri1, "text/plain");
        } else {
            Uri uri2 = UriUtils.getUriForFile(new File(param));
            intent.setDataAndType(uri2, "text/plain");
        }
        return intent;
    }

    //Android获取一个用于打开PDF文件的intent
    public static Intent getPdfFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri uri = UriUtils.getUriForFile(new File(param));
        intent.setDataAndType(uri, "application/pdf");
        return intent;
    }

    /***
     * 4.4以前的Uri跟4.4以后的Uri格式不一样，分开处理
     * 从Uri获取文件绝对路径
     *
     * @param context
     * @param uri
     * @return
     */
    @SuppressLint("NewApi")
    public static String getPathByUri4kitkat(final Context context, final Uri uri) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            if (isExternalStorageDocument(uri)) {// ExternalStorageProvider
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(uri)) {// DownloadsProvider
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(uri)) {// MediaProvider
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equalsIgnoreCase(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equalsIgnoreCase(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equalsIgnoreCase(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {// MediaStore
            // (and
            // general)
            return getDataColumn(context, uri, null, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {// File
            return uri.getPath();
        }
        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equalsIgnoreCase(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equalsIgnoreCase(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equalsIgnoreCase(uri.getAuthority());
    }

    /**
     * 获取文件的mimetype类型
     * @param filePath
     * @return
     */
    public static  String getMimeType(String filePath) {
        String ext = MimeTypeMap.getFileExtensionFromUrl(filePath);
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
    }
}
